_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q170700
Time.parseCRONExpression
test
public static Date parseCRONExpression(String cron) { try { return new CronExpression(cron).getNextValidTimeAfter(new Date()); } catch (Exception e) { throw new IllegalArgumentException("Invalid CRON pattern : " + cron, e); } }
java
{ "resource": "" }
q170701
Time.cronInterval
test
public static long cronInterval(String cron, Date date) { try { return new CronExpression(cron).getNextInterval(date); } catch (Exception e) { throw new IllegalArgumentException("Invalid CRON pattern : " + cron, e); } }
java
{ "resource": "" }
q170702
AhcWSClient.create
test
public static AhcWSClient create( AhcWSClientConfig config, AhcHttpCache cache, Materializer materializer) { final StandaloneAhcWSClient client = StandaloneAhcWSClient.create(config, cache, materializer); return new AhcWSClient(client, materializer); }
java
{ "resource": "" }
q170703
GuiceApplicationLoader.builder
test
public GuiceApplicationBuilder builder(ApplicationLoader.Context context) { return initialBuilder .in(context.environment()) .loadConfig(context.initialConfig()) .overrides(overrides(context)); }
java
{ "resource": "" }
q170704
Controller.TODO
test
public static Result TODO(Request request) { return status(NOT_IMPLEMENTED, views.html.defaultpages.todo.render(request.asScala())); }
java
{ "resource": "" }
q170705
Controller.session
test
@Deprecated public static void session(String key, String value) { session().put(key, value); }
java
{ "resource": "" }
q170706
Controller.flash
test
@Deprecated public static void flash(String key, String value) { flash().put(key, value); }
java
{ "resource": "" }
q170707
BindingKey.qualifiedWith
test
public <A extends Annotation> BindingKey<T> qualifiedWith(final A instance) { return underlying.qualifiedWith(instance).asJava(); }
java
{ "resource": "" }
q170708
BindingKey.qualifiedWith
test
public <A extends Annotation> BindingKey<T> qualifiedWith(final Class<A> annotation) { return underlying.qualifiedWith(annotation).asJava(); }
java
{ "resource": "" }
q170709
BindingKey.to
test
public Binding<T> to(final Class<? extends T> implementation) { return underlying.to(implementation).asJava(); }
java
{ "resource": "" }
q170710
BindingKey.to
test
public Binding<T> to(final Provider<? extends T> provider) { return underlying.to(provider).asJava(); }
java
{ "resource": "" }
q170711
BindingKey.to
test
public <A extends T> Binding<T> to(final Supplier<A> instance) { return underlying.to(new FromJavaSupplier<>(instance)).asJava(); }
java
{ "resource": "" }
q170712
BindingKey.to
test
public Binding<T> to(final BindingKey<? extends T> key) { return underlying.to(key.asScala()).asJava(); }
java
{ "resource": "" }
q170713
BindingKey.toProvider
test
public <P extends Provider<? extends T>> Binding<T> toProvider(final Class<P> provider) { return underlying.toProvider(provider).asJava(); }
java
{ "resource": "" }
q170714
Lang.availables
test
public static List<Lang> availables(Application app) { play.api.i18n.Langs langs = app.injector().instanceOf(play.api.i18n.Langs.class); List<play.api.i18n.Lang> availableLangs = Scala.asJava(langs.availables()); return availableLangs.stream().map(Lang::new).collect(toList()); }
java
{ "resource": "" }
q170715
Lang.preferred
test
public static Lang preferred(Application app, List<Lang> availableLangs) { play.api.i18n.Langs langs = app.injector().instanceOf(play.api.i18n.Langs.class); Stream<Lang> stream = availableLangs.stream(); List<play.api.i18n.Lang> langSeq = stream.map(l -> new play.api.i18n.Lang(l.toLocale())).collect(toList()); return new Lang(langs.preferred(Scala.toSeq(langSeq))); }
java
{ "resource": "" }
q170716
Evolutions.fromMap
test
public static play.api.db.evolutions.EvolutionsReader fromMap( Map<String, List<Evolution>> evolutions) { return new SimpleEvolutionsReader(evolutions); }
java
{ "resource": "" }
q170717
Evolutions.forDefault
test
public static play.api.db.evolutions.EvolutionsReader forDefault(Evolution... evolutions) { Map<String, List<Evolution>> map = new HashMap<String, List<Evolution>>(); map.put("default", Arrays.asList(evolutions)); return fromMap(map); }
java
{ "resource": "" }
q170718
Evolutions.cleanupEvolutions
test
public static void cleanupEvolutions(Database database, boolean autocommit, String schema) { DatabaseEvolutions evolutions = new DatabaseEvolutions(database.asScala(), schema); evolutions.evolve(evolutions.resetScripts(), autocommit); }
java
{ "resource": "" }
q170719
GuiceApplicationBuilder.withConfigLoader
test
public GuiceApplicationBuilder withConfigLoader(Function<Environment, Config> load) { return newBuilder( delegate.loadConfig( func( (play.api.Environment env) -> new play.api.Configuration(load.apply(new Environment(env)))))); }
java
{ "resource": "" }
q170720
GuiceApplicationBuilder.withModuleLoader
test
public GuiceApplicationBuilder withModuleLoader( BiFunction<Environment, Config, List<GuiceableModule>> loader) { return newBuilder( delegate.load( func( (play.api.Environment env, play.api.Configuration conf) -> Scala.toSeq(loader.apply(new Environment(env), conf.underlying()))))); }
java
{ "resource": "" }
q170721
GuiceApplicationBuilder.load
test
public GuiceApplicationBuilder load(GuiceableModule... modules) { return newBuilder(delegate.load(Scala.varargs(modules))); }
java
{ "resource": "" }
q170722
GuiceApplicationBuilder.load
test
public GuiceApplicationBuilder load(com.google.inject.Module... modules) { return load(Guiceable.modules(modules)); }
java
{ "resource": "" }
q170723
GuiceApplicationBuilder.load
test
public GuiceApplicationBuilder load(play.api.inject.Module... modules) { return load(Guiceable.modules(modules)); }
java
{ "resource": "" }
q170724
GuiceApplicationBuilder.load
test
public GuiceApplicationBuilder load(play.api.inject.Binding<?>... bindings) { return load(Guiceable.bindings(bindings)); }
java
{ "resource": "" }
q170725
GuiceApplicationBuilder.newBuilder
test
protected GuiceApplicationBuilder newBuilder( play.api.inject.guice.GuiceApplicationBuilder builder) { return new GuiceApplicationBuilder(builder); }
java
{ "resource": "" }
q170726
ClientCookieEncoder.encode
test
public String encode(Cookie cookie) { if (cookie == null) { throw new NullPointerException("cookie"); } StringBuilder buf = new StringBuilder(); encode(buf, cookie); return stripTrailingSeparator(buf); }
java
{ "resource": "" }
q170727
JPAEntityManagerContext.em
test
public EntityManager em() { Deque<EntityManager> ems = this.emStack(true); if (ems.isEmpty()) { Http.Context.safeCurrent() .map( ctx -> { throw new RuntimeException( "No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional"); }) .orElseGet( () -> { throw new RuntimeException( "No EntityManager bound to this thread. Try wrapping this call in JPAApi.withTransaction, or ensure that the HTTP context is setup on this thread."); }); } return ems.peekFirst(); }
java
{ "resource": "" }
q170728
JPAEntityManagerContext.emStack
test
@SuppressWarnings("unchecked") public Deque<EntityManager> emStack(boolean threadLocalFallback) { return Http.Context.safeCurrent() .map( context -> { Object emsObject = context.args.get(CURRENT_ENTITY_MANAGER); if (emsObject != null) { return (Deque<EntityManager>) emsObject; } else { Deque<EntityManager> ems = new ArrayDeque<>(); context.args.put(CURRENT_ENTITY_MANAGER, ems); return ems; } }) .orElseGet( () -> { // Not a web request if (threadLocalFallback) { return this.get(); } else { throw new RuntimeException( "No Http.Context is present. If you want to invoke this method outside of a HTTP request, you need to wrap the call with JPA.withTransaction instead."); } }); }
java
{ "resource": "" }
q170729
JPAEntityManagerContext.pushOrPopEm
test
void pushOrPopEm(EntityManager em, boolean threadLocalFallback) { Deque<EntityManager> ems = this.emStack(threadLocalFallback); if (em != null) { ems.push(em); } else { if (ems.isEmpty()) { throw new IllegalStateException("Tried to remove the EntityManager, but none was set."); } ems.pop(); } }
java
{ "resource": "" }
q170730
AkkaStreams.bypassWith
test
public static <In, FlowIn, Out> Flow<In, Out, ?> bypassWith( Function<In, F.Either<FlowIn, Out>> splitter, Flow<FlowIn, Out, ?> flow) { return bypassWith( Flow.<In>create().map(splitter::apply), play.api.libs.streams.AkkaStreams.onlyFirstCanFinishMerge(2), flow); }
java
{ "resource": "" }
q170731
AkkaStreams.bypassWith
test
public static <In, FlowIn, Out> Flow<In, Out, ?> bypassWith( Flow<In, F.Either<FlowIn, Out>, ?> splitter, Graph<UniformFanInShape<Out, Out>, ?> mergeStrategy, Flow<FlowIn, Out, ?> flow) { return splitter.via( Flow.fromGraph( GraphDSL.<FlowShape<F.Either<FlowIn, Out>, Out>>create( builder -> { // Eager cancel must be true so that if the flow cancels, that will be propagated // upstream. // However, that means the bypasser must block cancel, since when this flow // finishes, the merge // will result in a cancel flowing up through the bypasser, which could lead to // dropped messages. // Using scaladsl here because of https://github.com/akka/akka/issues/18384 UniformFanOutShape<F.Either<FlowIn, Out>, F.Either<FlowIn, Out>> broadcast = builder.add(Broadcast.create(2, true)); UniformFanInShape<Out, Out> merge = builder.add(mergeStrategy); Flow<F.Either<FlowIn, Out>, FlowIn, ?> collectIn = Flow.<F.Either<FlowIn, Out>>create() .collect( Scala.partialFunction( x -> { if (x.left.isPresent()) { return x.left.get(); } else { throw Scala.noMatch(); } })); Flow<F.Either<FlowIn, Out>, Out, ?> collectOut = Flow.<F.Either<FlowIn, Out>>create() .collect( Scala.partialFunction( x -> { if (x.right.isPresent()) { return x.right.get(); } else { throw Scala.noMatch(); } })); Flow<F.Either<FlowIn, Out>, F.Either<FlowIn, Out>, ?> blockCancel = play.api.libs.streams.AkkaStreams .<F.Either<FlowIn, Out>>ignoreAfterCancellation() .asJava(); // Normal flow builder .from(broadcast.out(0)) .via(builder.add(collectIn)) .via(builder.add(flow)) .toInlet(merge.in(0)); // Bypass flow, need to ignore downstream finish builder .from(broadcast.out(1)) .via(builder.add(blockCancel)) .via(builder.add(collectOut)) .toInlet(merge.in(1)); return new FlowShape<>(broadcast.in(), merge.out()); }))); }
java
{ "resource": "" }
q170732
ActorFlow.actorRef
test
public static <In, Out> Flow<In, Out, ?> actorRef( Function<ActorRef, Props> props, int bufferSize, OverflowStrategy overflowStrategy, ActorRefFactory factory, Materializer mat) { return play.api.libs.streams.ActorFlow.<In, Out>actorRef( new AbstractFunction1<ActorRef, Props>() { @Override public Props apply(ActorRef v1) { return props.apply(v1); } }, bufferSize, overflowStrategy, factory, mat) .asJava(); }
java
{ "resource": "" }
q170733
Form.convertErrorArguments
test
private List<Object> convertErrorArguments(Object[] arguments) { if (arguments == null) { return Collections.emptyList(); } List<Object> converted = Arrays.stream(arguments) .filter( arg -> !(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) .collect(Collectors.toList()); return Collections.unmodifiableList(converted); }
java
{ "resource": "" }
q170734
Form.fill
test
public Form<T> fill(T value) { if (value == null) { throw new RuntimeException("Cannot fill a form with a null value"); } return new Form<>( rootName, backedType, new HashMap<>(), new HashMap<>(), new ArrayList<>(), Optional.ofNullable(value), groups, messagesApi, formatters, validatorFactory, config, lang, directFieldAccess); }
java
{ "resource": "" }
q170735
Form.globalErrors
test
public List<ValidationError> globalErrors() { return Collections.unmodifiableList( errors.stream().filter(error -> error.key().isEmpty()).collect(Collectors.toList())); }
java
{ "resource": "" }
q170736
Form.errorsAsJson
test
public JsonNode errorsAsJson(Lang lang) { Map<String, List<String>> allMessages = new HashMap<>(); errors.forEach( error -> { if (error != null) { final List<String> messages = new ArrayList<>(); if (messagesApi != null && lang != null) { final List<String> reversedMessages = new ArrayList<>(error.messages()); Collections.reverse(reversedMessages); messages.add( messagesApi.get( lang, reversedMessages, translateMsgArg(error.arguments(), messagesApi, lang))); } else { messages.add(error.message()); } allMessages.put(error.key(), messages); } }); return play.libs.Json.toJson(allMessages); }
java
{ "resource": "" }
q170737
DynamicForm.value
test
public Optional<Object> value(String key) { return super.value().map(v -> v.getData().get(asNormalKey(key))); }
java
{ "resource": "" }
q170738
DynamicForm.fill
test
public DynamicForm fill(Map<String, Object> value) { Form<Dynamic> form = super.fill(new Dynamic(value)); return new DynamicForm( form.rawData(), form.files(), form.errors(), form.value(), messagesApi, formatters, validatorFactory, config, lang().orElse(null)); }
java
{ "resource": "" }
q170739
Formatters.parse
test
public <T> T parse(String text, Class<T> clazz) { return conversion.convert(text, clazz); }
java
{ "resource": "" }
q170740
Formatters.parse
test
@SuppressWarnings("unchecked") public <T> T parse(Field field, String text) { return (T) conversion.convert(text, new TypeDescriptor(field)); }
java
{ "resource": "" }
q170741
Formatters.print
test
public <T> String print(T t) { if (t == null) { return ""; } if (conversion.canConvert(t.getClass(), String.class)) { return conversion.convert(t, String.class); } else { return t.toString(); } }
java
{ "resource": "" }
q170742
Formatters.print
test
public <T> String print(Field field, T t) { return print(new TypeDescriptor(field), t); }
java
{ "resource": "" }
q170743
Formatters.print
test
public <T> String print(TypeDescriptor desc, T t) { if (t == null) { return ""; } if (desc != null && conversion.canConvert(desc, TypeDescriptor.valueOf(String.class))) { return (String) conversion.convert(t, desc, TypeDescriptor.valueOf(String.class)); } else if (conversion.canConvert(t.getClass(), String.class)) { return conversion.convert(t, String.class); } else { return t.toString(); } }
java
{ "resource": "" }
q170744
Formatters.registerOptional
test
private Formatters registerOptional() { conversion.addConverter( new GenericConverter() { public Object convert( Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (sourceType.getObjectType().equals(String.class)) { // From String to Optional Object element = conversion.convert(source, sourceType, targetType.elementTypeDescriptor(source)); return Optional.ofNullable(element); } else if (targetType.getObjectType().equals(String.class)) { // From Optional to String if (source == null) return ""; Optional<?> opt = (Optional) source; return opt.map( o -> conversion.convert( source, sourceType.getElementTypeDescriptor(), targetType)) .orElse(""); } return null; } public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> result = new HashSet<>(); result.add(new ConvertiblePair(Optional.class, String.class)); result.add(new ConvertiblePair(String.class, Optional.class)); return result; } }); return this; }
java
{ "resource": "" }
q170745
Formatters.register
test
public <T> Formatters register(final Class<T> clazz, final SimpleFormatter<T> formatter) { conversion.addFormatterForFieldType( clazz, new org.springframework.format.Formatter<T>() { public T parse(String text, Locale locale) throws java.text.ParseException { return formatter.parse(text, locale); } public String print(T t, Locale locale) { return formatter.print(t, locale); } public String toString() { return formatter.toString(); } }); return this; }
java
{ "resource": "" }
q170746
Formatters.register
test
@SuppressWarnings("unchecked") public <A extends Annotation, T> Formatters register( final Class<T> clazz, final AnnotationFormatter<A, T> formatter) { final Class<? extends Annotation> annotationType = (Class<? extends Annotation>) GenericTypeResolver.resolveTypeArguments( formatter.getClass(), AnnotationFormatter.class)[0]; conversion.addConverter( new ConditionalGenericConverter() { public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() { Set<GenericConverter.ConvertiblePair> types = new HashSet<>(); types.add(new GenericConverter.ConvertiblePair(clazz, String.class)); return types; } public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return (sourceType.getAnnotation(annotationType) != null); } public Object convert( Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { final A a = (A) sourceType.getAnnotation(annotationType); Locale locale = LocaleContextHolder.getLocale(); try { return formatter.print(a, (T) source, locale); } catch (Exception ex) { throw new ConversionFailedException(sourceType, targetType, source, ex); } } public String toString() { return "@" + annotationType.getName() + " " + clazz.getName() + " -> " + String.class.getName() + ": " + formatter; } }); conversion.addConverter( new ConditionalGenericConverter() { public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() { Set<GenericConverter.ConvertiblePair> types = new HashSet<>(); types.add(new GenericConverter.ConvertiblePair(String.class, clazz)); return types; } public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return (targetType.getAnnotation(annotationType) != null); } public Object convert( Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { final A a = (A) targetType.getAnnotation(annotationType); Locale locale = LocaleContextHolder.getLocale(); try { return formatter.parse(a, (String) source, locale); } catch (Exception ex) { throw new ConversionFailedException(sourceType, targetType, source, ex); } } public String toString() { return String.class.getName() + " -> @" + annotationType.getName() + " " + clazz.getName() + ": " + formatter; } }); return this; }
java
{ "resource": "" }
q170747
ServerCookieEncoder.encode
test
public String encode(Cookie cookie) { if (cookie == null) { throw new NullPointerException("cookie"); } final String name = cookie.name(); final String value = cookie.value() != null ? cookie.value() : ""; validateCookie(name, value); StringBuilder buf = new StringBuilder(); if (cookie.wrap()) { addQuoted(buf, name, value); } else { add(buf, name, value); } if (cookie.maxAge() != Integer.MIN_VALUE) { add(buf, CookieHeaderNames.MAX_AGE, cookie.maxAge()); Date expires = cookie.maxAge() <= 0 ? new Date(0) // Set expires to the Unix epoch : new Date(cookie.maxAge() * 1000L + System.currentTimeMillis()); add(buf, CookieHeaderNames.EXPIRES, HttpHeaderDateFormat.get().format(expires)); } if (cookie.sameSite() != null) { add(buf, CookieHeaderNames.SAMESITE, cookie.sameSite()); } if (cookie.path() != null) { add(buf, CookieHeaderNames.PATH, cookie.path()); } if (cookie.domain() != null) { add(buf, CookieHeaderNames.DOMAIN, cookie.domain()); } if (cookie.isSecure()) { add(buf, CookieHeaderNames.SECURE); } if (cookie.isHttpOnly()) { add(buf, CookieHeaderNames.HTTPONLY); } return stripTrailingSeparator(buf); }
java
{ "resource": "" }
q170748
XPath.selectNodes
test
public static NodeList selectNodes(String path, Object node) { return selectNodes(path, node, null); }
java
{ "resource": "" }
q170749
CrossScala.toSeq
test
public static <T> scala.collection.immutable.Seq<T> toSeq(java.util.List<T> list) { return scala.collection.JavaConverters.asScalaBufferConverter(list).asScala().toList(); }
java
{ "resource": "" }
q170750
CrossScala.toSeq
test
public static <T> scala.collection.immutable.Seq<T> toSeq(T[] array) { return toSeq(java.util.Arrays.asList(array)); }
java
{ "resource": "" }
q170751
CrossScala.varargs
test
@SafeVarargs public static <T> scala.collection.immutable.Seq<T> varargs(T... array) { return toSeq(array); }
java
{ "resource": "" }
q170752
WebSocket.json
test
public static <In, Out> MappedWebSocketAcceptor<In, Out> json(Class<In> in) { return new MappedWebSocketAcceptor<>( Scala.partialFunction( message -> { try { if (message instanceof Message.Binary) { return F.Either.Left( play.libs.Json.mapper() .readValue( ((Message.Binary) message).data().iterator().asInputStream(), in)); } else if (message instanceof Message.Text) { return F.Either.Left( play.libs.Json.mapper().readValue(((Message.Text) message).data(), in)); } } catch (Exception e) { return F.Either.Right(new Message.Close(CloseCodes.Unacceptable(), e.getMessage())); } throw Scala.noMatch(); }), outMessage -> { try { return new Message.Text(play.libs.Json.mapper().writeValueAsString(outMessage)); } catch (Exception e) { throw new RuntimeException(e); } }); }
java
{ "resource": "" }
q170753
WebSocket.acceptOrResult
test
private static <In, Out> WebSocket acceptOrResult( PartialFunction<Message, F.Either<In, Message>> inMapper, Function<Http.RequestHeader, CompletionStage<F.Either<Result, Flow<In, Out, ?>>>> f, Function<Out, Message> outMapper) { return new WebSocket() { @Override public CompletionStage<F.Either<Result, Flow<Message, Message, ?>>> apply( Http.RequestHeader request) { return f.apply(request) .thenApply( resultOrFlow -> { if (resultOrFlow.left.isPresent()) { return F.Either.Left(resultOrFlow.left.get()); } else { Flow<Message, Message, ?> flow = AkkaStreams.bypassWith( Flow.<Message>create().collect(inMapper), play.api.libs.streams.AkkaStreams.onlyFirstCanFinishMerge(2), resultOrFlow.right.get().map(outMapper::apply)); return F.Either.Right(flow); } }); } }; }
java
{ "resource": "" }
q170754
MemberUtils.setAccessibleWorkaround
test
static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; } final Member m = (Member) o; if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); return true; } catch (final SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false; }
java
{ "resource": "" }
q170755
MemberUtils.getPrimitivePromotionCost
test
private static float getPrimitivePromotionCost( final Class<?> srcClass, final Class<?> destClass) { float cost = 0.0f; Class<?> cls = srcClass; if (!cls.isPrimitive()) { // slight unwrapping penalty cost += 0.1f; cls = ClassUtils.wrapperToPrimitive(cls); } for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) { if (cls == ORDERED_PRIMITIVE_TYPES[i]) { cost += 0.1f; if (i < ORDERED_PRIMITIVE_TYPES.length - 1) { cls = ORDERED_PRIMITIVE_TYPES[i + 1]; } } } return cost; }
java
{ "resource": "" }
q170756
MemberUtils.getTotalTransformationCost
test
private static float getTotalTransformationCost( final Class<?>[] srcArgs, final Executable executable) { final Class<?>[] destArgs = executable.getParameterTypes(); final boolean isVarArgs = executable.isVarArgs(); // "source" and "destination" are the actual and declared args respectively. float totalCost = 0.0f; final long normalArgsLen = isVarArgs ? destArgs.length - 1 : destArgs.length; if (srcArgs.length < normalArgsLen) { return Float.MAX_VALUE; } for (int i = 0; i < normalArgsLen; i++) { totalCost += getObjectTransformationCost(srcArgs[i], destArgs[i]); } if (isVarArgs) { // When isVarArgs is true, srcArgs and dstArgs may differ in length. // There are two special cases to consider: final boolean noVarArgsPassed = srcArgs.length < destArgs.length; final boolean explicitArrayForVarags = srcArgs.length == destArgs.length && srcArgs[srcArgs.length - 1].isArray(); final float varArgsCost = 0.001f; final Class<?> destClass = destArgs[destArgs.length - 1].getComponentType(); if (noVarArgsPassed) { // When no varargs passed, the best match is the most generic matching type, not the most // specific. totalCost += getObjectTransformationCost(destClass, Object.class) + varArgsCost; } else if (explicitArrayForVarags) { final Class<?> sourceClass = srcArgs[srcArgs.length - 1].getComponentType(); totalCost += getObjectTransformationCost(sourceClass, destClass) + varArgsCost; } else { // This is typical varargs case. for (int i = destArgs.length - 1; i < srcArgs.length; i++) { final Class<?> srcClass = srcArgs[i]; totalCost += getObjectTransformationCost(srcClass, destClass) + varArgsCost; } } } return totalCost; }
java
{ "resource": "" }
q170757
MemberUtils.getObjectTransformationCost
test
private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) { if (destClass.isPrimitive()) { return getPrimitivePromotionCost(srcClass, destClass); } float cost = 0.0f; while (srcClass != null && !destClass.equals(srcClass)) { if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) { // slight penalty for interface match. // we still want an exact match to override an interface match, // but // an interface match should override anything where we have to // get a superclass. cost += 0.25f; break; } cost++; srcClass = srcClass.getSuperclass(); } /* * If the destination class is null, we've traveled all the way up to * an Object match. We'll penalize this by adding 1.5 to the cost. */ if (srcClass == null) { cost += 1.5f; } return cost; }
java
{ "resource": "" }
q170758
MessagesImpl.at
test
public String at(String key, Object... args) { return messagesApi.get(lang, key, args); }
java
{ "resource": "" }
q170759
MessagesImpl.at
test
public String at(List<String> keys, Object... args) { return messagesApi.get(lang, keys, args); }
java
{ "resource": "" }
q170760
Databases.createFrom
test
public static Database createFrom( String driver, String url, Map<String, ? extends Object> config) { return createFrom("default", driver, url, config); }
java
{ "resource": "" }
q170761
ParallelSorter.create
test
public static ParallelSorter create(Object[] arrays) { Generator gen = new Generator(); gen.setArrays(arrays); return gen.create(); }
java
{ "resource": "" }
q170762
ParallelSorter.quickSort
test
public void quickSort(int index, int lo, int hi, Comparator cmp) { chooseComparer(index, cmp); super.quickSort(lo, hi - 1); }
java
{ "resource": "" }
q170763
ParallelSorter.mergeSort
test
public void mergeSort(int index, int lo, int hi, Comparator cmp) { chooseComparer(index, cmp); super.mergeSort(lo, hi - 1); }
java
{ "resource": "" }
q170764
MethodProxy.invoke
test
public Object invoke(Object obj, Object[] args) throws Throwable { try { init(); FastClassInfo fci = fastClassInfo; return fci.f1.invoke(fci.i1, obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (IllegalArgumentException e) { if (fastClassInfo.i1 < 0) throw new IllegalArgumentException("Protected method: " + sig1); throw e; } }
java
{ "resource": "" }
q170765
CodeEmitter.cast_numeric
test
public void cast_numeric(Type from, Type to) { if (from != to) { if (from == Type.DOUBLE_TYPE) { if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.D2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.D2L); } else { mv.visitInsn(Constants.D2I); cast_numeric(Type.INT_TYPE, to); } } else if (from == Type.FLOAT_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.F2D); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.F2L); } else { mv.visitInsn(Constants.F2I); cast_numeric(Type.INT_TYPE, to); } } else if (from == Type.LONG_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.L2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.L2F); } else { mv.visitInsn(Constants.L2I); cast_numeric(Type.INT_TYPE, to); } } else { if (to == Type.BYTE_TYPE) { mv.visitInsn(Constants.I2B); } else if (to == Type.CHAR_TYPE) { mv.visitInsn(Constants.I2C); } else if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.I2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.I2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.I2L); } else if (to == Type.SHORT_TYPE) { mv.visitInsn(Constants.I2S); } } } }
java
{ "resource": "" }
q170766
CodeEmitter.load_arg
test
public void load_arg(int index) { load_local(state.argumentTypes[index], state.localOffset + skipArgs(index)); }
java
{ "resource": "" }
q170767
CodeEmitter.emit_field
test
void emit_field(int opcode, Type ctype, String name, Type ftype) { mv.visitFieldInsn(opcode, ctype.getInternalName(), name, ftype.getDescriptor()); }
java
{ "resource": "" }
q170768
CodeEmitter.zero_or_null
test
public void zero_or_null(Type type) { if (TypeUtils.isPrimitive(type)) { switch (type.getSort()) { case Type.DOUBLE: push(0d); break; case Type.LONG: push(0L); break; case Type.FLOAT: push(0f); break; case Type.VOID: aconst_null(); default: push(0); } } else { aconst_null(); } }
java
{ "resource": "" }
q170769
CodeEmitter.unbox_or_zero
test
public void unbox_or_zero(Type type) { if (TypeUtils.isPrimitive(type)) { if (type != Type.VOID_TYPE) { Label nonNull = make_label(); Label end = make_label(); dup(); ifnonnull(nonNull); pop(); zero_or_null(type); goTo(end); mark(nonNull); unbox(type); mark(end); } } else { checkcast(type); } }
java
{ "resource": "" }
q170770
EmitUtils.process_array
test
public static void process_array(CodeEmitter e, Type type, ProcessArrayCallback callback) { Type componentType = TypeUtils.getComponentType(type); Local array = e.make_local(); Local loopvar = e.make_local(Type.INT_TYPE); Label loopbody = e.make_label(); Label checkloop = e.make_label(); e.store_local(array); e.push(0); e.store_local(loopvar); e.goTo(checkloop); e.mark(loopbody); e.load_local(array); e.load_local(loopvar); e.array_load(componentType); callback.processElement(componentType); e.iinc(loopvar, 1); e.mark(checkloop); e.load_local(loopvar); e.load_local(array); e.arraylength(); e.if_icmp(e.LT, loopbody); }
java
{ "resource": "" }
q170771
EmitUtils.nullcmp
test
private static void nullcmp(CodeEmitter e, Label oneNull, Label bothNull) { e.dup2(); Label nonNull = e.make_label(); Label oneNullHelper = e.make_label(); Label end = e.make_label(); e.ifnonnull(nonNull); e.ifnonnull(oneNullHelper); e.pop2(); e.goTo(bothNull); e.mark(nonNull); e.ifnull(oneNullHelper); e.goTo(end); e.mark(oneNullHelper); e.pop2(); e.goTo(oneNull); e.mark(end); }
java
{ "resource": "" }
q170772
BridgeMethodResolver.resolveAll
test
public Map/*<Signature, Signature>*/resolveAll() { Map resolved = new HashMap(); for (Iterator entryIter = declToBridge.entrySet().iterator(); entryIter.hasNext(); ) { Map.Entry entry = (Map.Entry) entryIter.next(); Class owner = (Class) entry.getKey(); Set bridges = (Set) entry.getValue(); try { InputStream is = classLoader.getResourceAsStream(owner.getName().replace('.', '/') + ".class"); if (is == null) { return resolved; } try { new ClassReader(is) .accept(new BridgedFinder(bridges, resolved), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); } finally { is.close(); } } catch (IOException ignored) {} } return resolved; }
java
{ "resource": "" }
q170773
Enhancer.getMethods
test
public static void getMethods(Class superclass, Class[] interfaces, List methods) { getMethods(superclass, interfaces, methods, null, null); }
java
{ "resource": "" }
q170774
Enhancer.filterConstructors
test
protected void filterConstructors(Class sc, List constructors) { CollectionUtils.filter(constructors, new VisibilityPredicate(sc, true)); if (constructors.size() == 0) throw new IllegalArgumentException("No visible constructors in " + sc); }
java
{ "resource": "" }
q170775
BeanGenerator.setSuperclass
test
public void setSuperclass(Class superclass) { if (superclass != null && superclass.equals(Object.class)) { superclass = null; } this.superclass = superclass; }
java
{ "resource": "" }
q170776
FieldProviderTransformer.getField
test
private void getField(String[] names) throws Exception { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, PROVIDER_GET, null); e.load_this(); e.load_arg(0); EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { Type type = (Type)fields.get(key); e.getfield((String)key); e.box(type); e.return_value(); } public void processDefault() { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field name"); } }); e.end_method(); }
java
{ "resource": "" }
q170777
InterfaceMaker.add
test
public void add(Method method) { add(ReflectUtils.getSignature(method), ReflectUtils.getExceptionTypes(method)); }
java
{ "resource": "" }
q170778
TinyBitSet.cardinality
test
public int cardinality() { int w = value; int c = 0; while (w != 0) { c += T[w & 255]; w >>= 8; } return c; }
java
{ "resource": "" }
q170779
AbstractClassGenerator.setNamingPolicy
test
public void setNamingPolicy(NamingPolicy namingPolicy) { if (namingPolicy == null) namingPolicy = DefaultNamingPolicy.INSTANCE; this.namingPolicy = namingPolicy; }
java
{ "resource": "" }
q170780
ReflectUtils.findMethods
test
public static Method[] findMethods(String[] namesAndDescriptors, Method[] methods) { Map map = new HashMap(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; map.put(method.getName() + Type.getMethodDescriptor(method), method); } Method[] result = new Method[namesAndDescriptors.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = (Method)map.get(namesAndDescriptors[i * 2] + namesAndDescriptors[i * 2 + 1]); if (result[i] == null) { // TODO: error? } } return result; }
java
{ "resource": "" }
q170781
PathUtil.resolve
test
public static Path resolve(final Path base, String child) { if (StringUtil.startsWithChar(child, File.separatorChar)) { child = child.substring(1); } return base.resolve(child); }
java
{ "resource": "" }
q170782
PathUtil.readString
test
public static String readString(final Path path) throws IOException { try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { StringWriter writer = new StringWriter(); // flush & close not needed for StringWriter-instance StreamUtil.copy(reader, writer); return writer.toString(); } }
java
{ "resource": "" }
q170783
HttpRequest.host
test
public HttpRequest host(final String host) { this.host = host; if (headers.contains(HEADER_HOST)) { headerOverwrite(HEADER_HOST, host); } return this; }
java
{ "resource": "" }
q170784
HttpRequest.create
test
public static HttpRequest create(final String method, final String destination) { return new HttpRequest() .method(method.toUpperCase()) .set(destination); }
java
{ "resource": "" }
q170785
HttpRequest.connect
test
public static HttpRequest connect(final String destination) { return new HttpRequest() .method(HttpMethod.CONNECT) .set(destination); }
java
{ "resource": "" }
q170786
HttpRequest.get
test
public static HttpRequest get(final String destination) { return new HttpRequest() .method(HttpMethod.GET) .set(destination); }
java
{ "resource": "" }
q170787
HttpRequest.post
test
public static HttpRequest post(final String destination) { return new HttpRequest() .method(HttpMethod.POST) .set(destination); }
java
{ "resource": "" }
q170788
HttpRequest.put
test
public static HttpRequest put(final String destination) { return new HttpRequest() .method(HttpMethod.PUT) .set(destination); }
java
{ "resource": "" }
q170789
HttpRequest.patch
test
public static HttpRequest patch(final String destination) { return new HttpRequest() .method(HttpMethod.PATCH) .set(destination); }
java
{ "resource": "" }
q170790
HttpRequest.delete
test
public static HttpRequest delete(final String destination) { return new HttpRequest() .method(HttpMethod.DELETE) .set(destination); }
java
{ "resource": "" }
q170791
HttpRequest.head
test
public static HttpRequest head(final String destination) { return new HttpRequest() .method(HttpMethod.HEAD) .set(destination); }
java
{ "resource": "" }
q170792
HttpRequest.trace
test
public static HttpRequest trace(final String destination) { return new HttpRequest() .method(HttpMethod.TRACE) .set(destination); }
java
{ "resource": "" }
q170793
HttpRequest.options
test
public static HttpRequest options(final String destination) { return new HttpRequest() .method(HttpMethod.OPTIONS) .set(destination); }
java
{ "resource": "" }
q170794
HttpRequest.path
test
public HttpRequest path(String path) { // this must be the only place that sets the path if (!path.startsWith(StringPool.SLASH)) { path = StringPool.SLASH + path; } int ndx = path.indexOf('?'); if (ndx != -1) { String queryString = path.substring(ndx + 1); path = path.substring(0, ndx); query = HttpUtil.parseQuery(queryString, true); } else { query = HttpMultiMap.newCaseInsensitiveMap(); } this.path = path; return this; }
java
{ "resource": "" }
q170795
HttpRequest.cookies
test
public HttpRequest cookies(final Cookie... cookies) { if (cookies.length == 0) { return this; } StringBuilder cookieString = new StringBuilder(); boolean first = true; for (Cookie cookie : cookies) { Integer maxAge = cookie.getMaxAge(); if (maxAge != null && maxAge.intValue() == 0) { continue; } if (!first) { cookieString.append("; "); } first = false; cookieString.append(cookie.getName()); cookieString.append('='); cookieString.append(cookie.getValue()); } headerOverwrite("cookie", cookieString.toString()); return this; }
java
{ "resource": "" }
q170796
HttpRequest.query
test
public HttpRequest query(final String name1, final Object value1, final Object... parameters) { query(name1, value1 == null ? null : value1.toString()); for (int i = 0; i < parameters.length; i += 2) { String name = parameters[i].toString(); String value = parameters[i + 1].toString(); query.add(name, value); } return this; }
java
{ "resource": "" }
q170797
HttpRequest.query
test
public HttpRequest query(final Map<String, String> queryMap) { for (Map.Entry<String, String> entry : queryMap.entrySet()) { query.add(entry.getKey(), entry.getValue()); } return this; }
java
{ "resource": "" }
q170798
HttpRequest.queryString
test
public HttpRequest queryString(final String queryString, final boolean decode) { this.query = HttpUtil.parseQuery(queryString, decode); return this; }
java
{ "resource": "" }
q170799
HttpRequest.queryString
test
public String queryString() { if (query == null) { return StringPool.EMPTY; } return HttpUtil.buildQuery(query, queryEncoding); }
java
{ "resource": "" }