hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
b53b6f2ef58c4fb05485420cafdc045a8e935e34
1,221
package org.bcos.web3j.crypto; import org.bcos.web3j.crypto.sm3.SM3Digest; import org.bouncycastle.jcajce.provider.digest.Keccak; import org.bcos.web3j.utils.Numeric; /** * Crypto related functions. */ public class Hash { private static HashInterface hashInterface = new SHA3Digest(); public static HashInterface getHashInterface() { return hashInterface; } public static void setHashInterface(HashInterface hashInterface) { Hash.hashInterface = hashInterface; } /** * Keccak-256 hash function. * * @param hexInput hex encoded input data with optional 0x prefix * @return hash value as hex encoded string */ public static String sha3(String hexInput) { return hashInterface.hash(hexInput); } /** * Keccak-256 hash function. * * @param input binary encoded input data * @param offset of start of data * @param length of data * @return hash value */ public static byte[] sha3(byte[] input, int offset, int length) { return hashInterface.hash(input,offset,length); } public static byte[] sha3(byte[] input) { return hashInterface.hash(input,0,input.length); } }
25.4375
70
0.665848
e632202831340432eca0bf13006c70343cce57e0
346
package com.funcache.util; /** * TODO: Class description here. * * @author <a href="https://github.com/tjeubaoit">tjeubaoit</a> */ public interface FastLinkedListItem { FastLinkedListItem getPrevious(); void setPrevious(FastLinkedListItem previous); FastLinkedListItem getNext(); void setNext(FastLinkedListItem next); }
19.222222
63
0.725434
4de1c2e2e48e54af6bb8d82a1d60ee7b3e208413
1,459
package com.tma.tt.api.repository; import com.tma.tt.api.jpa.ScheduleJpaRepository; import com.tma.tt.api.model.Schedule; import io.katharsis.queryspec.QuerySpec; import io.katharsis.repository.ResourceRepositoryBase; import io.katharsis.resource.links.DefaultPagedLinksInformation; import io.katharsis.resource.list.DefaultResourceList; import io.katharsis.resource.list.ResourceList; import io.katharsis.resource.meta.DefaultPagedMetaInformation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class ScheduleRepositoryImpl extends ResourceRepositoryBase<Schedule, Long> implements ScheduleRepository { @Autowired private ScheduleJpaRepository jpaRepository; public ScheduleRepositoryImpl() { super(Schedule.class); } @Override public ResourceList<Schedule> findAll(QuerySpec querySpec) { ResourceList<Schedule> list = new DefaultResourceList<Schedule>(new DefaultPagedMetaInformation(), new DefaultPagedLinksInformation()); List<Schedule> schedules = jpaRepository.findAll(); querySpec.apply(schedules, list); return list; } @Override public Schedule save(Schedule obj){ obj.setWeekId(); return jpaRepository.save(obj); } @Override public void delete(Long id){ Schedule obj = jpaRepository.getOne(id); this.jpaRepository.delete(obj); } }
32.422222
137
0.770391
7097f4020c7506fa25a5a574a960d7ae94fe789a
3,469
package testpackage; import java.util.ArrayList; import rx.Observable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import rx.Scheduler; import rx.schedulers.Schedulers; import com.microsoft.azure.cosmosdb.ConnectionMode; import com.microsoft.azure.cosmosdb.Document; import java.util.UUID; public class DataProgram2 { private final ExecutorService executorService; private final Scheduler scheduler; private AsyncDocumentClient client; private final String databaseName = "FinancialDatabase"; private final String collectionId = "PeopleCollection"; private AsyncDocumentClient asyncClient; private final String partitionKeyPath = "/type"; private final int throughPut = 400; public DataProgram2() { executorService = Executors.newFixedThreadPool(100); scheduler = Schedulers.from(executorService); // Sets up the requirements for each test ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.Direct); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint("uri") .withMasterKeyOrResourceToken( "key") .withConnectionPolicy(connectionPolicy).withConsistencyLevel(ConsistencyLevel.Session).build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); } /** * Create a document with a programmatically set definition, in an Async manner */ public static void main(String[] args) { DataProgram2 p = new DataProgram2(); try { p.createDocument(); System.out.println("finished"); } catch (Exception e) { System.err.println(String.format("failed with %s", e)); } System.exit(0); } public void createDocument() throws Exception { ArrayList<Document> documents = new PersonDetail(1, 100).documentDefinitions; for (Document document : documents) { // Create a document Observable<ResourceResponse<Document>> createDocumentObservable = asyncClient .createDocument("dbs/" + databaseName + "/colls/" + collectionId, document, null, false); Observable<Double> totalChargeObservable = createDocumentObservable.map(ResourceResponse::getRequestCharge) // Map to request charge .reduce((totalCharge, charge) -> totalCharge + charge); // Sum up all the charges final CountDownLatch completionLatch = new CountDownLatch(1); // Subscribe to the total request charge observable totalChargeObservable.subscribe(totalCharge -> { // Print the total charge System.out.println("RU charge: "+totalCharge); completionLatch.countDown(); }, e -> completionLatch.countDown()); completionLatch.await(); } } }
38.977528
119
0.686653
59717ea3ad5557ef9917f6b4637a10d2bb7f9acf
878
package miw.ws.easidiomas.images.util; import java.awt.Image; import java.awt.image.BufferedImage; public class ImageUtils { /** * Resizes an image to the given dimensions. * * @param src java.awt.Image object with the original image to be resized. * @param finalWidth Target width that the final image will have. * @param finalHeight Target height that the final image will have. * @return BufferedImage object with the resized image data. */ public static BufferedImage resizeImage(Image src, int finalWidth, int finalHeight) { Image resultingImage = src.getScaledInstance(finalWidth, finalHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } }
36.583333
104
0.738041
ae85c253f4e9d43fc9d2eb155c26c8923afdb687
1,306
import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; @SuppressWarnings("unused") public class P073 implements Puzzle { @Override public String solve() { final BitSet primesBits = Util.primesBits(12_000); final Map<Integer, Set<Integer>> factors = IntStream.range(1, 12_001) .boxed() .collect(Collectors.toMap(i -> i, i -> Util.uniqueFactors(i, primesBits).mapToInt(integer -> (int) integer).boxed().collect(Collectors.toSet()))); return "" + IntStream.range(2, 12_001) .parallel() .map(denominator -> { int count = 0; for (int numerator = denominator / 3 + 1; numerator < (denominator - 1) / 2 + 1; ++numerator) { double result = 1.0 * numerator / denominator; if (result > 1.0 / 3.0 && result < 1.0 / 2.0 && Collections.disjoint(factors.get(numerator), factors.get(denominator))) { ++count; } } return count; }) .sum(); } }
36.277778
154
0.487749
50bfaf4767d9e694e505c2b6fd1170f5ec5ad290
1,354
package com.jwetherell.algorithms.data_structures.test; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.jwetherell.algorithms.data_structures.HashMap; import com.jwetherell.algorithms.data_structures.test.common.JavaMapTest; import com.jwetherell.algorithms.data_structures.test.common.MapTest; import com.jwetherell.algorithms.data_structures.test.common.Utils; import com.jwetherell.algorithms.data_structures.test.common.Utils.TestData; public class HashMapTests { @Test public void testHashMap() { TestData data = Utils.generateTestData(1000); String mapName = "ProbingHashMap"; HashMap<Integer,String> map = new HashMap<Integer,String>(HashMap.Type.PROBING); java.util.Map<Integer,String> jMap = map.toMap(); assertTrue(MapTest.testMap(map, Integer.class, mapName, data.unsorted, data.invalid)); assertTrue(JavaMapTest.testJavaMap(jMap, Integer.class, mapName, data.unsorted, data.sorted, data.invalid)); mapName = "LinkingHashMap"; map = new HashMap<Integer,String>(HashMap.Type.CHAINING); jMap = map.toMap(); assertTrue(MapTest.testMap(map, Integer.class, mapName, data.unsorted, data.invalid)); assertTrue(JavaMapTest.testJavaMap(jMap, Integer.class, mapName, data.unsorted, data.sorted, data.invalid)); } }
39.823529
116
0.745938
0a5a5eb47926a70dc76d9eb801864b7f5ead0bbc
1,605
import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.remote.MobileCapabilityType; public class base { public static AndroidDriver<AndroidElement> Capabilities() throws MalformedURLException { //get the apk file File f = new File("src/main/java"); File fs = new File(f, "Raaga.apk"); //create capabilities DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Pixel XL API 27"); cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath()); //driver to connect to server AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap); return driver; } public static AndroidDriver<AndroidElement> Capabilities(String device) throws MalformedURLException { //get the apk file File f = new File("src/main/java"); File fs = new File(f, "Raaga.apk"); //create capabilities DesiredCapabilities cap = new DesiredCapabilities(); if (device.equals("emulator")) { cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Pixel XL API 27"); } else { cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Device"); } cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath()); //driver to connect to server AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap); return driver; } }
40.125
107
0.759502
8942cb9c823faabd93b4b8c6832d5981ed5e3321
1,945
package org.mudebug.prapr.core.mutationtest.engine.mutators.util; /* * #%L * prapr-plugin * %% * Copyright (C) 2018 - 2019 University of Texas at Dallas * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.pitest.classinfo.ClassName; import org.pitest.reloc.asm.Opcodes; import java.util.List; /** * @author Ali Ghanbari ([email protected]) * @since 1.0.0 */ public class PraPRMethodInfo { public final String name; public final boolean isStatic; public final boolean isPublic; public final boolean isPrivate; public final boolean isProtected; public final List<LocalVarInfo> localsInfo; public final ClassName owningClassName; public final List<Integer> nullableParamIndices; PraPRMethodInfo(final int access, final String name, final List<LocalVarInfo> localsInfo, final ClassName owningClassName, final List<Integer> nullableParamIndices) { this.name = name; this.isStatic = (access & Opcodes.ACC_STATIC) != 0; this.isPublic = (access & Opcodes.ACC_PUBLIC) != 0; this.isPrivate = (access & Opcodes.ACC_PRIVATE) != 0; this.isProtected = (access & Opcodes.ACC_PROTECTED) != 0; this.localsInfo = localsInfo; this.owningClassName = owningClassName; this.nullableParamIndices = nullableParamIndices; } }
30.873016
75
0.684319
7669168d1f4a12359c15dad03dc1455f3928947f
17,141
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.server.lookup.namespace.cache; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.inject.Inject; import io.druid.java.util.emitter.service.ServiceEmitter; import io.druid.java.util.emitter.service.ServiceMetricEvent; import io.druid.guice.LazySingleton; import io.druid.java.util.common.ISE; import io.druid.java.util.common.StringUtils; import io.druid.java.util.common.logger.Logger; import io.druid.query.lookup.namespace.CacheGenerator; import io.druid.query.lookup.namespace.ExtractionNamespace; import sun.misc.Cleaner; import javax.annotation.Nullable; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Usage: * <pre>{@code * CacheScheduler.Entry entry = cacheScheduler.schedule(namespace); // or scheduleAndWait(namespace, timeout) * CacheState cacheState = entry.getCacheState(); * // cacheState could be either NoCache or VersionedCache. * if (cacheState instanceof NoCache) { * // the cache is not yet created, or already closed * } else if (cacheState instanceof VersionedCache) { * Map<String, String> cache = ((VersionedCache) cacheState).getCache(); // use the cache * // Although VersionedCache implements AutoCloseable, versionedCache shouldn't be manually closed * // when obtained from entry.getCacheState(). If the namespace updates should be ceased completely, * // entry.close() (see below) should be called, it will close the last VersionedCache itself. * // On scheduled updates, outdated VersionedCaches are also closed automatically. * } * ... * entry.close(); // close the last VersionedCache and unschedule future updates * }</pre> */ @LazySingleton public final class CacheScheduler { private static final Logger log = new Logger(CacheScheduler.class); public final class Entry<T extends ExtractionNamespace> implements AutoCloseable { private final EntryImpl<T> impl; private Entry(final T namespace, final CacheGenerator<T> cacheGenerator) { impl = new EntryImpl<>(namespace, this, cacheGenerator); } /** * Returns the last cache state, either {@link NoCache} or {@link VersionedCache}. */ public CacheState getCacheState() { return impl.cacheStateHolder.get(); } /** * @return the entry's cache if it is already initialized and not yet closed * @throws IllegalStateException if the entry's cache is not yet initialized, or {@link #close()} has * already been called */ public Map<String, String> getCache() { CacheState cacheState = getCacheState(); if (cacheState instanceof VersionedCache) { return ((VersionedCache) cacheState).getCache(); } else { throw new ISE("Cannot get cache: %s", cacheState); } } @VisibleForTesting Future<?> getUpdaterFuture() { return impl.updaterFuture; } public void awaitTotalUpdates(int totalUpdates) throws InterruptedException { impl.updateCounter.awaitTotalUpdates(totalUpdates); } void awaitNextUpdates(int nextUpdates) throws InterruptedException { impl.updateCounter.awaitNextUpdates(nextUpdates); } /** * Close the last {@link #getCacheState()}, if it is {@link VersionedCache}, and unschedule future updates. */ @Override public void close() { impl.close(); } @Override public String toString() { return impl.toString(); } } /** * This class effectively contains the whole state and most of the logic of {@link Entry}, need to be a separate class * because the Entry must not be referenced from the runnable executed in {@link #cacheManager}'s ExecutorService, * that would be a leak preventing the Entry to be collected by GC, and therefore {@link #entryCleaner} to be run by * the JVM. Also, {@link #entryCleaner} must not reference the Entry through it's Runnable hunk. */ public class EntryImpl<T extends ExtractionNamespace> implements AutoCloseable { private final T namespace; private final String asString; private final AtomicReference<CacheState> cacheStateHolder = new AtomicReference<CacheState>(NoCache.CACHE_NOT_INITIALIZED); private final Future<?> updaterFuture; private final Cleaner entryCleaner; private final CacheGenerator<T> cacheGenerator; private final UpdateCounter updateCounter = new UpdateCounter(); private final CountDownLatch startLatch = new CountDownLatch(1); private EntryImpl(final T namespace, final Entry<T> entry, final CacheGenerator<T> cacheGenerator) { try { this.namespace = namespace; this.asString = StringUtils.format("namespace [%s] : %s", namespace, super.toString()); this.updaterFuture = schedule(namespace); this.entryCleaner = createCleaner(entry); this.cacheGenerator = cacheGenerator; activeEntries.incrementAndGet(); } finally { startLatch.countDown(); } } private Cleaner createCleaner(Entry<T> entry) { return Cleaner.create(entry, new Runnable() { @Override public void run() { closeFromCleaner(); } }); } private Future<?> schedule(final T namespace) { final long updateMs = namespace.getPollMs(); Runnable command = new Runnable() { @Override public void run() { updateCache(); } }; if (updateMs > 0) { return cacheManager.scheduledExecutorService().scheduleAtFixedRate(command, 0, updateMs, TimeUnit.MILLISECONDS); } else { return cacheManager.scheduledExecutorService().schedule(command, 0, TimeUnit.MILLISECONDS); } } private void updateCache() { try { // Ensures visibility of the whole EntryImpl's state (fields and their state). startLatch.await(); CacheState currentCacheState = cacheStateHolder.get(); if (!Thread.currentThread().isInterrupted() && currentCacheState != NoCache.ENTRY_CLOSED) { final String currentVersion = currentVersionOrNull(currentCacheState); tryUpdateCache(currentVersion); } } catch (Throwable t) { try { close(); } catch (Exception e) { t.addSuppressed(e); } if (Thread.currentThread().isInterrupted() || t instanceof InterruptedException || t instanceof Error) { throw Throwables.propagate(t); } } } private void tryUpdateCache(String currentVersion) throws Exception { boolean updatedCacheSuccessfully = false; VersionedCache newVersionedCache = null; try { newVersionedCache = cacheGenerator.generateCache(namespace, this, currentVersion, CacheScheduler.this ); if (newVersionedCache != null) { CacheState previousCacheState = swapCacheState(newVersionedCache); if (previousCacheState != NoCache.ENTRY_CLOSED) { updatedCacheSuccessfully = true; if (previousCacheState instanceof VersionedCache) { ((VersionedCache) previousCacheState).close(); } log.debug("%s: the cache was successfully updated", this); } else { newVersionedCache.close(); log.debug("%s was closed while the cache was being updated, discarding the update", this); } } else { log.debug("%s: Version `%s` not updated, the cache is not updated", this, currentVersion); } } catch (Throwable t) { try { if (newVersionedCache != null && !updatedCacheSuccessfully) { newVersionedCache.close(); } log.error(t, "Failed to update %s", this); } catch (Exception e) { t.addSuppressed(e); } if (Thread.currentThread().isInterrupted() || t instanceof InterruptedException || t instanceof Error) { // propagate to the catch block in updateCache() throw t; } } } private String currentVersionOrNull(CacheState currentCacheState) { if (currentCacheState instanceof VersionedCache) { return ((VersionedCache) currentCacheState).version; } else { return null; } } private CacheState swapCacheState(VersionedCache newVersionedCache) { CacheState lastCacheState; // CAS loop do { lastCacheState = cacheStateHolder.get(); if (lastCacheState == NoCache.ENTRY_CLOSED) { return lastCacheState; } } while (!cacheStateHolder.compareAndSet(lastCacheState, newVersionedCache)); updateCounter.update(); return lastCacheState; } @Override public void close() { if (!doClose(true)) { log.error("Cache for %s has already been closed", this); } // This Cleaner.clean() call effectively just removes the Cleaner from the internal linked list of all cleaners. // It will delegate to closeFromCleaner() which will be a no-op because cacheStateHolder is already set to // ENTRY_CLOSED. entryCleaner.clean(); } private void closeFromCleaner() { try { if (doClose(false)) { log.error("Entry.close() was not called, closed resources by the JVM"); } } catch (Throwable t) { try { log.error(t, "Error while closing %s", this); } catch (Exception e) { t.addSuppressed(e); } Throwables.propagateIfInstanceOf(t, Error.class); // Must not throw exceptions in the cleaner thread, run by the JVM. } } /** * @param calledManually true if called manually from {@link #close()}, false if called by the JVM via Cleaner * @return true if successfully closed, false if has already closed before */ private boolean doClose(boolean calledManually) { CacheState lastCacheState = cacheStateHolder.getAndSet(NoCache.ENTRY_CLOSED); if (lastCacheState != NoCache.ENTRY_CLOSED) { try { log.info("Closing %s", this); logExecutionError(); } // Logging (above) is not the main goal of the closing process, so try to cancel the updaterFuture even if // logging failed for whatever reason. finally { activeEntries.decrementAndGet(); updaterFuture.cancel(true); // If calledManually = false, i. e. called by the JVM via Cleaner.clean(), let the JVM close cache itself // via it's own Cleaner as well, when the cache becomes unreachable. Because when somebody forgets to call // entry.close(), it may be harmful to forcibly close the cache, which could still be used, at some // non-deterministic point of time. Cleaners are introduced to mitigate possible errors, not to escalate them. if (calledManually && lastCacheState instanceof VersionedCache) { ((VersionedCache) lastCacheState).cacheHandler.close(); } } return true; } else { return false; } } private void logExecutionError() { if (updaterFuture.isDone()) { try { updaterFuture.get(); } catch (ExecutionException ee) { log.error(ee.getCause(), "Error in %s", this); } catch (CancellationException ce) { log.error(ce, "Future for %s has already been cancelled", this); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } } } @Override public String toString() { return asString; } } public interface CacheState {} public enum NoCache implements CacheState { CACHE_NOT_INITIALIZED, ENTRY_CLOSED } public final class VersionedCache implements CacheState, AutoCloseable { final String entryId; final CacheHandler cacheHandler; final String version; private VersionedCache(String entryId, String version) { this.entryId = entryId; this.cacheHandler = cacheManager.createCache(); this.version = version; } public Map<String, String> getCache() { return cacheHandler.getCache(); } public String getVersion() { return version; } @Override public void close() { cacheHandler.close(); // Log statement after cacheHandler.close(), because logging may fail (e. g. in shutdown hooks) log.debug("Closed version [%s] of %s", version, entryId); } } private final Map<Class<? extends ExtractionNamespace>, CacheGenerator<?>> namespaceGeneratorMap; private final NamespaceExtractionCacheManager cacheManager; private final AtomicLong updatesStarted = new AtomicLong(0); private final AtomicInteger activeEntries = new AtomicInteger(); @Inject public CacheScheduler( final ServiceEmitter serviceEmitter, final Map<Class<? extends ExtractionNamespace>, CacheGenerator<?>> namespaceGeneratorMap, NamespaceExtractionCacheManager cacheManager ) { this.namespaceGeneratorMap = namespaceGeneratorMap; this.cacheManager = cacheManager; cacheManager.scheduledExecutorService().scheduleAtFixedRate( new Runnable() { long priorUpdatesStarted = 0L; @Override public void run() { try { final long tasks = updatesStarted.get(); serviceEmitter.emit( ServiceMetricEvent.builder() .build("namespace/deltaTasksStarted", tasks - priorUpdatesStarted) ); priorUpdatesStarted = tasks; } catch (Exception e) { log.error(e, "Error emitting namespace stats"); if (Thread.currentThread().isInterrupted()) { throw Throwables.propagate(e); } } } }, 1, 10, TimeUnit.MINUTES ); } /** * This method should be used from {@link CacheGenerator#generateCache} implementations, to obtain a {@link * VersionedCache} to be returned. * * @param entryId an object uniquely corresponding to the {@link CacheScheduler.Entry}, for which VersionedCache is * created * @param version version, associated with the cache */ public VersionedCache createVersionedCache(@Nullable EntryImpl<? extends ExtractionNamespace> entryId, String version) { updatesStarted.incrementAndGet(); return new VersionedCache(String.valueOf(entryId), version); } @VisibleForTesting long updatesStarted() { return updatesStarted.get(); } @VisibleForTesting public long getActiveEntries() { return activeEntries.get(); } @Nullable public Entry scheduleAndWait(ExtractionNamespace namespace, long waitForFirstRunMs) throws InterruptedException { final Entry entry = schedule(namespace); log.debug("Scheduled new %s", entry); boolean success = false; try { success = entry.impl.updateCounter.awaitFirstUpdate(waitForFirstRunMs, TimeUnit.MILLISECONDS); if (success) { return entry; } else { return null; } } finally { if (!success) { // ExecutionException's cause is logged in entry.close() entry.close(); log.error("CacheScheduler[%s] - problem during start or waiting for the first run", entry); } } } public <T extends ExtractionNamespace> Entry schedule(final T namespace) { final CacheGenerator<T> generator = (CacheGenerator<T>) namespaceGeneratorMap.get(namespace.getClass()); if (generator == null) { throw new ISE("Cannot find generator for namespace [%s]", namespace); } return new Entry<>(namespace, generator); } }
33.413255
128
0.658713
1c437fdf995b3268077e7ede4b9d5d9f36a0ceb9
3,982
package com.skunkworks.fastorm.processor.tool; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeKind; import javax.tools.Diagnostic; import java.math.BigDecimal; import java.util.List; import java.util.Map; /** * stole on 19.02.17. */ public enum Tools { ; public static String getRecordsetType(Element element, Messager messager) { if (Long.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.LONG) { return Long.class.getSimpleName(); } else if (Integer.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.INT) { return "Int"; } else if (Boolean.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.BOOLEAN) { return Boolean.class.getSimpleName(); } else if (String.class.getCanonicalName().equals(element.asType().toString())) { return String.class.getSimpleName(); } else if (Float.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.FLOAT) { return Float.class.getSimpleName(); } else if (Double.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.DOUBLE) { return Double.class.getSimpleName(); } else if (Short.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.SHORT) { return Short.class.getSimpleName(); } else if (Byte.class.getCanonicalName().equals(element.asType().toString()) || element.asType().getKind() == TypeKind.BYTE) { return Byte.class.getSimpleName(); } else if (BigDecimal.class.getCanonicalName().equals(element.asType().toString())) { return BigDecimal.class.getSimpleName(); } error(messager, "Unrecognized type:" + element.asType()); return null; } public static boolean isFromSamePackage(Element leftElement, Element rightElement) { return rightElement.getEnclosingElement().getKind() == ElementKind.PACKAGE && leftElement.getEnclosingElement().getKind() == ElementKind.PACKAGE && !rightElement.getEnclosingElement().toString().equals(leftElement.getEnclosingElement().toString()); } public static AnnotationValue getAnnotationData(AnnotationMirror annotationMirror, String itemName) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (itemName.equals(entry.getKey().getSimpleName().toString())) { return entry.getValue(); } } return null; } public static AnnotationMirror findAnnotation(List<? extends AnnotationMirror> annotationMirrors, Class<?> annotationClass) { return annotationMirrors.stream(). filter(annotationMirror -> annotationClass.getName().equals(annotationMirror.getAnnotationType().toString())). findFirst().orElse(null); } public static void warn(Messager messager, String message) { messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, message); } public static void error(Messager messager, String message) { messager.printMessage(Diagnostic.Kind.ERROR, message); } public static String capitalizeFirstLetter(String item) { return item.substring(0, 1).toUpperCase() + item.substring(1); } public static String lowercaseFirstLetter(String item) { return item.substring(0, 1).toLowerCase() + item.substring(1); } }
47.975904
140
0.68659
f9be9fb85d01245407735fa490b2e0dd754d382d
1,257
package org.jeecf.manager.module.template.model.po; import org.jeecf.common.model.Request; import org.jeecf.manager.common.model.AbstractEntityPO; import org.jeecf.manager.module.template.model.query.GenTableColumnQuery; import org.jeecf.manager.module.template.model.schema.GenTableColumnSchema; /** * 业务表字段 PO实体 * * @author jianyiming * */ public class GenTableColumnPO extends AbstractEntityPO<GenTableColumnQuery> { public GenTableColumnPO(GenTableColumnQuery data) { this(data, new GenTableColumnSchema()); } public GenTableColumnPO(GenTableColumnQuery data, GenTableColumnSchema schema) { super(data); this.setSchema(schema); } public GenTableColumnPO(Request<GenTableColumnQuery, GenTableColumnSchema> request) { super(request); if (request.getSchema() == null) { this.setSchema(new GenTableColumnSchema()); } } @Override public String getTableName() { return "genTableColumn"; } @Override public void buildSorts() { super.buildSorts(this.getTableName()); } @Override public void buildContains() { super.buildContains(this.getTableName()); } }
26.1875
90
0.670644
56abc621bde1c4f6d53ea5a950f35be0facc920a
1,600
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cn.vlabs.rest.examples; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import cn.vlabs.rest.ServiceClient; import cn.vlabs.rest.ServiceContext; import cn.vlabs.rest.ServiceException; import cn.vlabs.rest.stream.StreamInfo; public class UploadStub { public UploadStub(ServiceContext context){ this.context=context; } public String upload(String message, String file) throws ServiceException, IOException{ ServiceClient client = new ServiceClient(context); StreamInfo stream = new StreamInfo(); File f = new File(file); stream.setFilename(f.getName()); stream.setInputStream(new FileInputStream(f)); stream.setLength(f.length()); String result =(String)client.sendService("System.upload", message, stream); stream.getInputStream().close(); return result; } private ServiceContext context; }
34.042553
99
0.745
82b2eaf91efdc482f38a870df874af53f08a2d9c
277
package core.interfaces; import utilities.VectorObservation; public interface IVectorObservation { /** * Encode the game state into a vector (fixed length during game). * @return - a vector observation. */ VectorObservation getVectorObservation(); }
19.785714
70
0.711191
9f993bc9422de5b9d44cb2d6856f1efc47d9dc78
6,415
package com.ucar.datalink.worker.core.runtime; import com.ucar.datalink.common.errors.DatalinkException; import com.ucar.datalink.domain.plugin.PluginWriterParameter; import com.ucar.datalink.domain.task.TaskInfo; import com.ucar.datalink.worker.api.task.TaskWriter; import com.ucar.datalink.worker.api.util.statistic.BaseWriterStatistic; import com.ucar.datalink.worker.api.util.statistic.WriterStatistic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.MessageFormat; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.locks.LockSupport; /** * 负责TaskWriter的生命周期管理. * <p> * Created by lubiao on 2017/2/14. */ public class WorkerTaskWriter extends WorkerTask { private static final Logger logger = LoggerFactory.getLogger(WorkerTaskWriter.class); private TaskWriter taskWriter; private final ArrayBlockingQueue<TaskChunk> queue; private final WorkerTaskWriterContext workerTaskWriterContext; private final PluginWriterParameter taskWriterParameter; private int errorTimes = 0; public WorkerTaskWriter(WorkerConfig workerConfig, TaskInfo taskInfo, TaskStatusListener statusListener, ArrayBlockingQueue<TaskChunk> queue, WorkerTaskWriterContext workerTaskWriterContext) { super(workerConfig, taskInfo, statusListener, workerTaskWriterContext.taskExecutionId()); this.queue = queue; this.workerTaskWriterContext = workerTaskWriterContext; this.taskWriterParameter = workerTaskWriterContext.getWriterParameter(); boolean autoAddColumnGlobal = workerConfig.getBoolean(WorkerConfig.SYNC_AUTO_ADD_COLUMN_CONFIG); boolean autoAddColumnTask = taskWriterParameter.isSyncAutoAddColumn(); this.taskWriterParameter.setSyncAutoAddColumn(autoAddColumnGlobal && autoAddColumnTask);//通过全局开关设置是否缺字段时自动加字段 } @SuppressWarnings({"unchecked"}) @Override public void initialize(TaskInfo taskInfo) { this.taskWriter = buildTaskWriter(); this.taskWriter.initialize(workerTaskWriterContext); } @Override @SuppressWarnings({"unchecked"}) void execute() { synchronized (this) { if (isStopping()) { return; } taskWriter.start(); logger.info("TaskWriter-{} finished initialization and start.", taskWriterParameter.getPluginName()); } while (!isStopping()) { try { if (shouldPause()) { awaitUnpause(); continue; } TaskChunk taskChunk = queue.take(); try { taskWriter.prePush(); BaseWriterStatistic statistic = workerTaskWriterContext.taskWriterSession().getData(WriterStatistic.KEY); long startTime = System.currentTimeMillis(); taskWriter.push(taskChunk.getRecordChunk()); statistic.setTimeForTotalPush(System.currentTimeMillis() - startTime); taskWriter.postPush(); taskChunk.getCallback().onCompletion(null, null); errorTimes = 0; } catch (Exception e) {//目前是对所有异常统一处理,后续视需要可以对异常进一步分类,把某些严重异常直接抛出,不用重试 logger.error(String.format("RecordChunk execute error in Writer [%s] ", taskWriterParameter.getPluginName()), e); errorTimes++; if (taskWriterParameter.getRetryMode() == PluginWriterParameter.RetryMode.Always) { taskChunk.getCallback().onCompletion(e, null); } else if (taskWriterParameter.getRetryMode() == PluginWriterParameter.RetryMode.TimesOutDiscard) { if (errorTimes == taskWriterParameter.getMaxRetryTimes()) { logger.error("RecordChunk has been discard due to retry times out.");//TODO,把废弃数据记录到日志或数据库 taskChunk.getCallback().onCompletion(null, null); errorTimes = 0; } else { taskChunk.getCallback().onCompletion(e, null); } } else if (taskWriterParameter.getRetryMode() == PluginWriterParameter.RetryMode.TimesOutError) { if (errorTimes == taskWriterParameter.getMaxRetryTimes()) { logger.error(MessageFormat.format("Plugin Writer {0} failed due to retry times out.", taskWriterParameter.getPluginName()), e); throw e; } else { taskChunk.getCallback().onCompletion(e, null); } } else if (taskWriterParameter.getRetryMode() == PluginWriterParameter.RetryMode.NoAndError) { throw e; } else { throw e; } long unit = 1000 * 1000L * 1000L;//1s long parkTime = errorTimes * unit > 30 * unit ? 30 * unit : errorTimes * unit;//最多暂停30s LockSupport.parkNanos(parkTime);//出现错误,暂停1s } } catch (InterruptedException e) { //do nothing } } logger.info("TaskWriter-{} has stopped executing.", taskWriterParameter.getPluginName()); } @Override public void stop() { //执行stop的线程和execute方法的线程是不同的,存在并发问题,需要加锁控制 synchronized (this) { super.stop(); if (taskWriter.isStart()) { taskWriter.stop(); } } } @Override void close() { Thread.interrupted();//如果有中断状态取消中断状态,保证后续操作正常进行 taskWriter.close(); } @SuppressWarnings({"unchecked"}) private TaskWriter buildTaskWriter() { String className = taskWriterParameter.getPluginClass(); try { //必须使用Thread.currentThread().getContextClassLoader().loadClass(className)获取class对象,这样使用的才是插件的classloader //不能用class.forname()方法,该方式使用的是调用类的classloader return TaskFactory.newTaskWriter((Class<TaskWriter>) Thread.currentThread().getContextClassLoader().loadClass(className)); } catch (ClassNotFoundException e) { throw new DatalinkException("The Task Reader Class can not found.", e); } } }
42.766667
155
0.617771
6360e055bcaad343c65dfbe2010cbf851717e3ef
634
package com.dongkap.feign.dto.master; import com.dongkap.feign.dto.common.BaseAuditDto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) @ToString public class LocaleDto extends BaseAuditDto { /** * */ private static final long serialVersionUID = -8125190677227153892L; private String localeCode; private String identifier; private String subIdentifier; private String icon; private boolean localeDefault; private boolean localeEnabled; }
21.862069
68
0.812303
ef285f41eb7402a6fd192a6cd027dc7255ea95b5
1,145
package cn.arvix.ontheway.business.controller; import cn.arvix.base.common.entity.JSONResult; import cn.arvix.base.common.web.controller.ExceptionHandlerController; import cn.arvix.ontheway.business.service.BusinessTypeService; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @author Created by yangyang on 2017/8/15. * e-mail :[email protected] ; tel :18580128658 ;QQ :296604153 */ @Controller @RequestMapping(value = "/app/business/type") public class AppBusinessTypeController extends ExceptionHandlerController { private BusinessTypeService service; @Autowired public void setService(BusinessTypeService service) { this.service = service; } @ResponseBody @ApiOperation(value = "获取所有的类型") @GetMapping(value = "/all") public JSONResult all() { return service.all(); } }
31.805556
76
0.771179
5501c9d719a1391dbc1b7dcae6b8b4e093b8d86d
814
package com.example.demo.common.i18n; /** * @author humbinal */ public interface CommonError { /** * @message 成功 */ public static final String SUCCESS = "0"; /** * @message 接口不存在 */ public static final String NOT_FOUND = "0x00001"; /** * @message 方法不被允许 */ public static final String METHOD_NOT_ALLOW = "0x00002"; /** * @message 服务器内部错误 */ public static final String INTERNAL_SERVER_ERROR = "0x00003"; /** * @message 参数不合法 */ public static final String INVALID_PARAMS = "0x00004"; /** * @message 页码不能小于{value} */ public static final String VALIDATION_PAGE_NO_MIN = "0x00101"; /** * @message 每页数量不能小于{value} */ public static final String VALIDATION_PAGE_SIZE_MIN = "0x00102"; }
18.5
68
0.597052
7a13cf12b621ca0eb9010b9ca8dbaa151021e61c
2,996
package org.elasticsearch.kafka.indexer.mappers; public class AccessLogMapper { private KafkaMetaDataMapper kafkaMetaData = new KafkaMetaDataMapper(); private String ip; private String protocol; private String method; private String url; private String payLoad; private String sessionID; private String timeStamp; private Integer responseTime; private Integer responseCode; private String hostName; private String serverName; private String serverAndInstance; private String instance; private String sourceIpAndPort; private String ajpThreadName; private String rawMessage; public KafkaMetaDataMapper getKafkaMetaData() { return kafkaMetaData; } public void setKafkaMetaData(KafkaMetaDataMapper kafkaMetaData) { this.kafkaMetaData = kafkaMetaData; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPayLoad() { return payLoad; } public void setPayLoad(String payLoad) { this.payLoad = payLoad; } public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public Integer getResponseTime() { return responseTime; } public void setResponseTime(Integer responseTime) { this.responseTime = responseTime; } public Integer getResponseCode() { return responseCode; } public void setResponseCode(Integer responseCode) { this.responseCode = responseCode; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public String getInstance() { return instance; } public void setInstance(String instance) { this.instance = instance; } public String getSourceIpAndPort() { return sourceIpAndPort; } public void setSourceIpAndPort(String sourceIpAndPort) { this.sourceIpAndPort = sourceIpAndPort; } public String getServerAndInstance() { return serverAndInstance; } public void setServerAndInstance(String serverAndInstance) { this.serverAndInstance = serverAndInstance; } public String getRawMessage() { return rawMessage; } public void setRawMessage(String rawMessage) { this.rawMessage = rawMessage; } public String getAjpThreadName() { return ajpThreadName; } public void setAjpThreadName(String ajpThreadName) { this.ajpThreadName = ajpThreadName; } }
18.493827
71
0.746996
342b227c8189d09702ecfa73052a57afd905fe6a
1,832
/** * Copyright (C) 2008-2010 Matt Gumbley, DevZendo.org <http://devzendo.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.devzendo.minimiser.gui.messagequeueviewer; import java.awt.Frame; import org.devzendo.minimiser.messagequeue.MessageQueue; /** * MessageQueueViewerFactory objects create, and receive notification of * closure of, their MessageQueueViewer. * * @author matt * */ public interface MessageQueueViewerFactory { /** * Create and show the MessageQueueViewer. * @return the MessageQueueViewer. */ MessageQueueViewer createMessageQueueViewer(); /** * Called by the MessageQueueViewer when it is closed by the user, so that * notification of this can be passed around (e.g. to the status bar, so * that it can enable the message queue indicator (if any messages remian)) */ void messageViewerClosed(); /** * Called by the MessageQueueViewer when it is creating its dialog, so that * the dialog can be made a child of the main application frame. * * @return the application main frame */ Frame getMainFrame(); /** * Called by the MessageQueueViewer so it can interact with the MessageQueue * @return the MessageQueue */ MessageQueue getMessageQueue(); }
31.050847
80
0.70524
470b9c92c0280a1b6b518d75e316572eb726a197
565
package Day17; public class Address { int RoomNo; String State; String City; int PinCode; Address(int RoomNo, String State, String City, int PinCode){ this.RoomNo = RoomNo; this.State = State; this.City = City; this.PinCode = PinCode; } @Override public String toString() { return "Address: " + "RoomNo=" + RoomNo + ", State='" + State + '\'' + ", City='" + City + '\'' + ", PinCode=" + PinCode + '}'; } }
21.730769
64
0.463717
381edf5f9193ce9bfa2afae087b73171d5155b38
2,193
package com.mh.ta.core.config.settings; /** * @author minhhoang * */ public class DriverConfig { private String driversFolderName = "drivers"; private String borderColor = "red"; private String backGroundColor = "yellow"; private int implicitWait = 30; private int pageloadTimeout = 60; private int drivercommandTimeout = 60; private int timeOutHighlight = 500; private boolean hidden = false; private boolean maximize = false; private boolean highLighElement = true; public String getDriversFolderName() { return driversFolderName; } public void setDriversFolderName(String driversFolderName) { this.driversFolderName = driversFolderName; } public int getImplicitWait() { return implicitWait; } public void setImplicitWait(int implicitWait) { this.implicitWait = implicitWait; } public int getPageloadTimeout() { return pageloadTimeout; } public void setPageloadTimeout(int pageloadTimeout) { this.pageloadTimeout = pageloadTimeout; } public int getDrivercommandTimeout() { return drivercommandTimeout; } public void setDrivercommandTimeout(int drivercommandTimeout) { this.drivercommandTimeout = drivercommandTimeout; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } public boolean isMaximize() { return maximize; } public void setMaximize(boolean maximize) { this.maximize = maximize; } public boolean isHighLighElement() { return highLighElement; } public void setHighLighElement(boolean highLighElement) { this.highLighElement = highLighElement; } public int getTimeOutHighlight() { return timeOutHighlight; } public void setTimeOutHighlight(int timeOutHighlight) { this.timeOutHighlight = timeOutHighlight; } public String getBorderColor() { return borderColor; } public void setBorderColor(String borderColor) { this.borderColor = borderColor; } public String getBackGroundColor() { return backGroundColor; } public void setBackGroundColor(String backGroundColor) { this.backGroundColor = backGroundColor; } }
21.93
65
0.726858
7b6930f344692c8abd9b6d340e3258abdef3e197
2,650
package net.sf.l2j.gameserver.model.multisell; import java.util.ArrayList; import java.util.LinkedList; import net.sf.l2j.gameserver.model.actor.Npc; import net.sf.l2j.gameserver.model.actor.Player; import net.sf.l2j.gameserver.model.item.instance.ItemInstance; import net.sf.l2j.gameserver.model.item.kind.Armor; import net.sf.l2j.gameserver.model.item.kind.Weapon; /** * A dynamic layer of {@link ListContainer}, which holds the current {@link Npc} objectId for security reasons.<br> * <br> * It can also allow to check inventory content. */ public class PreparedListContainer extends ListContainer { private int _npcObjectId = 0; public PreparedListContainer(ListContainer template, boolean inventoryOnly, Player player, Npc npc) { super(template.getId()); setMaintainEnchantment(template.getMaintainEnchantment()); setApplyTaxes(false); _npcsAllowed = template._npcsAllowed; double taxRate = 0; if (npc != null) { _npcObjectId = npc.getObjectId(); if (template.getApplyTaxes() && npc.getCastle() != null && npc.getCastle().getOwnerId() > 0) { setApplyTaxes(true); taxRate = npc.getCastle().getTaxRate(); } } if (inventoryOnly) { if (player == null) return; final ItemInstance[] items; if (getMaintainEnchantment()) items = player.getInventory().getUniqueItemsByEnchantLevel(false, false, false); else items = player.getInventory().getUniqueItems(false, false, false); _entries = new LinkedList<>(); for (ItemInstance item : items) { // only do the match up on equippable items that are not currently equipped // so for each appropriate item, produce a set of entries for the multisell list. if (!item.isEquipped() && (item.getItem() instanceof Armor || item.getItem() instanceof Weapon)) { // loop through the entries to see which ones we wish to include for (Entry ent : template.getEntries()) { // check ingredients of this entry to see if it's an entry we'd like to include. for (Ingredient ing : ent.getIngredients()) { if (item.getItemId() == ing.getItemId()) { _entries.add(new PreparedEntry(ent, item, getApplyTaxes(), getMaintainEnchantment(), taxRate)); break; // next entry } } } } } } else { _entries = new ArrayList<>(template.getEntries().size()); for (Entry ent : template.getEntries()) _entries.add(new PreparedEntry(ent, null, getApplyTaxes(), false, taxRate)); } } public final boolean checkNpcObjectId(int npcObjectId) { return (_npcObjectId != 0) ? _npcObjectId == npcObjectId : true; } }
30.113636
115
0.686792
42727951a480d4dfa45e41b47f878a64824691dd
37,626
package com.home.commonGame.tool.generate; import com.home.commonGame.constlist.generate.GameRequestType; import com.home.commonGame.net.request.activity.ActivityCompleteOnceRequest; import com.home.commonGame.net.request.activity.ActivityResetRequest; import com.home.commonGame.net.request.activity.ActivitySwitchRequest; import com.home.commonGame.net.request.func.auction.FuncAuctionAddSaleItemRequest; import com.home.commonGame.net.request.func.auction.FuncAuctionReQueryRequest; import com.home.commonGame.net.request.func.auction.FuncAuctionRefreshSaleItemRequest; import com.home.commonGame.net.request.func.auction.FuncAuctionRemoveSaleItemRequest; import com.home.commonGame.net.request.func.auction.FuncReGetAuctionItemSuggestPriceRequest; import com.home.commonGame.net.request.func.base.FuncCloseRequest; import com.home.commonGame.net.request.func.base.FuncOpenRequest; import com.home.commonGame.net.request.func.base.FuncPlayerRoleGroupSRequest; import com.home.commonGame.net.request.func.base.FuncSRequest; import com.home.commonGame.net.request.func.item.FuncAddItemRequest; import com.home.commonGame.net.request.func.item.FuncAddOneItemNumRequest; import com.home.commonGame.net.request.func.item.FuncAddOneItemRequest; import com.home.commonGame.net.request.func.item.FuncRefreshItemGridNumRequest; import com.home.commonGame.net.request.func.item.FuncRemoveItemRequest; import com.home.commonGame.net.request.func.item.FuncRemoveOneItemRequest; import com.home.commonGame.net.request.func.item.FuncSendCleanUpItemRequest; import com.home.commonGame.net.request.func.item.FuncSendMoveEquipRequest; import com.home.commonGame.net.request.func.item.FuncSendMoveItemRequest; import com.home.commonGame.net.request.func.item.FuncSendPutOffEquipRequest; import com.home.commonGame.net.request.func.item.FuncSendPutOnEquipRequest; import com.home.commonGame.net.request.func.item.FuncUseItemResultRequest; import com.home.commonGame.net.request.func.match.FuncCancelMatchRequest; import com.home.commonGame.net.request.func.match.FuncMatchOverRequest; import com.home.commonGame.net.request.func.match.FuncMatchSuccessRequest; import com.home.commonGame.net.request.func.match.FuncMatchTimeOutRequest; import com.home.commonGame.net.request.func.match.FuncReAddMatchRequest; import com.home.commonGame.net.request.func.match.FuncSendAcceptMatchRequest; import com.home.commonGame.net.request.func.match.FuncStartMatchRequest; import com.home.commonGame.net.request.func.rank.FuncReGetPageShowListRequest; import com.home.commonGame.net.request.func.rank.FuncReGetPageShowRequest; import com.home.commonGame.net.request.func.rank.FuncReGetSelfPageShowRequest; import com.home.commonGame.net.request.func.rank.FuncRefreshRankRequest; import com.home.commonGame.net.request.func.rank.FuncRefreshRoleGroupRankRequest; import com.home.commonGame.net.request.func.rank.FuncResetRankRequest; import com.home.commonGame.net.request.func.rank.FuncResetRoleGroupRankRequest; import com.home.commonGame.net.request.func.rank.subsection.FuncReGetSubsectionPageShowListRequest; import com.home.commonGame.net.request.func.rank.subsection.FuncRefreshSubsectionIndexRequest; import com.home.commonGame.net.request.func.rank.subsection.FuncRefreshSubsectionRankRequest; import com.home.commonGame.net.request.func.roleGroup.FuncReGetRoleGroupDataRequest; import com.home.commonGame.net.request.func.roleGroup.FuncRefeshTitleRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendAddApplyRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendAddApplyRoleGroupSelfRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendChangeCanInviteInAbsRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendChangeLeaderRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendHandleApplyResultRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendHandleApplyResultToMemberRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendHandleInviteResultRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendInviteRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendPlayerJoinRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendPlayerLeaveRoleGroupRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupAddMemberRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupChangeRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupInfoLogRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupMemberChangeRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupMemberRoleShowChangeRequest; import com.home.commonGame.net.request.func.roleGroup.FuncSendRoleGroupRemoveMemberRequest; import com.home.commonGame.net.request.guide.RefreshMainGuideStepRequest; import com.home.commonGame.net.request.item.AddRewardRequest; import com.home.commonGame.net.request.login.ClientHotfixRequest; import com.home.commonGame.net.request.login.CreatePlayerSuccessRequest; import com.home.commonGame.net.request.login.DeletePlayerSuccessRequest; import com.home.commonGame.net.request.login.InitClientRequest; import com.home.commonGame.net.request.login.RePlayerListRequest; import com.home.commonGame.net.request.login.SendBindPlatformRequest; import com.home.commonGame.net.request.login.SwitchGameRequest; import com.home.commonGame.net.request.login.SwitchSceneRequest; import com.home.commonGame.net.request.mail.AddMailRequest; import com.home.commonGame.net.request.mail.ReGetAllMailRequest; import com.home.commonGame.net.request.mail.SendDeleteMailRequest; import com.home.commonGame.net.request.mail.TakeMailSuccessRequest; import com.home.commonGame.net.request.quest.RefreshTaskRequest; import com.home.commonGame.net.request.quest.SendAcceptAchievementRequest; import com.home.commonGame.net.request.quest.SendAcceptQuestRequest; import com.home.commonGame.net.request.quest.SendAchievementCompleteRequest; import com.home.commonGame.net.request.quest.SendClearAllQuestByGMRequest; import com.home.commonGame.net.request.quest.SendCommitQuestRequest; import com.home.commonGame.net.request.quest.SendGetAchievementRewardSuccessRequest; import com.home.commonGame.net.request.quest.SendGiveUpQuestRequest; import com.home.commonGame.net.request.quest.SendQuestFailedRequest; import com.home.commonGame.net.request.quest.SendRemoveAcceptQuestRequest; import com.home.commonGame.net.request.role.ChangeRoleNameRequest; import com.home.commonGame.net.request.role.LevelUpRequest; import com.home.commonGame.net.request.role.RefreshCurrencyRequest; import com.home.commonGame.net.request.role.RefreshExpRequest; import com.home.commonGame.net.request.role.RefreshFightForceRequest; import com.home.commonGame.net.request.role.munit.MUnitAddBuffRequest; import com.home.commonGame.net.request.role.munit.MUnitAddGroupTimeMaxPercentRequest; import com.home.commonGame.net.request.role.munit.MUnitAddGroupTimeMaxValueRequest; import com.home.commonGame.net.request.role.munit.MUnitAddGroupTimePassRequest; import com.home.commonGame.net.request.role.munit.MUnitAddSkillRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshAttributesRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshAvatarPartRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshAvatarRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshBuffLastNumRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshBuffRequest; import com.home.commonGame.net.request.role.munit.MUnitRefreshStatusRequest; import com.home.commonGame.net.request.role.munit.MUnitRemoveBuffRequest; import com.home.commonGame.net.request.role.munit.MUnitRemoveGroupCDRequest; import com.home.commonGame.net.request.role.munit.MUnitRemoveSkillRequest; import com.home.commonGame.net.request.role.munit.MUnitSRequest; import com.home.commonGame.net.request.role.munit.MUnitStartCDsRequest; import com.home.commonGame.net.request.role.pet.AddPetRequest; import com.home.commonGame.net.request.role.pet.RefreshPetIsWorkingRequest; import com.home.commonGame.net.request.role.pet.RemovePetRequest; import com.home.commonGame.net.request.scene.EnterNoneSceneRequest; import com.home.commonGame.net.request.scene.EnterSceneFailedRequest; import com.home.commonGame.net.request.scene.EnterSceneRequest; import com.home.commonGame.net.request.scene.LeaveSceneRequest; import com.home.commonGame.net.request.scene.PreEnterSceneNextRequest; import com.home.commonGame.net.request.scene.PreEnterSceneRequest; import com.home.commonGame.net.request.scene.RefreshCurrentLineRequest; import com.home.commonGame.net.request.social.ReQueryPlayerRequest; import com.home.commonGame.net.request.social.ReSearchPlayerRequest; import com.home.commonGame.net.request.social.ReUpdateRoleSocialDataOneRequest; import com.home.commonGame.net.request.social.ReUpdateRoleSocialDataRequest; import com.home.commonGame.net.request.social.chat.SendPlayerChatRequest; import com.home.commonGame.net.request.social.friend.SendAddFriendBlackListRequest; import com.home.commonGame.net.request.social.friend.SendAddFriendRequest; import com.home.commonGame.net.request.social.friend.SendApplyAddFriendRequest; import com.home.commonGame.net.request.social.friend.SendRemoveFriendBlackListRequest; import com.home.commonGame.net.request.social.friend.SendRemoveFriendRequest; import com.home.commonGame.net.request.system.CenterTransGameToClientRequest; import com.home.commonGame.net.request.system.ClientHotfixConfigRequest; import com.home.commonGame.net.request.system.DailyRequest; import com.home.commonGame.net.request.system.GameTransGameToClientRequest; import com.home.commonGame.net.request.system.ReceiveClientOfflineWorkRequest; import com.home.commonGame.net.request.system.RefreshServerTimeRequest; import com.home.commonGame.net.request.system.SendGameReceiptToClientRequest; import com.home.commonGame.net.request.system.SendInfoCodeRequest; import com.home.commonGame.net.request.system.SendInfoCodeWithArgsRequest; import com.home.commonGame.net.request.system.SendInfoLogRequest; import com.home.commonGame.net.request.system.SendWarningLogRequest; import com.home.shine.data.BaseData; import com.home.shine.tool.CreateDataFunc; import com.home.shine.tool.DataMaker; /** (generated by shine) */ public class GameRequestMaker extends DataMaker { public GameRequestMaker() { offSet=GameRequestType.off; list=new CreateDataFunc[GameRequestType.count-offSet]; list[GameRequestType.ActivityCompleteOnce-offSet]=this::createActivityCompleteOnceRequest; list[GameRequestType.ActivityReset-offSet]=this::createActivityResetRequest; list[GameRequestType.ActivitySwitch-offSet]=this::createActivitySwitchRequest; list[GameRequestType.AddMail-offSet]=this::createAddMailRequest; list[GameRequestType.AddPet-offSet]=this::createAddPetRequest; list[GameRequestType.AddReward-offSet]=this::createAddRewardRequest; list[GameRequestType.CenterTransGameToClient-offSet]=this::createCenterTransGameToClientRequest; list[GameRequestType.ChangeRoleName-offSet]=this::createChangeRoleNameRequest; list[GameRequestType.ClientHotfixConfig-offSet]=this::createClientHotfixConfigRequest; list[GameRequestType.ClientHotfix-offSet]=this::createClientHotfixRequest; list[GameRequestType.CreatePlayerSuccess-offSet]=this::createCreatePlayerSuccessRequest; list[GameRequestType.Daily-offSet]=this::createDailyRequest; list[GameRequestType.DeletePlayerSuccess-offSet]=this::createDeletePlayerSuccessRequest; list[GameRequestType.EnterNoneScene-offSet]=this::createEnterNoneSceneRequest; list[GameRequestType.EnterSceneFailed-offSet]=this::createEnterSceneFailedRequest; list[GameRequestType.EnterScene-offSet]=this::createEnterSceneRequest; list[GameRequestType.FuncAddItem-offSet]=this::createFuncAddItemRequest; list[GameRequestType.FuncAddOneItem-offSet]=this::createFuncAddOneItemRequest; list[GameRequestType.FuncAddOneItemNum-offSet]=this::createFuncAddOneItemNumRequest; list[GameRequestType.FuncAuctionAddSaleItem-offSet]=this::createFuncAuctionAddSaleItemRequest; list[GameRequestType.FuncAuctionReQuery-offSet]=this::createFuncAuctionReQueryRequest; list[GameRequestType.FuncAuctionRefreshSaleItem-offSet]=this::createFuncAuctionRefreshSaleItemRequest; list[GameRequestType.FuncAuctionRemoveSaleItem-offSet]=this::createFuncAuctionRemoveSaleItemRequest; list[GameRequestType.FuncCancelMatch-offSet]=this::createFuncCancelMatchRequest; list[GameRequestType.FuncClose-offSet]=this::createFuncCloseRequest; list[GameRequestType.FuncMatchOver-offSet]=this::createFuncMatchOverRequest; list[GameRequestType.FuncMatchSuccess-offSet]=this::createFuncMatchSuccessRequest; list[GameRequestType.FuncMatchTimeOut-offSet]=this::createFuncMatchTimeOutRequest; list[GameRequestType.FuncOpen-offSet]=this::createFuncOpenRequest; list[GameRequestType.FuncPlayerRoleGroupS-offSet]=this::createFuncPlayerRoleGroupSRequest; list[GameRequestType.FuncReAddMatch-offSet]=this::createFuncReAddMatchRequest; list[GameRequestType.FuncReGetAuctionItemSuggestPrice-offSet]=this::createFuncReGetAuctionItemSuggestPriceRequest; list[GameRequestType.FuncReGetPageShowList-offSet]=this::createFuncReGetPageShowListRequest; list[GameRequestType.FuncReGetPageShow-offSet]=this::createFuncReGetPageShowRequest; list[GameRequestType.FuncReGetRoleGroupData-offSet]=this::createFuncReGetRoleGroupDataRequest; list[GameRequestType.FuncReGetSelfPageShow-offSet]=this::createFuncReGetSelfPageShowRequest; list[GameRequestType.FuncReGetSubsectionPageShowList-offSet]=this::createFuncReGetSubsectionPageShowListRequest; list[GameRequestType.FuncRefeshTitleRoleGroup-offSet]=this::createFuncRefeshTitleRoleGroupRequest; list[GameRequestType.FuncRefreshItemGridNum-offSet]=this::createFuncRefreshItemGridNumRequest; list[GameRequestType.FuncRefreshRank-offSet]=this::createFuncRefreshRankRequest; list[GameRequestType.FuncRefreshRoleGroupRank-offSet]=this::createFuncRefreshRoleGroupRankRequest; list[GameRequestType.FuncRefreshSubsectionRank-offSet]=this::createFuncRefreshSubsectionRankRequest; list[GameRequestType.FuncRemoveItem-offSet]=this::createFuncRemoveItemRequest; list[GameRequestType.FuncRemoveOneItem-offSet]=this::createFuncRemoveOneItemRequest; list[GameRequestType.FuncResetRank-offSet]=this::createFuncResetRankRequest; list[GameRequestType.FuncResetRoleGroupRank-offSet]=this::createFuncResetRoleGroupRankRequest; list[GameRequestType.FuncS-offSet]=this::createFuncSRequest; list[GameRequestType.FuncSendAcceptMatch-offSet]=this::createFuncSendAcceptMatchRequest; list[GameRequestType.FuncSendAddApplyRoleGroup-offSet]=this::createFuncSendAddApplyRoleGroupRequest; list[GameRequestType.FuncSendAddApplyRoleGroupSelf-offSet]=this::createFuncSendAddApplyRoleGroupSelfRequest; list[GameRequestType.FuncSendChangeCanInviteInAbsRoleGroup-offSet]=this::createFuncSendChangeCanInviteInAbsRoleGroupRequest; list[GameRequestType.FuncSendChangeLeaderRoleGroup-offSet]=this::createFuncSendChangeLeaderRoleGroupRequest; list[GameRequestType.FuncSendCleanUpItem-offSet]=this::createFuncSendCleanUpItemRequest; list[GameRequestType.FuncSendHandleApplyResultRoleGroup-offSet]=this::createFuncSendHandleApplyResultRoleGroupRequest; list[GameRequestType.FuncSendHandleApplyResultToMember-offSet]=this::createFuncSendHandleApplyResultToMemberRequest; list[GameRequestType.FuncSendHandleInviteResultRoleGroup-offSet]=this::createFuncSendHandleInviteResultRoleGroupRequest; list[GameRequestType.FuncSendInviteRoleGroup-offSet]=this::createFuncSendInviteRoleGroupRequest; list[GameRequestType.FuncSendMoveEquip-offSet]=this::createFuncSendMoveEquipRequest; list[GameRequestType.FuncSendMoveItem-offSet]=this::createFuncSendMoveItemRequest; list[GameRequestType.FuncSendPlayerJoinRoleGroup-offSet]=this::createFuncSendPlayerJoinRoleGroupRequest; list[GameRequestType.FuncSendPlayerLeaveRoleGroup-offSet]=this::createFuncSendPlayerLeaveRoleGroupRequest; list[GameRequestType.FuncSendPutOffEquip-offSet]=this::createFuncSendPutOffEquipRequest; list[GameRequestType.FuncSendPutOnEquip-offSet]=this::createFuncSendPutOnEquipRequest; list[GameRequestType.FuncSendRoleGroupAddMember-offSet]=this::createFuncSendRoleGroupAddMemberRequest; list[GameRequestType.FuncSendRoleGroupChange-offSet]=this::createFuncSendRoleGroupChangeRequest; list[GameRequestType.FuncSendRoleGroupInfoLog-offSet]=this::createFuncSendRoleGroupInfoLogRequest; list[GameRequestType.FuncSendRoleGroupMemberChange-offSet]=this::createFuncSendRoleGroupMemberChangeRequest; list[GameRequestType.FuncSendRoleGroupMemberRoleShowChange-offSet]=this::createFuncSendRoleGroupMemberRoleShowChangeRequest; list[GameRequestType.FuncSendRoleGroupRemoveMember-offSet]=this::createFuncSendRoleGroupRemoveMemberRequest; list[GameRequestType.FuncStartMatch-offSet]=this::createFuncStartMatchRequest; list[GameRequestType.FuncUseItemResult-offSet]=this::createFuncUseItemResultRequest; list[GameRequestType.GameTransGameToClient-offSet]=this::createGameTransGameToClientRequest; list[GameRequestType.InitClient-offSet]=this::createInitClientRequest; list[GameRequestType.LeaveScene-offSet]=this::createLeaveSceneRequest; list[GameRequestType.LevelUp-offSet]=this::createLevelUpRequest; list[GameRequestType.MUnitAddBuff-offSet]=this::createMUnitAddBuffRequest; list[GameRequestType.MUnitAddGroupTimeMaxPercent-offSet]=this::createMUnitAddGroupTimeMaxPercentRequest; list[GameRequestType.MUnitAddGroupTimeMaxValue-offSet]=this::createMUnitAddGroupTimeMaxValueRequest; list[GameRequestType.MUnitAddGroupTimePass-offSet]=this::createMUnitAddGroupTimePassRequest; list[GameRequestType.MUnitAddSkill-offSet]=this::createMUnitAddSkillRequest; list[GameRequestType.MUnitRefreshAttributes-offSet]=this::createMUnitRefreshAttributesRequest; list[GameRequestType.MUnitRefreshAvatar-offSet]=this::createMUnitRefreshAvatarRequest; list[GameRequestType.MUnitRefreshAvatarPart-offSet]=this::createMUnitRefreshAvatarPartRequest; list[GameRequestType.MUnitRefreshBuffLastNum-offSet]=this::createMUnitRefreshBuffLastNumRequest; list[GameRequestType.MUnitRefreshBuff-offSet]=this::createMUnitRefreshBuffRequest; list[GameRequestType.MUnitRefreshStatus-offSet]=this::createMUnitRefreshStatusRequest; list[GameRequestType.MUnitRemoveBuff-offSet]=this::createMUnitRemoveBuffRequest; list[GameRequestType.MUnitRemoveGroupCD-offSet]=this::createMUnitRemoveGroupCDRequest; list[GameRequestType.MUnitRemoveSkill-offSet]=this::createMUnitRemoveSkillRequest; list[GameRequestType.MUnitS-offSet]=this::createMUnitSRequest; list[GameRequestType.MUnitStartCDs-offSet]=this::createMUnitStartCDsRequest; list[GameRequestType.PreEnterScene-offSet]=this::createPreEnterSceneRequest; list[GameRequestType.PreEnterSceneNext-offSet]=this::createPreEnterSceneNextRequest; list[GameRequestType.ReGetAllMail-offSet]=this::createReGetAllMailRequest; list[GameRequestType.RePlayerList-offSet]=this::createRePlayerListRequest; list[GameRequestType.ReQueryPlayer-offSet]=this::createReQueryPlayerRequest; list[GameRequestType.ReSearchPlayer-offSet]=this::createReSearchPlayerRequest; list[GameRequestType.ReUpdateRoleSocialData-offSet]=this::createReUpdateRoleSocialDataRequest; list[GameRequestType.ReUpdateRoleSocialDataOne-offSet]=this::createReUpdateRoleSocialDataOneRequest; list[GameRequestType.ReceiveClientOfflineWork-offSet]=this::createReceiveClientOfflineWorkRequest; list[GameRequestType.RefreshCurrency-offSet]=this::createRefreshCurrencyRequest; list[GameRequestType.RefreshCurrentLine-offSet]=this::createRefreshCurrentLineRequest; list[GameRequestType.RefreshExp-offSet]=this::createRefreshExpRequest; list[GameRequestType.RefreshFightForce-offSet]=this::createRefreshFightForceRequest; list[GameRequestType.RefreshMainGuideStep-offSet]=this::createRefreshMainGuideStepRequest; list[GameRequestType.RefreshPetIsWorking-offSet]=this::createRefreshPetIsWorkingRequest; list[GameRequestType.RefreshServerTime-offSet]=this::createRefreshServerTimeRequest; list[GameRequestType.RefreshTask-offSet]=this::createRefreshTaskRequest; list[GameRequestType.RemovePet-offSet]=this::createRemovePetRequest; list[GameRequestType.SendAcceptAchievement-offSet]=this::createSendAcceptAchievementRequest; list[GameRequestType.SendAcceptQuest-offSet]=this::createSendAcceptQuestRequest; list[GameRequestType.SendAchievementComplete-offSet]=this::createSendAchievementCompleteRequest; list[GameRequestType.SendAddFriendBlackList-offSet]=this::createSendAddFriendBlackListRequest; list[GameRequestType.SendAddFriend-offSet]=this::createSendAddFriendRequest; list[GameRequestType.SendApplyAddFriend-offSet]=this::createSendApplyAddFriendRequest; list[GameRequestType.SendBindPlatform-offSet]=this::createSendBindPlatformRequest; list[GameRequestType.SendClearAllQuestByGM-offSet]=this::createSendClearAllQuestByGMRequest; list[GameRequestType.SendCommitQuest-offSet]=this::createSendCommitQuestRequest; list[GameRequestType.SendDeleteMail-offSet]=this::createSendDeleteMailRequest; list[GameRequestType.SendGameReceiptToClient-offSet]=this::createSendGameReceiptToClientRequest; list[GameRequestType.SendGetAchievementRewardSuccess-offSet]=this::createSendGetAchievementRewardSuccessRequest; list[GameRequestType.SendGiveUpQuest-offSet]=this::createSendGiveUpQuestRequest; list[GameRequestType.SendInfoCode-offSet]=this::createSendInfoCodeRequest; list[GameRequestType.SendInfoCodeWithArgs-offSet]=this::createSendInfoCodeWithArgsRequest; list[GameRequestType.SendInfoLog-offSet]=this::createSendInfoLogRequest; list[GameRequestType.SendPlayerChat-offSet]=this::createSendPlayerChatRequest; list[GameRequestType.SendQuestFailed-offSet]=this::createSendQuestFailedRequest; list[GameRequestType.SendRemoveAcceptQuest-offSet]=this::createSendRemoveAcceptQuestRequest; list[GameRequestType.SendRemoveFriendBlackList-offSet]=this::createSendRemoveFriendBlackListRequest; list[GameRequestType.SendRemoveFriend-offSet]=this::createSendRemoveFriendRequest; list[GameRequestType.SendWarningLog-offSet]=this::createSendWarningLogRequest; list[GameRequestType.SwitchGame-offSet]=this::createSwitchGameRequest; list[GameRequestType.SwitchScene-offSet]=this::createSwitchSceneRequest; list[GameRequestType.TakeMailSuccess-offSet]=this::createTakeMailSuccessRequest; list[GameRequestType.FuncRefreshSubsectionIndex-offSet]=this::createFuncRefreshSubsectionIndexRequest; } private BaseData createActivityCompleteOnceRequest() { return new ActivityCompleteOnceRequest(); } private BaseData createActivityResetRequest() { return new ActivityResetRequest(); } private BaseData createActivitySwitchRequest() { return new ActivitySwitchRequest(); } private BaseData createAddMailRequest() { return new AddMailRequest(); } private BaseData createAddRewardRequest() { return new AddRewardRequest(); } private BaseData createCenterTransGameToClientRequest() { return new CenterTransGameToClientRequest(); } private BaseData createChangeRoleNameRequest() { return new ChangeRoleNameRequest(); } private BaseData createClientHotfixRequest() { return new ClientHotfixRequest(); } private BaseData createCreatePlayerSuccessRequest() { return new CreatePlayerSuccessRequest(); } private BaseData createDailyRequest() { return new DailyRequest(); } private BaseData createDeletePlayerSuccessRequest() { return new DeletePlayerSuccessRequest(); } private BaseData createEnterNoneSceneRequest() { return new EnterNoneSceneRequest(); } private BaseData createEnterSceneFailedRequest() { return new EnterSceneFailedRequest(); } private BaseData createEnterSceneRequest() { return new EnterSceneRequest(); } private BaseData createFuncAuctionRefreshSaleItemRequest() { return new FuncAuctionRefreshSaleItemRequest(); } private BaseData createFuncAddItemRequest() { return new FuncAddItemRequest(); } private BaseData createFuncAddOneItemRequest() { return new FuncAddOneItemRequest(); } private BaseData createFuncAddOneItemNumRequest() { return new FuncAddOneItemNumRequest(); } private BaseData createFuncCancelMatchRequest() { return new FuncCancelMatchRequest(); } private BaseData createFuncMatchOverRequest() { return new FuncMatchOverRequest(); } private BaseData createFuncMatchSuccessRequest() { return new FuncMatchSuccessRequest(); } private BaseData createFuncMatchTimeOutRequest() { return new FuncMatchTimeOutRequest(); } private BaseData createFuncReAddMatchRequest() { return new FuncReAddMatchRequest(); } private BaseData createFuncReGetPageShowRequest() { return new FuncReGetPageShowRequest(); } private BaseData createFuncReGetSelfPageShowRequest() { return new FuncReGetSelfPageShowRequest(); } private BaseData createFuncRefreshRankRequest() { return new FuncRefreshRankRequest(); } private BaseData createFuncRemoveItemRequest() { return new FuncRemoveItemRequest(); } private BaseData createFuncRemoveOneItemRequest() { return new FuncRemoveOneItemRequest(); } private BaseData createFuncResetRankRequest() { return new FuncResetRankRequest(); } private BaseData createFuncSRequest() { return new FuncSRequest(); } private BaseData createFuncSendAcceptMatchRequest() { return new FuncSendAcceptMatchRequest(); } private BaseData createFuncSendCleanUpItemRequest() { return new FuncSendCleanUpItemRequest(); } private BaseData createFuncSendMoveEquipRequest() { return new FuncSendMoveEquipRequest(); } private BaseData createFuncSendPutOffEquipRequest() { return new FuncSendPutOffEquipRequest(); } private BaseData createFuncSendPutOnEquipRequest() { return new FuncSendPutOnEquipRequest(); } private BaseData createFuncStartMatchRequest() { return new FuncStartMatchRequest(); } private BaseData createFuncUseItemResultRequest() { return new FuncUseItemResultRequest(); } private BaseData createInitClientRequest() { return new InitClientRequest(); } private BaseData createLeaveSceneRequest() { return new LeaveSceneRequest(); } private BaseData createLevelUpRequest() { return new LevelUpRequest(); } private BaseData createMUnitAddBuffRequest() { return new MUnitAddBuffRequest(); } private BaseData createMUnitAddGroupTimeMaxPercentRequest() { return new MUnitAddGroupTimeMaxPercentRequest(); } private BaseData createMUnitAddGroupTimeMaxValueRequest() { return new MUnitAddGroupTimeMaxValueRequest(); } private BaseData createMUnitAddGroupTimePassRequest() { return new MUnitAddGroupTimePassRequest(); } private BaseData createMUnitAddSkillRequest() { return new MUnitAddSkillRequest(); } private BaseData createMUnitRefreshAttributesRequest() { return new MUnitRefreshAttributesRequest(); } private BaseData createMUnitRefreshAvatarRequest() { return new MUnitRefreshAvatarRequest(); } private BaseData createMUnitRefreshAvatarPartRequest() { return new MUnitRefreshAvatarPartRequest(); } private BaseData createMUnitRefreshBuffLastNumRequest() { return new MUnitRefreshBuffLastNumRequest(); } private BaseData createMUnitRefreshBuffRequest() { return new MUnitRefreshBuffRequest(); } private BaseData createMUnitRefreshStatusRequest() { return new MUnitRefreshStatusRequest(); } private BaseData createMUnitRemoveBuffRequest() { return new MUnitRemoveBuffRequest(); } private BaseData createMUnitRemoveGroupCDRequest() { return new MUnitRemoveGroupCDRequest(); } private BaseData createMUnitRemoveSkillRequest() { return new MUnitRemoveSkillRequest(); } private BaseData createMUnitStartCDsRequest() { return new MUnitStartCDsRequest(); } private BaseData createPreEnterSceneRequest() { return new PreEnterSceneRequest(); } private BaseData createPreEnterSceneNextRequest() { return new PreEnterSceneNextRequest(); } private BaseData createReGetAllMailRequest() { return new ReGetAllMailRequest(); } private BaseData createRePlayerListRequest() { return new RePlayerListRequest(); } private BaseData createReQueryPlayerRequest() { return new ReQueryPlayerRequest(); } private BaseData createReSearchPlayerRequest() { return new ReSearchPlayerRequest(); } private BaseData createReUpdateRoleSocialDataRequest() { return new ReUpdateRoleSocialDataRequest(); } private BaseData createReUpdateRoleSocialDataOneRequest() { return new ReUpdateRoleSocialDataOneRequest(); } private BaseData createReceiveClientOfflineWorkRequest() { return new ReceiveClientOfflineWorkRequest(); } private BaseData createRefreshCurrencyRequest() { return new RefreshCurrencyRequest(); } private BaseData createRefreshCurrentLineRequest() { return new RefreshCurrentLineRequest(); } private BaseData createRefreshExpRequest() { return new RefreshExpRequest(); } private BaseData createRefreshFightForceRequest() { return new RefreshFightForceRequest(); } private BaseData createRefreshMainGuideStepRequest() { return new RefreshMainGuideStepRequest(); } private BaseData createRefreshServerTimeRequest() { return new RefreshServerTimeRequest(); } private BaseData createRefreshTaskRequest() { return new RefreshTaskRequest(); } private BaseData createSendAcceptAchievementRequest() { return new SendAcceptAchievementRequest(); } private BaseData createSendAcceptQuestRequest() { return new SendAcceptQuestRequest(); } private BaseData createSendAchievementCompleteRequest() { return new SendAchievementCompleteRequest(); } private BaseData createSendAddFriendBlackListRequest() { return new SendAddFriendBlackListRequest(); } private BaseData createSendAddFriendRequest() { return new SendAddFriendRequest(); } private BaseData createSendApplyAddFriendRequest() { return new SendApplyAddFriendRequest(); } private BaseData createSendBindPlatformRequest() { return new SendBindPlatformRequest(); } private BaseData createSendClearAllQuestByGMRequest() { return new SendClearAllQuestByGMRequest(); } private BaseData createSendCommitQuestRequest() { return new SendCommitQuestRequest(); } private BaseData createSendDeleteMailRequest() { return new SendDeleteMailRequest(); } private BaseData createSendGameReceiptToClientRequest() { return new SendGameReceiptToClientRequest(); } private BaseData createSendGetAchievementRewardSuccessRequest() { return new SendGetAchievementRewardSuccessRequest(); } private BaseData createSendGiveUpQuestRequest() { return new SendGiveUpQuestRequest(); } private BaseData createSendInfoCodeRequest() { return new SendInfoCodeRequest(); } private BaseData createSendInfoCodeWithArgsRequest() { return new SendInfoCodeWithArgsRequest(); } private BaseData createSendQuestFailedRequest() { return new SendQuestFailedRequest(); } private BaseData createSendRemoveAcceptQuestRequest() { return new SendRemoveAcceptQuestRequest(); } private BaseData createSendRemoveFriendBlackListRequest() { return new SendRemoveFriendBlackListRequest(); } private BaseData createSendRemoveFriendRequest() { return new SendRemoveFriendRequest(); } private BaseData createSwitchGameRequest() { return new SwitchGameRequest(); } private BaseData createTakeMailSuccessRequest() { return new TakeMailSuccessRequest(); } private BaseData createFuncSendPlayerJoinRoleGroupRequest() { return new FuncSendPlayerJoinRoleGroupRequest(); } private BaseData createFuncSendPlayerLeaveRoleGroupRequest() { return new FuncSendPlayerLeaveRoleGroupRequest(); } private BaseData createFuncSendRoleGroupAddMemberRequest() { return new FuncSendRoleGroupAddMemberRequest(); } private BaseData createFuncSendRoleGroupRemoveMemberRequest() { return new FuncSendRoleGroupRemoveMemberRequest(); } private BaseData createFuncPlayerRoleGroupSRequest() { return new FuncPlayerRoleGroupSRequest(); } private BaseData createFuncSendAddApplyRoleGroupRequest() { return new FuncSendAddApplyRoleGroupRequest(); } private BaseData createFuncSendHandleApplyResultRoleGroupRequest() { return new FuncSendHandleApplyResultRoleGroupRequest(); } private BaseData createFuncSendHandleInviteResultRoleGroupRequest() { return new FuncSendHandleInviteResultRoleGroupRequest(); } private BaseData createFuncSendInviteRoleGroupRequest() { return new FuncSendInviteRoleGroupRequest(); } private BaseData createFuncReGetPageShowListRequest() { return new FuncReGetPageShowListRequest(); } private BaseData createFuncRefeshTitleRoleGroupRequest() { return new FuncRefeshTitleRoleGroupRequest(); } private BaseData createFuncSendChangeLeaderRoleGroupRequest() { return new FuncSendChangeLeaderRoleGroupRequest(); } private BaseData createFuncRefreshSubsectionRankRequest() { return new FuncRefreshSubsectionRankRequest(); } private BaseData createGameTransGameToClientRequest() { return new GameTransGameToClientRequest(); } private BaseData createFuncSendHandleApplyResultToMemberRequest() { return new FuncSendHandleApplyResultToMemberRequest(); } private BaseData createFuncSendAddApplyRoleGroupSelfRequest() { return new FuncSendAddApplyRoleGroupSelfRequest(); } private BaseData createFuncSendRoleGroupChangeRequest() { return new FuncSendRoleGroupChangeRequest(); } private BaseData createSendInfoLogRequest() { return new SendInfoLogRequest(); } private BaseData createFuncReGetSubsectionPageShowListRequest() { return new FuncReGetSubsectionPageShowListRequest(); } private BaseData createFuncSendChangeCanInviteInAbsRoleGroupRequest() { return new FuncSendChangeCanInviteInAbsRoleGroupRequest(); } private BaseData createClientHotfixConfigRequest() { return new ClientHotfixConfigRequest(); } private BaseData createFuncSendRoleGroupInfoLogRequest() { return new FuncSendRoleGroupInfoLogRequest(); } private BaseData createFuncSendRoleGroupMemberChangeRequest() { return new FuncSendRoleGroupMemberChangeRequest(); } private BaseData createFuncReGetRoleGroupDataRequest() { return new FuncReGetRoleGroupDataRequest(); } private BaseData createSendPlayerChatRequest() { return new SendPlayerChatRequest(); } private BaseData createAddPetRequest() { return new AddPetRequest(); } private BaseData createFuncSendRoleGroupMemberRoleShowChangeRequest() { return new FuncSendRoleGroupMemberRoleShowChangeRequest(); } private BaseData createFuncSendMoveItemRequest() { return new FuncSendMoveItemRequest(); } private BaseData createFuncRefreshItemGridNumRequest() { return new FuncRefreshItemGridNumRequest(); } private BaseData createFuncRefreshRoleGroupRankRequest() { return new FuncRefreshRoleGroupRankRequest(); } private BaseData createFuncResetRoleGroupRankRequest() { return new FuncResetRoleGroupRankRequest(); } private BaseData createSendWarningLogRequest() { return new SendWarningLogRequest(); } private BaseData createFuncCloseRequest() { return new FuncCloseRequest(); } private BaseData createFuncOpenRequest() { return new FuncOpenRequest(); } private BaseData createFuncAuctionAddSaleItemRequest() { return new FuncAuctionAddSaleItemRequest(); } private BaseData createFuncAuctionReQueryRequest() { return new FuncAuctionReQueryRequest(); } private BaseData createMUnitSRequest() { return new MUnitSRequest(); } private BaseData createRefreshPetIsWorkingRequest() { return new RefreshPetIsWorkingRequest(); } private BaseData createFuncReGetAuctionItemSuggestPriceRequest() { return new FuncReGetAuctionItemSuggestPriceRequest(); } private BaseData createRemovePetRequest() { return new RemovePetRequest(); } private BaseData createFuncAuctionRemoveSaleItemRequest() { return new FuncAuctionRemoveSaleItemRequest(); } private BaseData createSwitchSceneRequest() { return new SwitchSceneRequest(); } private BaseData createFuncRefreshSubsectionIndexRequest() { return new FuncRefreshSubsectionIndexRequest(); } }
39.112266
127
0.819221
0e0cc659fb5d591e30abaa7ffe0b36bd7506447d
1,062
/* * ©2018 HBT Hamburger Berater Team GmbH * All Rights Reserved. */ package de.hbt.dmn_eval_java.impl; import jdk.nashorn.api.scripting.ScriptObjectMirror; /** * Java interface to wrap functions from the Javascript dmn-eval-js library. */ public interface DmnEvalJsWrapper { /** * Evaluates the decision with the given decision id. The DMN definition of the decision (and its required decision) * must be given, as well as the decision input. * @param decisionId the id of the decision that shall be evaluated * @param parsedDecision the DMN definition of the decision * @param decisionInput the input as a {@link WrappedInputObject} * @return the decision result */ Object evaluateDecision(String decisionId, ScriptObjectMirror parsedDecision, Object decisionInput); /** * Parses the DMN definition of a decision from a string with the DMN XML content. * @param dmnXml the DMN XML content * @return the parsed DMN definition */ ScriptObjectMirror parseDmnXml(String dmnXml); }
33.1875
120
0.722222
fc39a6456e425bd8df0807e2a97d53e3f50c8f4a
206
package com.mypocket; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class MyPocketApplicationTests { @Test void contextLoads() { } }
14.714286
60
0.786408
39555e3f2f897aa2dae970e37dd4fc93191c09e9
2,158
package io.github.izdwuut.yarl.controllers; import java.util.ArrayList; import java.util.List; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import squidpony.squidgrid.gui.gdx.SquidInput; /** * A generic controller. Provides a default {@link #update() update} method * fired after every frame is {@link io.github.izdwuut.yarl.YARL#render() rendered}. * It also specifies common fields used by every controller: {@link #engine engine} * (passed either by {@link io.github.izdwuut.yarl.YARL YARL} or any controller) and * {@link #input input}. * * @author Bartosz "izdwuut" Konikiewicz * @since 2017-11-28 */ public abstract class Controller { /** * An input handler. */ protected SquidInput input; /** * An Ashley engine. */ protected Engine engine; /** * A game class. */ protected Game game; /** * Every entity system related to a controller. */ protected List<EntitySystem> systems; /** * Constructs a controller using an {@link com.badlogic.ashley.core.Engine Engine} * passed either by {@link io.github.izdwuut.yarl.YARL YARL} or any controller. * * @param engine an Ashley engine * @param game a main {@link com.badlogic.gdx.Game Game} class */ public Controller(Engine engine, Game game) { this.engine = engine; this.game = game; systems = new ArrayList<EntitySystem>(); } /** * Fired after a frame is {@link io.github.izdwuut.yarl.YARL#render() rendered}. Reacts to user input * and tells the {@link #engine engine} to update entities accordingly. */ public void update() { if(input.hasNext()) { input.next(); engine.update(Gdx.graphics.getDeltaTime()); } } /** * Declares systems related to this controller. */ protected abstract void declareSystems(); /** * Pauses systems. */ protected void pause() { for(EntitySystem sys : systems) { sys.setProcessing(false); } } /** * Resumes systems. */ protected void resume() { for(EntitySystem sys : systems) { sys.setProcessing(true); } } }
23.456522
103
0.677016
ac76557bfe39cef6ff36f1673a7e8d0eb85dc86a
2,355
package com.bdoemu.gameserver.model.creature.player.itemPack.events; import com.bdoemu.commons.model.enums.EStringTable; import com.bdoemu.core.network.sendable.SMRepurchaseItems; import com.bdoemu.gameserver.model.creature.npc.Npc; import com.bdoemu.gameserver.model.creature.player.Player; import com.bdoemu.gameserver.model.items.Item; import com.bdoemu.gameserver.model.items.enums.EItemStorageLocation; import com.bdoemu.gameserver.model.misc.enums.EPacketTaskType; import java.util.Collections; public class RepurchaseItemInShopEvent extends AItemEvent { private long count; private int itemId; private int enchantLevel; private int endurance; private Npc npc; private Item repurchaseItem; private EItemStorageLocation srcStorageLocation; public RepurchaseItemInShopEvent(final Player player, final EItemStorageLocation srcStorageLocation, final int itemId, final int enchantLevel, final int endurance, final long count, final Npc npc) { super(player, player, player, EStringTable.eErrNoItemRepurchaseFromShop, EStringTable.eErrNoItemRepurchaseFromShop, npc.getRegionId()); this.itemId = itemId; this.enchantLevel = enchantLevel; this.endurance = endurance; this.count = count; this.npc = npc; this.srcStorageLocation = srcStorageLocation; } @Override public void onEvent() { super.onEvent(); this.playerBag.getRepurchaseList().remove(this.repurchaseItem); this.player.sendPacket(new SMRepurchaseItems(Collections.singletonList(this.repurchaseItem), EPacketTaskType.Remove, this.npc.getGameObjectId())); } @Override public boolean canAct() { for (final Item rItem : this.playerBag.getRepurchaseList()) { if (rItem.getItemId() == this.itemId && rItem.getEnchantLevel() == this.enchantLevel && rItem.getEndurance() == this.endurance && rItem.getCount() == this.count) { this.repurchaseItem = rItem; break; } } if (this.repurchaseItem == null) { return false; } this.decreaseItem(0, this.repurchaseItem.getItemPrice() * this.repurchaseItem.getCount(), this.srcStorageLocation); this.addItem(new Item(this.repurchaseItem, this.repurchaseItem.getCount())); return super.canAct(); } }
42.818182
202
0.717622
a5c8017b0ef60a6fdb7d6c6d78f1e1a13a79bc42
1,064
class Solution { public String XXX(int num) { String[] roman = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; List<String> ans = new ArrayList<String>(); int index = 12; int yushu = 0; while(num>0){ yushu = num%10; if(yushu==4){ ans.add(roman[index-1]); }else if(yushu==5){ ans.add(roman[index-2]); }else if(yushu==9){ ans.add(roman[index-3]); }else if(yushu>5){ for(int i=yushu-5;i>0;i--){ ans.add(roman[index]); } ans.add(roman[index-2]); }else if(yushu>0){ for(int i=yushu;i>0;i--){ ans.add(roman[index]); } } num = num/10; index = index-4; } StringBuilder sb = new StringBuilder(); for(int i=ans.size()-1;i>=0;i--){ sb.append(ans.get(i)); } return sb.toString(); } }
29.555556
85
0.393797
cdccc79eab5f86dfaf9bee48f735092a87116128
3,209
package com.alorma.github.ui.fragment.commit; import android.os.Bundle; import android.view.LayoutInflater; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.CommitComment; import com.alorma.github.sdk.bean.info.CommitInfo; import com.alorma.github.sdk.services.client.GithubListClient; import com.alorma.github.sdk.services.commit.GetCommitCommentsClient; import com.alorma.github.ui.adapter.commit.CommitCommentAdapter; import com.alorma.github.ui.fragment.base.LoadingListFragment; import com.alorma.gitskarios.core.Pair; import com.mikepenz.octicons_typeface_library.Octicons; import java.util.List; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; public class CommitCommentsFragment extends LoadingListFragment<CommitCommentAdapter> implements Observer<List<CommitComment>> { private static final String INFO = "INFO"; private CommitInfo info; public static CommitCommentsFragment newInstance(CommitInfo info) { CommitCommentsFragment f = new CommitCommentsFragment(); Bundle b = new Bundle(); b.putParcelable(INFO, info); f.setArguments(b); return f; } @Override protected void executeRequest() { super.executeRequest(); if (info != null) { setAction(new GetCommitCommentsClient(info)); } } @Override protected int getLightTheme() { return R.style.AppTheme_Repository; } @Override protected int getDarkTheme() { return R.style.AppTheme_Dark_Repository; } @Override protected void executePaginatedRequest(int page) { super.executePaginatedRequest(page); if (info != null) { setAction(new GetCommitCommentsClient(info, page)); } } private void setAction(GithubListClient<List<CommitComment>> client) { client.observable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(new Func1<Pair<List<CommitComment>, Integer>, List<CommitComment>>() { @Override public List<CommitComment> call(Pair<List<CommitComment>, Integer> listIntegerPair) { setPage(listIntegerPair.second); return listIntegerPair.first; } }) .subscribe(this); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<CommitComment> commitComments) { if (commitComments != null && commitComments.size() > 0) { hideEmpty(); if (getAdapter() != null) { getAdapter().addAll(commitComments); } else { CommitCommentAdapter commentsAdapter = new CommitCommentAdapter(LayoutInflater.from(getActivity()), info.repoInfo); setAdapter(commentsAdapter); } } else if (getAdapter() == null || getAdapter().getItemCount() == 0) { setEmpty(); } } @Override protected void loadArguments() { info = (CommitInfo) getArguments().getParcelable(INFO); } @Override protected Octicons.Icon getNoDataIcon() { return Octicons.Icon.oct_comment_discussion; } @Override protected int getNoDataText() { return R.string.no_commit_comments; } }
28.39823
128
0.714864
e3910326a724a7ebb8233d8bb1b20981c8dc91f9
1,674
package com.cloudbees.groovy.cps; /** * Base class for {@link Block} that can come to the left hand side of an assignment, aka "l-value" * * Subtypes implement {@link #evalLValue(Env, Continuation)} that computes {@link LValue} object, * which provides read/write access. * * @author Kohsuke Kawaguchi */ public abstract class LValueBlock implements Block { /** * Evaluates to the value. Getter. */ public final Next eval(Env e, Continuation k) { return asLValue().eval(e, new GetAdapter(k)); } /** * Passes the {@link LValue#get(Continuation)} to the wrapped continuation */ private static class GetAdapter implements Continuation { private final Continuation k; public GetAdapter(Continuation k) { this.k = k; } public Next receive(Object l) { return ((LValue)l).get(k); } private static final long serialVersionUID = 1L; } /** * Evaluate the block as {@link LValue} and pass it to {@link Continuation} when done. * * <p> * {@link LValue} can then be used to set the value. */ protected abstract Next evalLValue(Env e, Continuation k); /** * Obtains an {@link Block} that's equivalent to this block except it "returns" * an {@link LValue}. */ public final Block asLValue() { return new BlockImpl(); } private class BlockImpl implements Block { public Next eval(Env e, Continuation k) { return evalLValue(e,k); } private static final long serialVersionUID = 1L; } private static final long serialVersionUID = 1L; }
26.571429
99
0.620072
90ad442a439cc4c17253317176190af09ea606e7
3,076
package fr.imie.tp.jsp; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import fr.imie.archi.AbstractFactory; import fr.imie.archi.ConcreteFactory; import fr.imie.archi.DTO.PersonneDTO; import fr.imie.archi.service.IEcoleService; /** * Servlet implementation class UserListServlet */ @WebServlet("/UserListServlet") public class UserListServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UserListServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object userDTOs = request.getSession().getAttribute("userDTOs"); request.setAttribute("users", userDTOs); // C'est le controleur qui fournis les données request.getRequestDispatcher("/WEB-INF/UserList.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TP8 : ajouter un bouton "delete" et realiser la suppression d'un user // Recupere l'id technique passer en parametre (solution basique pour le TP) Integer deleteId = Integer.valueOf(request.getParameter("deleteInput")); // Recherche le user correspondant aux users de la session AbstractFactory factory = new ConcreteFactory(); IEcoleService service = factory.createEcoleService(); PersonneDTO personneToFind = new PersonneDTO(); personneToFind.setId(deleteId); service.deletePersonne(personneToFind); /* List<UserDTO> userDTOs = (List<UserDTO>)request.getSession().getAttribute("userDTOs"); UserDTO userToDelete = null; for (UserDTO userDTO : userDTOs) { if( userDTO.getId() == deleteId ) { userToDelete = userDTO; break; } } */ // Retire de la session le connectedUser si le user à effacer est connecté PersonneDTO/*UserDTO*/ connectedUser = (PersonneDTO/*UserDTO*/)request.getSession().getAttribute("connectedUser"); if ( connectedUser.getId() == personneToFind/*userToDelete*/.getId() ) request.getSession().removeAttribute("connectedUser"); // Suppression du user de la list des users DTO, pas besoin de reinjecter userDTos dans la session car c'est une reference (il n' a pas de clonage) //userDTOs.remove(userToDelete); // Puis reinjection de la list des users pour la page jsp request.setAttribute("users", service.findAllPersonne()/*userDTOs*/); // Forward du resultat à la page UserList request.getRequestDispatcher("/WEB-INF/UserList.jsp").forward(request, response); } }
35.767442
149
0.745449
90f5c5c0b0f284b7c14c6cf249e10078c746dacb
2,291
package data_science.ui.loc.action; import com.lynden.gmapsfx.javascript.object.InfoWindowOptions; import com.lynden.gmapsfx.javascript.object.LatLong; import com.lynden.gmapsfx.javascript.object.MarkerOptions; import data_science.database.query.AllBicycleStallsQuery; import data_science.model.BicycleStall; import data_science.ui.ApplicationScene; import data_science.ui.loc.LocationViewActionBar; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.scene.control.CheckBox; /** * A {@link CheckBox} for a user to toggle whether to show all bicycle stalls. * @author I.A * @author Jasper Wijnhoven */ public final class BicycleStallsCheckBox extends CheckBox { /** * The action bar this checkbox belongs to. */ private final LocationViewActionBar actionBar; /** * Creates a new {@link BicycleStallsCheckBox}. */ public BicycleStallsCheckBox(LocationViewActionBar locationViewActionBar) { super("Show All Bicycle Stalls"); this.actionBar = locationViewActionBar; selectedProperty().addListener(this::stateChange); setIndeterminate(false); } /** * Reacts to a change of state e.g on user input. */ private void stateChange(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { ApplicationScene scene = (ApplicationScene) getScene(); boolean enabled = newValue; if (enabled) { applyMarkers(scene); scene.getListener().refresh(); actionBar.getSafestBicycleStallsBox().setSelected(false); actionBar.getBicycleTheftsFromStallsBox().setSelected(false); actionBar.getLeastSafeBicycleStallsBox().setSelected(false); } else { scene.clearAllMarkers(); } } private void applyMarkers(ApplicationScene scene) { AllBicycleStallsQuery.compute().subscribe((BicycleStall s) -> { Platform.runLater(() -> { // TODO integrate Platform thread with RxJava LatLong coordinates = new LatLong(s.getLatitude(), s.getLongitude()); InfoWindowOptions infoWindowOptions = new InfoWindowOptions(); infoWindowOptions.content("<h2>" + s.getArea() + "</h2>" + "Street Name: " + s.getName() + "<br>" ); scene.presentMarker(new MarkerOptions().position(coordinates).visible(Boolean.TRUE), infoWindowOptions); }); }); scene.clearAllMarkers(); } }
31.383562
110
0.755129
82a1534d40e29b4058e8017695dca91cc72874c2
1,470
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package com.creditease.dbus.service.explain; import com.creditease.dbus.domain.model.DataSource; import com.creditease.dbus.domain.model.DataTable; /** * This is Description * * @author xiancangao * @date 2018/12/28 */ public class OracleExplainFetcher extends SqlExplainFetcher { public OracleExplainFetcher(DataSource ds) { super(ds); } @Override public String buildQuery(DataTable dataTable, String codition) { //String sql = "EXPLAIN PLAN FOR SELECT * FROM " + // dataTable.getSchemaName() + "." + dataTable.getTableName() + // " WHERE " + codition + " AND ROWNUM <=1 "; String sql = "SELECT * FROM " + dataTable.getSchemaName() + "." + dataTable.getTableName() + " WHERE ( " + codition + " ) AND 1 = 2 "; return sql; } }
30
100
0.656463
4fcc0f0651c663ee313beb96daacb0c70383ed81
1,801
package com.liyouzhi.dataprocess.service.impl; import com.liyouzhi.dataprocess.domain.KeyWordPosition; import com.liyouzhi.dataprocess.service.DataWrite; import com.opencsv.CSVWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.*; import java.util.List; @Service("keyPositionWriteToCSV") public class KeyPositionWriteToCSV implements DataWrite<String, List<KeyWordPosition>, String> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void write(String csvName, List<KeyWordPosition> keyWordPositionsList, String charset) { BufferedWriter fileWriter = null; try { OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(csvName), charset); fileWriter = new BufferedWriter(w); CSVWriter csvWriter = new CSVWriter(fileWriter, ','); String[] head = {"序号", "文件名(含路径)", "行号", "行起始位置", "行结束位置", "关键字"}; csvWriter.writeNext(head); for (KeyWordPosition keyWordPosition : keyWordPositionsList) { String[] row = {Long.toString(keyWordPosition.getId()), keyWordPosition.getFile(), Integer.toString(keyWordPosition.getLinenum()), Integer.toString(keyWordPosition.getStart()), Integer.toString(keyWordPosition.getEnd()), keyWordPosition.getKeyWord()}; csvWriter.writeNext(row); } } catch (IOException e) { logger.error(e.toString()); } finally { try { fileWriter.close(); } catch (IOException e) { logger.error(e.toString()); } } } }
37.520833
99
0.62965
44a61a4e2d7637a056dbd522fdf093c99381c7cc
2,701
package com.cjh.tp.manage.controller; import com.cjh.tp.manage.constant.Constants; import com.cjh.tp.manage.service.CacheConfig; import com.cjh.tp.manage.service.notify.entity.ConfigDataChangeEvent; import com.cjh.tp.manage.service.notify.entity.Event; import com.cjh.tp.manage.service.notify.NotifyCenter; import com.cjh.tp.manage.service.notify.listener.Subscriber; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @program: tp * @description: * @author: chenjiehan * @create: 2020-11-27 13:04 **/ @RestController @RequestMapping(Constants.CONFIG_CONTROLLER_PATH) public class TpConfigController { CacheConfig cacheConfig = CacheConfig.getInstance(); /** * 配置中心 进行配置的修改、新增,并推给服务(未区分谁更新) * * @param configName * @param configValueJson * @return */ @PostMapping("/publishConfig") public Boolean publishConfig(String configName, String configValueJson) { cacheConfig.saveConfig(configName, configValueJson); NotifyCenter.publishEvent(new ConfigDataChangeEvent(configName)); return true; } /** * 长轮询 查看配置中心数据 * * @return key, value */ @PostMapping("/longPolling") public Map<String, String> longPollingConfig() throws InterruptedException { final String[] configValueJson = new String[1]; final String[] configName = new String[1]; //注册主题(就是监听),当事件发生的时候,会回调这里 NotifyCenter.registerSubscriber(new Subscriber() { @Override public void onEvent(Event event) { if (event instanceof ConfigDataChangeEvent) { ConfigDataChangeEvent configDataChangeEvent = (ConfigDataChangeEvent) event; configName[0] = configDataChangeEvent.configName; //获取新的数据 configValueJson[0] = cacheConfig.getConfig(configName[0]); } } }); int i = 0; while (configValueJson[0] == null) { System.out.println("自旋中,等待数据"); TimeUnit.SECONDS.sleep(1); if (i >= 30) { break; } i++; } Map<String, String> map = new HashMap<>(); if (configName[0] == null) { map.put("好家伙", "没更新"); return map; } map.put(configName[0], configValueJson[0]); System.out.println("获取数据,key:" + configName[0] + "value:" + configValueJson[0]); return map; } }
32.542169
96
0.63532
10d66c41519e0467a569fa7b5820eb32207944df
1,268
package searchengine.core.repository; import java.sql.SQLException; import java.util.List; import searchengine.core.Page; /** * Represents a repository that contains data about the crawled pages */ public interface IPagesRepository { /** * Sets the repository to read pages from the beginning */ void reset(); /** * Retrieves the next pages that can be sequentially iterated from the repository * * @param pagesChunkSize * Determines the number of pages that should be retrieved * * @throws SQLException */ List<Page> retrieveNextPages(int pagesChunkSize) throws SQLException; /** * Inserts pages into the repository * * @throws SQLException * * @return Value indicating if the operation was performed successfully */ int[] insertPages(List<Page> pages) throws SQLException; /** * Updates pages in the repository * * @throws SQLException * * @return Value indicating if the operation was performed successfully */ int[] updatePages(List<Page> pages) throws SQLException; /** * Deletes pages from the repository * * @throws SQLException * * @return Values indicating if the operations were performed successfully */ int[] deletePages(List<Page> pages) throws SQLException; }
23.481481
82
0.716088
d5c014d52291b171664981b5b6ad789f038bd532
5,781
package fi.laverca.jaxb.wsssecext; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import com.sun.xml.bind.Locatable; import com.sun.xml.bind.annotation.XmlLocation; import org.w3c.dom.Element; import org.xml.sax.Locator; /** * This type represents a username token per Section 4.1 * * <p>Java class for UsernameTokenType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="UsernameTokenType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Username" type="{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}AttributedString"/&gt; * &lt;choice maxOccurs="unbounded" minOccurs="0"&gt; * &lt;element ref="{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Password"/&gt; * &lt;any processContents='lax'/&gt; * &lt;/choice&gt; * &lt;/sequence&gt; * &lt;attribute ref="{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id"/&gt; * &lt;anyAttribute processContents='lax' namespace='##other'/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UsernameTokenType", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", propOrder = { "username", "passwordsAndAnies" }) public class UsernameTokenType implements Locatable { @XmlElement(name = "Username", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", required = true) protected AttributedString username; @XmlElementRef(name = "Password", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", type = Password.class, required = false) @XmlAnyElement protected List<Object> passwordsAndAnies; @XmlAttribute(name = "Id", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); @XmlLocation @XmlTransient protected Locator locator; /** * Gets the value of the username property. * * @return * possible object is * {@link AttributedString } * */ public AttributedString getUsername() { return username; } /** * Sets the value of the username property. * * @param value * allowed object is * {@link AttributedString } * */ public void setUsername(AttributedString value) { this.username = value; } /** * Gets the value of the passwordsAndAnies property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the passwordsAndAnies property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPasswordsAndAnies().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Password } * {@link Element } * * */ public List<Object> getPasswordsAndAnies() { if (passwordsAndAnies == null) { passwordsAndAnies = new ArrayList<Object>(); } return this.passwordsAndAnies; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } public Locator sourceLocation() { return locator; } public void setSourceLocation(Locator newLocator) { locator = newLocator; } }
31.248649
175
0.651098
46b7912cd8dd08f854ecb3e8349a69266c26b67d
3,424
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.security.config; import javax.annotation.Nonnull; import com.helger.commons.annotation.IsSPIImplementation; import com.helger.photon.security.object.accarea.AccountingArea; import com.helger.photon.security.object.accarea.AccountingAreaMicroTypeConverter; import com.helger.photon.security.object.tenant.Tenant; import com.helger.photon.security.object.tenant.TenantMicroTypeConverter; import com.helger.photon.security.role.Role; import com.helger.photon.security.role.RoleMicroTypeConverter; import com.helger.photon.security.token.accesstoken.AccessToken; import com.helger.photon.security.token.accesstoken.AccessTokenMicroTypeConverter; import com.helger.photon.security.token.revocation.RevocationStatus; import com.helger.photon.security.token.revocation.RevocationStatusMicroTypeConverter; import com.helger.photon.security.token.user.UserToken; import com.helger.photon.security.token.user.UserTokenMicroTypeConverter; import com.helger.photon.security.user.User; import com.helger.photon.security.user.UserMicroTypeConverter; import com.helger.photon.security.usergroup.UserGroup; import com.helger.photon.security.usergroup.UserGroupMicroTypeConverter; import com.helger.tenancy.tenant.ITenantResolver; import com.helger.xml.microdom.convert.IMicroTypeConverterRegistrarSPI; import com.helger.xml.microdom.convert.IMicroTypeConverterRegistry; /** * Special micro type converter for this project. * * @author Philip Helger */ @IsSPIImplementation public final class MicroTypeConverterRegistrar_ph_oton_security implements IMicroTypeConverterRegistrarSPI { public void registerMicroTypeConverter (@Nonnull final IMicroTypeConverterRegistry aRegistry) { aRegistry.registerMicroElementTypeConverter (AccessToken.class, new AccessTokenMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (Tenant.class, new TenantMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (RevocationStatus.class, new RevocationStatusMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (Role.class, new RoleMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (User.class, new UserMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (UserGroup.class, new UserGroupMicroTypeConverter ()); aRegistry.registerMicroElementTypeConverter (UserToken.class, new UserTokenMicroTypeConverter ()); } public static void registerSpecialMicroTypeConverter (@Nonnull final IMicroTypeConverterRegistry aRegistry, @Nonnull final ITenantResolver aTenantResolver) { aRegistry.registerMicroElementTypeConverter (AccountingArea.class, new AccountingAreaMicroTypeConverter (aTenantResolver)); } }
51.104478
127
0.812792
c56c174a6f96ec829f550bf32890b295f9b13609
985
package br.com.casadocodigo.model; import br.com.casadocodigo.validator.ExisteId; import br.com.casadocodigo.validator.ValorUnico; import javax.persistence.EntityManager; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class NovoEstadoRequest { @NotBlank @ValorUnico(domainClass = Estado.class, fieldName = "nome") private String nome; @NotNull @ExisteId(domainClass = Pais.class, fieldName = "id") private Long idPais; public NovoEstadoRequest(@NotBlank String nome, @NotNull Long idPais) { super(); this.nome = nome; this.idPais = idPais; } public Estado toEstado(EntityManager entityManager){ return new Estado(nome, entityManager.find(Pais.class, idPais)); } @Override public String toString() { return "NovoEstadoRequest{" + "nome='" + nome + '\'' + ", idPais=" + idPais + '}'; } }
25.921053
75
0.654822
d86e2d28b36ea27e7de4c507227ceb1c92cd9328
1,036
package net.henryco.sqlightning.reflect.table.stb; import java.lang.reflect.Field; /** * Created by HenryCo on 10/05/17. */ public enum StbType { NULL(), REAL(), TEXT(), BLOB(), INTEGER(); public static StbType findType(Field field) { return findType(field.getType()); } public static StbType findType(Object instance) { return findType(instance.getClass()); } public static StbType findType(Class obClass) { //TODO ARRAYS if (obClass == String.class || obClass == char.class || obClass == Character.class) return StbType.TEXT; if (obClass == byte.class || obClass == Byte.class || obClass == long.class || obClass == Long.class || obClass == int.class || obClass == Integer.class || obClass == short.class || obClass == Short.class || obClass == boolean.class || obClass == Boolean.class) return StbType.INTEGER; if (obClass == float.class || obClass == Float.class || obClass == double.class || obClass == Double.class) return StbType.REAL; return StbType.BLOB; } }
24.093023
57
0.664093
ef9d50ea5604ae3e4e41093173efb32aeda20641
3,668
/** * This class is generated by jOOQ */ package lifetime.backend.persistence.jooq.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import lifetime.backend.persistence.jooq.Keys; import lifetime.backend.persistence.jooq.Lifetime; import lifetime.backend.persistence.jooq.tables.records.TaskRecord; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.1" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Task extends TableImpl<TaskRecord> { private static final long serialVersionUID = 2086919192; /** * The reference instance of <code>lifetime.task</code> */ public static final Task TASK = new Task(); /** * The class holding records for this type */ @Override public Class<TaskRecord> getRecordType() { return TaskRecord.class; } /** * The column <code>lifetime.task.id</code>. */ public final TableField<TaskRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>lifetime.task.title</code>. */ public final TableField<TaskRecord, String> TITLE = createField("title", org.jooq.impl.SQLDataType.VARCHAR.length(45).nullable(false), this, ""); /** * The column <code>lifetime.task.summary</code>. */ public final TableField<TaskRecord, String> SUMMARY = createField("summary", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>lifetime.task.project_id</code>. */ public final TableField<TaskRecord, Integer> PROJECT_ID = createField("project_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * Create a <code>lifetime.task</code> table reference */ public Task() { this("task", null); } /** * Create an aliased <code>lifetime.task</code> table reference */ public Task(String alias) { this(alias, TASK); } private Task(String alias, Table<TaskRecord> aliased) { this(alias, aliased, null); } private Task(String alias, Table<TaskRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Lifetime.LIFETIME; } /** * {@inheritDoc} */ @Override public Identity<TaskRecord, Integer> getIdentity() { return Keys.IDENTITY_TASK; } /** * {@inheritDoc} */ @Override public UniqueKey<TaskRecord> getPrimaryKey() { return Keys.KEY_TASK_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<TaskRecord>> getKeys() { return Arrays.<UniqueKey<TaskRecord>>asList(Keys.KEY_TASK_PRIMARY, Keys.KEY_TASK_ID_UNIQUE); } /** * {@inheritDoc} */ @Override public List<ForeignKey<TaskRecord, ?>> getReferences() { return Arrays.<ForeignKey<TaskRecord, ?>>asList(Keys.FK_TASK_PROJECT1); } /** * {@inheritDoc} */ @Override public Task as(String alias) { return new Task(alias, this); } /** * Rename this table */ public Task rename(String name) { return new Task(name, null); } }
24.291391
149
0.632497
1aade594982a9a13b2062d621837d885155ebc0a
1,323
package net.andreinc.jbvext.test; import lombok.Data; import net.andreinc.jbvext.annotations.digits.MaxDigits; import net.andreinc.jbvext.annotations.digits.MinDigits; import org.junit.Assert; import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; public class MinDigitsMaxDigitsTest { private Validator validator = Validation .buildDefaultValidatorFactory() .getValidator(); @Test public void testFields() { MinDigitsMaxDigitsDoubleBean minDigitsMaxDigitsDoubleBean = new MinDigitsMaxDigitsDoubleBean(); Set<ConstraintViolation<MinDigitsMaxDigitsDoubleBean>> violations = validator.validate(minDigitsMaxDigitsDoubleBean); Assert.assertEquals(2, violations.size()); } @Data class MinDigitsMaxDigitsDoubleBean { @MinDigits(value = "10.5") @MaxDigits(value = "11.5") private Double isOk = new Double(11.0); // Passes @MinDigits(value = "9.5") @MaxDigits(value = "9.6") private Double isTooHigh = new Double(10.0); // Do not Pass @MinDigits(value = "9.5") @MaxDigits(value = "9.6") private Double isTooLow = new Double(9.2); // Do not Pass } }
28.148936
103
0.687075
ad0aee45cb6c7bd7bff800dd4f209aefef447da7
1,599
package hhp.tictactoe.simple.smart.startingmatch; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class Trainer { public static Classifier train(URL gameDataURL) throws URISyntaxException { /* * Create a new classifier instance. The context features are Strings and the * context will be classified with a String according to the featureset of the * context. */ Classifier classifier = new Classifier(); /* * The classifier can learn from classifications that are handed over to the * learn methods. Imagine a tokenized text as follows. The tokens are the text's * features. The category of the text will either be positive or negative. */ try (Stream<String> stream = Files.lines(Paths.get(gameDataURL.toURI()))) { stream.filter(line -> line.endsWith("positive")).forEach(line -> { line = line.replaceAll(",positive", ""); String[] s = line.split(","); StringBuilder category = new StringBuilder(); for (int i = 0; i < s.length; i++) { category.append(s[i]); classifier.setScrambledWeight(category.toString(), line); } }); } catch (IOException e) { e.printStackTrace(); } return classifier; } public static void main(String[] args) throws URISyntaxException { URL resource = TicTacToe.class.getResource("/supervised/tic-tac-toe.data.txt"); Classifier classifier = Trainer.train(resource); classifier.printClassification(); } }
34.021277
83
0.693558
3b8e56fbe9ae8e0a3e77e3cebdbe0f59450ac005
78
package org.zstack.sdk; public class DeleteCephPrimaryStoragePoolResult { }
13
49
0.820513
a558d6a5e4cd04bfed783400c4e395ca30a5716d
2,239
package themepark0419; import java.io.IOException; import java.util.ArrayList; public class OutputClass { // 가격 내역 출력 public static void printResult(String ticketSelect_Zone , String sort, int totalPrice, int ticketnum) { System.out.printf("가격은 %d원 입니다.\n", totalPrice); } // 우대 사유 출력 public static String reason(int discountNum) throws IOException { String result = null; if(discountNum == 1) { result = "*우대적용 없음"; return result; } else if(discountNum == 2) { result = "*장애인 우대적용"; return result; } else if(discountNum == 3) { result = "*국가유공자 우대적용"; return result; } else if(discountNum == 4) { result = "*다자녀 우대적용"; return result; } else if (discountNum == 5) { result = "*임산부 우대적용"; return result; } else { result = "잘못 입력하셨습니다."; return result; } } // 내역 출력 public static void printDetail(int ticketType, String sort, int totalPrice, int ticketNum, String result, ArrayList<OrderInfo> orderListArray) { System.out.println("========= polypoly world ========="); String text = ""; for (int i = 0; i < orderListArray.size(); i++) { OrderInfo info = orderListArray.get(i); text = info.gettTicketSelectZone() + ", " + info.getSort() + ", " + info.getTicketNum() + ", " + info.getFinalPrice() + ", " + info.getResult(); System.out.println(text); } } // 총 내역 저장 메서드 public static void savelist(int ticketType, String sort, int totalPrice, int ticketNum, String result, ArrayList<OrderInfo> orderListArray) { OrderInfo infoset = new OrderInfo(); infoset.settTicketSelectZone(ticketType); infoset.setSort(sort); infoset.setTicketNum(ticketNum); infoset.setFinalPrice(totalPrice); infoset.setResult(result); orderListArray.add(infoset); } //파일 저장 public static void Ordersave(String ticketSelect_Zone, String sort, int finalPrice, int ticketNum, String result) throws IOException { SaveList.list(String.valueOf(ticketSelect_Zone)); SaveList.list(String.valueOf(sort)); SaveList.list(String.valueOf(ticketNum)); SaveList.list(String.valueOf(finalPrice)); SaveList.reason(result); } }
30.256757
136
0.645824
f8ab9d01c6fb1d0e40ac852169d3976183a3e8fd
704
package br.com.ernanilima.jpdv.Model; /** * Classe com os dados de acesso do suporte tecnico. * * @author Ernani Lima */ public class Support { /** ID do usuario Suporte */ private int id = 999; /** * Senha do usuario Suporte criptografada em sha256 * @see br.com.ernanilima.jpdv.Util.Encrypt */ private String pwd = "83CF8B609DE60036A8277BD0E96135751BBC07EB234256D4B65B893360651BF2"; // Construtor vazio public Support() {} /** * @return int - ID do usuario Suporte */ public int getId() { return id; } /** * @return String - Senha do usuario Suporte */ public String getPwd() { return pwd; } }
20.114286
92
0.610795
d4eefa00bc04f2d5fb452e4450a5b16be39c255a
1,822
package com.skedgo.android.tripkit.tsp; import com.skedgo.android.common.model.Region; import java.util.List; import javax.inject.Inject; import dagger.Lazy; import okhttp3.HttpUrl; import rx.Observable; import rx.functions.Func1; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; /** * A facade of {@link RegionInfoApi} that has failover on multiple servers. */ public class RegionInfoService { private final Lazy<RegionInfoApi> regionInfoApiLazy; @Inject public RegionInfoService(Lazy<RegionInfoApi> regionInfoApiLazy) { this.regionInfoApiLazy = regionInfoApiLazy; } /** * @param baseUrls Can be {@link Region#getURLs()}. * @param regionName Can be {@link Region#getName()}. */ public Observable<RegionInfo> fetchRegionInfoAsync( List<String> baseUrls, final String regionName) { return Observable.from(baseUrls) .concatMapDelayError(new Func1<String, Observable<RegionInfoResponse>>() { @Override public Observable<RegionInfoResponse> call(final String baseUrl) { final String url = HttpUrl.parse(baseUrl).newBuilder() .addPathSegment("regionInfo.json") .build() .toString(); return regionInfoApiLazy.get().fetchRegionInfoAsync( url, ImmutableRegionInfoBody.of(regionName) ); } }) .first(new Func1<RegionInfoResponse, Boolean>() { @Override public Boolean call(RegionInfoResponse response) { return isNotEmpty(response.regions()); } }) .map(new Func1<RegionInfoResponse, RegionInfo>() { @Override public RegionInfo call(RegionInfoResponse response) { return response.regions().get(0); } }); } }
31.964912
86
0.660263
e18a0594c0e9e144d6354946a493615234f112db
3,080
/* * Copyright 2019 Roessingh Research and Development. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package eu.woolplatform.utils.xml; import java.util.List; import org.xml.sax.Attributes; import eu.woolplatform.utils.exception.ParseException; /** * This is a simplified handler for SAX XML parsers. It can be used with a * {@link SimpleSAXParser SimpleSAXParser}. The handler receives XML events * from a SAX parser and constructs an object of a specified type. If the * parser completes without errors, the object can be obtained with {@link * #getObject() getObject()}. * * @author Dennis Hofs */ public interface SimpleSAXHandler<T> { /** * Called when the start tag of a new element is found. * * @param name the name of the element * @param atts the attributes defined in the start tag * @param parents the parents of the new element (ending with the direct * parent) * @throws ParseException if the content is invalid */ void startElement(String name, Attributes atts, List<String> parents) throws ParseException; /** * Called when the end tag of a new element is found. * * @param name the name of the element * @param parents the parents of the element (ending with the direct * parent) * @throws ParseException if the content is invalid */ void endElement(String name, List<String> parents) throws ParseException; /** * Called when text content is found. This method is called when the text * node is completed, so all consecutive characters are included in one * string. It also includes all whitespace. * * @param ch the text * @param parents the names of the elements that are parents of the text * node (ending with the direct parent) * @throws ParseException if the content is invalid */ void characters(String ch, List<String> parents) throws ParseException; /** * Returns the object that was constructed from the XML code. This method * can be called if the parser completed without errors. * * @return the object */ T getObject(); }
37.108434
78
0.739935
cb24b7d62e62758c9c1e3057d212eb0cf8233d05
128
package soya.lang; /** * @author: Jun Gong */ public interface Pattern { boolean isMatch(Object obj) throws Throwable; }
14.222222
49
0.6875
859865008c2b4e485b3e78e3f787898570cf6015
12,229
/** Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package bftsmart.communication.client.netty; import bftsmart.communication.client.ClientCommunicationServerSide; import bftsmart.communication.client.RequestReceiver; import bftsmart.reconfiguration.ViewTopology; import bftsmart.tom.ReplicaConfiguration; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.util.TOMUtil; import bftsmart.util.SSLContextFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.ssl.SslHandler; import org.slf4j.LoggerFactory; import utils.net.SSLMode; import utils.net.SSLSecurity; import javax.crypto.Mac; import javax.net.ssl.SSLEngine; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; /** * * @author Paulo */ @Sharable public class NettyClientServerCommunicationSystemServerSide extends SimpleChannelInboundHandler<TOMMessage> implements ClientCommunicationServerSide { private RequestReceiver requestReceiver; private Map<Integer, NettyClientServerSession> sessionTable; private ReentrantReadWriteLock rl; private ViewTopology controller; private boolean closed = false; private Channel mainChannel; // This locked seems to introduce a bottleneck and seems useless, but I cannot // recall why I added it // private ReentrantLock sendLock = new ReentrantLock(); private NettyServerPipelineFactory serverPipelineFactory; private static final org.slf4j.Logger LOGGER = LoggerFactory .getLogger(NettyClientServerCommunicationSystemServerSide.class); public NettyClientServerCommunicationSystemServerSide(ViewTopology controller) { this(controller, new SSLSecurity()); } public NettyClientServerCommunicationSystemServerSide(ViewTopology controller, SSLSecurity sslSecurity) { try { this.controller = controller; sessionTable = new ConcurrentHashMap<>(); rl = new ReentrantReadWriteLock(); ReplicaConfiguration staticConf = controller.getStaticConf(); int processId = staticConf.getProcessId(); // Configure the server. Mac macDummy = Mac.getInstance(staticConf.getHmacAlgorithm()); serverPipelineFactory = new NettyServerPipelineFactory(this, sessionTable, macDummy.getMacLength(), controller, rl, TOMUtil.getSignatureSize(controller)); EventLoopGroup bossGroup = new NioEventLoopGroup(); // If the numbers of workers are not specified by the configuration file, // the event group is created with the default number of threads, which // should be twice the number of cores available. int nWorkers = this.controller.getStaticConf().getNumNettyWorkers(); EventLoopGroup workerGroup = (nWorkers > 0 ? new NioEventLoopGroup(nWorkers) : new NioEventLoopGroup()); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ServerChannelInitializer(staticConf.isSecure(processId), sslSecurity)) .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true); // Bind and start to accept incoming connections. ChannelFuture f = b.bind( new InetSocketAddress(staticConf.getHost(processId), staticConf.getPort(processId))).sync(); LOGGER.info("-- secure = {}", staticConf.isSecure(processId)); LOGGER.info("-- ID = {}", processId); LOGGER.info("-- N = {}", controller.getCurrentViewN()); LOGGER.info("-- F = {}", controller.getCurrentViewF()); LOGGER.info("-- Port = {}", staticConf.getPort(processId)); LOGGER.info("-- requestTimeout = {}", staticConf.getRequestTimeout()); LOGGER.info("-- maxBatch = {}", staticConf.getMaxBatchSize()); if (staticConf.isUseMACs()) LOGGER.info("-- Using MACs"); if (staticConf.isUseSignatures()) LOGGER.info("-- Using Signatures"); // ******* EDUARDO END **************// mainChannel = f.channel(); } catch (Throwable ex) { LOGGER.error("[NettyClientServerCommunicationSystemServerSide] start exception!", ex); throw new RuntimeException("[NettyClientServerCommunicationSystemServerSide] exception.", ex); } } private class ServerChannelInitializer extends ChannelInitializer<SocketChannel> { private boolean secure; private SSLSecurity sslSecurity; public ServerChannelInitializer(boolean secure, SSLSecurity sslSecurity) { this.secure = secure; this.sslSecurity = sslSecurity; } @Override protected void initChannel(SocketChannel ch) throws Exception { if(secure) { SSLEngine sslEngine = SSLContextFactory.getSSLContext(false, sslSecurity).createSSLEngine(); sslEngine.setUseClientMode(false); if(null != sslSecurity.getEnabledProtocols() && sslSecurity.getEnabledProtocols().length > 0) { sslEngine.setEnabledProtocols(sslSecurity.getEnabledProtocols()); } if(null != sslSecurity.getCiphers() && sslSecurity.getCiphers().length > 0) { sslEngine.setEnabledCipherSuites(sslSecurity.getCiphers()); } sslEngine.setNeedClientAuth(sslSecurity.getSslMode(false).equals(SSLMode.TWO_WAY)); ch.pipeline().addFirst(new SslHandler(sslEngine)); } ch.pipeline().addLast(serverPipelineFactory.getDecoder()); ch.pipeline().addLast(serverPipelineFactory.getEncoder()); ch.pipeline().addLast(serverPipelineFactory.getHandler()); } } private void closeChannelAndEventLoop(Channel c) { c.flush(); c.deregister(); c.close(); c.eventLoop().shutdownGracefully(); } @Override public void shutdown() { if (closed) { return; } LOGGER.debug("Shutting down Netty system"); this.closed = true; closeChannelAndEventLoop(mainChannel); rl.readLock().lock(); ArrayList<NettyClientServerSession> sessions = new ArrayList<>(sessionTable.values()); rl.readLock().unlock(); for (NettyClientServerSession ncss : sessions) { closeChannelAndEventLoop(ncss.getChannel()); } LOGGER.info("NettyClientServerCommunicationSystemServerSide is halting."); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (this.closed) { closeChannelAndEventLoop(ctx.channel()); return; } if (cause instanceof ClosedChannelException) LOGGER.error("Connection with client closed."); else if (cause instanceof ConnectException) { LOGGER.error("Impossible to connect to client."); } else { LOGGER.error("exceptionCaught", cause); } } @Override protected void channelRead0(ChannelHandlerContext ctx, TOMMessage sm) throws Exception { if (this.closed) { closeChannelAndEventLoop(ctx.channel()); return; } // delivers message to TOMLayer if (requestReceiver == null) LOGGER.debug("RECEIVER NULO!!!!!!!!!!!!"); else requestReceiver.requestReceived(sm); } @Override public void channelActive(ChannelHandlerContext ctx) { if (this.closed) { closeChannelAndEventLoop(ctx.channel()); return; } LOGGER.debug("Session Created, active clients {} ", sessionTable.size()); } @Override public void channelInactive(ChannelHandlerContext ctx) { if (this.closed) { closeChannelAndEventLoop(ctx.channel()); return; } rl.writeLock().lock(); try { Set s = sessionTable.entrySet(); Iterator i = s.iterator(); while (i.hasNext()) { Entry m = (Entry) i.next(); NettyClientServerSession value = (NettyClientServerSession) m.getValue(); if (ctx.channel().equals(value.getChannel())) { int key = (Integer) m.getKey(); LOGGER.debug("#Removing client channel with ID {} ", key); sessionTable.remove(key); LOGGER.debug("#active clients {}", sessionTable.size()); break; } } } finally { rl.writeLock().unlock(); } LOGGER.debug("Session Closed, active clients {}", sessionTable.size()); } @Override public void setRequestReceiver(RequestReceiver tl) { this.requestReceiver = tl; } @Override public void send(int[] targets, TOMMessage sm, boolean serializeClassHeaders) { // serialize message DataOutputStream dos = null; byte[] data = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); sm.wExternal(dos); dos.flush(); data = baos.toByteArray(); sm.serializedMessage = data; } catch (IOException ex) { LOGGER.error("Error enconding message."); } finally { try { dos.close(); } catch (IOException ex) { LOGGER.error("Exception closing DataOutputStream: {}", ex.getMessage()); } } // replies are not signed in the current JBP version sm.signed = false; // produce signature if necessary (never in the current version) if (sm.signed) { // ******* EDUARDO BEGIN **************// byte[] data2 = TOMUtil.signMessage(controller.getStaticConf().getRSAPrivateKey(), data); // ******* EDUARDO END **************// sm.serializedMessageSignature = data2; } for (int i = 0; i < targets.length; i++) { rl.readLock().lock(); // sendLock.lock(); try { NettyClientServerSession ncss = (NettyClientServerSession) sessionTable.get(targets[i]); if (ncss != null) { Channel session = ncss.getChannel(); sm.destination = targets[i]; // send message session.writeAndFlush(sm); // This used to invoke "await". Removed to avoid blockage and race // condition. /////// TODO: replace this patch for a proper client preamble } else if (sm.getSequence() >= 0 && sm.getSequence() <= 5) { final int id = targets[i]; final TOMMessage msg = sm; Thread t = new Thread() { public void run() { LOGGER.debug( "Received request from {} before establishing Netty connection. Re-trying until connection is established", id); NettyClientServerSession ncss = null; while (ncss == null) { rl.readLock().lock(); try { Thread.sleep(1000); } catch (InterruptedException ex) { java.util.logging.Logger .getLogger(NettyClientServerCommunicationSystemServerSide.class.getName()) .log(Level.SEVERE, null, ex); } ncss = (NettyClientServerSession) sessionTable.get(id); if (ncss != null) { Channel session = ncss.getChannel(); msg.destination = id; // send message session.writeAndFlush(msg); } rl.readLock().unlock(); } LOGGER.debug("Connection with {} established", id); } }; t.start(); /////////////////////////////////////////// } else { LOGGER.debug("!!!!!!!!NettyClientServerSession NULL !!!!!! sequence: {}, ID: {}", sm.getSequence(), targets[i]); } } finally { // sendLock.unlock(); rl.readLock().unlock(); } } } @Override public int[] getClients() { rl.readLock().lock(); Set s = sessionTable.keySet(); int[] clients = new int[s.size()]; Iterator it = s.iterator(); int i = 0; while (it.hasNext()) { clients[i] = ((Integer) it.next()).intValue(); i++; } rl.readLock().unlock(); return clients; } }
31.117048
117
0.709216
c8478b9dcd26e4d689b9cfde1c06eb347d8981ba
1,758
package com.example.fn; import com.fnproject.fn.api.FnConfiguration; import com.fnproject.fn.api.RuntimeContext; import com.goplacesairlines.api.GoPlacesAirlines; import java.io.Serializable; import java.util.Date; public class Flight implements Serializable { private GoPlacesAirlines apiClient; public static class FlightBookingRequest implements Serializable { public String flightCode; public Date departureTime; } public static class FlightBookingResponse implements Serializable { public FlightBookingResponse(String confirmation) { this.confirmation = confirmation; } public String confirmation; } @FnConfiguration public void configure(RuntimeContext ctx) { String airlineApiUrl = ctx.getConfigurationByKey("FLIGHT_API_URL") .orElse("http://localhost:3000"); String airlineApiSecret = ctx.getConfigurationByKey("FLIGHT_API_SECRET") .orElseThrow(() -> new RuntimeException("No credentials provided for airline API.")); this.apiClient = new GoPlacesAirlines(airlineApiUrl, airlineApiSecret); } public FlightBookingResponse book(FlightBookingRequest flightDetails) { GoPlacesAirlines.BookingResponse apiResponse = apiClient.bookFlight(flightDetails.flightCode, flightDetails.departureTime); return new FlightBookingResponse(apiResponse.confirmation); } public FlightBookingResponse cancel(FlightBookingRequest cancellationRequest) { GoPlacesAirlines.CancellationResponse apiResponse = apiClient.cancelFlight(cancellationRequest.departureTime, cancellationRequest.flightCode); return new FlightBookingResponse(apiResponse.confirmation.toString()); } }
36.625
151
0.750853
7009238bb9446236a8d679ed5f86802bf1595c4f
522
package org.kyojo.schemaOrg.m3n3.doma.core.clazz; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaOrg.m3n3.core.impl.MOTEL; import org.kyojo.schemaOrg.m3n3.core.Clazz.Motel; @ExternalDomain public class MotelConverter implements DomainConverter<Motel, String> { @Override public String fromDomainToValue(Motel domain) { return domain.getNativeValue(); } @Override public Motel fromValueToDomain(String value) { return new MOTEL(value); } }
22.695652
71
0.793103
d642309c851a8bf5dae1dc89574a427259635b19
670
package com.pandawork.service.nature; import com.pandawork.common.entity.nature.Nature; import com.pandawork.core.common.exception.SSException; import java.util.List; /** * @author : kongyy * @time : 2018/12/23 16:52 */ public interface NatureService { public List<Nature> listAll( ) throws SSException; public List<Nature> listAll2( ) throws SSException; public boolean addNature(Nature nature) throws SSException; public boolean update(Nature nature) throws SSException; public boolean update2(int id) throws SSException; public boolean update3(int id) throws SSException; public boolean delById(int id) throws SSException; }
23.103448
63
0.749254
a7435772c2e39d01456471af54da57514accfe77
4,139
/* * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.file.dsl; import java.nio.charset.Charset; import org.springframework.integration.dsl.MessageHandlerSpec; import org.springframework.integration.file.splitter.FileSplitter; import org.springframework.util.StringUtils; /** * The {@link MessageHandlerSpec} for the {@link FileSplitter}. * * @author Artem Bilan * * @since 5.0 * * @see FileSplitter */ public class FileSplitterSpec extends MessageHandlerSpec<FileSplitterSpec, FileSplitter> { private final boolean iterator; private boolean markers; private boolean markersJson; private Charset charset; private boolean applySequence; private String firstLineHeaderName; protected FileSplitterSpec() { this(true); } protected FileSplitterSpec(boolean iterator) { this(iterator, false); } protected FileSplitterSpec(boolean iterator, boolean markers) { this.iterator = iterator; this.markers = markers; } /** * Set the charset to be used when reading the file, when something other than the default * charset is required. * @param charset the charset. * @return the FileSplitterSpec */ public FileSplitterSpec charset(String charset) { return charset(Charset.forName(charset)); } /** * Set the charset to be used when reading the file, when something other than the default * charset is required. * @param charset the charset. * @return the FileSplitterSpec */ public FileSplitterSpec charset(Charset charset) { this.charset = charset; return this; } /** * Specify if {@link FileSplitter} should emit * {@link org.springframework.integration.file.splitter.FileSplitter.FileMarker}s * Defaults to {@code false}. * @return the FileSplitterSpec */ public FileSplitterSpec markers() { return markers(false); } /** * Specify if {@link FileSplitter} should emit * {@link org.springframework.integration.file.splitter.FileSplitter.FileMarker}s * and if they should be converted to the JSON string representation. * Defaults to {@code false} for markers and {@code false} for markersJson. * @param asJson the asJson flag to use. * @return the FileSplitterSpec */ public FileSplitterSpec markers(boolean asJson) { this.markers = true; this.markersJson = asJson; return this; } /** * A {@code boolean} flag to indicate if {@code sequenceDetails} should be * applied for messages based on the lines from file. * Defaults to {@code false}. * @param applySequence the applySequence flag to use. * @return the FileSplitterSpec * @see org.springframework.integration.splitter.AbstractMessageSplitter#setApplySequence(boolean) */ public FileSplitterSpec applySequence(boolean applySequence) { this.applySequence = applySequence; return this; } /** * Specify the header name for the first line to be carried as a header in the * messages emitted for the remaining lines. * @param firstLineHeaderName the header name to carry first line. * @return the FileSplitterSpec */ public FileSplitterSpec firstLineAsHeader(String firstLineHeaderName) { this.firstLineHeaderName = firstLineHeaderName; return this; } @Override protected FileSplitter doGet() { FileSplitter fileSplitter = new FileSplitter(this.iterator, this.markers, this.markersJson); fileSplitter.setApplySequence(this.applySequence); fileSplitter.setCharset(this.charset); if (StringUtils.hasText(this.firstLineHeaderName)) { fileSplitter.setFirstLineAsHeader(this.firstLineHeaderName); } return fileSplitter; } }
29.147887
99
0.750906
117480890de3951b539662df4702d247f605e7b1
7,420
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.executor.mpp.operator; import com.alibaba.polardbx.common.utils.logger.Logger; import com.alibaba.polardbx.common.utils.logger.LoggerFactory; import com.alibaba.polardbx.executor.operator.ConsumerExecutor; import com.alibaba.polardbx.executor.operator.CorrelateExec; import com.alibaba.polardbx.executor.operator.Executor; import com.alibaba.polardbx.executor.operator.ProducerExecutor; import com.alibaba.polardbx.executor.operator.SortMergeExchangeExec; import com.alibaba.polardbx.executor.operator.SourceExec; import com.alibaba.polardbx.executor.operator.spill.MemoryRevoker; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class DriverExec { private static final Logger log = LoggerFactory.getLogger(DriverExec.class); private int pipelineId; private Executor producer; private ConsumerExecutor consumer; private final DriverYieldSignal yieldSignal; private boolean isSpill; private boolean opened = false; private boolean closed = false; private boolean producerIsClosed = false; private boolean consumerIsClosed = false; private boolean consumerIsBuffer; private List<ProducerExecutor> forceCloseExecs = new ArrayList<>(); private List<Integer> allInputIds = new ArrayList<>(); private List<MemoryRevoker> memoryRevokers = new ArrayList<>(); private HashMap<Integer, List<SourceExec>> sourceExecs = new HashMap<>(); public DriverExec(int pipelineId, DriverContext driverContext, Executor producer, ConsumerExecutor consumer, int parallelism) { this.pipelineId = pipelineId; this.producer = producer; this.consumer = consumer; this.yieldSignal = driverContext.getYieldSignal(); this.isSpill = driverContext.getPipelineContext().getTaskContext().isSpillable(); visitChild(producer); if (isSpill) { if (consumer instanceof MemoryRevoker) { memoryRevokers.add((MemoryRevoker) consumer); } if (consumer instanceof LocalExchanger) { for (ConsumerExecutor executor : ((LocalExchanger) consumer).getExecutors()) { if (executor instanceof MemoryRevoker) { if (parallelism > 1 && ((LocalExchanger) consumer).getExecutors().size() > 1) { throw new RuntimeException( "The MemoryRevoker must only be contain by one driver in spill mode!"); } memoryRevokers.add((MemoryRevoker) executor); } } } } for (List<SourceExec> sourceExecs : sourceExecs.values()) { for (SourceExec sourceExec : sourceExecs) { if (sourceExec instanceof SortMergeExchangeExec) { ((SortMergeExchangeExec) sourceExec).setYieldSignal(yieldSignal); } } } driverContext.setDriverExecRef(this); if (consumer instanceof LocalBufferExec) { this.consumerIsBuffer = true; } else if (consumer instanceof LocalExchanger) { this.consumerIsBuffer = ((LocalExchanger) consumer).executorIsLocalBuffer(); } } private void visitChild(Executor executor) { if (executor instanceof EmptyExecutor) { return; } if (executor instanceof SourceExec) { SourceExec sourceExec = (SourceExec) executor; List<SourceExec> list = sourceExecs.get(sourceExec.getSourceId()); if (list == null) { list = new ArrayList<>(); sourceExecs.put(sourceExec.getSourceId(), list); } list.add(sourceExec); this.forceCloseExecs.add(sourceExec); } if (executor instanceof MemoryRevoker) { this.memoryRevokers.add((MemoryRevoker) executor); } if (executor instanceof CorrelateExec) { this.forceCloseExecs.add(executor); } this.allInputIds.add(executor.getId()); for (Executor child : executor.getInputs()) { visitChild(child); } } public synchronized void open() { if (opened) { return; } try { if (!closed) { producer.open(); consumer.openConsume(); } } finally { opened = true; } } public synchronized void closeProducer() { try { if (!producerIsClosed && opened) { producer.close(); } } finally { producerIsClosed = true; } } public synchronized boolean isProducerIsClosed() { return producerIsClosed; } public synchronized void close() { try { if (!closed) { if (opened) { try { producer.close(); } catch (Throwable e) { //ignore } try { consumer.buildConsume(); } catch (Throwable e) { log.warn("buildConsume consumer:" + consumer, e); } } else if (consumerIsBuffer) { try { consumer.buildConsume(); } catch (Throwable e) { log.warn("buildConsume consumer:" + consumer, e); } } } } finally { closed = true; } } public synchronized void closeOnException() { close(); if (!consumerIsClosed) { try { consumer.closeConsume(false); } catch (Throwable e) { log.warn("closeConsume consumer:" + consumer, e); } finally { consumerIsClosed = true; } } } public synchronized boolean isOpened() { return opened; } public synchronized boolean isFinished() { return closed; } public List<MemoryRevoker> getMemoryRevokers() { return memoryRevokers; } public ConsumerExecutor getConsumer() { return consumer; } public Executor getProducer() { return producer; } public List<Integer> getAllInputIds() { return allInputIds; } public int getPipelineId() { return pipelineId; } public HashMap<Integer, List<SourceExec>> getSourceExecs() { return sourceExecs; } public List<ProducerExecutor> getForceCloseExecs() { return forceCloseExecs; } }
31.982759
112
0.586658
986734d2c9cb48e34ffeac4c54e8ef95423bea70
2,486
package com.kickstarter.viewmodels; import android.support.annotation.NonNull; import android.util.Pair; import com.kickstarter.KSRobolectricTestCase; import com.kickstarter.factories.ProjectFactory; import com.kickstarter.factories.ProjectStatsEnvelopeFactory; import com.kickstarter.libs.Environment; import com.kickstarter.libs.utils.PairUtils; import com.kickstarter.models.Project; import com.kickstarter.services.apiresponses.ProjectStatsEnvelope; import org.junit.Test; import java.util.Arrays; import java.util.List; import rx.observers.TestSubscriber; public class CreatorDashboardReferrerStatsHolderViewModelTest extends KSRobolectricTestCase { private CreatorDashboardReferrerStatsHolderViewModel.ViewModel vm; private final TestSubscriber<List<ProjectStatsEnvelope.ReferrerStats>> referrerStatsOutput = new TestSubscriber<>(); private final TestSubscriber<Project> projectOutput = new TestSubscriber<>(); protected void setUpEnvironment(final @NonNull Environment environment) { this.vm = new CreatorDashboardReferrerStatsHolderViewModel.ViewModel(environment); this.vm.outputs.projectAndReferrerStats().map(PairUtils::first).subscribe(this.projectOutput); this.vm.outputs.projectAndReferrerStats().map(PairUtils::second).subscribe(this.referrerStatsOutput); } @Test public void testProjectAndReferrerStats() { final Project project = ProjectFactory.project(); final ProjectStatsEnvelope.ReferrerStats referrerWithOnePledged = ProjectStatsEnvelopeFactory.ReferrerStatsFactory.referrerStats().toBuilder().pledged(1).build(); final ProjectStatsEnvelope.ReferrerStats referrerWithTwoPledged = ProjectStatsEnvelopeFactory.ReferrerStatsFactory.referrerStats().toBuilder().pledged(2).build(); final ProjectStatsEnvelope.ReferrerStats referrerWithThreePledged = ProjectStatsEnvelopeFactory.ReferrerStatsFactory.referrerStats().toBuilder().pledged(3).build(); final List<ProjectStatsEnvelope.ReferrerStats> unsortedReferrerList = Arrays.asList(referrerWithOnePledged, referrerWithThreePledged, referrerWithTwoPledged); final List<ProjectStatsEnvelope.ReferrerStats> sortedReferrerList = Arrays.asList(referrerWithThreePledged, referrerWithTwoPledged, referrerWithOnePledged); setUpEnvironment(environment()); this.vm.inputs.projectAndReferrerStatsInput(Pair.create(project, unsortedReferrerList)); this.projectOutput.assertValues(project); this.referrerStatsOutput.assertValues(sortedReferrerList); } }
51.791667
168
0.835881
abaa8a9b3d0d05741c9a198ac02b530c8656b57d
2,824
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Victor A. Martynov * @version $Revision: 1.1.2.4 $ */ package org.apache.harmony.rmi.activation; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import org.apache.harmony.rmi.common.RMILog; import org.apache.harmony.rmi.internal.nls.Messages; /** * Factory class to create RmidMonitors. * * @author Victor A. Martynov * @version $Revision: 1.1.2.4 $ */ class RmidMonitorFactory { /** * Standard logger for RMI Activation. * * @see org.apache.harmony.rmi.common.RMILog#getActivationLog() */ private static RMILog rLog = RMILog.getActivationLog(); /** * Factory method intended to obtain RmidMonitor implementation. * * @param className * Fully qualified class name of the monitor. * * @return instance of the monitor class, <code>null</code> - if class * was not found. * @see Rmid * @see org.apache.harmony.rmi.common.RMIProperties#ACTIVATION_MONITOR_CLASS_NAME_PROP * @see org.apache.harmony.rmi.common.RMIConstants#DEFAULT_ACTIVATION_MONITOR_CLASS_NAME * @see org.apache.harmony.rmi.activation.RmidMonitorAdapter */ static RmidMonitor getRmidMonitor(String className) { try { final Class cl = Class.forName(className); // rmi.log.36=RMID Monitor class = {0} rLog.log(Rmid.commonDebugLevel, Messages.getString("rmi.log.36", cl)); //$NON-NLS-1$ return (RmidMonitor) AccessController .doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Constructor constructor = cl .getConstructor(new Class[0]); return constructor.newInstance(new Object[0]); } }); } catch (Exception e) { return null; } } }
33.619048
96
0.654037
5ace1b04b152549089fa53f570c007b9bf982cd0
1,501
package org.zimmob.zimlx.settings.ui; import android.os.Bundle; import androidx.appcompat.widget.Toolbar; import com.android.launcher3.R; import com.android.launcher3.Utilities; import org.zimmob.zimlx.theme.ThemeOverride; import org.zimmob.zimlx.util.ThemeActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by saul on 04-25-18. * Project ZimLX * [email protected] */ public class AboutActivity extends ThemeActivity { @BindView(R.id.toolbar) public Toolbar toolbar; private ThemeOverride themeOverride; private int currentTheme = 0; private ThemeOverride.ThemeSet themeSet; @Override protected void onCreate(Bundle savedInstanceState) { Utilities.setupPirateLocale(this); themeSet = new ThemeOverride.Settings(); themeOverride = new ThemeOverride(themeSet, this); themeOverride.applyTheme(this); currentTheme = themeOverride.getTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_more); ButterKnife.bind(this); setSupportActionBar(toolbar); toolbar.setBackgroundColor(Utilities.getZimPrefs(this).getPrimaryColor()); toolbar.setTitleTextColor(getResources().getColor(R.color.white)); toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24px)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setTitle(R.string.about_title); } }
32.630435
99
0.742172
8f83e55a66f1fd669d1384f58f72ec5ec1e200cf
850
package com.coder.happensbefore; import java.util.concurrent.TimeUnit; /** * @author: lichunxia * @create: 2021-03-27 17:46 */ public class ThreadJoinDemo { private int a = 10; public static void main(String[] args) { ThreadJoinDemo threadJoinDemo = new ThreadJoinDemo(); Thread thread = new Thread(() -> { try { TimeUnit.SECONDS.sleep(5); } catch (Exception e) { e.printStackTrace(); } threadJoinDemo.a = ++threadJoinDemo.a; System.out.println(Thread.currentThread().getName() + " : " + threadJoinDemo.a); }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadJoinDemo.a); } }
23.611111
92
0.548235
173994745fdea1033f53344f9c0c9aed6711c0f2
1,854
/* * MIT License * * Copyright (c) 2020 Alen Turkovic * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.github.alturkovic.asn.annotation; import com.github.alturkovic.asn.tag.Type; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Represents the tag in the TLV describing a specific location. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface AsnTag { /** * Tag type. UNIVERSAL, APPLICATION, CONTEXT, PRIVATE */ Type type() default Type.CONTEXT; /** * Tag value. If the value is -1, it is a hint for the decoder/encoder * to try to resolve a UNIVERSAL tag, regardless of {@link #type()}. */ int value() default -1; }
36.352941
81
0.748652
ea997c4353bf14c398e0358784fce02b0c0cb52d
3,403
package com.example.ex2_034; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { String [] listitem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button a=findViewById(R.id.button_red); final Button b=findViewById(R.id.button_blue); final Button c=findViewById(R.id.button_green); a.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int red = Color.parseColor("#ff0000"); a.setTextColor(red); } }); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int blue=Color.parseColor("#0000ff"); b.setTextColor(blue); ; } }); c.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int green=Color.parseColor("#008000"); c.setTextColor(green); } } ); final Spinner sp=findViewById(R.id.spinner5); final ListView lv=findViewById(R.id.lsv); listitem=getResources().getStringArray(R.array.list_item); ArrayAdapter adapter=new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,listitem); lv.setAdapter(adapter); sp.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int x=i; if(x==0){ Toast.makeText(MainActivity.this,"Red",Toast.LENGTH_SHORT).show(); } else if(x==1){ Toast.makeText(MainActivity.this,"green",Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(MainActivity.this,"Blue",Toast.LENGTH_SHORT).show(); } } }); sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(i==0){ Toast.makeText(MainActivity.this,"Red",Toast.LENGTH_SHORT).show(); } else if(i==1){ Toast.makeText(MainActivity.this,"green",Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(MainActivity.this,"Blue",Toast.LENGTH_SHORT).show(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }
35.082474
107
0.557743
ba1bf3f6f98ef6736a3eb03daf51ea861fa562db
3,449
package me.ehp246.aufjms.core.byjms; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.UUID; import org.junit.jupiter.api.Assertions; import me.ehp246.aufjms.api.dispatch.DispatchConfig; import me.ehp246.aufjms.api.dispatch.InvocationDispatchBuilder; import me.ehp246.aufjms.api.jms.AtDestination; import me.ehp246.aufjms.core.dispatch.DefaultInvocationDispatchBuilder; /** * @author Lei Yang * */ class DefaultInvocationDispatchProviderTest { private final static String[] NAMES = new String[2]; private final static String replyToName = UUID.randomUUID().toString(); private final static String destinationName = UUID.randomUUID().toString(); private final static String connectionName = UUID.randomUUID().toString(); private final static AtDestination destination = new AtDestination() { @Override public String name() { return destinationName; } }; private final static DispatchConfig proxyConfig = new DispatchConfig() { @Override public String ttl() { return Duration.ofMillis(334).toString(); } @Override public AtDestination destination() { return destination; } @Override public String context() { return connectionName; } @Override public AtDestination replyTo() { return null; } }; private InvocationDispatchBuilder dispatchBuilder = null; void destintationResolver_01() { // fromInvocation.get(proxyConfig, new // TypeTestCases.Case01().getM01Invocation()); Assertions.assertEquals(connectionName, NAMES[0]); Assertions.assertEquals(replyToName, NAMES[1]); } void propertyResolver_02() throws NoSuchMethodException, SecurityException { final String[] names = new String[2]; new DefaultInvocationDispatchBuilder((dest) -> { names[1] = dest; return destinationName; }).get(null, new DispatchConfig() { @Override public String ttl() { return Duration.ofMillis(334).toString(); } @Override public AtDestination destination() { return null; } @Override public String context() { return connectionName; } @Override public AtDestination replyTo() { return null; } }); Assertions.assertEquals(connectionName, names[0]); Assertions.assertEquals(destinationName, names[1]); } void body_01() throws NoSuchMethodException, SecurityException { final var args = new ArrayList<>(); args.add(null); final var dispatch = dispatchBuilder.get(null, proxyConfig); Assertions.assertEquals(1, dispatch.bodyValues().size()); Assertions.assertEquals(null, dispatch.bodyValues().get(0)); Assertions.assertThrows(Exception.class, () -> dispatch.bodyValues().clear()); } void body_02() throws NoSuchMethodException, SecurityException { final var now = Instant.now(); final var dispatch = dispatchBuilder.get(null, proxyConfig); Assertions.assertEquals(1, dispatch.bodyValues().size()); Assertions.assertEquals(now, dispatch.bodyValues().get(0)); } }
29.991304
86
0.634677
790ce6f48c4530111c652061873da995e209e60c
489
package co.yixiang.modules.shop.repository; import co.yixiang.modules.shop.domain.YxExpress; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * @author hupeng * @date 2019-12-12 */ public interface YxExpressRepository extends JpaRepository<YxExpress, Integer>, JpaSpecificationExecutor { /** * findByCode * @param code * @return */ YxExpress findByCode(String code); }
25.736842
106
0.754601
9261bbe594a200ffc09f39423c9c188d4fe6a4fa
12,165
package org.stormroboticsnj.stormappmaster2019.Fragments; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; import android.widget.Toast; import org.stormroboticsnj.stormappmaster2019.R; import org.stormroboticsnj.stormappmaster2019.db.DeepSpace; import org.stormroboticsnj.stormappmaster2019.db.Handler; import org.w3c.dom.Text; public class TeamData extends Fragment { /** Called when the activity is first created. */ private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public TeamData() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment TeamData. */ // TODO: Rename and change types and number of parameters public static TeamData newInstance(String param1, String param2) { TeamData fragment = new TeamData(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_team_data, container, false); final TextView txtHeader = (TextView) view.findViewById(R.id.txtTopView); final TextView txtSummary = (TextView) view.findViewById(R.id.txtSummary); final EditText searchBar = (EditText) view.findViewById(R.id.editSearchNum); final Button searchBtn = (Button) view.findViewById(R.id.btnSearchTmDt); searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String teamNum = searchBar.getText().toString(); String insertErrString = ""; if (teamNum.matches("")) insertErrString = "Please enter a team number."; else if(teamNum.length() > 5) insertErrString = "Team Number is too long."; if (!insertErrString.matches("")) { //If something is missing, display error to user. Toast.makeText(getActivity(), "Error: " + insertErrString, Toast.LENGTH_SHORT).show(); return; } DeepSpace[] deep = Handler.getInstance(getActivity().getBaseContext()).getTeamData(teamNum); if (deep.length == 0) return; //System.out.println(deep[0].toString()); TableRow.LayoutParams wrapWrapTableRowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); int[] fixedColumnWidths = new int[]{20, 20, 20, 20, 20}; int[] scrollableColumnWidths = new int[]{20, 20, 20, 30, 30}; int fixedRowHeight = 50; int fixedHeaderHeight = 60; TableRow row = new TableRow(getActivity().getApplicationContext()); /*//header (fixed vertically) TableLayout header = (TableLayout) view.findViewById(R.id.table_header); row.setLayoutParams(wrapWrapTableRowParams); row.setGravity(Gravity.CENTER); row.addView(makeTableRowWithText("col 1", fixedColumnWidths[0], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 2", fixedColumnWidths[1], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 3", fixedColumnWidths[2], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 4", fixedColumnWidths[3], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 5", fixedColumnWidths[4], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 6", fixedColumnWidths[0], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 7", fixedColumnWidths[1], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 8", fixedColumnWidths[2], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 9", fixedColumnWidths[3], fixedHeaderHeight)); row.addView(makeTableRowWithText("col 10", fixedColumnWidths[4], fixedHeaderHeight)); header.addView(row);*/ // not in use //header (fixed horizontally) TableLayout fixedColumn = (TableLayout) view.findViewById(R.id.fixed_column); //rest of the table (within a scroll view) TableLayout scrollablePart = (TableLayout) view.findViewById(R.id.scrollable_part); final String[] rows = {"Match #", "Sandstorm", "Start Pos", "Pass Line", "Hatches", "Cargo", "Cargo", "Level 3", "Level 2", "Level 1", "Ship", "Player", "Ground", "Hatches", "Level 3", "Level 2", "Level 1", "Ship", "Player", "Ground", "Endgame", "Self", "Assist 1", "Assist 2"}; // = { // {"12", "18", "34", "35", "57", "24", "31", "51", "41"}, // {" ", " ", " ", " ", " ", " ", " ", " ", " "}, // {"1", "0", "2", "2", "0", "3", "1", "2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {" ", " ", " ", " ", " ", " ", " ", " ", " "}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {" ", " ", " ", " ", " ", " ", " ", " ", " "}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}, // {"3", "0", "2", "3" ,"1", "0", "3" ,"2", "2"}}; String[][] data = new String[rows.length][deep.length]; for(int j = 0; j < deep.length; j++){ data[0][j] = Integer.toString(deep[j].getMatchNum()); data[1][j] = " "; data[2][j] = Integer.toString(deep[j].getStartingPosition()); data[3][j] = deep[j].getPassAutoLine() == 1 ? "Y" : "N"; data[4][j] = Integer.toString(deep[j].getAutoHatches()); data[5][j] = Integer.toString(deep[j].getAutoCargo()); data[6][j] = " "; data[7][j] = Integer.toString(deep[j].getCargoRT()); data[8][j] = Integer.toString(deep[j].getCargoRD()); data[9][j] = Integer.toString(deep[j].getCargoRU());; data[10][j] = Integer.toString(deep[j].getCargoShip()); data[11][j] = Integer.toString(deep[j].getCargoPlayer()); data[12][j] = Integer.toString(deep[j].getCargoGround()); data[13][j] = " "; data[14][j] = Integer.toString(deep[j].getHatchRT()); data[15][j] = Integer.toString(deep[j].getHatchRD()); data[16][j] = Integer.toString(deep[j].getHatchRU());; data[17][j] = Integer.toString(deep[j].getHatchShip()); data[18][j] = Integer.toString(deep[j].getHatchPlayer()); data[19][j] = Integer.toString(deep[j].getHatchGround()); data[20][j] = " "; data[21][j] = Integer.toString(deep[j].getSelfLevel()); data[22][j] = Integer.toString(deep[j].getAssistLevel()); data[23][j] = Integer.toString(deep[j].getAssistTwoLevel()); System.out.println(deep[j].toString()); } String headerText = "Team " + teamNum + " played " + data[0].length + " match" + (data[0].length==1 ? ":\n" : "es:\n"); for (int l = 0; l < data[0].length; l++){ headerText += String.format(l == data[0].length - 1 ? "%s" : "%s, ", data[0][l]); } txtHeader.setText("Team Data: Team " + teamNum); txtSummary.setText(headerText); for(int i = 0; i < rows.length; i++) { TextView fixedView = makeTableRowWithText(rows[i], scrollableColumnWidths[0], fixedRowHeight, (data[i][0].equals(" ")), true, new int[]{1,1}); fixedColumn.addView(fixedView); row = new TableRow(getActivity().getApplicationContext()); row.setLayoutParams(wrapWrapTableRowParams); row.setGravity(Gravity.CENTER); for (int k = 0; k < deep.length; k++){ row.addView(makeTableRowWithText(data[i][k], scrollableColumnWidths[0], fixedRowHeight, (data[i][0].equals(" ")), false, new int[]{k,i})); } scrollablePart.addView(row); } } }); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } //util method private TextView recyclableTextView; public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth, int fixedHeightInPixels, boolean header, boolean subheader, int[] index) { int screenWidth = getResources().getDisplayMetrics().widthPixels; recyclableTextView = new TextView(getActivity().getApplicationContext()); recyclableTextView.setText(text); recyclableTextView.setTextColor(getResources().getColor(R.color.colorPrimaryDark)); recyclableTextView.setTextSize(24); recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100); recyclableTextView.setHeight(fixedHeightInPixels); if (header) { recyclableTextView.setTypeface(recyclableTextView.getTypeface(), Typeface.BOLD); } else if (!subheader){ recyclableTextView.setGravity(Gravity.CENTER); recyclableTextView.setBackgroundResource(index[0] % 2 == 0 ? R.drawable.cell_border : R.drawable.cell_border_white); } else { recyclableTextView.setBackgroundResource(index[0] % 2 == 0 ? R.drawable.cell_border : R.drawable.cell_border_white); } if (index[1] == 0) recyclableTextView.setTypeface(recyclableTextView.getTypeface(), Typeface.BOLD); return recyclableTextView; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } }
51.54661
162
0.575339
cd177d9580c385767318c00fa20a6a86338d7a43
572
// // Decompiled by Procyon v0.5.36 // package org.xml.sax; import java.io.IOException; import java.util.Locale; public interface Parser { void setLocale(final Locale p0) throws SAXException; void setEntityResolver(final EntityResolver p0); void setDTDHandler(final DTDHandler p0); void setDocumentHandler(final DocumentHandler p0); void setErrorHandler(final ErrorHandler p0); void parse(final InputSource p0) throws SAXException, IOException; void parse(final String p0) throws SAXException, IOException; }
22
70
0.722028
28e981484767824794314db924ad0fb116ace88f
2,492
package io.tidb.bigdata.cdc.json.jackson; import java.math.BigDecimal; public class JacksonObjectNode { private final JacksonContext context; private final Object object; JacksonObjectNode(final JacksonContext context, final Object object) { this.context = context; this.object = object; } Object getImpl() { return object; } public JacksonObjectNode put(String fieldName, BigDecimal v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, boolean v) { return put(fieldName, Boolean.valueOf(v)); } public JacksonObjectNode put(String fieldName, Boolean v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, byte[] v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, double v) { return put(fieldName, Double.valueOf(v)); } public JacksonObjectNode put(String fieldName, Double v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, float v) { return put(fieldName, Float.valueOf(v)); } public JacksonObjectNode put(String fieldName, Float v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, short v) { return put(fieldName, Short.valueOf(v)); } public JacksonObjectNode put(String fieldName, Short v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, int v) { return put(fieldName, Integer.valueOf(v)); } public JacksonObjectNode put(String fieldName, Integer v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, long v) { return put(fieldName, Long.valueOf(v)); } public JacksonObjectNode put(String fieldName, Long v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode put(String fieldName, String v) { context.objectNodePut(object, fieldName, v); return this; } public JacksonObjectNode putNull(String fieldName) { context.objectNodePutNull(object, fieldName); return this; } public JacksonObjectNode putObject(String fieldName) { return new JacksonObjectNode(context, context.objectNodePutObject(object, fieldName)); } }
25.428571
90
0.720305
c247bc40cdfc0be4c89b89726c2e275cdb953146
1,730
/** * Copyright 2017 Hortonworks. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.hortonworks.streamline.streams.udaf; import com.hortonworks.streamline.streams.rule.UDAF; public class NumberSum implements UDAF<Number, Number, Number> { @Override public Number init() { return 0; } @Override public Number add(Number aggregate, Number val) { if (val instanceof Byte) { return (byte) (aggregate.byteValue() + val.byteValue()); } else if (val instanceof Short) { return (short) (aggregate.shortValue() + val.shortValue()); } else if (val instanceof Integer) { return aggregate.intValue() + val.intValue(); } else if (val instanceof Long) { return aggregate.longValue() + val.longValue(); } else if (val instanceof Float) { return aggregate.floatValue() + val.floatValue(); } else if (val instanceof Double) { return aggregate.doubleValue() + val.doubleValue(); } throw new IllegalArgumentException("Value type " + val.getClass()); } @Override public Number result(Number aggregate) { return aggregate; } }
34.6
76
0.657225
a7ed94afa5c94b7dd5f35ed04f71687b0eaaedf7
3,631
package org.thoughtcrime.securesms.util; import android.app.Activity; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.job.JobScheduler; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.hardware.display.DisplayManager; import android.location.LocationManager; import android.media.AudioManager; import android.net.ConnectivityManager; import android.os.Build; import android.os.PowerManager; import android.os.Vibrator; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.view.WindowManager; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.InputMethodManager; public class ServiceUtil { public static InputMethodManager getInputMethodManager(Context context) { return (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); } public static WindowManager getWindowManager(Context context) { return (WindowManager) context.getSystemService(Activity.WINDOW_SERVICE); } public static ConnectivityManager getConnectivityManager(Context context) { return (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE); } public static NotificationManager getNotificationManager(Context context) { return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } public static TelephonyManager getTelephonyManager(Context context) { return (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); } public static AudioManager getAudioManager(Context context) { return (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); } public static PowerManager getPowerManager(Context context) { return (PowerManager)context.getSystemService(Context.POWER_SERVICE); } public static AlarmManager getAlarmManager(Context context) { return (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); } public static Vibrator getVibrator(Context context) { return (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); } public static DisplayManager getDisplayManager(@NonNull Context context) { return (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); } public static AccessibilityManager getAccessibilityManager(@NonNull Context context) { return (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); } public static ClipboardManager getClipboardManager(@NonNull Context context) { return (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); } @RequiresApi(26) public static JobScheduler getJobScheduler(Context context) { return (JobScheduler) context.getSystemService(JobScheduler.class); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) public static @Nullable SubscriptionManager getSubscriptionManager(@NonNull Context context) { return (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); } public static ActivityManager getActivityManager(@NonNull Context context) { return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); } public static LocationManager getLocationManager(@NonNull Context context) { return ContextCompat.getSystemService(context, LocationManager.class); } }
37.822917
98
0.822363
09e85de54587f3a100cd697dfd94bc3141b3903d
8,313
// Copyright (C) 2002 IAIK // http://jce.iaik.at // // Copyright (C) 2003 - 2015 Stiftung Secure Information and // Communication Technologies SIC // http://www.sic.st // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. package demo.pkcs.pkcs11.provider.ciphers; //class and interface imports import iaik.pkcs.pkcs11.provider.ComparableByteArray; import iaik.pkcs.pkcs11.provider.IAIKPkcs11; import iaik.pkcs.pkcs11.provider.IAIKPkcs11Exception; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyException; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import javax.crypto.Cipher; import demo.pkcs.pkcs11.provider.utils.DemoUtils; import demo.pkcs.pkcs11.provider.utils.KeyFinder; /** * This class shows a short demonstration of how to use this provider implementation for asymmetric * encryption and decryption. Most parts are identical to applications using other providers. The * only difference is the treatment of keystores. Smart card keystores cannot be read from streams * in general. */ public class AsymmetricCipherDemo { /** * The data that will be encrypted. A real application would e.g. read it from file. */ protected static byte[] DATA = "This is some data to be encrypted.".getBytes(); /** * The PKCS#11 JCE provider. */ protected IAIKPkcs11 pkcs11Provider_; /** * The decryption key. In this case only a proxy object, but the application cannot see the * difference. */ protected PrivateKey decryptionKey_; /** * This is the key used for encryption. */ protected PublicKey encryptionKey_; /** * This is the encrypted data. */ protected byte[] cipherText_; /** * The initialization vector for the cipher in CBC mode. */ protected byte[] initializationVector_ = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; /** * The decrpytion cipher engine. */ protected Cipher decryptionEngine_; /** * This empty constructor registers the new provider to the Java security system. */ public AsymmetricCipherDemo() { DemoUtils.addSoftwareProvider(); pkcs11Provider_ = new IAIKPkcs11(); Security.addProvider(pkcs11Provider_); } public static void main(String[] args) throws GeneralSecurityException, IOException { AsymmetricCipherDemo demo = new AsymmetricCipherDemo(); String algorithm = (args.length > 0) ? args[0] : "RSA"; String padding = "pkcs1padding"; demo.getOrGenerateKey(algorithm); demo.encryptData(algorithm, padding); demo.decryptData(algorithm, padding); demo.decryptDataAgain(); System.out.flush(); System.err.flush(); } /** * First, this method tries to find the required keys on a token. If there are none, this method * generates a temporary key pair and stores them in the member variables * <code>encryptionKey_</code> and <code>decryptionKey_</code>. * * @throws GeneralSecurityException * If anything with the provider fails. * @throws IOException * If initializing the key store fails. */ public void getOrGenerateKey(String algorithm) throws GeneralSecurityException, IOException { KeyPair keyPair; try { keyPair = KeyFinder.findCipherKeyPair(pkcs11Provider_, algorithm); } catch (KeyException e) { keyPair = KeyFinder.generateCipherKeyPair(pkcs11Provider_, algorithm); } encryptionKey_ = keyPair.getPublic(); decryptionKey_ = keyPair.getPrivate(); } /** * This method encrypts the data. It uses the software provider for this purpose. * * @exception GeneralSecurityException * If encryption fails for some reason. */ public void encryptData(String algorithm, String padding) throws GeneralSecurityException { System.out.println("##########"); System.out.print("Encrypting this data: \""); System.out.print(new String(DATA)); System.out.println("\""); System.out.println(); System.out.print("encrypting... "); // get a cipher object from the PKCS#11 provider for encryption Cipher encryptionEngine = Cipher.getInstance(algorithm + "/ECB/" + padding, pkcs11Provider_.getName()); // initialize for encryption with the secret key encryptionEngine.init(Cipher.ENCRYPT_MODE, encryptionKey_); // put the original data and encrypt it cipherText_ = encryptionEngine.doFinal(DATA); System.out.println("finished"); System.out.println("##########"); } /** * This method decrypts the data. It uses the PKCS#11 provider for this purpose. * * @exception GeneralSecurityException * If decryption fails for some reason. */ public void decryptData(String algorithm, String padding) throws GeneralSecurityException { System.out.println("##########"); System.out.print("decrypting... "); // Get a cipher object from our new provider decryptionEngine_ = Cipher.getInstance(algorithm + "/ECB/" + padding, pkcs11Provider_.getName()); // initialize for decryption with our secret key decryptionEngine_.init(Cipher.DECRYPT_MODE, decryptionKey_); // decrpyt the data byte[] recoveredPlainText = decryptionEngine_.doFinal(cipherText_); System.out.println("finished"); // put the data that should be signed System.out.println("The recovered data is:"); System.out.print("\""); System.out.print(new String(recoveredPlainText)); System.out.println("\""); System.out.println(); ComparableByteArray originalData = new ComparableByteArray(DATA); ComparableByteArray recoveredData = new ComparableByteArray(recoveredPlainText); if (recoveredData.equals(originalData)) { System.out.println("decrypted and original data match - SUCCESS"); } else { System.out.println("decrypted and original data mismatch - FAILURE"); throw new IAIKPkcs11Exception( "Decryption error: decrypted and original data mismatch"); } System.out.println("##########"); } /** * This method decrypts the data. It reuses the PKCS#11 cipher engine for this purpose. * * @exception GeneralSecurityException * If decryption fails for some reason. */ public void decryptDataAgain() throws GeneralSecurityException { System.out.println("##########"); System.out.print("testing cipher reuse... "); // test reuse of cipher object byte[] recoveredPlainText2 = decryptionEngine_.doFinal(cipherText_); ComparableByteArray recoveredData2 = new ComparableByteArray(recoveredPlainText2); ComparableByteArray originalData = new ComparableByteArray(DATA); if (recoveredData2.equals(originalData)) { System.out.println("SUCCESS"); } else { System.out.println("FAILURE"); throw new IAIKPkcs11Exception( "Decryption Engine reuse error: decrypted and original data mismatch"); } System.out.println("##########"); } }
34.782427
99
0.707927
f9406dd3bd91aa6ebc72d91e43fb0f4586fe6928
2,224
package com.instructure.canvasapi.model; import android.os.Parcel; import android.os.Parcelable; import java.util.Date; /** * @author Josh Ruesch * * Copyright (c) 2014 Instructure. All rights reserved. */ public class DiscussionTopicPermission extends CanvasModel<DiscussionTopicPermission> { private static final long serialVersionUID = 1L; private boolean attach = false; private boolean update = false; private boolean delete = false; /////////////////////////////////////////////////////////////////////////// // Getters and Setters /////////////////////////////////////////////////////////////////////////// public boolean canAttach() { return attach; } public void setCanAttach(boolean can_attach) { this.attach = can_attach; } public boolean canUpdate(){ return update; } public void setCanUpdate(boolean update){ this.update = update; } public boolean canDelete(){ return delete; } public void setCanDelete(boolean delete){ this.delete = delete; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeByte(attach ? (byte) 1 : (byte) 0); dest.writeByte(update ? (byte) 1 : (byte) 0); dest.writeByte(delete ? (byte) 1 : (byte) 0); } public DiscussionTopicPermission() {} private DiscussionTopicPermission(Parcel in) { this.attach = in.readByte() != 0; this.update = in.readByte() != 0; this.delete = in.readByte() != 0; } public static Creator<DiscussionTopicPermission> CREATOR = new Creator<DiscussionTopicPermission>() { public DiscussionTopicPermission createFromParcel(Parcel source) { return new DiscussionTopicPermission(source); } public DiscussionTopicPermission[] newArray(int size) { return new DiscussionTopicPermission[size]; } }; @Override public long getId() { return 0; } @Override public Date getComparisonDate() { return null; } @Override public String getComparisonString() { return null; } }
24.43956
105
0.59982
185ab87c4012e36207c93e30fffffa46e5c550d9
1,997
package seedu.expensela.model.transaction; import static java.util.Objects.requireNonNull; import static seedu.expensela.commons.util.AppUtil.checkArgument; /** * Represents a Transaction's category. * Guarantees: immutable; is valid as declared in {@link #isValidCategory(String)} */ public class Category { public static final String MESSAGE_CONSTRAINTS = "Valid categories are: FOOD," + " SHOPPING," + " TRANSPORT," + " GROCERIES," + " HEALTH," + " RECREATION," + " INCOME," + " UTILITIES OR" + " MISC"; /* * The first character of the category must not be a whitespace, * otherwise " " (a blank string) becomes a valid input. */ public final String transactionCategory; /** * Constructs a {@code Category}. * * @param category A valid category. */ public Category(String category) { requireNonNull(category); checkArgument(isValidCategory(category), MESSAGE_CONSTRAINTS); transactionCategory = category.toUpperCase(); } /** * Returns true if a given string is a valid category. */ public static boolean isValidCategory(String test) { for (CategoryEnum c : CategoryEnum.values()) { if (c.name().equalsIgnoreCase(test)) { return true; } } return false; } @Override public String toString() { return transactionCategory; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Category // instanceof handles nulls && transactionCategory.equals(((Category) other).transactionCategory)); // state check } @Override public int hashCode() { return transactionCategory.hashCode(); } }
27.736111
102
0.580871
6be3645463a38af9b7fcdd0010dba2b9897c641e
1,721
package com.trivadis.plsql.formatter; import org.junit.jupiter.api.BeforeEach; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Collectors; public abstract class AbstractTvdFormatTest { Path tempDir; @BeforeEach public void setup() { try { tempDir = Files.createTempDirectory("tvdformat-test-"); var url = Thread.currentThread().getContextClassLoader().getResource("input"); assert url != null; var resourceDir = Paths.get(url.getPath()); var sources = Files.walk(resourceDir) .filter(Files::isRegularFile) .collect(Collectors.toList()); for (Path source : sources) { var target = Paths.get(tempDir.toString() + File.separator + source.getFileName()); Files.copy(source, target); } } catch (IOException e) { throw new RuntimeException(e); } } private String getFileContent(Path file) { try { return new String(Files.readAllBytes(file)); } catch (IOException e) { throw new RuntimeException(e); } } public String getFormattedContent(String fileName) { var file = Paths.get(tempDir.toString() + File.separator + fileName); return getFileContent(file); } public String getExpectedContent(String fileName) { var url = Thread.currentThread().getContextClassLoader().getResource("expected"); assert url != null; return getFileContent(Paths.get(url.getPath() + File.separator + fileName)); } }
32.471698
99
0.62115
a5999078491db6d70d9d158b3e830832838db1a4
365
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline; import org.codehaus.jackson.annotate.JsonValue; /** * @author Jan Molak */ public class Headline { private final String value; public Headline(String value) { this.value = value; } @JsonValue public String value() { return value; } }
18.25
84
0.679452
f5a8c89483aa76ba7ef1abbfa9a701f1c3d5c35b
573
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; }
57.3
126
0.724258
ac03f89bfe6671a1137526289ca6a51b8bdeb27e
648
package org.javamaster.b2c.test.initializer; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; /** * @author yudong * @date 2020/10/23 */ @Slf4j public class CustomerApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { log.info("{},{}", configurableApplicationContext.getBeanFactory().getBeanDefinitionCount(), configurableApplicationContext.getId()); } }
36
140
0.816358
870fd1308d1117f7fd508d2de8d14dcaf2610235
2,262
package io.choerodon.iam.api.validator; import io.choerodon.core.exception.CommonException; import io.choerodon.iam.infra.dto.PasswordPolicyDTO; import io.choerodon.iam.infra.mapper.PasswordPolicyMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author wuguokai */ @Component public class PasswordPolicyValidator { @Autowired private PasswordPolicyMapper passwordPolicyMapper; public void create(Long orgId, PasswordPolicyDTO passwordPolicyDTO) { PasswordPolicyDTO dto = new PasswordPolicyDTO(); dto.setOrganizationId(orgId); if (!passwordPolicyMapper.select(dto).isEmpty()) { throw new CommonException("error.passwordPolicy.organizationId.exist"); } dto.setOrganizationId(null); dto.setCode(passwordPolicyDTO.getCode()); if (!passwordPolicyMapper.select(dto).isEmpty()) { throw new CommonException("error.passwordPolicy.code.exist"); } } public void update(Long orgId, Long passwordPolicyId, PasswordPolicyDTO passwordPolicyDTO) { PasswordPolicyDTO dto = passwordPolicyMapper.selectByPrimaryKey(passwordPolicyId); if (dto == null) { throw new CommonException("error.passwordPolicy.not.exist"); } if (!orgId.equals(dto.getOrganizationId())) { throw new CommonException("error.passwordPolicy.organizationId.not.same"); } // the sum of all the fields with least length requirement is greater than maxLength int allLeastRequiredLength = passwordPolicyDTO.getDigitsCount() + passwordPolicyDTO.getSpecialCharCount() + passwordPolicyDTO.getLowercaseCount() + passwordPolicyDTO.getUppercaseCount(); if (allLeastRequiredLength > passwordPolicyDTO.getMaxLength()) { throw new CommonException("error.allLeastRequiredLength.greaterThan.maxLength"); } if (passwordPolicyDTO.getMinLength() > passwordPolicyDTO.getMaxLength()) { throw new CommonException("error.maxLength.lessThan.minLength"); } passwordPolicyDTO.setCode(null); passwordPolicyDTO.setOrganizationId(null); } }
39
96
0.704686
00784565faf791f6d9042b120e1996e66d3e3367
15,999
/* * Copyright (C) 2018 Kweny. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kweny.carefree.mongodb; import com.mongodb.*; import com.mongodb.event.*; import com.mongodb.selector.ServerSelector; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * 根据 {@link MongoCarefreeStructure} 的配置创建 {@link MongoClientOptions.Builder}。 * * @author Kweny * @since 1.0.0 */ class _OptionBuilder { // w1 / w2 / w10 ... private static final Pattern PATTERN_WX = Pattern.compile("w(\\d+)"); // w2-10000-true / w2-10000-false private static final Pattern PATTERN_WX_TIMEOUT_JOURNAL = Pattern.compile("w(\\d+)-(\\d+)-([a-zA-Z]+)"); // secondary-[{a=0,b=1},{c=3,d=4},{e=5,f=6}]-10000 / secondary-[{a=0,b=1}] / secondary-10000 / secondary private static final Pattern PATTERN_READ_PREFERENCE = Pattern.compile("([a-zA-Z]+)(-\\[(\\{[a-zA-Z=0-9,]+}(,\\{[a-zA-Z=0-9,]+})*)?])?(-(\\d+))?"); static MongoClientOptions.Builder buildMongoClientOptions(MongoCarefreeStructure structure) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (structure.getDescription() != null) { builder.description(structure.getDescription()); } if (structure.getApplicationName() != null) { builder.applicationName(structure.getApplicationName()); } if (structure.getConnectTimeout() != null) { builder.connectTimeout(structure.getConnectTimeout()); } if (structure.getSocketTimeout() != null) { builder.socketTimeout(structure.getSocketTimeout()); } if (structure.getMaxWaitTime() != null) { builder.maxWaitTime(structure.getMaxWaitTime()); } if (structure.getMinConnectionsPerHost() != null) { builder.minConnectionsPerHost(structure.getMinConnectionsPerHost()); } if (structure.getMaxConnectionsPerHost() != null) { builder.connectionsPerHost(structure.getMaxConnectionsPerHost()); } if (structure.getMaxConnectionIdleTime() != null) { builder.maxConnectionIdleTime(structure.getMaxConnectionIdleTime()); } if (structure.getMaxConnectionLifeTime() != null) { builder.maxConnectionLifeTime(structure.getMaxConnectionLifeTime()); } if (structure.getThreadsAllowedToBlockForConnectionMultiplier() != null) { builder.threadsAllowedToBlockForConnectionMultiplier(structure.getThreadsAllowedToBlockForConnectionMultiplier()); } if (structure.getRetryWrites() != null) { builder.retryWrites(structure.getRetryWrites()); } if (structure.getAlwaysUseMBeans() != null) { builder.alwaysUseMBeans(structure.getAlwaysUseMBeans()); } if (structure.getSslEnabled() != null) { builder.sslEnabled(structure.getSslEnabled()); } if (structure.getSslInvalidHostNameAllowed() != null) { builder.sslInvalidHostNameAllowed(structure.getSslInvalidHostNameAllowed()); } if (structure.getLocalThreshold() != null) { builder.localThreshold(structure.getLocalThreshold()); } if (structure.getServerSelectionTimeout() != null) { builder.serverSelectionTimeout(structure.getServerSelectionTimeout()); } if (structure.getServerSelector() != null) { try { Class<?> clazz = Class.forName(structure.getServerSelector()); Object serverSelector = clazz.getConstructor().newInstance(); builder.serverSelector((ServerSelector) serverSelector); } catch (Exception e) { throw new IllegalArgumentException(e); } } if (structure.getRequiredReplicaSetName() != null) { builder.requiredReplicaSetName(structure.getRequiredReplicaSetName()); } if (structure.getWriteConcern() != null) { WriteConcern writeConcern = resolveWriteConcern(structure.getWriteConcern()); if (writeConcern != null) { builder.writeConcern(writeConcern); } } if (structure.getReadConcern() != null) { ReadConcern readConcern = resolveReadConcern(structure.getReadConcern()); if (readConcern != null) { builder.readConcern(readConcern); } } if (structure.getReadPreference() != null) { ReadPreference readPreference = resolveReadPreference(structure.getReadConcern()); if (readPreference != null) { builder.readPreference(readPreference); } } resolveListeners(builder, structure.getCommandListeners(), ListenerType.COMMAND); resolveListeners(builder, structure.getClusterListeners(), ListenerType.CLUSTER); resolveListeners(builder, structure.getConnectionPoolListeners(), ListenerType.CONNECTION_POOL); resolveListeners(builder, structure.getServerListeners(), ListenerType.SERVER); resolveListeners(builder, structure.getServerMonitorListeners(), ListenerType.SERVER_MONITOR); List<MongoCarefreeOptionedListener> optionedListeners = resolveOptionedListeners(structure.getOptionedListeners()); if (optionedListeners != null && optionedListeners.size() > 0) { for (MongoCarefreeOptionedListener optionedListener : optionedListeners) { optionedListener.optioned(structure, builder); } } return builder; } private static WriteConcern resolveWriteConcern(String propertyValue) { if ("w0".equalsIgnoreCase(propertyValue)) { return WriteConcern.UNACKNOWLEDGED; } else if ("w1".equalsIgnoreCase(propertyValue)) { return WriteConcern.W1; } else if ("w2".equalsIgnoreCase(propertyValue)) { return WriteConcern.W2; } else if ("w3".equalsIgnoreCase(propertyValue)) { return WriteConcern.W3; } else if ("majority".equalsIgnoreCase(propertyValue)) { return WriteConcern.MAJORITY; } else if ("journal".equalsIgnoreCase(propertyValue)) { return WriteConcern.JOURNALED; } else { String culledPropertyValue = _Assistant.deleteWhitespace(propertyValue); if (PATTERN_WX.matcher(culledPropertyValue.toLowerCase()).matches()) { String wStr = culledPropertyValue.toLowerCase().replaceAll(PATTERN_WX.pattern(), "$1"); return new WriteConcern(Integer.parseInt(wStr)); } else if (PATTERN_WX_TIMEOUT_JOURNAL.matcher(culledPropertyValue.toLowerCase()).matches()) { String wStr = culledPropertyValue.toLowerCase().replaceAll(PATTERN_WX_TIMEOUT_JOURNAL.pattern(), "$1"); String wTimeoutStr = culledPropertyValue.toLowerCase().replaceAll(PATTERN_WX_TIMEOUT_JOURNAL.pattern(), "$2"); String journalStr = culledPropertyValue.toLowerCase().replaceAll(PATTERN_WX_TIMEOUT_JOURNAL.pattern(), "$3"); int w = Integer.parseInt(wStr); int wTimeout = Integer.parseInt(wTimeoutStr); boolean journal = Boolean.parseBoolean(journalStr); return new WriteConcern(w).withWTimeout(wTimeout, TimeUnit.MILLISECONDS).withJournal(journal); } } return null; } private static ReadConcern resolveReadConcern(String propertyValue) { if ("local".equalsIgnoreCase(propertyValue)) { return ReadConcern.LOCAL; } else if ("majority".equalsIgnoreCase(propertyValue)) { return ReadConcern.MAJORITY; } else if ("linearizable".equalsIgnoreCase(propertyValue)) { return ReadConcern.LINEARIZABLE; } else if ("snapshot".equalsIgnoreCase(propertyValue)) { return ReadConcern.SNAPSHOT; } else { return null; } } private static ReadPreference resolveReadPreference(String propertyValue) { if ("primary".equalsIgnoreCase(propertyValue)) { return ReadPreference.primary(); } else if ("primaryPreferred".equalsIgnoreCase(propertyValue)) { return ReadPreference.primaryPreferred(); } else if ("secondary".equalsIgnoreCase(propertyValue)) { return ReadPreference.secondary(); } else if ("secondaryPreferred".equalsIgnoreCase(propertyValue)) { return ReadPreference.secondaryPreferred(); } else if ("nearest".equalsIgnoreCase(propertyValue)) { return ReadPreference.nearest(); } else { String culledPropertyValue = _Assistant.deleteWhitespace(propertyValue); if (PATTERN_READ_PREFERENCE.matcher(culledPropertyValue).matches()) { String mode = culledPropertyValue.replaceAll(PATTERN_READ_PREFERENCE.pattern(), "$1"); String tagSetListStr = culledPropertyValue.replaceAll(PATTERN_READ_PREFERENCE.pattern(), "$3"); String stalenessStr = culledPropertyValue.replaceAll(PATTERN_READ_PREFERENCE.pattern(), "$6"); List<TagSet> tagSetList = new ArrayList<>(); if (tagSetListStr.trim().length() > 0) { String[] tagSetElements = tagSetListStr.split(","); for (String tagSetElement : tagSetElements) { tagSetElement = tagSetElement.substring(1, tagSetElement.length() - 1); List<Tag> tagList = new ArrayList<>(); String[] tagElements = tagSetElement.split(","); for (String tagElement : tagElements) { String[] parts = tagElement.split("="); if (parts.length != 2) { throw new IllegalArgumentException("Invalid readPreference value: " + propertyValue); } Tag tag = new Tag(parts[0], parts[1]); tagList.add(tag); } if (tagList.size() > 0) { TagSet tagSet = new TagSet(tagList); tagSetList.add(tagSet); } } } Integer maxStaleness = null; if (stalenessStr.trim().length() > 0) { maxStaleness = Integer.parseInt(stalenessStr.trim()); } if ("primary".equalsIgnoreCase(mode)) { return ReadPreference.primary(); } else if ("primaryPreferred".equalsIgnoreCase(mode)) { if (tagSetList.size() > 0 && maxStaleness != null) { return ReadPreference.primaryPreferred(tagSetList, maxStaleness, TimeUnit.MILLISECONDS); } else if (tagSetList.size() > 0) { return ReadPreference.primaryPreferred(tagSetList); } else if (maxStaleness != null) { return ReadPreference.primaryPreferred(maxStaleness, TimeUnit.MILLISECONDS); } else { return ReadPreference.primaryPreferred(); } } else if ("secondary".equalsIgnoreCase(mode)) { if (tagSetList.size() > 0 && maxStaleness != null) { return ReadPreference.secondary(tagSetList, maxStaleness, TimeUnit.MILLISECONDS); } else if (tagSetList.size() > 0) { return ReadPreference.secondary(tagSetList); } else if (maxStaleness != null) { return ReadPreference.secondary(maxStaleness, TimeUnit.MILLISECONDS); } else { return ReadPreference.secondary(); } } else if ("secondaryPreferred".equalsIgnoreCase(mode)) { if (tagSetList.size() > 0 && maxStaleness != null) { return ReadPreference.secondaryPreferred(tagSetList, maxStaleness, TimeUnit.MILLISECONDS); } else if (tagSetList.size() > 0) { return ReadPreference.secondaryPreferred(tagSetList); } else if (maxStaleness != null) { return ReadPreference.secondaryPreferred(maxStaleness, TimeUnit.MILLISECONDS); } else { return ReadPreference.secondaryPreferred(); } } else if ("nearest".equalsIgnoreCase(mode)) { if (tagSetList.size() > 0 && maxStaleness != null) { return ReadPreference.nearest(tagSetList, maxStaleness, TimeUnit.MILLISECONDS); } else if (tagSetList.size() > 0) { return ReadPreference.nearest(tagSetList); } else if (maxStaleness != null) { return ReadPreference.nearest(maxStaleness, TimeUnit.MILLISECONDS); } else { return ReadPreference.nearest(); } } } } return null; } private enum ListenerType { COMMAND, CLUSTER, CONNECTION_POOL, SERVER, SERVER_MONITOR } private static void resolveListeners(MongoClientOptions.Builder builder, List<String> classNames, ListenerType type) { if (classNames == null || classNames.size() == 0) { return; } for (String className : classNames) { try { Object listener = Class.forName(className).getConstructor().newInstance(); switch (type) { case COMMAND: builder.addCommandListener((CommandListener) listener); break; case CLUSTER: builder.addClusterListener((ClusterListener) listener); break; case CONNECTION_POOL: builder.addConnectionPoolListener((ConnectionPoolListener) listener); break; case SERVER: builder.addServerListener((ServerListener) listener); break; case SERVER_MONITOR: builder.addServerMonitorListener((ServerMonitorListener) listener); break; } } catch (Exception e) { throw new IllegalArgumentException(e); } } } private static List<MongoCarefreeOptionedListener> resolveOptionedListeners(List<String> classNames) { if (classNames == null || classNames.size() == 0) { return null; } List<MongoCarefreeOptionedListener> listeners = new LinkedList<>(); for (String className : classNames) { try { Object listener = Class.forName(className).getConstructor().newInstance(); listeners.add((MongoCarefreeOptionedListener) listener); } catch (Exception e) { throw new IllegalArgumentException(e); } } return listeners; } }
46.917889
151
0.594225
1b67d5367d1878b4b5445d5c171bb3dd85e5acc7
592
package com.photowey.fx.action; import com.photowey.fx.action.layout.dialog.DialogLauncher; import javafx.application.Application; /** * FX App * * @author photowey * @date 2020/11/24 * @since 1.0.0 */ public class App { public static void main(String[] args) throws Exception { // Application.launch(Launcher.class, args); // Application.launch(BorderPaneLauncher.class, args); // Application.launch(TextFLowLauncher.class, args); // Application.launch(TileLowLauncher.class, args); Application.launch(DialogLauncher.class, args); } }
26.909091
62
0.692568
8bd154ac3e2badb5605781d4bd0497c9592f6662
1,883
/* * Copyright (c) 2011-2014 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.io.net; import reactor.fn.Consumer; import reactor.rx.Promise; import reactor.rx.Stream; /** * A network-aware client. * * @author Jon Brisbin */ public interface NetClient<IN, OUT> extends Iterable<NetChannel<IN, OUT>> { /** * Open a channel to the configured address and return a {@link reactor.rx.Promise} that will be * fulfilled with the connected {@link NetChannel}. * * @return {@link reactor.rx.Promise} that will be completed when connected */ Promise<NetChannel<IN, OUT>> open(); /** * Open a channel to the configured address and return a {@link reactor.core.composable.Stream} that will be populated * by the {@link NetChannel NetChannels} every time a connection or reconnection is made. * * @param reconnect * the reconnection strategy to use when disconnects happen * * @return */ Stream<NetChannel<IN, OUT>> open(Reconnect reconnect); /** * Close this client and the underlying channel. */ Promise<Boolean> close(); /** * Close this client and the underlying channel and invoke the given {@link reactor.fn.Consumer} when the * operation has completed. * * @param onClose * consumer to invoke when client is closed */ void close(Consumer<Boolean> onClose); }
29.421875
119
0.712693
d46e402ae8906200f49e0d4092f95092964f8930
13,370
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nylon.report; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.StringTokenizer; /** * * @author somchit */ public class iFormat { private final String[] DIGIT_TH = {"๐", "๑", "๒", "๓", "๔", "๕", "๖", "๗", "๘", "๙"}; // private String valueText; // ···········Methods·············· public String toThaiNumber(Object amountx) { String amount = String.valueOf(amountx); if (amount == null || amount.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); for (char c : amount.toCharArray()) { if (Character.isDigit(c)) { String index = DIGIT_TH[Character.getNumericValue(c)].toString(); sb.append(index); } else { sb.append(c); } } return sb.toString(); } public String toFormat(Object obj, String format) { DecimalFormat df = new DecimalFormat(format); String x = df.format(obj); return x; } public String toDate(String srtDate, String... local) { if (local.length == 0) { return toDateEng(srtDate); } if ("th".equals(local[0].toLowerCase())) { return toDateThai(srtDate); } else { return toDateEng(srtDate); } } public String toDateShort(String srtDate, String... local) { if (local.length == 0) { return toDateEngShort(srtDate); } if ("th".equals(local[0].toLowerCase())) { return toDateThaiShort(srtDate); } else { return toDateEngShort(srtDate); } } public String toDateThai(String strDate) { String Months[] = { "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"}; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); int year = 0, month = 0, day = 0; try { Date date = df.parse(strDate); Calendar c = Calendar.getInstance(); c.setTime(date); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DATE); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return String.format("%s %s %s", day, Months[month], year + 543); } public String toDateThai2(String strDate) { String Months[] = { "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"}; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); int year = 0, month = 0, day = 0; try { Date date = df.parse(strDate); Calendar c = Calendar.getInstance(); c.setTime(date); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DATE); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return String.format("%s %s พ.ศ. %s", day, Months[month], year + 543); } public String toDateThaiShort(String strDate) { String Months[] = { "ม.ค", "ก.พ", "มี.ค", "เม.ย", "พ.ค", "มิ.ย", "ก.ค", "ส.ค", "ก.ย", "ต.ค", "พ.ย", "ธ.ค"}; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); int year = 0, month = 0, day = 0; try { Date date = df.parse(strDate); Calendar c = Calendar.getInstance(); c.setTime(date); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DATE); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return String.format("%s %s %s", day, Months[month], year + 543); } public String toDateEng(String strDate) { try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); DateFormat df2 = new SimpleDateFormat("dd MMMM yyyy", Locale.US); Date date = df.parse(strDate); return df2.format(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public String toDateEngShort(String strDate) { try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); DateFormat df2 = new SimpleDateFormat("dd MMM yyyy", Locale.US); Date date = df.parse(strDate); return df2.format(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public String toThaiString(Object amountx) { String txt = amountx.toString();//String.valueOf(amountx); String bahtTxt, n, bahtTH = ""; Double amount; try { amount = Double.parseDouble(txt); } catch (Exception ex) { amount = 0.00; } try { DecimalFormat df = new DecimalFormat("####.00"); bahtTxt = df.format(amount); String[] num = {"ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "สิบ"}; String[] rank = {"", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน", "สิบล้าน", "ร้อยล้าน", "พันล้าน", "หมื่นล้าน", "แสนล้าน"}; String[] temp = bahtTxt.split("[.]"); String intVal = temp[0]; String decVal = temp[1]; if (Double.parseDouble(bahtTxt) == 0) { bahtTH = "ศูนย์บาทถ้วน"; } else { for (int i = 0; i < intVal.length(); i++) { n = intVal.substring(i, i + 1); if (n != "0") { if ((i == (intVal.length() - 1)) && (n == "1")) { bahtTH += "เอ็ด"; } else if ((i == (intVal.length() - 2)) && (n == "2")) { bahtTH += "ยี่"; } else if ((i == (intVal.length() - 2)) && (n == "1")) { bahtTH += ""; } else { bahtTH += num[Integer.parseInt(n)]; } bahtTH += rank[(intVal.length() - i) - 1]; } } bahtTH += "บาท"; if (decVal == "00") { bahtTH += "ถ้วน"; } else { for (int i = 0; i < decVal.length(); i++) { n = decVal.substring(i, i + 1); if (n != "0") { if ((i == decVal.length() - 1) && (n == "1")) { bahtTH += "เอ็ด"; } else if ((i == (decVal.length() - 2)) && (n == "2")) { bahtTH += "ยี่"; } else if ((i == (decVal.length() - 2)) && (n == "1")) { bahtTH += ""; } else { bahtTH += num[Integer.parseInt(n)]; } bahtTH += rank[(decVal.length() - i) - 1]; } } bahtTH += "สตางค์"; } } } catch (Exception exe) { System.out.print(exe.getMessage()); } return bahtTH; } private final String[] tensNames = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety" }; private final String[] numNames = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" }; // private EnglishNumberToWords() { // } private String convertLessThanOneThousand(int number) { String soFar; if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) { return soFar; } return numNames[number] + " hundred" + soFar; } // public static String toEngString(Double numberx) { // // long d=numberx.longValue(); // // long i= numberx/ Double.valueOf(d.); // long x=Long.valueOf(i+""); // // String sd=convertEngString(d); // String sx=convertEngString(x); // // return sd + " and " + sx; // } // public String toEngString(long number) { // 0 to 999 999 999 999 if (number == 0) { return "zero"; } String snumber = Long.toString(number); // pad with "0" String mask = "000000000000"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); // XXXnnnnnnnnn int billions = Integer.parseInt(snumber.substring(0, 3)); // nnnXXXnnnnnn int millions = Integer.parseInt(snumber.substring(3, 6)); // nnnnnnXXXnnn int hundredThousands = Integer.parseInt(snumber.substring(6, 9)); // nnnnnnnnnXXX int thousands = Integer.parseInt(snumber.substring(9, 12)); String tradBillions; switch (billions) { case 0: tradBillions = ""; break; case 1: tradBillions = convertLessThanOneThousand(billions) + " billion "; break; default: tradBillions = convertLessThanOneThousand(billions) + " billion "; } String result = tradBillions; String tradMillions; switch (millions) { case 0: tradMillions = ""; break; case 1: tradMillions = convertLessThanOneThousand(millions) + " million "; break; default: tradMillions = convertLessThanOneThousand(millions) + " million "; } result = result + tradMillions; String tradHundredThousands; switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1: tradHundredThousands = "one thousand "; break; default: tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand "; } result = result + tradHundredThousands; String tradThousand; tradThousand = convertLessThanOneThousand(thousands); result = result + tradThousand; // remove extra spaces! return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ").toUpperCase(); } /** * @param args */ public static void main(String[] args) { System.out.println("new iFormat().toThaiNumber(-1257000.5463) : " + new iFormat().toThaiNumber(-1257000.5463)); System.out.println("new iFormat().toFormat(1234.5463, \"#,##0.00\") : " + new iFormat().toFormat(1234.5463, "#,##0.00")); System.out.println("new iFormat().toDate(\"2016-12-31\",\"th\") : " + new iFormat().toDate("2016-12-31","th")); System.out.println("new iFormat().toDateThai2(\"2016-12-31\") : " + new iFormat().toDateThai2("2016-12-31")); System.out.println("new iFormat().toDateThaiShort(\"2016-12-31\") : " + new iFormat().toDateThaiShort("2016-12-31")); System.out.println("new iFormat().toThaiNumber(new iFormat().toDateThai2(\"2016-12-31\")) : " + new iFormat().toThaiNumber(new iFormat().toDateThai2("2016-12-31"))); System.out.println("new iFormat().toDateEng(\"2016-12-31\") : " + new iFormat().toDateEng("2016-12-31")); System.out.println("new iFormat().toDateEngShort(\"2016-12-31\") : " + new iFormat().toDateEngShort("2016-12-31")); System.out.println("new iFormat().toThaiString(123489121231.23) : " + new iFormat().toThaiString(123489121231.23)); System.out.println("new iFormat().toEngString(1234891) : " + new iFormat().toEngString(1234891)); } }
32.451456
173
0.476365
816fdf2e3be5768d0346a9651d6943cadbd5d17b
1,375
package com.packt.springboot.formhandling.blogpost; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.time.LocalDateTime; @Controller @RequestMapping("/blogposts") @Slf4j public class BlogPostController { @GetMapping("new-multiple-values") public String renderFormViewForSeparateValues(Model model) { model.addAttribute("title", "Default Title"); model.addAttribute("slug", "default-slug"); model.addAttribute("content", "I always wanted to say..."); return "blogposts/form-multiple-values"; } // Insert createBlogPostFromMultipleValues() here // Insert renderFormViewForBackingBean() // Insert createBlogPostFromBackingBean() // Insert renderFormViewForValidatedBean() // Insert createBlogPostFromValidatedBean() private BlogPost createBlogPost(String title, String slug, String content, boolean visible) { BlogPost createdBlogPost = new BlogPost( LocalDateTime.now(), title, slug, content, visible); log.info("Created blog post {}", createdBlogPost); return createdBlogPost; } }
28.645833
97
0.698909
d865e155556abd02587220f25c9faae1b6e4a8f3
1,391
package io.tornadofaces.component; import javax.faces.component.UIComponent; import javax.faces.component.behavior.ClientBehavior; import javax.faces.component.behavior.ClientBehaviorHolder; import javax.faces.context.FacesContext; import javax.faces.render.Renderer; import java.util.List; import java.util.Map; public abstract class CoreRenderer extends Renderer { public void decode(FacesContext context, UIComponent component) { decodeBehaviors(context, component); } private void decodeBehaviors(FacesContext context, UIComponent component) { if (!(component instanceof ClientBehaviorHolder)) return; Map<String, List<ClientBehavior>> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors(); if (behaviors.isEmpty()) return; Map<String, String> params = context.getExternalContext().getRequestParameterMap(); String behaviorEvent = params.get("javax.faces.behavior.event"); if (behaviorEvent != null) { List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent); if (behaviorsForEvent != null && !behaviorsForEvent.isEmpty()) { String behaviorSource = params.get("javax.faces.source"); String clientId = component.getClientId(); if (behaviorSource != null && clientId.equals(behaviorSource)) { for (ClientBehavior behavior : behaviorsForEvent) behavior.decode(context, component); } } } } }
31.613636
104
0.762761
f1059768dd32632a55d4ff12d8ba8a5dfe1a64ef
663
package co.amasel.client.reports; import io.vertx.core.Future; import co.amasel.client.common.AmaselClientException; import co.amasel.client.common.AmaselClientBase; import co.amasel.client.common.MwsApiResponse; import co.amasel.client.reports.MethodMap; import co.amasel.model.reports.*; public class ManageReportSchedule { protected AmaselClientBase client; public ManageReportSchedule(AmaselClientBase client) { this.client = client; } public Future<MwsApiResponse> invoke(ManageReportScheduleRequest request) throws AmaselClientException { return client.invoke(MethodMap.ManageReportSchedule, request); } }
27.625
108
0.776772
f6aaeef89030799e73a914d48e52923bcd1e1515
7,929
package cz.habarta.typescript.generator; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import java.io.Serializable; import java.io.StringWriter; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import static org.junit.Assert.assertEquals; import org.junit.Test; public class GenericsTest { @Test public void testAdvancedGenerics() throws Exception { final Settings settings = TestUtils.settings(); settings.outputKind = TypeScriptOutputKind.module; settings.addTypeNamePrefix = "I"; final StringWriter stringWriter = new StringWriter(); new TypeScriptGenerator(settings).generateTypeScript(Input.from(A.class), Output.to(stringWriter)); final String actual = stringWriter.toString().trim(); final String nl = settings.newline; final String expected = "export interface IA<U, V> {" + nl + " x: IA<string, string>;" + nl + " y: IA<IA<string, IB>, string[]>;" + nl + " z: IA<{ [index: string]: V }, number[]>;" + nl + "}" + nl + "" + nl + "export interface IB {" + nl + "}"; assertEquals(expected, actual); assertEquals("IA<string, string>", TestUtils.compileType(settings, A.class.getField("x").getGenericType()).toString()); assertEquals("IA<IA<string, IB>, string[]>", TestUtils.compileType(settings, A.class.getField("y").getGenericType()).toString()); assertEquals("IA<{ [index: string]: V }, number[]>", TestUtils.compileType(settings, A.class.getField("z").getGenericType()).toString()); } @Test public void testWildcardGeneric() { final Settings settings = TestUtils.settings(); settings.outputKind = TypeScriptOutputKind.module; settings.addTypeNamePrefix = "I"; final StringWriter stringWriter = new StringWriter(); new TypeScriptGenerator(settings).generateTypeScript(Input.from(C.class), Output.to(stringWriter)); final String actual = stringWriter.toString().trim(); final String nl = settings.newline; final String expected = "export interface IC {" + nl + " x: string[];" + nl + "}"; assertEquals(expected, actual); } @Test public void testNonGenericExtends() { final Settings settings = TestUtils.settings(); settings.outputKind = TypeScriptOutputKind.module; settings.sortDeclarations = true; final StringWriter stringWriter = new StringWriter(); new TypeScriptGenerator(settings).generateTypeScript(Input.from(E.class), Output.to(stringWriter)); final String actual = stringWriter.toString().trim(); final String nl = settings.newline; final String expected = "export interface D<T> {" + nl + " x: T;" + nl + "}" + nl + "" + nl + "export interface E extends D<F> {" + nl + " x: F;" + nl + "}" + nl + "" + nl + "export interface F {" + nl + "}"; assertEquals(expected, actual); } @Test public void testImplements() { final Settings settings = TestUtils.settings(); settings.outputKind = TypeScriptOutputKind.module; settings.sortDeclarations = true; settings.setExcludeFilter(Arrays.asList(Comparable.class.getName()), null); final StringWriter stringWriter = new StringWriter(); new TypeScriptGenerator(settings).generateTypeScript(Input.from(IA.class), Output.to(stringWriter)); final String actual = stringWriter.toString().trim(); final String nl = settings.newline; final String expected = "export interface IA extends IB<string> {" + nl + " type: string;" + nl + " x: string;" + nl + "}" + nl + "" + nl + "export interface IB<T> {" + nl + " type: string;" + nl + " x: T;" + nl + "}"; assertEquals(expected, actual); } @Test public void testGenericsWithoutTypeArgument() { final Settings settings = TestUtils.settings(); final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Table.class, Page1.class, Page2.class)); final String expected = "interface Table<T> {\n" + " rows: T[];\n" + "}\n" + "\n" + "interface Page1 {\n" + " stringTable: Table<string>;\n" + "}\n" + "\n" + "interface Page2 {\n" + " someTable: Table<any>;\n" + "}"; assertEquals(expected, output.trim()); } @Test public void testGenericArray() { final Settings settings = TestUtils.settings(); final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(TableGA.class)); final String expected = "interface TableGA<T> {\n" + " rows: T[];\n" + "}"; assertEquals(expected, output.trim()); } @Test public void testArbitraryGenericParameter() { final Settings settings = TestUtils.settings(); final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ExecutionResult.class)); final String expected = "interface ExecutionResult {\n" + " data: number;\n" + "}"; assertEquals(expected, output.trim()); } class A<U,V> { public A<String, String> x; public A<A<String, B>, List<String>> y; public A<Map<String, V>, Set<Integer>> z; } class B { } class C { public List<? extends String> x; } class D<T> { public T x; } class E extends D<F> { } class F { } abstract class IA implements IB<String>, Comparable<IA> { } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", include = As.PROPERTY, visible = false) interface IB<T> { public T getX(); } class Table<T> { public List<T> rows; } class Page1 { public Table<String> stringTable; } class Page2 { @SuppressWarnings("rawtypes") public Table someTable; } class TableGA<T> { public T[] rows; } interface ExecutionResult { public <T extends Number> T getData(); } @Test public void testSpecificTypeInGeneratedClass() { final Settings settings = TestUtils.settings(); settings.outputFileType = TypeScriptFileType.implementationFile; settings.outputKind = TypeScriptOutputKind.module; settings.mapClasses = ClassMapping.asClasses; final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Entity1View.class)); Assert.assertTrue(output.contains("" + "export class Entity1View implements Entity1IdView {\n" + " id: MyId;\n" + " name: string;\n" + "}")); Assert.assertTrue(output.contains("export class MyId")); } public static class MyId implements Serializable { private static final long serialVersionUID = 1L; } public interface IdView<T extends Serializable> { T getId(); } public interface Entity1IdView extends IdView<MyId> { } public static abstract class Entity1View implements Entity1IdView { public String name; } }
34.030043
145
0.575482
32493c4411341c90088fe989e8b9f5113496bef9
548
import java.util.*; import java.util.regex.*; public class A4qno6 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.nextLine(); Pattern p=Pattern.compile("\\w+"); Matcher m=p.matcher(str); while(m.find()) { Pattern p1=Pattern.compile("^[\\w]"); Matcher m1=p1.matcher(m.group(0)); while(m1.find()) { System.out.print(m1.group(0)); } } // Pattern p=Pattern.compile("\\b[a-zA-Z]"); // Matcher m=p.matcher(str); // while(m.find()) { // System.out.print(m.group(0)); // } } }
24.909091
45
0.614964
bd14656f25b279ac215218ecf29cae469b9e7d8d
20,146
/******************************************************************************* * Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ /** Copyright (C) 2017 T Mobile Inc - All Rights Reserve Purpose: Author :santoshi Modified Date: Jul 10, 2018 **/ package com.tmobile.pacman.api.notification.service; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.util.ReflectionTestUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.tmobile.pacman.api.notification.client.ComplianceServiceClient; import com.tmobile.pacman.api.notification.client.StatisticsServiceClient; import com.tmobile.pacman.api.notification.domain.Response; @RunWith(PowerMockRunner.class) public class AssetGroupEmailServiceTest { @InjectMocks AssetGroupEmailService assetGroupEmailService; @Mock private NotificationService notificationService; @Mock private MailService mailService; @Mock private ComplianceServiceClient complianceServiceClient; @Mock @Autowired private StatisticsServiceClient statisticsServiceClient; @Value("${template.digest-mail.url}") private String mailTemplateUrl; @Test public void executeEmailServiceForAssetGroupTest(){ List<Map<String, Object>> ownerEmailDetails=new ArrayList<Map<String,Object>>(); Map<String,Object>ownerDetails=new HashMap<>(); ownerDetails.put("ownerName", "jack"); ownerDetails.put("assetGroup", "aws-all"); ownerDetails.put("ownerEmail", "[email protected]"); ownerDetails.put("ownerName", "jack"); ownerEmailDetails.add(ownerDetails); Map<String,Object>patchingDetails=new HashMap<>(); patchingDetails.put("unpatched_instances", 0); patchingDetails.put("patched_instances", 5816); patchingDetails.put("total_instances", 5816); patchingDetails.put("patching_percentage", 100); Response patchingResponse = new Response(); patchingResponse.setData(patchingDetails); Map<String,Object>certificateDetails=new HashMap<>(); certificateDetails.put("certificates", 1284); certificateDetails.put("certificates_expiring", 0); Response CertificateResponse = new Response(); CertificateResponse.setData(certificateDetails); Map<String,Object> taggingDetails=new HashMap<>(); taggingDetails.put("assets", 122083); taggingDetails.put("untagged", 47744); taggingDetails.put("tagged", 74339); taggingDetails.put("compliance", 60); Response taggingResponse = new Response(); taggingResponse.setData(taggingDetails); Map<String,Object> vulnerabilityDetails=new HashMap<>(); vulnerabilityDetails.put("hosts", 6964); vulnerabilityDetails.put("vulnerabilities", 94258); vulnerabilityDetails.put("totalVulnerableAssets", 5961); Response vulnerabilityResponse = new Response(); vulnerabilityResponse.setData(taggingDetails); Map<String,Object> complianceStats=new HashMap<>(); complianceStats.put("hosts", 6964); complianceStats.put("vulnerabilities", 94258); complianceStats.put("totalVulnerableAssets", 5961); Response complianceStatsResponse = new Response(); complianceStatsResponse.setData(complianceStats); Map<String,Object> topNonCompliant = new HashMap<>(); topNonCompliant.put("hosts", 6964); topNonCompliant.put("vulnerabilities", 94258); topNonCompliant.put("totalVulnerableAssets", 5961); Response topNonCompliantAppsResponse = new Response(); topNonCompliantAppsResponse.setData(topNonCompliant); Map<String, Object> responseDetails = Maps.newHashMap(); responseDetails.put("application", "application123"); List<Map<String, Object>> response = Lists.newArrayList(); response.add(responseDetails); Map<String,Object> applicationNames = new HashMap<>(); applicationNames.put("response", response); applicationNames.put("vulnerabilities", 94258); applicationNames.put("totalVulnerableAssets", 5961); Response applicationNamesResponse = new Response(); applicationNamesResponse.setData(applicationNames); Map<String,Object> issueDetails = new HashMap<>(); issueDetails.put("hosts", 6964); issueDetails.put("vulnerabilities", 94258); issueDetails.put("totalVulnerableAssets", 5961); Response issueDetailsResponse = new Response(); issueDetailsResponse.setData(issueDetails); issueDetailsResponse.setMessage("message"); assertTrue(issueDetailsResponse.getMessage().equals("message")); ReflectionTestUtils.setField(assetGroupEmailService, "mailTemplateUrl", mailTemplateUrl); when(complianceServiceClient.getPatching(anyString())).thenReturn(patchingResponse); when(complianceServiceClient.getCertificates(anyString())).thenReturn(CertificateResponse); when(complianceServiceClient.getTagging(anyString())).thenReturn(taggingResponse); when(statisticsServiceClient.getComplianceStats(anyString())).thenReturn(complianceStatsResponse); when(complianceServiceClient.getVulnerabilities(anyString())).thenReturn(vulnerabilityResponse); when(complianceServiceClient.getTopNonCompliantApps(anyString())).thenReturn(topNonCompliantAppsResponse); when(complianceServiceClient.getVulnerabilityByApplications(anyString())).thenReturn(applicationNamesResponse); when(complianceServiceClient.getDistribution(anyString())).thenReturn(issueDetailsResponse); when(notificationService.getAllAssetGroupOwnerEmailDetails()).thenReturn(ownerEmailDetails); assetGroupEmailService.executeEmailServiceForAssetGroup(); } @Test public void sendDigestMail1(){ List<Map<String, Object>> ownerEmailDetails=new ArrayList<Map<String,Object>>(); Map<String,Object>ownerDetails=new HashMap<>(); ownerDetails.put("ownerName", "jack"); ownerDetails.put("assetGroup", "aws-all"); ownerDetails.put("ownerEmail", "[email protected]"); ownerDetails.put("ownerName", "jack"); ownerEmailDetails.add(ownerDetails); Map<String,Object>patchingDetails=new HashMap<>(); patchingDetails.put("unpatched_instances", 0); patchingDetails.put("patched_instances", 5816); patchingDetails.put("total_instances", 5816); patchingDetails.put("patching_percentage", 100); patchingDetails.put("output", getOutput()); Response patchingResponse = new Response(); patchingResponse.setData(patchingDetails); Map<String,Object>certificateDetails=new HashMap<>(); certificateDetails.put("certificates", 1284); certificateDetails.put("certificates_expiring", 0); certificateDetails.put("output", getOutput()); Response CertificateResponse = new Response(); CertificateResponse.setData(certificateDetails); Map<String,Object> taggingDetails=new HashMap<>(); taggingDetails.put("assets", 122083); taggingDetails.put("untagged", 47744); taggingDetails.put("tagged", 74339); taggingDetails.put("compliance", 60); taggingDetails.put("output", getOutput()); Response taggingResponse = new Response(); taggingResponse.setData(taggingDetails); Map<String,Object> vulnerabilityDetails=new HashMap<>(); vulnerabilityDetails.put("hosts", 6964); vulnerabilityDetails.put("vulnerabilities", 94258); vulnerabilityDetails.put("totalVulnerableAssets", 5961); vulnerabilityDetails.put("output", getOutput()); Response vulnerabilityResponse = new Response(); vulnerabilityResponse.setData(taggingDetails); Map<String,Object> complianceStats=new HashMap<>(); complianceStats.put("hosts", 6964); complianceStats.put("vulnerabilities", 94258); complianceStats.put("totalVulnerableAssets", 5961); complianceStats.put("output", getOutput()); Map<String, Double> compliant = Maps.newHashMap(); compliant.put("overall_compliance", 1234d); compliant.put("patch_compliance", 1234d); compliant.put("vuln_compliance", 1234d); compliant.put("tag_compliance", 1234d); compliant.put("cert_compliance", 1234d); complianceStats.put("compliance_stats", compliant); Response complianceStatsResponse = new Response(); complianceStatsResponse.setData(complianceStats); Map<String, Object> responsetopNonCompliantDetails = Maps.newHashMap(); responsetopNonCompliantDetails.put("application", "application123"); List<Map<String, Object>> topNonCompliantResponse = Lists.newArrayList(); topNonCompliantResponse.add(responsetopNonCompliantDetails); Map<String,Object> topNonCompliant = new HashMap<>(); topNonCompliant.put("response", topNonCompliantResponse); topNonCompliant.put("hosts", 6964); topNonCompliant.put("vulnerabilities", 94258); topNonCompliant.put("totalVulnerableAssets", 5961); Response topNonCompliantAppsResponse = new Response(); topNonCompliantAppsResponse.setData(topNonCompliant); Map<String, Object> responseDetails = Maps.newHashMap(); responseDetails.put("application", "application123"); List<Map<String, Object>> response = Lists.newArrayList(); response.add(responseDetails); Map<String,Object> applicationNames = new HashMap<>(); applicationNames.put("response", response); applicationNames.put("hosts", 6964); applicationNames.put("vulnerabilities", 94258); applicationNames.put("totalVulnerableAssets", 5961); Response applicationNamesResponse = new Response(); applicationNamesResponse.setData(applicationNames); Map<String,Object> issueDetails = new HashMap<>(); issueDetails.put("hosts", 6964); issueDetails.put("vulnerabilities", 94258); issueDetails.put("totalVulnerableAssets", 5961); Map<String, Object> issueDistributionDetails = Maps.newHashMap(); Map<String, Integer> distributionBySeverity = Maps.newHashMap(); distributionBySeverity.put("critical", 1233); issueDistributionDetails.put("distribution_by_severity", Maps.newHashMap()); issueDetails.put("distribution", Maps.newHashMap()); Response issueDetailsResponse = new Response(); issueDetailsResponse.setData(issueDetails); issueDetailsResponse.setMessage("message"); assertTrue(issueDetailsResponse.getMessage().equals("message")); ReflectionTestUtils.setField(assetGroupEmailService, "mailTemplateUrl", mailTemplateUrl); when(complianceServiceClient.getPatching(anyString())).thenReturn(patchingResponse); when(complianceServiceClient.getCertificates(anyString())).thenReturn(CertificateResponse); when(complianceServiceClient.getTagging(anyString())).thenReturn(taggingResponse); when(statisticsServiceClient.getComplianceStats(anyString())).thenReturn(complianceStatsResponse); when(complianceServiceClient.getVulnerabilities(anyString())).thenReturn(vulnerabilityResponse); when(complianceServiceClient.getTopNonCompliantApps(anyString())).thenReturn(topNonCompliantAppsResponse); when(complianceServiceClient.getVulnerabilityByApplications(anyString())).thenReturn(applicationNamesResponse); when(complianceServiceClient.getDistribution(anyString())).thenReturn(issueDetailsResponse); when(notificationService.getAllAssetGroupOwnerEmailDetails()).thenReturn(ownerEmailDetails); assetGroupEmailService.sendDigestMail("assetGroupName", "ownerName", "ownerEmail", "mainTemplateUrl", "domainUrl"); } @Test public void sendDigestMail(){ List<Map<String, Object>> ownerEmailDetails=new ArrayList<Map<String,Object>>(); Map<String,Object>ownerDetails=new HashMap<>(); ownerDetails.put("ownerName", "jack"); ownerDetails.put("assetGroup", "aws-all"); ownerDetails.put("ownerEmail", "[email protected]"); ownerDetails.put("ownerName", "jack"); ownerEmailDetails.add(ownerDetails); Map<String,Object>patchingDetails=new HashMap<>(); patchingDetails.put("unpatched_instances", 0); patchingDetails.put("patched_instances", 5816); patchingDetails.put("total_instances", 5816); patchingDetails.put("patching_percentage", 100); patchingDetails.put("output", getOutput()); Response patchingResponse = new Response(); patchingResponse.setData(patchingDetails); Map<String,Object>certificateDetails=new HashMap<>(); certificateDetails.put("certificates", 1284); certificateDetails.put("certificates_expiring", 0); certificateDetails.put("output", getOutput()); Response CertificateResponse = new Response(); CertificateResponse.setData(certificateDetails); Map<String,Object> taggingDetails=new HashMap<>(); taggingDetails.put("assets", 122083); taggingDetails.put("untagged", 47744); taggingDetails.put("tagged", 74339); taggingDetails.put("compliance", 60); taggingDetails.put("output", getOutput()); Response taggingResponse = new Response(); taggingResponse.setData(taggingDetails); Map<String,Object> vulnerabilityDetails=new HashMap<>(); vulnerabilityDetails.put("hosts", 6964); vulnerabilityDetails.put("vulnerabilities", 94258); vulnerabilityDetails.put("totalVulnerableAssets", 5961); vulnerabilityDetails.put("output", getOutput()); Response vulnerabilityResponse = new Response(); vulnerabilityResponse.setData(taggingDetails); Map<String,Object> complianceStats=new HashMap<>(); complianceStats.put("hosts", 6964); complianceStats.put("vulnerabilities", 94258); complianceStats.put("totalVulnerableAssets", 5961); complianceStats.put("output", getOutput()); Map<String, Double> compliant = Maps.newHashMap(); compliant.put("overall_compliance", 1234d); compliant.put("patch_compliance", 1234d); compliant.put("vuln_compliance", 1234d); compliant.put("tag_compliance", 1234d); compliant.put("cert_compliance", 1234d); complianceStats.put("compliance_stats", compliant); Response complianceStatsResponse = new Response(); complianceStatsResponse.setData(complianceStats); Map<String, Object> responsetopNonCompliantDetails = Maps.newHashMap(); responsetopNonCompliantDetails.put("application", "application123"); List<Map<String, Object>> topNonCompliantResponse = Lists.newArrayList(); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); topNonCompliantResponse.add(responsetopNonCompliantDetails); Map<String,Object> topNonCompliant = new HashMap<>(); topNonCompliant.put("response", topNonCompliantResponse); topNonCompliant.put("hosts", 6964); topNonCompliant.put("vulnerabilities", 94258); topNonCompliant.put("totalVulnerableAssets", 5961); Response topNonCompliantAppsResponse = new Response(); topNonCompliantAppsResponse.setData(topNonCompliant); Map<String, Object> responseDetails = Maps.newHashMap(); responseDetails.put("application", "application123"); List<Map<String, Object>> response = Lists.newArrayList(); response.add(responseDetails); Map<String,Object> applicationNames = new HashMap<>(); applicationNames.put("response", response); applicationNames.put("hosts", 6964); applicationNames.put("vulnerabilities", 94258); applicationNames.put("totalVulnerableAssets", 5961); Response applicationNamesResponse = new Response(); applicationNamesResponse.setData(applicationNames); Map<String,Object> issueDetails = new HashMap<>(); issueDetails.put("hosts", 6964); issueDetails.put("vulnerabilities", 94258); issueDetails.put("totalVulnerableAssets", 5961); Map<String, Object> issueDistributionDetails = Maps.newHashMap(); Map<String, Integer> distributionBySeverity = Maps.newHashMap(); distributionBySeverity.put("critical", 1233); issueDistributionDetails.put("distribution_by_severity", distributionBySeverity); issueDetails.put("distribution", issueDistributionDetails); Response issueDetailsResponse = new Response(); issueDetailsResponse.setData(issueDetails); issueDetailsResponse.setMessage("message"); assertTrue(issueDetailsResponse.getMessage().equals("message")); ReflectionTestUtils.setField(assetGroupEmailService, "mailTemplateUrl", mailTemplateUrl); when(complianceServiceClient.getPatching(anyString())).thenReturn(patchingResponse); when(complianceServiceClient.getCertificates(anyString())).thenReturn(CertificateResponse); when(complianceServiceClient.getTagging(anyString())).thenReturn(taggingResponse); when(statisticsServiceClient.getComplianceStats(anyString())).thenReturn(complianceStatsResponse); when(complianceServiceClient.getVulnerabilities(anyString())).thenReturn(vulnerabilityResponse); when(complianceServiceClient.getTopNonCompliantApps(anyString())).thenReturn(topNonCompliantAppsResponse); when(complianceServiceClient.getVulnerabilityByApplications(anyString())).thenReturn(applicationNamesResponse); when(complianceServiceClient.getDistribution(anyString())).thenReturn(issueDetailsResponse); when(notificationService.getAllAssetGroupOwnerEmailDetails()).thenReturn(ownerEmailDetails); assetGroupEmailService.sendDigestMail("assetGroupName", "ownerName", "ownerEmail", "mainTemplateUrl", "domainUrl"); } private Map<String, Integer> getOutput() { Map<String, Integer> output = Maps.newHashMap(); output.put("unpatched_instances", 123); output.put("total_instances", 123); output.put("assets", 123); output.put("hosts", 123); output.put("certificates", 123); output.put("vulnerabilities", 123); output.put("untagged", 123); output.put("certificates_expiring", 123); return output; } }
48.311751
120
0.715477
d50f1f503442d010724930b5a3170df90e232cce
11,263
package kasirgalabs; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.Socket; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.JProgressBar; /** * This class contains methods for FoxProject's client side application. Main * purpose of this class is to satisfy the requirements of FoxProject. * <p> * This class is used to send usage data to a remote host along with the user * information. Some methods in this class are used to establish a connection * with a remote host, modify and send files, they can also be used to verify * the name, surname and id for an exam attendance of a student. * <p> * Some methods use {@link java.net.Socket} to connect to a remote host and may * send or receive data.<br> * {@link #createZipFile(java.io.File[]) createZipFile(File[] files)} method may * modify some files. */ public class FoxClientUtilities { /** * Check in a student or establish a reconnection to a predefined host. This * method uses {@link java.net.Socket} class to connect to a host. * <p> * Method parameters are saved in instance variables for further use. * * @param name The student name. * @param surname The student surname. * @param id The student id. * @param exam The exam name. * * @return The status of the check in; returns 0 if exam folder is missing * in remote host, 1 if reconnection is successful, 2 if check in is * successful, returns -1 if an error occurred. * * @throws java.io.IOException If an I/O error occurs when creating socket, * reading from socket, or sending to socket. */ public int checkIn(String name, String surname, String id, String exam) throws IOException { if(name == null || surname == null || id == null || exam == null) { throw new NullPointerException(); } // Save informations to instance variables. // Connect to the host. Socket socket = new Socket(MainClient.getIpAddress(), 50101); DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF("Check in"); // Tell host which operation will occur. // Send informations to the host. out.writeUTF(name); out.writeUTF(surname); out.writeUTF(id); out.writeUTF(exam); out.flush(); String status = in.readUTF(); // Read status code of check in. if(status != null) { char c = status.charAt(0); return Character.getNumericValue(c); } socket.close(); return -1; } /** * Verifies the enrollment of a student by connecting to a predefined host * This method uses {@link java.net.Socket} object to connect to the host. * <p> * Implementation note: Student informations are stored in instance * variables. Before using this method, * {@link #checkIn(java.lang.String, java.lang.String, * java.lang.String, java.lang.String)} * method must be used to store them. If not, returns -1. * * @param instructorKey The instructor key * * @return Returns 0 if exam folder or key file is missing in remote host, * returns 1 if key is accepted, returns 2 if key is not accepted, * returns -1 if an error is occurred. * * @throws java.io.IOException If an I/O error occurs when creating socket, * reading from socket, or sending to socket. */ public int verifyInstructorKey(String name, String surname, String id, String exam, String instructorKey) throws IOException { if(name == null || surname == null || id == null || exam == null || instructorKey == null) { return -1; } // Connect to the host. Socket socket = new Socket(MainClient.getIpAddress(), 50101); DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF("Key verify"); // Tell host which operation will occur. // Send informations. out.writeUTF(name); out.writeUTF(surname); out.writeUTF(id); out.writeUTF(exam); out.writeUTF(instructorKey); out.flush(); String status = in.readUTF(); // Read the status code. if(status != null) { char c = status.charAt(0); return Character.getNumericValue(c); } socket.close(); return -1; } /** * Requests the available exam list from a predefined host. * * @return Each element of the array list represents an exam. Returns null * if there is no exam. * * @throws java.lang.ClassNotFoundException Class of a serialized object * cannot be found. * @throws java.io.IOException Any of the usual I/O related * exceptions. * @see Exam */ public Exam[] availableExams() throws IOException, ClassNotFoundException { Socket socket = null; Exam[] examList = null; try { // Connect to the host. socket = new Socket(MainClient.getIpAddress(),50101); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); // Tell host which operation will occur. out.writeUTF("List exams"); out.flush(); ObjectInputStream ois = new ObjectInputStream( socket.getInputStream()); Object examListObject = ois.readObject(); examList = (Exam[]) examListObject; } catch(IOException | ClassNotFoundException e) { throw e; } finally { if(socket != null) { socket.close(); } } return examList; } /** * Creates a zip file on the current working directory which contains * file(s) specified with the parameter. Original files will not be moved * and their contents will not be changed. * <p> * The name of the zip file will be same with the first {@link java.io.File} * object's name specified with the parameter. If the file already exists it * will be overwritten. * * @param files Array list of {@link java.io.File} objects, which will be * zipped. All files must be in the current working directory. * * @return The name of the zip file. * * @throws FileNotFoundException File with the specified pathname does not * exist or is a directory. * @throws IOException If an I/O error occurs. */ public String createZipFile(File[] files) throws FileNotFoundException, IOException { String zipFileName = files[0].getName(); int pos = zipFileName.lastIndexOf('.'); if(pos > 0) { zipFileName = zipFileName.substring(0, pos) + ".zip"; } else { zipFileName = zipFileName + ".zip"; } FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); String fileName; for(File file : files) { fileName = file.getName(); FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); byte[] buffer = new byte[4096]; int length; while((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); return zipFileName; } /** * Sends a file to a predefined host by creating a {@link java.net.Socket} * object. On success returns the MD5 checksum of the file. * * @param fileName Relative path name of the file for current working * directory. * @param id The student id. * @param exam The exam name. * @param object * * @return Checksum of the file. * * @throws java.io.FileNotFoundException If the file does not exist, is a * directory rather than a regular * file, or for some other reason * cannot be opened for reading. * @throws java.lang.SecurityException If a security manager exists and * its checkRead method denies read * access to the file. * @throws java.io.IOException If an I/O error occurs. */ public String sendFile(String fileName, String id, String exam, Object object) throws FileNotFoundException, SecurityException, IOException { // Create a socket and initialize it's streams. // Create a socket and initialize it's streams. JProgressBar jpb = (JProgressBar) object; Socket socket = new Socket(MainClient.getIpAddress(), 50101); DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF("Sending file"); out.writeUTF(fileName); out.writeUTF(id); out.writeUTF(exam); out.flush(); // Read file and send it over the socket. long fileSize = new File(fileName).length(); FileInputStream fileIn = new FileInputStream(fileName); OutputStream os_out = socket.getOutputStream(); long sentBytes = 0; int progress = 0; int bytesCount; byte[] fileData = new byte[1024]; do { bytesCount = fileIn.read(fileData); if(bytesCount > 0) { os_out.write(fileData, 0, bytesCount); sentBytes += bytesCount; if(sentBytes >= fileSize / 100) { sentBytes = 0; jpb.setValue(progress++); } } } while(bytesCount > 0); if(progress != 100) // Check if remainder exists. { jpb.setValue(100); } os_out.flush(); // Shut down output to tell server no more data. socket.shutdownOutput(); String checksum; if(in.readUTF().equals("Exam file is found.")) { checksum = in.readUTF(); //Read checksum from socket. } else { checksum = null; } fileIn.close(); socket.close(); return checksum; } }
38.179661
82
0.585723
590a1ec205bae95d925ba75f61604bfdf070ec47
475
package me.interview.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @Entity @DiscriminatorValue(value="CATEGORY") public class Category extends OptionValue { private static final long serialVersionUID = -6491132286349017021L; public Category() { } public Category(String name) { super(name); } }
21.590909
68
0.793684
4c513e31f8136837840b4fb3fb9a28bef36b93ff
1,441
package com.github.brunoais.xpath_to_xml.parsing; import java.util.ArrayList; import org.apache.commons.jxpath.ri.compiler.Constant; import org.apache.commons.jxpath.ri.compiler.CoreOperationEqual; import org.apache.commons.jxpath.ri.compiler.Expression; import org.apache.commons.jxpath.ri.compiler.LocationPath; import org.apache.commons.jxpath.ri.compiler.NodeNameTest; import org.apache.commons.jxpath.ri.compiler.Step; public class GatherRequiredPaths { private ArrayList<String> paths; private ArrayList<String> currentPath; public GatherRequiredPaths() { paths = new ArrayList<String>(); currentPath = new ArrayList<String>(); } public void addPath(LocationPath path) { Step[] steps = path.getSteps(); for (Step step : steps) { stepSolve(step); } } private void stepSolve(Step step) { StepSolver solver = new StepSolver(currentPath, step); } private void resolvePredicates(Expression[] predicates) { for (Expression predicate : predicates) { if (predicate instanceof CoreOperationEqual) { CoreOperationEqual equalPredicate = (CoreOperationEqual) predicate; for (Expression calculationArgument : equalPredicate.getArguments()) { if (calculationArgument instanceof LocationPath) { // Compiler.NODE_TYPE_TEXT // ^ text node pathMade2 = pathMade + calculationArgument.toString(); } else if (predicate instanceof Constant) { } } } } }
24.844828
74
0.739764
18491442db22f43a921872b6bd4668ac83f8447f
758
package baseball.controller; import baseball.utils.AnswerNumberFactory; import baseball.utils.HintFactory; import baseball.utils.PlayerNumberFactory; import baseball.utils.TerminateUtil; import baseball.models.AnswerNumber; import baseball.models.PlayerNumber; import baseball.view.InputView; public class GameController { private GameController() { } public static void controlGame() { AnswerNumber answerNumber = AnswerNumberFactory.createRandomNumber(); while (true) { PlayerNumber playerNumber = PlayerNumberFactory.createPlayerNumber(InputView.getInputNumber()); HintFactory.makeHint(answerNumber, playerNumber); if (TerminateUtil.correctAnswer(answerNumber, playerNumber)) { TerminateUtil.finishGame(); break; } } } }
27.071429
98
0.796834
bad88826efcebe814265edb55576e4d5186b0842
9,655
package com.bluegosling.collections.queues; import java.util.AbstractQueue; import java.util.Comparator; import java.util.Iterator; import java.util.Queue; import com.bluegosling.collections.CollectionUtils; import com.bluegosling.collections.queues.PriorityQueue.Entry; /** * Utility methods for working with instances of {@link PriorityQueue} (not to be mistaken for * {@link java.util.PriorityQueue}). * * <p>The meat of this class includes a {@linkplain AutoEntry useful base class} for value types * that are stored into priority queues, and methods for adapting a priority queue to the standard * {@link Queue} interface. * * @author Joshua Humphries ([email protected]) */ // TODO: tests public final class PriorityQueues { private PriorityQueues() { } /** * A type of value that automatically associates itself with a queue entry when added to a * {@link PriorityQueue}. This only works when using the object's {@link #add} method. * * <p>This can be very useful since sophisticated usage of a {@link PriorityQueue} requires * keeping track of an {@link Entry} after adding a value to the queue. A common pattern is to * store a reference to the associated entry in the actual value, after it is added to the queue. * This class encapsulates that pattern. * * <p>To use, extend this class and add fields that represent the actual object/state being added * to a queue. Always use the object's {@link #add} method (instead of using the queue's * {@link PriorityQueue#add} method). This class also provides utility methods for interacting * with the queue, like for removing the entry or changing its priority. * * @param <P> the type of priority associated with this object * @param <E> the type of this object * * @author Joshua Humphries ([email protected]) */ public abstract class AutoEntry<P, E extends AutoEntry<P, E>> { private Entry<E, P> entry; /** * Gets the element's associated queue entry. This will be {@code null} if the object has * never been {@linkplain #add(Object, PriorityQueue) added to a queue}. * * @return the element's associated queue entry */ protected Entry<E, P> getEntry() { return entry; } /** * Adds this element to the given queue with the given priority. The element can only be * associated with one queue at any given time. If the object needs to be added to a different * queue, it must first be {@linkplain #remove() removed}. * * @param priority the priority for this object * @param queue the queue into which the object will be added * @throws IllegalStateException if the object is already associated with a queue */ public void add(P priority, PriorityQueue<E, P> queue) { if (entry != null) { throw new IllegalStateException("This entry is already associated with another queue"); } @SuppressWarnings("unchecked") // if this class is sub-classes correctly, this is safe E element = (E) this; entry = queue.add(element, priority); } /** * Removes the object from the queue that contains it. * * @throws IllegalStateException if this object has never been {@linkplain * #add(Object, PriorityQueue) added} to a queue or has already been removed */ public void remove() { if (entry == null) { throw new IllegalStateException("This entry is not associated with a queue"); } entry.remove(); entry = null; } /** * Changes the priority associated with this object. The priority is initially assigned when * the element is added to a queue. * * @throws IllegalStateException if this object has never been {@linkplain * #add(Object, PriorityQueue) added} to a queue or has already been removed */ public void setPriority(P priority) { if (entry == null) { throw new IllegalStateException("This entry is not associated with a queue"); } entry.setPriority(priority); } /** * Gets the priority associated with this object. The priority is initially assigned when * the element is added to a queue. * * @return the priority associated with this object * @throws IllegalStateException if this object has never been {@linkplain * #add(Object, PriorityQueue) added} to a queue or has already been removed */ public P getPriority() { if (entry == null) { throw new IllegalStateException("This entry is not associated with a queue"); } return entry.getPriority(); } } /** * Returns a view of a {@link PriorityQueue} as an {@link OrderedQueue}. The elements in the * queue have intrinsic priority instead of a separate explicit priority. So when added to the * given queue, the priority value is the same as the element value. * * @param priorityQueue a priority queue * @return a view of the given priority queue as a {@link OrderedQueue} */ public static <E> OrderedQueue<E> asQueue(PriorityQueue<E, E> priorityQueue) { return new QueueImpl<>(priorityQueue); } /** * A simple meldable ordered queue. You can attempt to meld it with any other instance of * {@link MeldableQueue}. A runtime exception will be thrown if the two queues are not actually * of compatible types for melding. * * @param <E> the type * @author Joshua Humphries ([email protected]) */ public interface MeldableQueue<E> extends MeldableOrderedQueue<E, MeldableQueue<? extends E>> { } /** * Returns a view of a {@link MeldablePriorityQueue} as a {@link MeldableOrderedQueue}. The * elements in the queue have intrinsic priority instead of a separate explicit priority. So when * added to the given queue, the priority value is the same as the element value. Attempting to * meld the returned queue with another whose underlying priority queue is not actually meldable * will also result in a {@link ClassCastException}. * * @param priorityQueue a priority queue * @return a view of the given priority queue as a {@link MeldableOrderedQueue} */ public static <E, Q extends MeldablePriorityQueue<E, E, Q>> MeldableQueue<E> asQueue(Q priorityQueue) { return new MeldableQueueImpl<>(priorityQueue); } /** * An {@link OrderedQueue}, implemented on top of a {@link PriorityQueue}. * * @param <E> the type of elements in the queue * @param <P> the type of priorities associated with elements in the queue * * @author Joshua Humphries ([email protected]) */ private static class QueueImpl<E> extends AbstractQueue<E> implements OrderedQueue<E> { final PriorityQueue<E, E> priorityQueue; QueueImpl(PriorityQueue<E, E> priorityQueue) { this.priorityQueue = priorityQueue; } @Override public boolean offer(E e) { return priorityQueue.offer(e, e) != null; } @Override public E poll() { Entry<E, E> entry = priorityQueue.poll(); return entry == null ? null : entry.getElement(); } @Override public E peek() { Entry<E, E> entry = priorityQueue.peek(); return entry == null ? null : entry.getElement(); } @Override public boolean contains(Object o) { return priorityQueue.elements().contains(o); } @Override public boolean remove(Object o) { return priorityQueue.elements().remove(o); } @Override public void clear() { priorityQueue.clear(); } @Override public Comparator<? super E> comparator() { return priorityQueue.comparator(); } @Override public String toString() { return CollectionUtils.toString(this); } @Override public Iterator<E> iterator() { return priorityQueue.elements().iterator(); } @Override public int size() { return priorityQueue.size(); } } /** * A {@linkplain MeldableOrderedQueue meldable} version of {@link QueueImpl}. * * @param <E> the type of elements in the queue * @param <P> the type of priorities associated with elements in the queue * * @author Joshua Humphries ([email protected]) */ private static class MeldableQueueImpl<E> extends QueueImpl<E> implements MeldableQueue<E> { <Q extends MeldablePriorityQueue<E, E, Q>> MeldableQueueImpl(Q priorityQueue) { super(priorityQueue); } @Override public boolean mergeFrom(MeldableQueue<? extends E> other) { @SuppressWarnings("unchecked") // this isn't really unchecked, but confuses compiler... MeldablePriorityQueue<? extends E, ? extends E, ?> otherQueue = (MeldablePriorityQueue<? extends E, ? extends E, ?>) ((MeldableQueueImpl<? extends E>) other).priorityQueue; @SuppressWarnings("unchecked") MeldablePriorityQueue<E, E, MeldablePriorityQueue<? extends E, ? extends E, ?>> queue = (MeldablePriorityQueue<E, E, MeldablePriorityQueue<? extends E, ? extends E, ?>>) priorityQueue; return queue.mergeFrom(otherQueue); } } }
37.422481
100
0.642983
30517ccb23b9eb8c5ec26d2f3cb884da6da35f69
2,196
package net.blazecode.vanillify.mixins.packets; import it.unimi.dsi.fastutil.shorts.ShortSet; import net.blazecode.vanillify.api.interfaces.BlockStateProxy; import net.minecraft.block.BlockState; import net.minecraft.network.Packet; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.listener.ClientPlayPacketListener; import net.minecraft.network.packet.s2c.play.ChunkDeltaUpdateS2CPacket; import net.minecraft.util.math.ChunkSectionPos; import net.minecraft.world.chunk.ChunkSection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ChunkDeltaUpdateS2CPacket.class) public abstract class ChunkDeltaPacketMixin implements Packet<ClientPlayPacketListener> { @Mutable @Final @Shadow private BlockState[] blockStates; private void doInitProxy() { BlockState[] replacementStates = new BlockState[blockStates.length]; for(int i=0; i < blockStates.length; i++ ) { BlockState s = blockStates[ i ]; if( s.getBlock() instanceof BlockStateProxy ) { replacementStates[ i ] = ((( BlockStateProxy )s.getBlock()).getClientBlockState( s )); } else { replacementStates[ i ] = s; } } blockStates = replacementStates; } @Inject( method = "<init>(Lnet/minecraft/network/PacketByteBuf;)V", at = @At("RETURN") ) public void onInitPacketByteBuf( PacketByteBuf buf, CallbackInfo ci ) { doInitProxy(); } @Inject( method = "<init>(Lnet/minecraft/util/math/ChunkSectionPos;Lit/unimi/dsi/fastutil/shorts/ShortSet;Lnet/minecraft/world/chunk/ChunkSection;Z)V", at = @At( "RETURN" )) void onInitStupidlyLongParam( ChunkSectionPos sectionPos, ShortSet positions, ChunkSection section, boolean noLightingUpdates, CallbackInfo ci ) { doInitProxy(); } }
37.220339
177
0.711749
3397b1fbacb2e9d73616b16e39529debeed1d9e1
2,479
/* * * * Copyright 2018 Uber Technologies Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.uber.ugb.model; import com.uber.ugb.schema.QualifiedName; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class PartitionerTest { @Test public void partitionerIsCorrect() { Partitioner partitioner = new Partitioner(); partitioner.put(new QualifiedName("zero"), 0); partitioner.put(new QualifiedName("one"), 1); partitioner.put(new QualifiedName("two"), 2); partitioner.put(new QualifiedName("four"), 4); Map<QualifiedName, Long> partition = partitioner.getPartitionSizes(70); assertEquals(true, partition.get(new QualifiedName("zero")) == 0); assertEquals(true, partition.get(new QualifiedName("one")) == 10); assertEquals(true, partition.get(new QualifiedName("two")) == 20); assertEquals(true, partition.get(new QualifiedName("four")) == 40); assertNull(partition.get(new QualifiedName("five"))); } @Test public void partitionLargeGraph() { Partitioner partitioner = new Partitioner(); partitioner.put(new QualifiedName("user"), 13); partitioner.put(new QualifiedName("trip"), 8); partitioner.put(new QualifiedName("document"), 1); Map<QualifiedName, Long> partition = partitioner.getPartitionSizes(1000000000); // System.out.println("user:" + partition.get("user").size()); // System.out.println("trip:" + partition.get("trip").size()); // System.out.println("document:" + partition.get("document").size()); assertEquals(true, partition.get(new QualifiedName("user")) > 0); assertEquals(true, partition.get(new QualifiedName("trip")) > 0); assertEquals(true, partition.get(new QualifiedName("document")) > 0); } }
38.138462
87
0.674062
445fa30e77edf04e72f3fe88bdf4fffd7856afc6
1,136
/** * */ package org.collectionspace.services; import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; /** * @author pschmitz * */ public interface PersonJAXBSchema extends AuthorityItemJAXBSchema { final static String PERSONS_COMMON = "persons_common"; final static String FORE_NAME = "foreName"; final static String MIDDLE_NAME = "middleName"; final static String SUR_NAME = "surName"; final static String INITIALS = "initials"; final static String SALUTATIONS = "salutations"; final static String TITLE = "title"; final static String NAME_ADDITIONS = "nameAdditions"; final static String BIRTH_DATE = "birthDate"; final static String DEATH_DATE = "deathDate"; final static String BIRTH_PLACE = "birthPlace"; final static String DEATH_PLACE = "deathPlace"; final static String GROUPS = "groups"; final static String NATIONALITIES = "nationalities"; final static String GENDER = "gender"; final static String OCCUPATIONS = "occupations"; final static String SCHOOLS_OR_STYLES = "schoolsOrStyles"; final static String BIO_NOTE = "bioNote"; final static String NAME_NOTE = "nameNote"; }
34.424242
78
0.769366
e5b9329851fe8e5595313aaf46cb8528de32edf5
734
package com.tieto.ipac.presence; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum VisibilityLevel { NONE("none"), PERSONAL("personal"), WORKGROUP("workgroup"), SITE("site"), COMPANY("company"), FEDERATION("federation"), ALL("all"); private final String value; VisibilityLevel(String v) { value = v; } @JsonValue public String value() { return value; } @JsonCreator public static VisibilityLevel fromValue(String v) { for (VisibilityLevel c : VisibilityLevel.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
19.837838
57
0.638965
c8113d07a81baa3177938711e37f44e9d6d5767c
4,339
package com.tonymontes.comicvine; /* Created by tony on 2/13/17. */ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Publisher { @SerializedName("aliases") @Expose private Object aliases; @SerializedName("api_detail_url") @Expose private String apiDetailUrl; @SerializedName("characters") @Expose private List<Character> characters = null; @SerializedName("date_added") @Expose private String dateAdded; @SerializedName("date_last_updated") @Expose private String dateLastUpdated; @SerializedName("deck") @Expose private String deck; @SerializedName("description") @Expose private String description; @SerializedName("id") @Expose private Integer id; @SerializedName("image") @Expose private Image image; @SerializedName("location_address") @Expose private String locationAddress; @SerializedName("location_city") @Expose private String locationCity; @SerializedName("location_state") @Expose private String locationState; @SerializedName("name") @Expose private String name; @SerializedName("site_detail_url") @Expose private String siteDetailUrl; @SerializedName("story_arcs") @Expose private List<Storyarc> storyArcs = null; @SerializedName("teams") @Expose private List<Thing> teams = null; @SerializedName("volumes") @Expose private List<Volume> volumes = null; public Object getAliases() { return aliases; } public void setAliases(Object aliases) { this.aliases = aliases; } public String getApiDetailUrl() { return apiDetailUrl; } public void setApiDetailUrl(String apiDetailUrl) { this.apiDetailUrl = apiDetailUrl; } public List<Character> getCharacters() { return characters; } public void setCharacters(List<Character> characters) { this.characters = characters; } public String getDateAdded() { return dateAdded; } public void setDateAdded(String dateAdded) { this.dateAdded = dateAdded; } public String getDateLastUpdated() { return dateLastUpdated; } public void setDateLastUpdated(String dateLastUpdated) { this.dateLastUpdated = dateLastUpdated; } public String getDeck() { return deck; } public void setDeck(String deck) { this.deck = deck; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public String getLocationAddress() { return locationAddress; } public void setLocationAddress(String locationAddress) { this.locationAddress = locationAddress; } public String getLocationCity() { return locationCity; } public void setLocationCity(String locationCity) { this.locationCity = locationCity; } public String getLocationState() { return locationState; } public void setLocationState(String locationState) { this.locationState = locationState; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSiteDetailUrl() { return siteDetailUrl; } public void setSiteDetailUrl(String siteDetailUrl) { this.siteDetailUrl = siteDetailUrl; } public List<Storyarc> getStoryArcs() { return storyArcs; } public void setStoryArcs(List<Storyarc> storyArcs) { this.storyArcs = storyArcs; } public List<Thing> getTeams() { return teams; } public void setTeams(List<Thing> teams) { this.teams = teams; } public List<Volume> getVolumes() { return volumes; } public void setVolumes(List<Volume> volumes) { this.volumes = volumes; } }
21.374384
60
0.642314
20c237cffb602b722cfb005d86dcadec0616848e
2,416
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("35") class Record_2907 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 2907: FirstName is Jamal") void FirstNameOfRecord2907() { assertEquals("Jamal", customers.get(2906).getFirstName()); } @Test @DisplayName("Record 2907: LastName is Wicke") void LastNameOfRecord2907() { assertEquals("Wicke", customers.get(2906).getLastName()); } @Test @DisplayName("Record 2907: Company is French, Joseph C Esq") void CompanyOfRecord2907() { assertEquals("French, Joseph C Esq", customers.get(2906).getCompany()); } @Test @DisplayName("Record 2907: Address is 1946 N 13th St") void AddressOfRecord2907() { assertEquals("1946 N 13th St", customers.get(2906).getAddress()); } @Test @DisplayName("Record 2907: City is Toledo") void CityOfRecord2907() { assertEquals("Toledo", customers.get(2906).getCity()); } @Test @DisplayName("Record 2907: County is Lucas") void CountyOfRecord2907() { assertEquals("Lucas", customers.get(2906).getCounty()); } @Test @DisplayName("Record 2907: State is OH") void StateOfRecord2907() { assertEquals("OH", customers.get(2906).getState()); } @Test @DisplayName("Record 2907: ZIP is 43624") void ZIPOfRecord2907() { assertEquals("43624", customers.get(2906).getZIP()); } @Test @DisplayName("Record 2907: Phone is 419-241-3579") void PhoneOfRecord2907() { assertEquals("419-241-3579", customers.get(2906).getPhone()); } @Test @DisplayName("Record 2907: Fax is 419-241-1134") void FaxOfRecord2907() { assertEquals("419-241-1134", customers.get(2906).getFax()); } @Test @DisplayName("Record 2907: Email is [email protected]") void EmailOfRecord2907() { assertEquals("[email protected]", customers.get(2906).getEmail()); } @Test @DisplayName("Record 2907: Web is http://www.jamalwicke.com") void WebOfRecord2907() { assertEquals("http://www.jamalwicke.com", customers.get(2906).getWeb()); } }
25.166667
74
0.728477
310a87d742ffae6dcefad737fabd5db658ca58fc
582
package ru.eexxyyq.solutions.tasks.week2; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Task9Test { @Test void solution() { assertArrayEquals(new int[]{}, Task9.solution(new int[]{})); assertNull(Task9.solution(null)); assertArrayEquals(new int[]{1, 1, 1, 1, 1}, Task9.solution(new int[]{1, 1, 1, 1, 1})); assertArrayEquals(new int[]{2, 2, 4, 4}, Task9.solution(new int[]{2, 4, -1, -1})); assertArrayEquals(new int[]{2, 2, 1, 4, 4}, Task9.solution(new int[]{2, 1, 4, -1, -1})); } }
34.235294
96
0.611684
7956c2e8690ce280773af62e80041deec49bc97d
5,604
package de.jmonitoring.standardPlots.common; import de.jmonitoring.base.MoniSoftConstants; import de.jmonitoring.utils.intervals.CustomMinutePeriod; import de.jmonitoring.utils.intervals.CustomSecondPeriod; import java.util.Date; import org.jfree.data.time.*; /** * Defining methods used by all dataset generators * * @author togro */ public abstract class GeneralDataSetGenerator { /** * Return the {@link RegularTimePeriod} object defined by the given * parameters * * @param interval The interval type TODO: replace by enum or int * @param time The time which should be converted * @return */ public static RegularTimePeriod getPeriodForTimeStamp(double interval, Long time) { RegularTimePeriod regPeriod = null; if (interval < 0) { switch ((int) interval) { case (int) MoniSoftConstants.RAW_INTERVAL: regPeriod = null; break; case (int) MoniSoftConstants.HOUR_INTERVAL: regPeriod = new Hour(new Date(time)); break; case (int) MoniSoftConstants.DAY_INTERVAL: regPeriod = new Day(new Date(time)); break; case (int) MoniSoftConstants.WEEK_INTERVAL: regPeriod = new Week(new Date(time)); break; case (int) MoniSoftConstants.MONTH_INTERVAL: regPeriod = new Month(new Date(time)); break; case (int) MoniSoftConstants.YEAR_INTERVAL: regPeriod = new Year(new Date(time)); break; // default: // regPeriod = new CustomMinutePeriod((byte) interval, new Date(time)); } } else if (interval < 1) { regPeriod = new CustomSecondPeriod((byte) (interval * 60), new Date(time)); } else { regPeriod = new CustomMinutePeriod((byte) interval, new Date(time)); } return regPeriod; } /** * Return the interval suffix defined by the given parameters * * @param aggType The aggregation interval * @param showAsPower Flag that indicates if the user wants to calculate * power * @param showAsCounter Flag that indicates if the user wants to show * counter values * @param isCounter Flag taht indicates if the sensor is a counter * @return The suffix */ public static String getSuffix(double aggInterval, boolean showAsPower, boolean showAsCounter, boolean isCounter, boolean hasUsageUnit) { String suffix = ""; // 1. Teil if (aggInterval < 0) { switch ((int) aggInterval) { case (int) MoniSoftConstants.RAW_INTERVAL: suffix = "(" + 10 + java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MIN"); break; case (int) MoniSoftConstants.HOUR_INTERVAL: suffix = java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("STUNDEN"); break; case (int) MoniSoftConstants.DAY_INTERVAL: suffix = java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("TAGES"); break; case (int) MoniSoftConstants.WEEK_INTERVAL: suffix = java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("WOCHEN"); break; case (int) MoniSoftConstants.MONTH_INTERVAL: suffix = java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MONATS"); break; case (int) MoniSoftConstants.YEAR_INTERVAL: suffix = java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("JAHRES"); break; // default: // suffix = " (" + aggInterval + java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MIN"); } } else if (aggInterval < 1) { suffix = "x Sekunden"; } else { suffix = "(" + aggInterval + java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MIN"); } // 2. Teil if ((isCounter || hasUsageUnit) && showAsPower) { suffix += java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("LEISTUNG"); } else if ((isCounter || hasUsageUnit) && showAsCounter) { suffix += java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("ZÄHLERSTAND"); } else if ((isCounter || hasUsageUnit)) { suffix += java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("VERBRAUCH"); } else { if (suffix.contains(java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MIN"))) { suffix += java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("-MITTEL)"); } else { suffix += java.util.ResourceBundle.getBundle("de/jmonitoring/standardPlots/common/resource").getString("MITTEL)"); } } return suffix; } }
47.491525
152
0.605639