_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q166300 | DerUtils.encodeSequence | validation | public static byte[] encodeSequence(byte[]... encodedValues)
{
int length = 0;
for (byte[] encodedValue : encodedValues) {
length += encodedValue.length;
}
byte[] lengthEncoded = encodeLength(length);
ByteArrayDataOutput out = ByteStreams.newDataOutput(1 + lengthEncoded.length + length);
out.write(SEQUENCE_TAG);
out.write(lengthEncoded);
for (byte[] entry : encodedValues) {
out.write(entry);
}
return out.toByteArray();
} | java | {
"resource": ""
} |
q166301 | DerUtils.decodeSequence | validation | public static List<byte[]> decodeSequence(byte[] sequence)
{
int index = 0;
// check tag
checkArgument(sequence[0] == SEQUENCE_TAG, "Expected sequence tag");
index++;
// read length
int sequenceDataLength = decodeLength(sequence, index);
index += encodedLengthSize(sequenceDataLength);
checkArgument(sequenceDataLength + index == sequence.length, "Invalid sequence");
// read elements
ImmutableList.Builder<byte[]> elements = ImmutableList.builder();
while (index < sequence.length) {
int elementStart = index;
// skip the tag
index++;
// read length
int length = decodeLength(sequence, index);
index += encodedLengthSize(length);
byte[] data = Arrays.copyOfRange(sequence, elementStart, index + length);
elements.add(data);
index += length;
}
return elements.build();
} | java | {
"resource": ""
} |
q166302 | DerUtils.decodeSequenceOptionalElement | validation | public static byte[] decodeSequenceOptionalElement(byte[] element)
{
int index = 0;
// check tag
checkArgument((element[0] & 0xE0) == 0xA0, "Expected optional sequence element tag");
index++;
// read length
int length = decodeLength(element, index);
index += encodedLengthSize(length);
checkArgument(length + index == element.length, "Invalid optional sequence element");
return Arrays.copyOfRange(element, index, index + length);
} | java | {
"resource": ""
} |
q166303 | DerUtils.encodeBitString | validation | public static byte[] encodeBitString(int padBits, byte[] value)
{
checkArgument(padBits >= 0 && padBits < 8, "Invalid pad bits");
byte[] lengthEncoded = encodeLength(value.length + 1);
ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length);
out.write(BIT_STRING_TAG);
out.write(lengthEncoded);
out.write(padBits);
out.write(value);
return out.toByteArray();
} | java | {
"resource": ""
} |
q166304 | DerUtils.encodeOctetString | validation | public static byte[] encodeOctetString(byte[] value)
{
byte[] lengthEncoded = encodeLength(value.length);
ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length);
out.write(OCTET_STRING_TAG);
out.write(lengthEncoded);
out.write(value);
return out.toByteArray();
} | java | {
"resource": ""
} |
q166305 | DerUtils.encodeLength | validation | public static byte[] encodeLength(int length)
{
if (length < 128) {
return new byte[] {(byte) length};
}
int numberOfBits = 32 - Integer.numberOfLeadingZeros(length);
int numberOfBytes = (numberOfBits + 7) / 8;
byte[] encoded = new byte[1 + numberOfBytes];
encoded[0] = (byte) (numberOfBytes | 0x80);
for (int i = 0; i < numberOfBytes; i++) {
int byteToEncode = (numberOfBytes - i);
int shiftSize = (byteToEncode - 1) * 8;
encoded[i + 1] = (byte) (length >>> shiftSize);
}
return encoded;
} | java | {
"resource": ""
} |
q166306 | Logger.get | validation | public static Logger get(String name)
{
java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name);
return new Logger(logger);
} | java | {
"resource": ""
} |
q166307 | Logger.debug | validation | public void debug(Throwable exception, String message)
{
logger.log(FINE, message, exception);
} | java | {
"resource": ""
} |
q166308 | Logger.warn | validation | public void warn(Throwable exception, String message)
{
logger.log(WARNING, message, exception);
} | java | {
"resource": ""
} |
q166309 | Logger.error | validation | public void error(Throwable exception, String message)
{
logger.log(SEVERE, message, exception);
} | java | {
"resource": ""
} |
q166310 | HttpUriBuilder.replacePath | validation | public HttpUriBuilder replacePath(String path)
{
requireNonNull(path, "path is null");
if (!path.isEmpty() && !path.startsWith("/")) {
path = "/" + path;
}
this.path = path;
return this;
} | java | {
"resource": ""
} |
q166311 | HttpUriBuilder.percentDecode | validation | private static String percentDecode(String encoded)
{
Preconditions.checkArgument(ascii().matchesAllOf(encoded), "string must be ASCII");
ByteArrayOutputStream out = new ByteArrayOutputStream(encoded.length());
for (int i = 0; i < encoded.length(); i++) {
char c = encoded.charAt(i);
if (c == '%') {
Preconditions.checkArgument(i + 2 < encoded.length(), "percent encoded value is truncated");
int high = Character.digit(encoded.charAt(i + 1), 16);
int low = Character.digit(encoded.charAt(i + 2), 16);
Preconditions.checkArgument(high != -1 && low != -1, "percent encoded value is not a valid hex string: ", encoded.substring(i, i + 2));
int value = (high << 4) | (low);
out.write(value);
i += 2;
}
else {
out.write((int) c);
}
}
try {
return UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(out.toByteArray()))
.toString();
}
catch (CharacterCodingException e) {
throw new IllegalArgumentException("input does not represent a proper UTF8-encoded string");
}
} | java | {
"resource": ""
} |
q166312 | HttpServerChannelListener.processContentTimestamps | validation | @Nullable
private static DoubleSummaryStats processContentTimestamps(List<Long> contentTimestamps)
{
requireNonNull(contentTimestamps, "contentTimestamps is null");
// no content (HTTP 204) or there was a single response chunk (so no interarrival time)
if (contentTimestamps.size() == 0 || contentTimestamps.size() == 1) {
return null;
}
DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();
long previousTimestamp = contentTimestamps.get(0);
for (int i = 1; i < contentTimestamps.size(); i++) {
long timestamp = contentTimestamps.get(i);
statistics.accept(NANOSECONDS.toMillis(timestamp - previousTimestamp));
previousTimestamp = timestamp;
}
return new DoubleSummaryStats(statistics);
} | java | {
"resource": ""
} |
q166313 | ConfigurationFactory.build | validation | <T> T build(ConfigurationProvider<T> configurationProvider)
{
requireNonNull(configurationProvider, "configurationProvider");
registerConfigurationProvider(configurationProvider, Optional.empty());
// check for a prebuilt instance
T instance = getCachedInstance(configurationProvider);
if (instance != null) {
return instance;
}
ConfigurationBinding<T> configurationBinding = configurationProvider.getConfigurationBinding();
ConfigurationHolder<T> holder = build(configurationBinding.getConfigClass(), configurationBinding.getPrefix(), getConfigDefaults(configurationBinding.getKey()));
instance = holder.getInstance();
// inform caller about warnings
if (warningsMonitor != null) {
for (Message message : holder.getProblems().getWarnings()) {
warningsMonitor.onWarning(message.toString());
}
}
// add to instance cache
T existingValue = putCachedInstance(configurationProvider, instance);
// if key was already associated with a value, there was a
// creation race and we lost. Just use the winners' instance;
if (existingValue != null) {
return existingValue;
}
return instance;
} | java | {
"resource": ""
} |
q166314 | ExponentiallyDecayingSample.update | validation | public void update(long value, long timestamp)
{
lockForRegularUsage();
try {
final double priority = weight(timestamp - startTime) / random();
final long newCount = count.incrementAndGet();
if (newCount <= reservoirSize) {
values.put(priority, value);
}
else {
Double first = values.firstKey();
if (first < priority) {
if (values.putIfAbsent(priority, value) == null) {
// ensure we always remove an item
while (values.remove(first) == null) {
first = values.firstKey();
}
}
}
}
}
finally {
unlockForRegularUsage();
}
final long now = System.nanoTime();
final long next = nextScaleTime.get();
if (now >= next) {
rescale(now, next);
}
} | java | {
"resource": ""
} |
q166315 | HttpMBeanServerRpc.base64Encode | validation | public static String base64Encode(byte[] bytes)
{
// always sequence of 4 characters for each 3 bytes; padded with '='s as necessary:
StringBuilder buf = new StringBuilder(((bytes.length + 2) / 3) * 4);
// first, handle complete chunks (fast loop)
int i = 0;
for (int end = bytes.length - 2; i < end; ) {
int chunk = ((bytes[i++] & 0xFF) << 16)
| ((bytes[i++] & 0xFF) << 8)
| (bytes[i++] & 0xFF);
buf.append(lookup[chunk >> 18]);
buf.append(lookup[(chunk >> 12) & 0x3F]);
buf.append(lookup[(chunk >> 6) & 0x3F]);
buf.append(lookup[chunk & 0x3F]);
}
// then leftovers, if any
int len = bytes.length;
if (i < len) { // 1 or 2 extra bytes?
int chunk = ((bytes[i++] & 0xFF) << 16);
buf.append(lookup[chunk >> 18]);
if (i < len) { // 2 bytes
chunk |= ((bytes[i] & 0xFF) << 8);
buf.append(lookup[(chunk >> 12) & 0x3F]);
buf.append(lookup[(chunk >> 6) & 0x3F]);
}
else { // 1 byte
buf.append(lookup[(chunk >> 12) & 0x3F]);
buf.append('=');
}
buf.append('=');
}
return buf.toString();
} | java | {
"resource": ""
} |
q166316 | HttpMBeanServerRpc.base64Decode | validation | public static byte[] base64Decode(String encoded)
{
int padding = 0;
for (int i = encoded.length() - 1; encoded.charAt(i) == '='; i--) {
padding++;
}
int length = encoded.length() * 6 / 8 - padding;
byte[] bytes = new byte[length];
for (int i = 0, index = 0, n = encoded.length(); i < n; i += 4) {
int word = reverseLookup[encoded.charAt(i)] << 18;
word += reverseLookup[encoded.charAt(i + 1)] << 12;
word += reverseLookup[encoded.charAt(i + 2)] << 6;
word += reverseLookup[encoded.charAt(i + 3)];
for (int j = 0; j < 3 && index + j < length; j++) {
bytes[index + j] = (byte) (word >> (8 * (2 - j)));
}
index += 3;
}
return bytes;
} | java | {
"resource": ""
} |
q166317 | LoggingOutputStream.flush | validation | @Override
public synchronized void flush()
throws IOException
{
super.flush();
String record = this.toString();
reset();
if (record.isEmpty() || record.equals(lineSeparator)) {
// avoid empty records
return;
}
logger.info(record);
} | java | {
"resource": ""
} |
q166318 | JettyHttpClient.dumpDestination | validation | @SuppressWarnings("UnusedDeclaration")
public String dumpDestination(URI uri)
{
Destination destination = httpClient.getDestination(uri.getScheme(), uri.getHost(), uri.getPort());
if (destination == null) {
return null;
}
return dumpDestination(destination);
} | java | {
"resource": ""
} |
q166319 | ExponentialDecay.computeAlpha | validation | public static double computeAlpha(double targetWeight, long targetAgeInSeconds)
{
checkArgument(targetAgeInSeconds > 0, "targetAgeInSeconds must be > 0");
checkArgument(targetWeight > 0 && targetWeight < 1, "targetWeight must be in range (0, 1)");
return -Math.log(targetWeight) / targetAgeInSeconds;
} | java | {
"resource": ""
} |
q166320 | MoreFutures.propagateCancellation | validation | public static <X, Y> void propagateCancellation(ListenableFuture<? extends X> source, Future<? extends Y> destination, boolean mayInterruptIfRunning)
{
source.addListener(() -> {
if (source.isCancelled()) {
destination.cancel(mayInterruptIfRunning);
}
}, directExecutor());
} | java | {
"resource": ""
} |
q166321 | MoreFutures.unmodifiableFuture | validation | @Deprecated
public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future)
{
return unmodifiableFuture(future, false);
} | java | {
"resource": ""
} |
q166322 | MoreFutures.unmodifiableFuture | validation | @Deprecated
public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future, boolean propagateCancel)
{
requireNonNull(future, "future is null");
Function<Boolean, Boolean> onCancelFunction;
if (propagateCancel) {
onCancelFunction = future::cancel;
}
else {
onCancelFunction = mayInterrupt -> false;
}
UnmodifiableCompletableFuture<V> unmodifiableFuture = new UnmodifiableCompletableFuture<>(onCancelFunction);
future.whenComplete((value, exception) -> {
if (exception != null) {
unmodifiableFuture.internalCompleteExceptionally(exception);
}
else {
unmodifiableFuture.internalComplete(value);
}
});
return unmodifiableFuture;
} | java | {
"resource": ""
} |
q166323 | MoreFutures.failedFuture | validation | @Deprecated
public static <V> CompletableFuture<V> failedFuture(Throwable throwable)
{
requireNonNull(throwable, "throwable is null");
CompletableFuture<V> future = new CompletableFuture<>();
future.completeExceptionally(throwable);
return future;
} | java | {
"resource": ""
} |
q166324 | MoreFutures.getFutureValue | validation | public static <V, E extends Exception> V getFutureValue(Future<V> future, Class<E> exceptionType)
throws E
{
requireNonNull(future, "future is null");
requireNonNull(exceptionType, "exceptionType is null");
try {
return future.get();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted", e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
propagateIfPossible(cause, exceptionType);
throw new RuntimeException(cause);
}
} | java | {
"resource": ""
} |
q166325 | MoreFutures.tryGetFutureValue | validation | public static <T> Optional<T> tryGetFutureValue(Future<T> future)
{
requireNonNull(future, "future is null");
if (!future.isDone()) {
return Optional.empty();
}
return tryGetFutureValue(future, 0, MILLISECONDS);
} | java | {
"resource": ""
} |
q166326 | MoreFutures.tryGetFutureValue | validation | public static <V> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit)
{
return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class);
} | java | {
"resource": ""
} |
q166327 | MoreFutures.tryGetFutureValue | validation | public static <V, E extends Exception> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit, Class<E> exceptionType)
throws E
{
requireNonNull(future, "future is null");
checkArgument(timeout >= 0, "timeout is negative");
requireNonNull(timeUnit, "timeUnit is null");
requireNonNull(exceptionType, "exceptionType is null");
try {
return Optional.ofNullable(future.get(timeout, timeUnit));
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted", e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
propagateIfPossible(cause, exceptionType);
throw new RuntimeException(cause);
}
catch (TimeoutException expected) {
// expected
}
return Optional.empty();
} | java | {
"resource": ""
} |
q166328 | MoreFutures.checkSuccess | validation | public static void checkSuccess(Future<?> future, String errorMessage)
{
requireNonNull(future, "future is null");
requireNonNull(errorMessage, "errorMessage is null");
checkArgument(future.isDone(), "future not done yet");
try {
getFutureValue(future);
}
catch (RuntimeException e) {
throw new IllegalArgumentException(errorMessage, e);
}
} | java | {
"resource": ""
} |
q166329 | MoreFutures.whenAnyComplete | validation | public static <V> ListenableFuture<V> whenAnyComplete(Iterable<? extends ListenableFuture<? extends V>> futures)
{
requireNonNull(futures, "futures is null");
checkArgument(!isEmpty(futures), "futures is empty");
ExtendedSettableFuture<V> firstCompletedFuture = ExtendedSettableFuture.create();
for (ListenableFuture<? extends V> future : futures) {
firstCompletedFuture.setAsync(future);
}
return firstCompletedFuture;
} | java | {
"resource": ""
} |
q166330 | MoreFutures.firstCompletedFuture | validation | @Deprecated
public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures)
{
return firstCompletedFuture(futures, false);
} | java | {
"resource": ""
} |
q166331 | MoreFutures.firstCompletedFuture | validation | @Deprecated
public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures, boolean propagateCancel)
{
requireNonNull(futures, "futures is null");
checkArgument(!isEmpty(futures), "futures is empty");
CompletableFuture<V> future = new CompletableFuture<>();
for (CompletionStage<? extends V> stage : futures) {
stage.whenComplete((value, exception) -> {
if (exception != null) {
future.completeExceptionally(exception);
}
else {
future.complete(value);
}
});
}
if (propagateCancel) {
future.exceptionally(throwable -> {
if (throwable instanceof CancellationException) {
for (CompletionStage<? extends V> sourceFuture : futures) {
if (sourceFuture instanceof Future) {
((Future<?>) sourceFuture).cancel(true);
}
}
}
return null;
});
}
return future;
} | java | {
"resource": ""
} |
q166332 | MoreFutures.allAsList | validation | @Deprecated
public static <V> CompletableFuture<List<V>> allAsList(List<CompletableFuture<? extends V>> futures)
{
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
// Eagerly propagate exceptions, rather than waiting for all the futures to complete first (default behavior)
for (CompletableFuture<? extends V> future : futures) {
future.whenComplete((v, throwable) -> {
if (throwable != null) {
allDoneFuture.completeExceptionally(throwable);
}
});
}
return unmodifiableFuture(allDoneFuture.thenApply(v ->
futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.<V>toList())));
} | java | {
"resource": ""
} |
q166333 | MoreFutures.toCompletableFuture | validation | public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture)
{
requireNonNull(listenableFuture, "listenableFuture is null");
CompletableFuture<V> future = new CompletableFuture<>();
future.exceptionally(throwable -> {
if (throwable instanceof CancellationException) {
listenableFuture.cancel(true);
}
return null;
});
FutureCallback<V> callback = new FutureCallback<V>()
{
@Override
public void onSuccess(V result)
{
future.complete(result);
}
@Override
public void onFailure(Throwable t)
{
future.completeExceptionally(t);
}
};
Futures.addCallback(listenableFuture, callback, directExecutor());
return future;
} | java | {
"resource": ""
} |
q166334 | MoreFutures.toListenableFuture | validation | public static <V> ListenableFuture<V> toListenableFuture(CompletableFuture<V> completableFuture)
{
requireNonNull(completableFuture, "completableFuture is null");
SettableFuture<V> future = SettableFuture.create();
propagateCancellation(future, completableFuture, true);
completableFuture.whenComplete((value, exception) -> {
if (exception != null) {
future.setException(exception);
}
else {
future.set(value);
}
});
return future;
} | java | {
"resource": ""
} |
q166335 | MoreFutures.addExceptionCallback | validation | public static <T> void addExceptionCallback(ListenableFuture<T> future, Runnable exceptionCallback, Executor executor)
{
requireNonNull(exceptionCallback, "exceptionCallback is null");
addExceptionCallback(future, t -> exceptionCallback.run(), executor);
} | java | {
"resource": ""
} |
q166336 | QuantileDigest.getHistogram | validation | public List<Bucket> getHistogram(List<Long> bucketUpperBounds, MiddleFunction middleFunction)
{
checkArgument(Ordering.natural().isOrdered(bucketUpperBounds), "buckets must be sorted in increasing order");
ImmutableList.Builder<Bucket> builder = ImmutableList.builder();
PeekingIterator<Long> iterator = Iterators.peekingIterator(bucketUpperBounds.iterator());
HistogramBuilderStateHolder holder = new HistogramBuilderStateHolder();
double normalizationFactor = weight(TimeUnit.NANOSECONDS.toSeconds(ticker.read()));
postOrderTraversal(root, node -> {
while (iterator.hasNext() && iterator.peek() <= upperBound(node)) {
double bucketCount = holder.sum - holder.lastSum;
Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount);
builder.add(bucket);
holder.lastSum = holder.sum;
holder.bucketWeightedSum = 0;
iterator.next();
}
holder.bucketWeightedSum += middleFunction.middle(lowerBound(node), upperBound(node)) * counts[node];
holder.sum += counts[node];
return iterator.hasNext();
});
while (iterator.hasNext()) {
double bucketCount = holder.sum - holder.lastSum;
Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount);
builder.add(bucket);
iterator.next();
}
return builder.build();
} | java | {
"resource": ""
} |
q166337 | QuantileDigest.tryRemove | validation | private int tryRemove(int node)
{
checkArgument(node != -1, "node is -1");
int left = lefts[node];
int right = rights[node];
if (left == -1 && right == -1) {
// leaf, just remove it
remove(node);
return -1;
}
if (left != -1 && right != -1) {
// node has both children so we can't physically remove it
counts[node] = 0;
return node;
}
// node has a single child, so remove it and return the child
remove(node);
if (left != -1) {
return left;
}
else {
return right;
}
} | java | {
"resource": ""
} |
q166338 | QuantileDigest.computeMaxPathWeight | validation | private double computeMaxPathWeight(int node)
{
if (node == -1 || levels[node] == 0) {
return 0;
}
double leftMaxWeight = computeMaxPathWeight(lefts[node]);
double rightMaxWeight = computeMaxPathWeight(rights[node]);
return Math.max(leftMaxWeight, rightMaxWeight) + counts[node];
} | java | {
"resource": ""
} |
q166339 | HyperLogLog.addHash | validation | public void addHash(long hash)
{
instance.insertHash(hash);
if (instance instanceof SparseHll) {
instance = makeDenseIfNecessary((SparseHll) instance);
}
} | java | {
"resource": ""
} |
q166340 | ConfigurationLoader.loadPropertiesFrom | validation | public static Map<String, String> loadPropertiesFrom(String path)
throws IOException
{
Properties properties = new Properties();
try (InputStream inputStream = new FileInputStream(path)) {
properties.load(inputStream);
}
return fromProperties(properties);
} | java | {
"resource": ""
} |
q166341 | ConfigBinder.bindConfigGlobalDefaults | validation | public <T> void bindConfigGlobalDefaults(Class<T> configClass, ConfigDefaults<T> configDefaults)
{
Key<T> key = Key.get(configClass, GlobalDefaults.class);
binder.bindConfigDefaults(new ConfigDefaultsHolder<>(key, configDefaults));
} | java | {
"resource": ""
} |
q166342 | FibonacciPollInterval.next | validation | public Duration next(int pollCount, Duration previousDuration) {
return new Duration(fibonacci(offset + pollCount), timeUnit);
} | java | {
"resource": ""
} |
q166343 | FibonacciPollInterval.fib | validation | private int fib(int value, int current, int previous) {
if (value == 0) {
return previous;
} else if (value == 1) {
return current;
}
return fib(value - 1, current + previous, current);
} | java | {
"resource": ""
} |
q166344 | Duration.multiply | validation | public Duration multiply(long amount) {
return new Multiply().apply(this, unit == null ? FOREVER : new Duration(amount, unit));
} | java | {
"resource": ""
} |
q166345 | Duration.divide | validation | public Duration divide(long amount) {
return new Divide().apply(this, unit == null ? FOREVER : new Duration(amount, unit));
} | java | {
"resource": ""
} |
q166346 | WhiteboxImpl.findSingleFieldUsingStrategy | validation | private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object,
boolean checkHierarchy, Class<?> startClass) {
assertObjectInGetInternalStateIsNotNull(object);
Field foundField = null;
final Class<?> originalStartClass = startClass;
while (startClass != null) {
final Field[] declaredFields = startClass.getDeclaredFields();
for (Field field : declaredFields) {
if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
if (foundField != null) {
throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + ".");
}
foundField = field;
}
}
if (foundField != null) {
break;
} else if (!checkHierarchy) {
break;
}
startClass = startClass.getSuperclass();
}
if (foundField == null) {
strategy.notFound(originalStartClass, !isClass(object));
return null;
}
foundField.setAccessible(true);
return foundField;
} | java | {
"resource": ""
} |
q166347 | WhiteboxImpl.hasFieldProperModifier | validation | private static boolean hasFieldProperModifier(Object object, Field field) {
return ((object instanceof Class<?> && Modifier.isStatic(field.getModifiers())) || !(object instanceof Class<?> || Modifier
.isStatic(field.getModifiers())));
} | java | {
"resource": ""
} |
q166348 | WhiteboxImpl.throwExceptionIfFieldWasNotFound | validation | public static void throwExceptionIfFieldWasNotFound(Class<?> type, String fieldName, Field field) {
if (field == null) {
throw new FieldNotFoundException("No field was found with name '" + fieldName + "' in class "
+ type.getName() + ".");
}
} | java | {
"resource": ""
} |
q166349 | WhiteboxImpl.getFieldAnnotatedWith | validation | public static Field getFieldAnnotatedWith(Object object, Class<? extends Annotation> annotationType) {
return findSingleFieldUsingStrategy(new FieldAnnotationMatcherStrategy(annotationType), object, true,
getType(object));
} | java | {
"resource": ""
} |
q166350 | ConditionFactory.conditionEvaluationListener | validation | public ConditionFactory conditionEvaluationListener(ConditionEvaluationListener conditionEvaluationListener) {
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
} | java | {
"resource": ""
} |
q166351 | ConditionFactory.pollExecutorService | validation | public ConditionFactory pollExecutorService(ExecutorService executorService) {
if (executorService != null && executorService instanceof ScheduledExecutorService) {
throw new IllegalArgumentException("Poll executor service cannot be an instance of " + ScheduledExecutorService.class.getName());
}
return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withoutCleanup(executorService));
} | java | {
"resource": ""
} |
q166352 | ConditionFactory.untilTrue | validation | public void untilTrue(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.TRUE), is(true)));
} | java | {
"resource": ""
} |
q166353 | ConditionFactory.untilFalse | validation | public void untilFalse(final AtomicBoolean atomic) {
untilAtomic(atomic, anyOf(is(Boolean.FALSE), is(false)));
} | java | {
"resource": ""
} |
q166354 | Awaitility.catchUncaughtExceptions | validation | public static ConditionFactory catchUncaughtExceptions() {
return new ConditionFactory(null, defaultWaitConstraint, defaultPollInterval, defaultPollDelay,
defaultCatchUncaughtExceptions, defaultExceptionIgnorer, defaultConditionEvaluationListener,
defaultExecutorLifecycle);
} | java | {
"resource": ""
} |
q166355 | Awaitility.setDefaultTimeout | validation | public static void setDefaultTimeout(long timeout, TimeUnit unit) {
defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(new Duration(timeout, unit));
} | java | {
"resource": ""
} |
q166356 | Awaitility.setDefaultTimeout | validation | public static void setDefaultTimeout(Duration defaultTimeout) {
if (defaultTimeout == null) {
throw new IllegalArgumentException("You must specify a default timeout (was null).");
}
defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(defaultTimeout);
} | java | {
"resource": ""
} |
q166357 | ArgumentTokenizer.tokenize | validation | public static List<String> tokenize(String arguments, boolean stringify) {
LinkedList<String> argList = new LinkedList<>();
StringBuilder currArg = new StringBuilder();
boolean escaped = false;
int state = NO_TOKEN_STATE; // start in the NO_TOKEN_STATE
int len = arguments.length();
// Loop over each character in the string
for (int i = 0; i < len; i++) {
char c = arguments.charAt(i);
if (escaped) {
// Escaped state: just append the next character to the current arg.
escaped = false;
currArg.append(c);
}
else {
switch(state) {
case SINGLE_QUOTE_STATE:
if (c == '\'') {
// Seen the close quote; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE;
}
else {
currArg.append(c);
}
break;
case DOUBLE_QUOTE_STATE:
if (c == '"') {
// Seen the close quote; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE;
}
else if (c == '\\') {
// Look ahead, and only escape quotes or backslashes
i++;
char next = arguments.charAt(i);
if (next == '"' || next == '\\') {
currArg.append(next);
}
else {
currArg.append(c);
currArg.append(next);
}
}
else {
currArg.append(c);
}
break;
// case NORMAL_TOKEN_STATE:
// if (Character.isWhitespace(c)) {
// // Whitespace ends the token; start a new one
// argList.add(currArg.toString());
// currArg = new StringBuffer();
// state = NO_TOKEN_STATE;
// }
// else if (c == '\\') {
// // Backslash in a normal token: escape the next character
// escaped = true;
// }
// else if (c == '\'') {
// state = SINGLE_QUOTE_STATE;
// }
// else if (c == '"') {
// state = DOUBLE_QUOTE_STATE;
// }
// else {
// currArg.append(c);
// }
// break;
case NO_TOKEN_STATE:
case NORMAL_TOKEN_STATE:
switch(c) {
case '\\':
escaped = true;
state = NORMAL_TOKEN_STATE;
break;
case '\'':
state = SINGLE_QUOTE_STATE;
break;
case '"':
state = DOUBLE_QUOTE_STATE;
break;
default:
if (!Character.isWhitespace(c)) {
currArg.append(c);
state = NORMAL_TOKEN_STATE;
}
else if (state == NORMAL_TOKEN_STATE) {
// Whitespace ends the token; start a new one
argList.add(currArg.toString());
currArg = new StringBuilder();
state = NO_TOKEN_STATE;
}
}
break;
default:
throw new IllegalStateException("ArgumentTokenizer state " + state + " is invalid!");
}
}
}
// If we're still escaped, put in the backslash
if (escaped) {
currArg.append('\\');
argList.add(currArg.toString());
}
// Close the last argument if we haven't yet
else if (state != NO_TOKEN_STATE) {
argList.add(currArg.toString());
}
// Format each argument if we've been told to stringify them
if (stringify) {
for (int i = 0; i < argList.size(); i++) {
argList.set(i, "\"" + _escapeQuotesAndBackslashes(argList.get(i)) + "\"");
}
}
return argList;
} | java | {
"resource": ""
} |
q166358 | ArgumentTokenizer._escapeQuotesAndBackslashes | validation | protected static String _escapeQuotesAndBackslashes(String s) {
final StringBuilder buf = new StringBuilder(s);
// Walk backwards, looking for quotes or backslashes.
// If we see any, insert an extra backslash into the buffer at
// the same index. (By walking backwards, the index into the buffer
// will remain correct as we change the buffer.)
for (int i = s.length()-1; i >= 0; i--) {
char c = s.charAt(i);
if ((c == '\\') || (c == '"')) {
buf.insert(i, '\\');
}
// Replace any special characters with escaped versions
else if (c == '\n') {
buf.deleteCharAt(i);
buf.insert(i, "\\n");
}
else if (c == '\t') {
buf.deleteCharAt(i);
buf.insert(i, "\\t");
}
else if (c == '\r') {
buf.deleteCharAt(i);
buf.insert(i, "\\r");
}
else if (c == '\b') {
buf.deleteCharAt(i);
buf.insert(i, "\\b");
}
else if (c == '\f') {
buf.deleteCharAt(i);
buf.insert(i, "\\f");
}
}
return buf.toString();
} | java | {
"resource": ""
} |
q166359 | AssetsController.serveStatic | validation | public Result serveStatic() {
Object renderable = new Renderable() {
@Override
public void render(Context context, Result result) {
String fileName = getFileNameFromPathOrReturnRequestPath(context);
URL url = getStaticFileFromAssetsDir(fileName);
streamOutUrlEntity(url, context, result);
}
};
return Results.ok().render(renderable);
} | java | {
"resource": ""
} |
q166360 | MessagesImpl.loadLanguageConfiguration | validation | private PropertiesConfiguration loadLanguageConfiguration(String fileOrUrl) {
PropertiesConfiguration configuration = SwissKnife
.loadConfigurationInUtf8(fileOrUrl);
if (configuration != null && ninjaProperties.isDev()) {
// enable runtime reloading of translations in dev mode
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
configuration.setReloadingStrategy(strategy);
}
return configuration;
} | java | {
"resource": ""
} |
q166361 | MessagesImpl.loadAllMessageFilesForRegisteredLanguages | validation | private Map<String, Configuration> loadAllMessageFilesForRegisteredLanguages() {
Map<String, Configuration> langToKeyAndValuesMappingMutable = Maps.newHashMap();
// Load default messages:
Configuration defaultLanguage = loadLanguageConfiguration("conf/messages.properties");
// Make sure we got the file.
// Everything else does not make much sense.
if (defaultLanguage == null) {
throw new RuntimeException(
"Did not find conf/messages.properties. Please add a default language file.");
} else {
langToKeyAndValuesMappingMutable.put("", defaultLanguage);
}
// Get the languages from the application configuration.
String[] applicationLangs = ninjaProperties
.getStringArray(NinjaConstant.applicationLanguages);
// If we don't have any languages declared we just return.
// We'll use the default messages.properties file.
if (applicationLangs == null) {
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
}
// Load each language into the HashMap containing the languages:
for (String lang : applicationLangs) {
// First step: Load complete language eg. en-US
Configuration configuration = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", lang));
Configuration configurationLangOnly = null;
// If the language has a country code load the default values for
// the language, too. For instance missing variables in en-US will
// be
// Overwritten by the default languages.
if (lang.contains("-")) {
// get the lang
String langOnly = lang.split("-")[0];
// And load the configuraion
configurationLangOnly = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", langOnly));
}
// This is strange. If you defined the language in application.conf
// it should be there propably.
if (configuration == null) {
logger.info(
"Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead.",
lang);
} else {
// add new language, but combine with default language if stuff
// is missing...
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
// Add eg. "en-US"
compositeConfiguration.addConfiguration(configuration);
// Add eg. "en"
if (configurationLangOnly != null) {
compositeConfiguration
.addConfiguration(configurationLangOnly);
}
// Add messages.conf (default pack)
compositeConfiguration.addConfiguration(defaultLanguage);
// and add the composed configuration to the hashmap with the
// mapping.
langToKeyAndValuesMappingMutable.put(lang,
(Configuration) compositeConfiguration);
}
}
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
} | java | {
"resource": ""
} |
q166362 | LogbackConfigurator.getUrlForStringFromClasspathAsFileOrUrl | validation | protected static URL getUrlForStringFromClasspathAsFileOrUrl(String logbackConfigurationFile) {
URL url = null;
try {
url = Resources.getResource(logbackConfigurationFile);
} catch (IllegalArgumentException ex) {
// doing nothing intentionally..
}
if (url == null) {
// configuring from file:
try {
File file = new File(logbackConfigurationFile);
if (file.exists()) {
url = new File(logbackConfigurationFile).toURI().toURL();
}
} catch (MalformedURLException ex) {
// doing nothing intentionally..
}
}
if (url == null) {
try {
// we assume we got a real http://... url here...
url = new URL(logbackConfigurationFile);
} catch (MalformedURLException ex) {
// doing nothing intentionally..
}
}
return url;
} | java | {
"resource": ""
} |
q166363 | SecretGenerator.generateSecret | validation | protected static String generateSecret(Random random) {
String charsetForSecret = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder stringBuilder = new StringBuilder(64);
for (int i = 0; i < 64; i++) {
int charToPoPickFromCharset = random.nextInt(charsetForSecret.length());
stringBuilder.append(charsetForSecret.charAt(charToPoPickFromCharset));
}
return stringBuilder.toString();
} | java | {
"resource": ""
} |
q166364 | NinjaRunMojo.buildRunClassInSeparateJvmMachine | validation | protected RunClassInSeparateJvmMachine buildRunClassInSeparateJvmMachine(
String name,
String classNameWithMainToRun,
List<String> classpath,
List<String> jvmArguments,
File mavenBaseDir) {
return new RunClassInSeparateJvmMachine(
name,
classNameWithMainToRun,
classpath,
buildJvmArguments(),
mavenBaseDir
);
} | java | {
"resource": ""
} |
q166365 | NinjaRunMojo.getAllArtifactsComingFromNinjaStandalone | validation | protected List<Artifact> getAllArtifactsComingFromNinjaStandalone(
List<Artifact> artifacts) {
List<Artifact> resultingArtifacts = new ArrayList<>();
for (Artifact artifact: artifacts) {
for (String dependencyTrail: artifact.getDependencyTrail()) {
// something like: org.ninjaframework:ninja-standalone:jar:2.5.2
if (dependencyTrail.contains(NinjaMavenPluginConstants.NINJA_STANDALONE_ARTIFACT_ID)) {
resultingArtifacts.add(artifact);
break;
}
}
}
return resultingArtifacts;
} | java | {
"resource": ""
} |
q166366 | StandaloneHelper.resolveStandaloneClass | validation | static public Class<? extends Standalone> resolveStandaloneClass() {
return resolveStandaloneClass(
System.getProperty(Standalone.KEY_NINJA_STANDALONE_CLASS),
ForwardingServiceLoader.loadWithSystemServiceLoader(Standalone.class),
Standalone.DEFAULT_STANDALONE_CLASS
);
} | java | {
"resource": ""
} |
q166367 | CookieEncryption.encrypt | validation | public String encrypt(String data) {
Objects.requireNonNull(data, "Data to be encrypted");
if (!secretKeySpec.isPresent()) {
return data;
}
try {
// encrypt data
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec.get());
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
// convert encrypted bytes to string in base64
return Base64.encodeBase64URLSafeString(encrypted);
} catch (InvalidKeyException ex) {
logger.error(getHelperLogMessage(), ex);
throw new RuntimeException(ex);
} catch (GeneralSecurityException ex) {
logger.error("Failed to encrypt data.", ex);
return "";
}
} | java | {
"resource": ""
} |
q166368 | CookieEncryption.decrypt | validation | public String decrypt(String data) {
Objects.requireNonNull(data, "Data to be decrypted");
if (!secretKeySpec.isPresent()) {
return data;
}
// convert base64 encoded string to bytes
byte[] decoded = Base64.decodeBase64(data);
try {
// decrypt bytes
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec.get());
byte[] decrypted = cipher.doFinal(decoded);
// convert bytes to string
return new String(decrypted, StandardCharsets.UTF_8);
} catch (InvalidKeyException ex) {
logger.error(getHelperLogMessage(), ex);
throw new RuntimeException(ex);
} catch (GeneralSecurityException ex) {
logger.error("Failed to decrypt data.", ex);
return "";
}
} | java | {
"resource": ""
} |
q166369 | NinjaDefault.readNinjaVersion | validation | private final String readNinjaVersion() {
// location of the properties file
String LOCATION_OF_NINJA_BUILTIN_PROPERTIES = "ninja/ninja-builtin.properties";
// and the key inside the properties file.
String NINJA_VERSION_PROPERTY_KEY = "ninja.version";
String ninjaVersion;
try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(LOCATION_OF_NINJA_BUILTIN_PROPERTIES)){
Properties prop = new Properties();
prop.load(stream);
ninjaVersion = prop.getProperty(NINJA_VERSION_PROPERTY_KEY);
} catch (Exception e) {
//this should not happen. Never.
throw new RuntimeErrorException(new Error("Something is wrong with your build. Cannot find resource " + LOCATION_OF_NINJA_BUILTIN_PROPERTIES));
}
return ninjaVersion;
} | java | {
"resource": ""
} |
q166370 | WatchAndRestartMachine.register | validation | private void register(Path path) throws IOException {
////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//// USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS:
////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WatchKey watchKey = path.register(
// watchService,
// ENTRY_CREATE,
// ENTRY_DELETE,
// ENTRY_MODIFY);
////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//// BUT THIS IS DAMN SLOW (at least on a Mac)
//// THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
//// THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
//// MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WatchKey watchKey = path.register(
watchService,
new WatchEvent.Kind[]{
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE
},
SensitivityWatchEventModifier.HIGH);
mapOfWatchKeysToPaths.put(watchKey, path);
} | java | {
"resource": ""
} |
q166371 | NinjaModeHelper.determineModeFromSystemPropertiesOrProdIfNotSet | validation | public static NinjaMode determineModeFromSystemPropertiesOrProdIfNotSet() {
Optional<NinjaMode> ninjaModeOptional = determineModeFromSystemProperties();
NinjaMode ninjaMode;
if (!ninjaModeOptional.isPresent()) {
ninjaMode = NinjaMode.prod;
} else {
ninjaMode = ninjaModeOptional.get();
}
logger.info("Ninja is running in mode {}", ninjaMode.toString());
return ninjaMode;
} | java | {
"resource": ""
} |
q166372 | MimeTypes.isValidMimeType | validation | public boolean isValidMimeType(String mimeType) {
if (mimeType == null) {
return false;
} else if (mimeType.indexOf(";") != -1) {
return mimetypes.contains(mimeType.split(";")[0]);
} else {
return mimetypes.contains(mimeType);
}
} | java | {
"resource": ""
} |
q166373 | RouteBuilderImpl.buildRoute | validation | public Route buildRoute(Injector injector) {
if (functionalMethod == null) {
log.error("Error in route configuration for {}", uri);
throw new IllegalStateException("Route missing a controller method");
}
// Calculate filters
LinkedList<Class<? extends Filter>> allFilters = new LinkedList<>();
allFilters.addAll(calculateGlobalFilters(this.globalFiltersOptional, injector));
allFilters.addAll(this.localFilters);
allFilters.addAll(calculateFiltersForClass(functionalMethod.getDeclaringClass()));
FilterWith filterWith = functionalMethod.getAnnotation(FilterWith.class);
if (filterWith != null) {
allFilters.addAll(Arrays.asList(filterWith.value()));
}
FilterChain filterChain = buildFilterChain(injector, allFilters);
return new Route(httpMethod, uri, functionalMethod, filterChain);
} | java | {
"resource": ""
} |
q166374 | AbstractStandalone.run | validation | @Override
final public void run() {
// name current thread for improved logging/debugging
Thread.currentThread().setName(this.name);
try {
this.configure();
} catch (Exception e) {
logger.error("Unable to configure {}", name, e);
System.exit(1);
}
try {
this.start();
} catch (Exception e) {
logger.error("Unable to start {}", name, e);
System.exit(1);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
shutdown();
}
});
try {
// do not simply exit main() -- join something (likely server)
join();
} catch (Exception e) {
logger.warn("Interrupted (most likely JVM is shutting down and this is safe to ignore)");
}
} | java | {
"resource": ""
} |
q166375 | AbstractStandalone.createServerUrl | validation | protected String createServerUrl(String scheme, String host, Integer port) {
StringBuilder sb = new StringBuilder();
sb.append(scheme);
sb.append("://");
sb.append((host != null ? host : "localhost"));
if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
sb.append(":");
sb.append(port);
}
return sb.toString();
} | java | {
"resource": ""
} |
q166376 | JaxyRoutes.init | validation | @Override
public void init(Router router) {
this.router = router;
configureReflections();
controllers = Maps.newHashMap();
methods = Sets.newHashSet();
processFoundMethods();
sortMethods();
registerMethods();
} | java | {
"resource": ""
} |
q166377 | JaxyRoutes.processFoundMethods | validation | private void processFoundMethods() {
for (Method method : findControllerMethods()) {
if (allowMethod(method)) {
// add the method to our todo list
methods.add(method);
// generate the paths for the controller class
final Class<?> controllerClass = method.getDeclaringClass();
if (!controllers.containsKey(controllerClass)) {
Set<String> paths = collectPaths(controllerClass);
controllers.put(controllerClass, paths);
}
}
}
} | java | {
"resource": ""
} |
q166378 | JaxyRoutes.sortMethods | validation | private void sortMethods() {
List<Method> methodList = new ArrayList<>(methods);
Collections.sort(methodList, new Comparator<Method>() {
@Override
public int compare(Method m1, Method m2) {
int o1 = Integer.MAX_VALUE;
if (m1.isAnnotationPresent(Order.class)) {
Order order = m1.getAnnotation(Order.class);
o1 = order.value();
}
int o2 = Integer.MAX_VALUE;
if (m2.isAnnotationPresent(Order.class)) {
Order order = m2.getAnnotation(Order.class);
o2 = order.value();
}
if (o1 == o2) {
// same or unsorted, compare controller+method
String s1 = m1.getDeclaringClass().getName() + "."
+ m1.getName();
String s2 = m2.getDeclaringClass().getName() + "."
+ m2.getName();
return s1.compareTo(s2);
}
if (o1 < o2) {
return -1;
} else {
return 1;
}
}
});
methods = new LinkedHashSet<>(methodList);
} | java | {
"resource": ""
} |
q166379 | JaxyRoutes.findControllerMethods | validation | @SuppressWarnings("unchecked")
private Set<Method> findControllerMethods() {
Set<Method> methods = Sets.newLinkedHashSet();
methods.addAll(reflections.getMethodsAnnotatedWith(Path.class));
boolean enableCustomHttpMethods = ninjaProperties.getBooleanWithDefault(NINJA_CUSTOM_HTTP_METHODS, false);
if (enableCustomHttpMethods) {
Reflections annotationReflections = new Reflections("", new TypeAnnotationsScanner(), new SubTypesScanner());
for (Class<?> httpMethod : annotationReflections.getTypesAnnotatedWith(HttpMethod.class)) {
if (httpMethod.isAnnotation()) {
methods.addAll(reflections.getMethodsAnnotatedWith((Class<? extends Annotation>) httpMethod));
}
}
} else {
// Only look for standard HTTP methods annotations
Reflections annotationReflections = new Reflections("ninja.jaxy", new TypeAnnotationsScanner(), new SubTypesScanner());
for (Class<?> httpMethod : annotationReflections.getTypesAnnotatedWith(HttpMethod.class)) {
if (httpMethod.isAnnotation()) {
methods.addAll(reflections.getMethodsAnnotatedWith((Class<? extends Annotation>) httpMethod));
}
}
}
return methods;
} | java | {
"resource": ""
} |
q166380 | JaxyRoutes.configureReflections | validation | private void configureReflections() {
Optional<String> basePackage = Optional.ofNullable(ninjaProperties.get(NinjaConstant.APPLICATION_MODULES_BASE_PACKAGE));
if (basePackage.isPresent()) {
reflections = new Reflections(
basePackage.get() + "." + NinjaConstant.CONTROLLERS_DIR,
new MethodAnnotationsScanner());
} else {
reflections = new Reflections(
NinjaConstant.CONTROLLERS_DIR,
new MethodAnnotationsScanner());
}
} | java | {
"resource": ""
} |
q166381 | JaxyRoutes.allowMethod | validation | private boolean allowMethod(Method method) {
// NinjaProperties-based route exclusions/inclusions
if (method.isAnnotationPresent(Requires.class)) {
String key = method.getAnnotation(Requires.class).value();
String value = ninjaProperties.get(key);
if (value == null) {
return false;
}
}
// NinjaMode-based route exclusions/inclusions
Set<NinjaMode> modes = Sets.newTreeSet();
for (Annotation annotation : method.getAnnotations()) {
Class<? extends Annotation> annotationClass = annotation
.annotationType();
if (annotationClass.isAnnotationPresent(RuntimeMode.class)) {
RuntimeMode mode = annotationClass
.getAnnotation(RuntimeMode.class);
modes.add(mode.value());
}
}
return modes.isEmpty() || modes.contains(runtimeMode);
} | java | {
"resource": ""
} |
q166382 | JaxyRoutes.getHttpMethod | validation | private String getHttpMethod(Method method) {
for (Annotation annotation : method.getAnnotations()) {
Class<? extends Annotation> annotationClass = annotation
.annotationType();
if (annotationClass.isAnnotationPresent(HttpMethod.class)) {
HttpMethod httpMethod = annotationClass
.getAnnotation(HttpMethod.class);
return httpMethod.value();
}
}
// default to GET
logger.info(String
.format("%s.%s does not specify an HTTP method annotation! Defaulting to GET.",
method.getClass().getName(), method.getName()));
return HttpMethod.GET;
} | java | {
"resource": ""
} |
q166383 | ControllerMethodInvoker.build | validation | public static ControllerMethodInvoker build(
Method functionalMethod,
Method implementationMethod,
Injector injector,
NinjaProperties ninjaProperties) {
// get both the parameters...
final Type[] genericParameterTypes = implementationMethod.getGenericParameterTypes();
final MethodParameter[] methodParameters = MethodParameter.convertIntoMethodParameters(genericParameterTypes);
// ... and all annotations for the parameters
final Annotation[][] paramAnnotations = implementationMethod
.getParameterAnnotations();
ArgumentExtractor<?>[] argumentExtractors = new ArgumentExtractor<?>[methodParameters.length];
// now we skip through the parameters and process the annotations
for (int i = 0; i < methodParameters.length; i++) {
try {
argumentExtractors[i] = getArgumentExtractor(methodParameters[i], paramAnnotations[i],
injector);
} catch (RoutingException e) {
throw new RoutingException("Error building argument extractor for parameter " + i +
" in method " + implementationMethod.getDeclaringClass().getName() + "." + implementationMethod.getName() + "()", e);
}
}
// Replace a null extractor with a bodyAs extractor, but make sure there's only one
int bodyAsFound = -1;
for (int i = 0; i < argumentExtractors.length; i++) {
if (argumentExtractors[i] == null) {
if (bodyAsFound > -1) {
throw new RoutingException("Only one parameter may be deserialised as the body "
+ implementationMethod.getDeclaringClass().getName() + "." + implementationMethod.getName() + "()\n"
+ "Extracted parameter is type: " + methodParameters[bodyAsFound].parameterClass.getName() + "\n"
+ "Extra parmeter is type: " + methodParameters[i].parameterClass.getName());
} else {
argumentExtractors[i] = new ArgumentExtractors.BodyAsExtractor(methodParameters[i].parameterClass);
bodyAsFound = i;
}
}
}
// Now that every parameter has an argument extractor we can run validation on the annotated
// parameters
for (int i = 0; i < argumentExtractors.length; i++) {
argumentExtractors[i] =
validateArgumentWithExtractor(
methodParameters[i],
paramAnnotations[i],
injector,
argumentExtractors[i]);
}
boolean useStrictArgumentExtractors = determineWhetherToUseStrictArgumentExtractorMode(ninjaProperties);
return new ControllerMethodInvoker(functionalMethod, argumentExtractors, useStrictArgumentExtractors);
} | java | {
"resource": ""
} |
q166384 | SwissKnife.getRealClassNameLowerCamelCase | validation | public static String getRealClassNameLowerCamelCase(Object object) {
return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, object.getClass().getSimpleName());
} | java | {
"resource": ""
} |
q166385 | SwissKnife.doesClassExist | validation | public static boolean doesClassExist(String nameWithPackage, Object instanceToGetClassloaderFrom) {
boolean exists = false;
try {
Class.forName(nameWithPackage, false, instanceToGetClassloaderFrom.getClass().getClassLoader());
exists = true;
} catch (ClassNotFoundException e) {
exists = false;
}
return exists;
} | java | {
"resource": ""
} |
q166386 | DiagnosticErrorBuilder.getSourceCodeRelativePathForStackTraceElement | validation | static public String getSourceCodeRelativePathForStackTraceElement(StackTraceElement ste) {
String packageName = ste.getClassName();
// e.g. com.fizzed.test.Application$1 for an internal class
int pos = packageName.lastIndexOf('.');
if (pos > 0) {
packageName = packageName.substring(0, pos);
return
packageName.replace(".", File.separator)
+ File.separator
+ ste.getFileName();
} else {
// must be in default package
return
ste.getFileName();
}
} | java | {
"resource": ""
} |
q166387 | NinjaCache.add | validation | public void add(String key, Object value, String expiration) {
checkSerializable(value);
cache.add(key, value, TimeUtil.parseDuration(expiration));
} | java | {
"resource": ""
} |
q166388 | NinjaCache.get | validation | @SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> clazz) {
return (T) cache.get(key);
} | java | {
"resource": ""
} |
q166389 | NinjaCache.checkSerializable | validation | void checkSerializable(Object value) {
if (value != null && !(value instanceof Serializable)) {
throw new CacheException(
"Cannot cache a non-serializable value of type "
+ value.getClass().getName(),
new NotSerializableException(value.getClass().getName()));
}
} | java | {
"resource": ""
} |
q166390 | Result.render | validation | public Result render(String key, Object value) {
render(new AbstractMap.SimpleEntry<String, Object>(key, value));
return this;
} | java | {
"resource": ""
} |
q166391 | Result.renderRaw | validation | @Deprecated
public Result renderRaw(final String string) {
Renderable renderable = new Renderable() {
@Override
public void render(Context context, Result result) {
if (result.getContentType() == null) {
result.contentType(Result.TEXT_PLAIN);
}
ResponseStreams resultJsonCustom = context
.finalizeHeaders(result);
try (Writer writer = resultJsonCustom.getWriter()) {
writer.write(string);
} catch (IOException ioException) {
logger.error(
"Error rendering raw String via renderRaw(...)",
ioException);
}
}
};
render(renderable);
return this;
} | java | {
"resource": ""
} |
q166392 | Result.renderRaw | validation | public Result renderRaw(final byte [] bytes) {
Renderable renderable = new Renderable() {
@Override
public void render(Context context, Result result) {
if (result.getContentType() == null) {
result.contentType(Result.APPLICATION_OCTET_STREAM);
}
ResponseStreams responseStreams = context
.finalizeHeaders(result);
try (OutputStream outputStream = responseStreams.getOutputStream()) {
outputStream.write(bytes);
} catch (IOException ioException) {
throw new InternalServerErrorException(ioException);
}
}
};
render(renderable);
return this;
} | java | {
"resource": ""
} |
q166393 | Result.getCookie | validation | public Cookie getCookie(String cookieName) {
for (Cookie cookie : getCookies()) {
if (cookie.getName().equals(cookieName)) {
return cookie;
}
}
return null;
} | java | {
"resource": ""
} |
q166394 | Result.doNotCacheContent | validation | public Result doNotCacheContent() {
addHeader(CACHE_CONTROL, CACHE_CONTROL_DEFAULT_NOCACHE_VALUE);
addHeader(DATE, DateUtil.formatForHttpHeader(System.currentTimeMillis()));
addHeader(EXPIRES, DateUtil.formatForHttpHeader(0L));
return this;
} | java | {
"resource": ""
} |
q166395 | NinjaPropertiesImplTool.checkThatApplicationSecretIsSet | validation | public static void checkThatApplicationSecretIsSet(
boolean isProd,
String baseDirWithoutTrailingSlash,
PropertiesConfiguration defaultConfiguration,
Configuration compositeConfiguration) {
String applicationSecret = compositeConfiguration.getString(NinjaConstant.applicationSecret);
if (applicationSecret == null
|| applicationSecret.isEmpty()) {
// If in production we stop the startup process. It simply does not make
// sense to run in production if the secret is not set.
if (isProd) {
String errorMessage = "Fatal error. Key application.secret not set. Please fix that.";
logger.error(errorMessage);
throw new RuntimeException(errorMessage);
}
logger.info("Key application.secret not set. Generating new one and setting in conf/application.conf.");
// generate new secret
String secret = SecretGenerator.generateSecret();
// set in overall composite configuration => this enables this instance to
// start immediately. Otherwise we would have another build cycle.
compositeConfiguration.setProperty(NinjaConstant.applicationSecret, secret);
// defaultConfiguration is: conf/application.conf (not prefixed)
defaultConfiguration.setProperty(NinjaConstant.applicationSecret, secret);
try {
// STEP 1: Save in source directories:
// save to compiled version => in src/main/target/
String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION;
Files.createParentDirs(new File(pathToApplicationConfInSrcDir));
// save to source
defaultConfiguration.save(pathToApplicationConfInSrcDir);
// STEP 2: Save in classes dir (target/classes or similar).
// save in target directory (compiled version aka war aka classes dir)
defaultConfiguration.save();
} catch (ConfigurationException e) {
logger.error("Error while saving new secret to application.conf.", e);
} catch (IOException e) {
logger.error("Error while saving new secret to application.conf.", e);
}
}
} | java | {
"resource": ""
} |
q166396 | ArrayAdapter.addAll | validation | public boolean addAll(@NonNull final Collection<? extends T> collection) {
boolean result = mItems.addAll(collection);
notifyDataSetChanged();
return result;
} | java | {
"resource": ""
} |
q166397 | DragAndDropHandler.getPositionForId | validation | private int getPositionForId(final long itemId) {
View v = getViewForId(itemId);
if (v == null) {
return AdapterView.INVALID_POSITION;
} else {
return mWrapper.getPositionForView(v);
}
} | java | {
"resource": ""
} |
q166398 | DragAndDropHandler.switchViews | validation | private void switchViews(final View switchView, final long switchId, final float translationY) {
assert mHoverDrawable != null;
assert mAdapter != null;
assert mMobileView != null;
final int switchViewPosition = mWrapper.getPositionForView(switchView);
int mobileViewPosition = mWrapper.getPositionForView(mMobileView);
((Swappable) mAdapter).swapItems(switchViewPosition - mWrapper.getHeaderViewsCount(), mobileViewPosition - mWrapper.getHeaderViewsCount());
((BaseAdapter) mAdapter).notifyDataSetChanged();
mHoverDrawable.shift(switchView.getHeight());
mSwitchViewAnimator.animateSwitchView(switchId, translationY);
} | java | {
"resource": ""
} |
q166399 | InsertQueue.removeActiveIndex | validation | public void removeActiveIndex(final int index) {
boolean found = false;
for (Iterator<AtomicInteger> iterator = mActiveIndexes.iterator(); iterator.hasNext() && !found; ) {
if (iterator.next().get() == index) {
iterator.remove();
found = true;
}
}
if (mActiveIndexes.isEmpty()) {
insertPending();
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.