_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q170400
JsonPath.get
test
public <T> T get(String path) { final JSONAssertion jsonAssertion = createJsonAssertion(path, params); final Object json = jsonParser.parseWith(createConfigurableJsonSlurper()); return (T) jsonAssertion.getResult(json, null); }
java
{ "resource": "" }
q170401
JsonPath.getInt
test
public int getInt(String path) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get(path); if (value instanceof Integer) { return (Integer) value; } else if (value instanceof Short) { return ((Short) value).intValue(); } else if (value instanceof Long) { return ((Long) value).intValue(); } else { return ObjectConverter.convertObjectTo(value, Integer.class); } }
java
{ "resource": "" }
q170402
JsonPath.getByte
test
public byte getByte(String path) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get(path); if (value instanceof Byte) { return (Byte) value; } else if (value instanceof Long) { return ((Long) value).byteValue(); } else if (value instanceof Integer) { return ((Integer) value).byteValue(); } else { return ObjectConverter.convertObjectTo(value, Byte.class); } }
java
{ "resource": "" }
q170403
JsonPath.getShort
test
public short getShort(String path) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get(path); if (value instanceof Short) { return (Short) value; } else if (value instanceof Long) { return ((Long) value).shortValue(); } else if (value instanceof Integer) { return ((Integer) value).shortValue(); } else { return ObjectConverter.convertObjectTo(value, Short.class); } }
java
{ "resource": "" }
q170404
JsonPath.getFloat
test
public float getFloat(String path) { final Object value = get(path); //Groovy will always return a Double for floating point values. if (value instanceof Double) { return ((Double) value).floatValue(); } else { return ObjectConverter.convertObjectTo(value, Float.class); } }
java
{ "resource": "" }
q170405
JsonPath.getDouble
test
public double getDouble(String path) { final Object value = get(path); if (value instanceof Double) { return (Double) value; } return ObjectConverter.convertObjectTo(value, Double.class); }
java
{ "resource": "" }
q170406
JsonPath.getLong
test
public long getLong(String path) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get(path); if (value instanceof Long) { return (Long) value; } else if (value instanceof Short) { return ((Short) value).longValue(); } else if (value instanceof Integer) { return ((Integer) value).longValue(); } else { return ObjectConverter.convertObjectTo(value, Long.class); } }
java
{ "resource": "" }
q170407
JsonPath.getList
test
public <T> List<T> getList(String path, Class<T> genericType) { if (genericType == null) { throw new IllegalArgumentException("Generic type cannot be null"); } final List<T> original = get(path); final List<T> newList = new LinkedList<T>(); if (original != null) { for (T t : original) { T e; if (t instanceof Map && !genericType.isAssignableFrom(Map.class)) { // TODO Avoid double parsing String str = objectToString(t); //noinspection unchecked e = (T) jsonStringToObject(str, genericType); } else { e = ObjectConverter.convertObjectTo(t, genericType); } newList.add(e); } } return Collections.unmodifiableList(newList); }
java
{ "resource": "" }
q170408
JsonPath.getMap
test
public <K, V> Map<K, V> getMap(String path) { return get(path); }
java
{ "resource": "" }
q170409
XmlPath.getObject
test
public <T> T getObject(String path, Class<T> objectType) { Object object = getFromPath(path, false); return getObjectAsType(object, objectType); }
java
{ "resource": "" }
q170410
RequestSpecBuilder.setBody
test
public RequestSpecBuilder setBody(Object object, ObjectMapper mapper) { spec.body(object, mapper); return this; }
java
{ "resource": "" }
q170411
RequestSpecBuilder.addCookie
test
public RequestSpecBuilder addCookie(String key, Object value, Object... cookieNameValuePairs) { spec.cookie(key, value, cookieNameValuePairs); return this; }
java
{ "resource": "" }
q170412
RequestSpecBuilder.addParam
test
public RequestSpecBuilder addParam(String parameterName, Object... parameterValues) { spec.param(parameterName, parameterValues); return this; }
java
{ "resource": "" }
q170413
RequestSpecBuilder.addParam
test
public RequestSpecBuilder addParam(String parameterName, Collection<?> parameterValues) { spec.param(parameterName, parameterValues); return this; }
java
{ "resource": "" }
q170414
MockMvcParamConfig.formParamsUpdateStrategy
test
public MockMvcParamConfig formParamsUpdateStrategy(UpdateStrategy updateStrategy) { return new MockMvcParamConfig(queryParamsUpdateStrategy, updateStrategy, requestParameterUpdateStrategy, attributeUpdateStrategy, sessionUpdateStrategy, true); }
java
{ "resource": "" }
q170415
ResponseLoggingFilter.logResponseToIfMatches
test
public static Filter logResponseToIfMatches(PrintStream stream, Matcher<Integer> matcher) { return new ResponseLoggingFilter(stream, matcher); }
java
{ "resource": "" }
q170416
Cookies.cookies
test
public static Cookies cookies(Cookie cookie, Cookie... additionalCookies) { AssertParameter.notNull(cookie, "Cookie"); final List<Cookie> cookieList = new LinkedList<Cookie>(); cookieList.add(cookie); Collections.addAll(cookieList, additionalCookies); return new Cookies(cookieList); }
java
{ "resource": "" }
q170417
WeakKeySet.cleanUpForCollectedState
test
private void cleanUpForCollectedState(Set<KeyAndSource> keysAndSources) { synchronized (lock) { for (KeyAndSource keyAndSource : keysAndSources) { Multiset<Object> set = backingMap.get(keyAndSource.key); if (set != null) { set.remove(keyAndSource.source); if (set.isEmpty()) { backingMap.remove(keyAndSource.key); } } } } }
java
{ "resource": "" }
q170418
InjectorImpl.index
test
void index() { for (Binding<?> binding : state.getExplicitBindingsThisLevel().values()) { bindingsMultimap.put(binding.getKey().getTypeLiteral(), binding); } }
java
{ "resource": "" }
q170419
InjectorImpl.getBindingOrThrow
test
<T> BindingImpl<T> getBindingOrThrow(Key<T> key, Errors errors, JitLimitation jitType) throws ErrorsException { // Check explicit bindings, i.e. bindings created by modules. BindingImpl<T> binding = state.getExplicitBinding(key); if (binding != null) { return binding; } // Look for an on-demand binding. return getJustInTimeBinding(key, errors, jitType); }
java
{ "resource": "" }
q170420
InjectorImpl.convertConstantStringBinding
test
private <T> BindingImpl<T> convertConstantStringBinding(Key<T> key, Errors errors) throws ErrorsException { // Find a constant string binding. Key<String> stringKey = key.ofType(STRING_TYPE); BindingImpl<String> stringBinding = state.getExplicitBinding(stringKey); if (stringBinding == null || !stringBinding.isConstant()) { return null; } // We can't call getProvider().get() because this InstanceBinding may not have been inintialized // yet (because we may have been called during InternalInjectorCreator.initializeStatically and // instance binding validation hasn't happened yet.) @SuppressWarnings("unchecked") String stringValue = ((InstanceBinding<String>) stringBinding).getInstance(); Object source = stringBinding.getSource(); // Find a matching type converter. TypeLiteral<T> type = key.getTypeLiteral(); TypeConverterBinding typeConverterBinding = state.getConverter(stringValue, type, errors, source); if (typeConverterBinding == null) { // No converter can handle the given type. return null; } // Try to convert the string. A failed conversion results in an error. try { @SuppressWarnings("unchecked") // This cast is safe because we double check below. T converted = (T) typeConverterBinding.getTypeConverter().convert(stringValue, type); if (converted == null) { throw errors .converterReturnedNull(stringValue, source, type, typeConverterBinding) .toException(); } if (!type.getRawType().isInstance(converted)) { throw errors .conversionTypeError(stringValue, source, type, typeConverterBinding, converted) .toException(); } return new ConvertedConstantBindingImpl<T>( this, key, converted, stringBinding, typeConverterBinding); } catch (ErrorsException e) { throw e; } catch (RuntimeException e) { throw errors .conversionError(stringValue, source, type, typeConverterBinding, e) .toException(); } }
java
{ "resource": "" }
q170421
InjectorImpl.cleanup
test
private boolean cleanup(BindingImpl<?> binding, Set<Key> encountered) { boolean bindingFailed = false; Set<Dependency<?>> deps = getInternalDependencies(binding); for (Dependency dep : deps) { Key<?> depKey = dep.getKey(); InjectionPoint ip = dep.getInjectionPoint(); if (encountered.add(depKey)) { // only check if we haven't looked at this key yet BindingImpl depBinding = jitBindings.get(depKey); if (depBinding != null) { // if the binding still exists, validate boolean failed = cleanup(depBinding, encountered); // if children fail, we fail if (depBinding instanceof ConstructorBindingImpl) { ConstructorBindingImpl ctorBinding = (ConstructorBindingImpl) depBinding; ip = ctorBinding.getInternalConstructor(); if (!ctorBinding.isInitialized()) { failed = true; } } if (failed) { removeFailedJitBinding(depBinding, ip); bindingFailed = true; } } else if (state.getExplicitBinding(depKey) == null) { // ignore keys if they were explicitly bound, but if neither JIT // nor explicit, it's also invalid & should let parent know. bindingFailed = true; } } } return bindingFailed; }
java
{ "resource": "" }
q170422
InjectorImpl.removeFailedJitBinding
test
private void removeFailedJitBinding(Binding<?> binding, InjectionPoint ip) { failedJitBindings.add(binding.getKey()); jitBindings.remove(binding.getKey()); membersInjectorStore.remove(binding.getKey().getTypeLiteral()); provisionListenerStore.remove(binding); if (ip != null) { constructors.remove(ip); } }
java
{ "resource": "" }
q170423
InjectorImpl.getInternalDependencies
test
@SuppressWarnings("unchecked") private Set<Dependency<?>> getInternalDependencies(BindingImpl<?> binding) { if (binding instanceof ConstructorBindingImpl) { return ((ConstructorBindingImpl) binding).getInternalDependencies(); } else if (binding instanceof HasDependencies) { return ((HasDependencies) binding).getDependencies(); } else { return ImmutableSet.of(); } }
java
{ "resource": "" }
q170424
InjectorImpl.createUninitializedBinding
test
<T> BindingImpl<T> createUninitializedBinding( Key<T> key, Scoping scoping, Object source, Errors errors, boolean jitBinding) throws ErrorsException { Class<?> rawType = key.getTypeLiteral().getRawType(); ImplementedBy implementedBy = rawType.getAnnotation(ImplementedBy.class); // Don't try to inject arrays or enums annotated with @ImplementedBy. if (rawType.isArray() || (rawType.isEnum() && implementedBy != null)) { throw errors.missingImplementationWithHint(key, this).toException(); } // Handle TypeLiteral<T> by binding the inner type if (rawType == TypeLiteral.class) { @SuppressWarnings("unchecked") // we have to fudge the inner type as Object BindingImpl<T> binding = (BindingImpl<T>) createTypeLiteralBinding((Key<TypeLiteral<Object>>) key, errors); return binding; } // Handle @ImplementedBy if (implementedBy != null) { Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors); return createImplementedByBinding(key, scoping, implementedBy, errors); } // Handle @ProvidedBy. ProvidedBy providedBy = rawType.getAnnotation(ProvidedBy.class); if (providedBy != null) { Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors); return createProvidedByBinding(key, scoping, providedBy, errors); } return ConstructorBindingImpl.create( this, key, null, /* use default constructor */ source, scoping, errors, jitBinding && options.jitDisabled, options.atInjectRequired); }
java
{ "resource": "" }
q170425
SingleParameterInjector.getAll
test
static Object[] getAll(InternalContext context, SingleParameterInjector<?>[] parameterInjectors) throws InternalProvisionException { if (parameterInjectors == null) { return NO_ARGUMENTS; } int size = parameterInjectors.length; Object[] parameters = new Object[size]; // optimization: use manual for/each to save allocating an iterator here for (int i = 0; i < size; i++) { parameters[i] = parameterInjectors[i].inject(context); } return parameters; }
java
{ "resource": "" }
q170426
InjectorShell.bindInjector
test
private static void bindInjector(InjectorImpl injector) { Key<Injector> key = Key.get(Injector.class); InjectorFactory injectorFactory = new InjectorFactory(injector); injector.state.putBinding( key, new ProviderInstanceBindingImpl<Injector>( injector, key, SourceProvider.UNKNOWN_SOURCE, injectorFactory, Scoping.UNSCOPED, injectorFactory, ImmutableSet.<InjectionPoint>of())); }
java
{ "resource": "" }
q170427
InjectorShell.bindLogger
test
private static void bindLogger(InjectorImpl injector) { Key<Logger> key = Key.get(Logger.class); LoggerFactory loggerFactory = new LoggerFactory(); injector.state.putBinding( key, new ProviderInstanceBindingImpl<Logger>( injector, key, SourceProvider.UNKNOWN_SOURCE, loggerFactory, Scoping.UNSCOPED, loggerFactory, ImmutableSet.<InjectionPoint>of())); }
java
{ "resource": "" }
q170428
InjectionPoint.checkForMisplacedBindingAnnotations
test
private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) { Annotation misplacedBindingAnnotation = Annotations.findBindingAnnotation( errors, member, ((AnnotatedElement) member).getAnnotations()); if (misplacedBindingAnnotation == null) { return false; } // don't warn about misplaced binding annotations on methods when there's a field with the same // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242. if (member instanceof Method) { try { if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) { return false; } } catch (NoSuchFieldException ignore) { } } errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation); return true; }
java
{ "resource": "" }
q170429
InjectionPoint.overrides
test
private static boolean overrides(Method a, Method b) { // See JLS section 8.4.8.1 int modifiers = b.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { return true; } if (Modifier.isPrivate(modifiers)) { return false; } // b must be package-private return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage()); }
java
{ "resource": "" }
q170430
MembersInjectorLookup.initializeDelegate
test
public void initializeDelegate(MembersInjector<T> delegate) { checkState(this.delegate == null, "delegate already initialized"); this.delegate = checkNotNull(delegate, "delegate"); }
java
{ "resource": "" }
q170431
TypeLiteral.providerType
test
@SuppressWarnings("unchecked") final TypeLiteral<Provider<T>> providerType() { // This cast is safe and wouldn't generate a warning if Type had a type // parameter. return (TypeLiteral<Provider<T>>) get(Types.providerOf(getType())); }
java
{ "resource": "" }
q170432
TypeLiteral.resolveAll
test
private List<TypeLiteral<?>> resolveAll(Type[] types) { TypeLiteral<?>[] result = new TypeLiteral<?>[types.length]; for (int t = 0; t < types.length; t++) { result[t] = resolve(types[t]); } return ImmutableList.copyOf(result); }
java
{ "resource": "" }
q170433
MoreTypes.canonicalizeForKey
test
public static <T> TypeLiteral<T> canonicalizeForKey(TypeLiteral<T> typeLiteral) { Type type = typeLiteral.getType(); if (!isFullySpecified(type)) { Errors errors = new Errors().keyNotFullySpecified(typeLiteral); throw new ConfigurationException(errors.getMessages()); } if (typeLiteral.getRawType() == javax.inject.Provider.class) { ParameterizedType parameterizedType = (ParameterizedType) type; // the following casts are generally unsafe, but com.google.inject.Provider extends // javax.inject.Provider and is covariant @SuppressWarnings("unchecked") TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get(Types.providerOf(parameterizedType.getActualTypeArguments()[0])); return guiceProviderType; } @SuppressWarnings("unchecked") TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral); if (wrappedPrimitives != null) { return wrappedPrimitives; } // If we know this isn't a subclass, return as-is. if (typeLiteral.getClass() == TypeLiteral.class) { return typeLiteral; } // recreate the TypeLiteral to avoid anonymous TypeLiterals from holding refs to their // surrounding classes. @SuppressWarnings("unchecked") TypeLiteral<T> recreated = (TypeLiteral<T>) TypeLiteral.get(typeLiteral.getType()); return recreated; }
java
{ "resource": "" }
q170434
TypeConverterBindingProcessor.prepareBuiltInConverters
test
static void prepareBuiltInConverters(InjectorImpl injector) { // Configure type converters. convertToPrimitiveType(injector, int.class, Integer.class); convertToPrimitiveType(injector, long.class, Long.class); convertToPrimitiveType(injector, boolean.class, Boolean.class); convertToPrimitiveType(injector, byte.class, Byte.class); convertToPrimitiveType(injector, short.class, Short.class); convertToPrimitiveType(injector, float.class, Float.class); convertToPrimitiveType(injector, double.class, Double.class); convertToClass( injector, Character.class, new TypeConverter() { @Override public Object convert(String value, TypeLiteral<?> toType) { value = value.trim(); if (value.length() != 1) { throw new RuntimeException("Length != 1."); } return value.charAt(0); } @Override public String toString() { return "TypeConverter<Character>"; } }); convertToClasses( injector, Matchers.subclassesOf(Enum.class), new TypeConverter() { @Override @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { return Enum.valueOf((Class) toType.getRawType(), value); } @Override public String toString() { return "TypeConverter<E extends Enum<E>>"; } }); internalConvertToTypes( injector, new AbstractMatcher<TypeLiteral<?>>() { @Override public boolean matches(TypeLiteral<?> typeLiteral) { return typeLiteral.getRawType() == Class.class; } @Override public String toString() { return "Class<?>"; } }, new TypeConverter() { @Override @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { try { return Class.forName(value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage()); } } @Override public String toString() { return "TypeConverter<Class<?>>"; } }); }
java
{ "resource": "" }
q170435
BytecodeGen.canonicalize
test
private static ClassLoader canonicalize(ClassLoader classLoader) { return classLoader != null ? classLoader : SystemBridgeHolder.SYSTEM_BRIDGE.getParent(); }
java
{ "resource": "" }
q170436
BytecodeGen.hasSameVersionOfCglib
test
private static boolean hasSameVersionOfCglib(ClassLoader classLoader) { Class<?> fc = net.sf.cglib.reflect.FastClass.class; try { return classLoader.loadClass(fc.getName()) == fc; } catch (ClassNotFoundException e) { return false; } }
java
{ "resource": "" }
q170437
BytecodeGen.isPubliclyCallable
test
private static boolean isPubliclyCallable(Member member) { if (!Modifier.isPublic(member.getModifiers())) { return false; } Class<?>[] parameterTypes; if (member instanceof Constructor) { parameterTypes = ((Constructor) member).getParameterTypes(); } else { Method method = (Method) member; if (!Modifier.isPublic(method.getReturnType().getModifiers())) { return false; } parameterTypes = method.getParameterTypes(); } for (Class<?> type : parameterTypes) { if (!Modifier.isPublic(type.getModifiers())) { return false; } } return true; }
java
{ "resource": "" }
q170438
Parameter.fixAnnotations
test
public Key<?> fixAnnotations(Key<?> key) { return key.getAnnotation() == null ? key : Key.get(key.getTypeLiteral(), key.getAnnotation().annotationType()); }
java
{ "resource": "" }
q170439
Initializer.requestInjection
test
<T> Initializable<T> requestInjection( InjectorImpl injector, T instance, Binding<T> binding, Object source, Set<InjectionPoint> injectionPoints) { checkNotNull(source); Preconditions.checkState( !validationStarted, "Member injection could not be requested after validation is started"); ProvisionListenerStackCallback<T> provisionCallback = binding == null ? null : injector.provisionListenerStore.get(binding); // short circuit if the object has no injections or listeners. if (instance == null || (injectionPoints.isEmpty() && !injector.membersInjectorStore.hasTypeListeners() && provisionCallback == null)) { return Initializables.of(instance); } if (initializablesCache.containsKey(instance)) { @SuppressWarnings("unchecked") // Map from T to InjectableReference<T> Initializable<T> cached = (Initializable<T>) initializablesCache.get(instance); return cached; } InjectableReference<T> injectableReference = new InjectableReference<T>( injector, instance, binding == null ? null : binding.getKey(), provisionCallback, source, cycleDetectingLockFactory.create(instance.getClass())); initializablesCache.put(instance, injectableReference); pendingInjections.add(injectableReference); return injectableReference; }
java
{ "resource": "" }
q170440
Initializer.validateOustandingInjections
test
void validateOustandingInjections(Errors errors) { validationStarted = true; initializablesCache.clear(); for (InjectableReference<?> reference : pendingInjections) { try { reference.validate(errors); } catch (ErrorsException e) { errors.merge(e.getErrors()); } } }
java
{ "resource": "" }
q170441
AssistedConstructor.newInstance
test
public T newInstance(Object[] args) throws Throwable { constructor.setAccessible(true); try { return constructor.newInstance(args); } catch (InvocationTargetException e) { throw e.getCause(); } }
java
{ "resource": "" }
q170442
ManagedFilterPipeline.withDispatcher
test
@SuppressWarnings({"JavaDoc", "deprecation"}) private ServletRequest withDispatcher( ServletRequest servletRequest, final ManagedServletPipeline servletPipeline) { // don't wrap the request if there are no servlets mapped. This prevents us from inserting our // wrapper unless it's actually going to be used. This is necessary for compatibility for apps // that downcast their HttpServletRequests to a concrete implementation. if (!servletPipeline.hasServletsMapped()) { return servletRequest; } HttpServletRequest request = (HttpServletRequest) servletRequest; //noinspection OverlyComplexAnonymousInnerClass return new HttpServletRequestWrapper(request) { @Override public RequestDispatcher getRequestDispatcher(String path) { final RequestDispatcher dispatcher = servletPipeline.getRequestDispatcher(path); return (null != dispatcher) ? dispatcher : super.getRequestDispatcher(path); } }; }
java
{ "resource": "" }
q170443
Scoping.scope
test
static <T> InternalFactory<? extends T> scope( Key<T> key, InjectorImpl injector, InternalFactory<? extends T> creator, Object source, Scoping scoping) { if (scoping.isNoScope()) { return creator; } Scope scope = scoping.getScopeInstance(); // NOTE: SingletonScope relies on the fact that we are passing a // ProviderToInternalFactoryAdapter here. If you change the type make sure to update // SingletonScope as well. Provider<T> scoped = scope.scope(key, new ProviderToInternalFactoryAdapter<T>(injector, creator)); return new InternalFactoryToProviderAdapter<T>(scoped, source); }
java
{ "resource": "" }
q170444
Scoping.makeInjectable
test
static Scoping makeInjectable(Scoping scoping, InjectorImpl injector, Errors errors) { Class<? extends Annotation> scopeAnnotation = scoping.getScopeAnnotation(); if (scopeAnnotation == null) { return scoping; } ScopeBinding scope = injector.state.getScopeBinding(scopeAnnotation); if (scope != null) { return forInstance(scope.getScope()); } errors.scopeNotFound(scopeAnnotation); return UNSCOPED; }
java
{ "resource": "" }
q170445
ServletUtils.normalizePath
test
static String normalizePath(String path) { StringBuilder sb = new StringBuilder(path.length()); int queryStart = path.indexOf('?'); String query = null; if (queryStart != -1) { query = path.substring(queryStart); path = path.substring(0, queryStart); } // Normalize the path. we need to decode path segments, normalize and rejoin in order to // 1. decode and normalize safe percent escaped characters. e.g. %70 -> 'p' // 2. decode and interpret dangerous character sequences. e.g. /%2E/ -> '/./' -> '/' // 3. preserve dangerous encoded characters. e.g. '/%2F/' -> '///' -> '/%2F' List<String> segments = new ArrayList<>(); for (String segment : SLASH_SPLITTER.split(path)) { // This decodes all non-special characters from the path segment. so if someone passes // /%2E/foo we will normalize it to /./foo and then /foo String normalized = UrlEscapers.urlPathSegmentEscaper().escape(lenientDecode(segment, UTF_8, false)); if (".".equals(normalized)) { // skip } else if ("..".equals(normalized)) { if (segments.size() > 1) { segments.remove(segments.size() - 1); } } else { segments.add(normalized); } } SLASH_JOINER.appendTo(sb, segments); if (query != null) { sb.append(query); } return sb.toString(); }
java
{ "resource": "" }
q170446
Annotations.generateAnnotation
test
public static <T extends Annotation> T generateAnnotation(Class<T> annotationType) { Preconditions.checkState( isAllDefaultMethods(annotationType), "%s is not all default methods", annotationType); return (T) cache.getUnchecked(annotationType); }
java
{ "resource": "" }
q170447
Annotations.isRetainedAtRuntime
test
public static boolean isRetainedAtRuntime(Class<? extends Annotation> annotationType) { Retention retention = annotationType.getAnnotation(Retention.class); return retention != null && retention.value() == RetentionPolicy.RUNTIME; }
java
{ "resource": "" }
q170448
Annotations.findScopeAnnotation
test
public static Class<? extends Annotation> findScopeAnnotation( Errors errors, Annotation[] annotations) { Class<? extends Annotation> found = null; for (Annotation annotation : annotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); if (isScopeAnnotation(annotationType)) { if (found != null) { errors.duplicateScopeAnnotations(found, annotationType); } else { found = annotationType; } } } return found; }
java
{ "resource": "" }
q170449
Annotations.getKey
test
public static Key<?> getKey( TypeLiteral<?> type, Member member, Annotation[] annotations, Errors errors) throws ErrorsException { int numErrorsBefore = errors.size(); Annotation found = findBindingAnnotation(errors, member, annotations); errors.throwIfNewErrors(numErrorsBefore); return found == null ? Key.get(type) : Key.get(type, found); }
java
{ "resource": "" }
q170450
Annotations.nameOf
test
public static String nameOf(Key<?> key) { Annotation annotation = key.getAnnotation(); Class<? extends Annotation> annotationType = key.getAnnotationType(); if (annotation != null && !isMarker(annotationType)) { return key.getAnnotation().toString(); } else if (key.getAnnotationType() != null) { return "@" + key.getAnnotationType().getName(); } else { return ""; } }
java
{ "resource": "" }
q170451
ProviderLookup.initializeDelegate
test
public void initializeDelegate(Provider<T> delegate) { checkState(this.delegate == null, "delegate already initialized"); this.delegate = checkNotNull(delegate, "delegate"); }
java
{ "resource": "" }
q170452
RealOptionalBinder.addDirectTypeBinding
test
private void addDirectTypeBinding(Binder binder) { binder .bind(bindingSelection.getDirectKey()) .toProvider(new RealDirectTypeProvider<T>(bindingSelection)); }
java
{ "resource": "" }
q170453
ConstructorInjectorStore.get
test
public ConstructorInjector<?> get(InjectionPoint constructorInjector, Errors errors) throws ErrorsException { return cache.get(constructorInjector, errors); }
java
{ "resource": "" }
q170454
Struts2Factory.hasScope
test
private static boolean hasScope(Class<? extends Interceptor> interceptorClass) { for (Annotation annotation : interceptorClass.getAnnotations()) { if (Annotations.isScopeAnnotation(annotation.annotationType())) { return true; } } return false; }
java
{ "resource": "" }
q170455
RealMapBinder.newRealMapBinder
test
static <K, V> RealMapBinder<K, V> newRealMapBinder( Binder binder, TypeLiteral<K> keyType, Key<V> valueTypeAndAnnotation) { binder = binder.skipSources(RealMapBinder.class); TypeLiteral<V> valueType = valueTypeAndAnnotation.getTypeLiteral(); return newRealMapBinder( binder, keyType, valueType, valueTypeAndAnnotation.ofType(mapOf(keyType, valueType)), RealMultibinder.newRealSetBinder( binder, valueTypeAndAnnotation.ofType(entryOfProviderOf(keyType, valueType)))); }
java
{ "resource": "" }
q170456
RealMapBinder.getKeyForNewValue
test
Key<V> getKeyForNewValue(K key) { checkNotNull(key, "key"); checkConfiguration(!bindingSelection.isInitialized(), "MapBinder was already initialized"); RealMultibinder<Map.Entry<K, Provider<V>>> entrySetBinder = bindingSelection.getEntrySetBinder(); Key<V> valueKey = Key.get( bindingSelection.getValueType(), new RealElement( entrySetBinder.getSetName(), MAPBINDER, bindingSelection.getKeyType().toString())); entrySetBinder.addBinding().toProvider(new ProviderMapEntry<K, V>(key, valueKey)); return valueKey; }
java
{ "resource": "" }
q170457
ConstructorInjector.provision
test
private T provision(InternalContext context, ConstructionContext<T> constructionContext) throws InternalProvisionException { try { T t; try { Object[] parameters = SingleParameterInjector.getAll(context, parameterInjectors); t = constructionProxy.newInstance(parameters); constructionContext.setProxyDelegates(t); } finally { constructionContext.finishConstruction(); } // Store reference. If an injector re-enters this factory, they'll get the same reference. constructionContext.setCurrentReference(t); MembersInjectorImpl<T> localMembersInjector = membersInjector; localMembersInjector.injectMembers(t, context, false); localMembersInjector.notifyListeners(t); return t; } catch (InvocationTargetException userException) { Throwable cause = userException.getCause() != null ? userException.getCause() : userException; throw InternalProvisionException.errorInjectingConstructor(cause) .addSource(constructionProxy.getInjectionPoint()); } finally { constructionContext.removeCurrentReference(); } }
java
{ "resource": "" }
q170458
Message.writeReplace
test
private Object writeReplace() throws ObjectStreamException { Object[] sourcesAsStrings = sources.toArray(); for (int i = 0; i < sourcesAsStrings.length; i++) { sourcesAsStrings[i] = Errors.convert(sourcesAsStrings[i]).toString(); } return new Message(ImmutableList.copyOf(sourcesAsStrings), message, cause); }
java
{ "resource": "" }
q170459
CheckedProviderMethodsModule.forModule
test
static Module forModule(Module module) { // avoid infinite recursion, since installing a module always installs itself if (module instanceof CheckedProviderMethodsModule) { return Modules.EMPTY_MODULE; } return new CheckedProviderMethodsModule(module); }
java
{ "resource": "" }
q170460
FactoryProvider2.getAssistedMethods
test
@Override @SuppressWarnings("unchecked") public Collection<AssistedMethod> getAssistedMethods() { return (Collection<AssistedMethod>) (Collection<?>) assistDataByMethod.values(); }
java
{ "resource": "" }
q170461
FactoryProvider2.isTypeNotSpecified
test
private boolean isTypeNotSpecified(TypeLiteral<?> typeLiteral, ConfigurationException ce) { Collection<Message> messages = ce.getErrorMessages(); if (messages.size() == 1) { Message msg = Iterables.getOnlyElement(new Errors().keyNotFullySpecified(typeLiteral).getMessages()); return msg.getMessage().equals(Iterables.getOnlyElement(messages).getMessage()); } else { return false; } }
java
{ "resource": "" }
q170462
FactoryProvider2.constructorHasMatchingParams
test
private boolean constructorHasMatchingParams( TypeLiteral<?> type, Constructor<?> constructor, List<Key<?>> paramList, Errors errors) throws ErrorsException { List<TypeLiteral<?>> params = type.getParameterTypes(constructor); Annotation[][] paramAnnotations = constructor.getParameterAnnotations(); int p = 0; List<Key<?>> constructorKeys = Lists.newArrayList(); for (TypeLiteral<?> param : params) { Key<?> paramKey = Annotations.getKey(param, constructor, paramAnnotations[p++], errors); constructorKeys.add(paramKey); } // Require that every key exist in the constructor to match up exactly. for (Key<?> key : paramList) { // If it didn't exist in the constructor set, we can't use it. if (!constructorKeys.remove(key)) { return false; } } // If any keys remain and their annotation is Assisted, we can't use it. for (Key<?> key : constructorKeys) { if (key.getAnnotationType() == Assisted.class) { return false; } } // All @Assisted params match up to the method's parameters. return true; }
java
{ "resource": "" }
q170463
FactoryProvider2.getDependencies
test
private Set<Dependency<?>> getDependencies( InjectionPoint ctorPoint, TypeLiteral<?> implementation) { ImmutableSet.Builder<Dependency<?>> builder = ImmutableSet.builder(); builder.addAll(ctorPoint.getDependencies()); if (!implementation.getRawType().isInterface()) { for (InjectionPoint ip : InjectionPoint.forInstanceMethodsAndFields(implementation)) { builder.addAll(ip.getDependencies()); } } return builder.build(); }
java
{ "resource": "" }
q170464
FactoryProvider2.removeAssistedDeps
test
private Set<Dependency<?>> removeAssistedDeps(Set<Dependency<?>> deps) { ImmutableSet.Builder<Dependency<?>> builder = ImmutableSet.builder(); for (Dependency<?> dep : deps) { Class<?> annotationType = dep.getKey().getAnnotationType(); if (annotationType == null || !annotationType.equals(Assisted.class)) { builder.add(dep); } } return builder.build(); }
java
{ "resource": "" }
q170465
FactoryProvider2.isValidForOptimizedAssistedInject
test
private boolean isValidForOptimizedAssistedInject( Set<Dependency<?>> dependencies, Class<?> implementation, TypeLiteral<?> factoryType) { Set<Dependency<?>> badDeps = null; // optimization: create lazily for (Dependency<?> dep : dependencies) { if (isInjectorOrAssistedProvider(dep)) { if (badDeps == null) { badDeps = Sets.newHashSet(); } badDeps.add(dep); } } if (badDeps != null && !badDeps.isEmpty()) { logger.log( Level.WARNING, "AssistedInject factory {0} will be slow " + "because {1} has assisted Provider dependencies or injects the Injector. " + "Stop injecting @Assisted Provider<T> (instead use @Assisted T) " + "or Injector to speed things up. (It will be a ~6500% speed bump!) " + "The exact offending deps are: {2}", new Object[] {factoryType, implementation, badDeps}); return false; } return true; }
java
{ "resource": "" }
q170466
FactoryProvider2.getBindingFromNewInjector
test
public Binding<?> getBindingFromNewInjector( final Method method, final Object[] args, final AssistData data) { checkState( injector != null, "Factories.create() factories cannot be used until they're initialized by Guice."); final Key<?> returnType = data.returnType; // We ignore any pre-existing binding annotation. final Key<?> returnKey = Key.get(returnType.getTypeLiteral(), RETURN_ANNOTATION); Module assistedModule = new AbstractModule() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) // raw keys are necessary for the args array and return value protected void configure() { Binder binder = binder().withSource(method); int p = 0; if (!data.optimized) { for (Key<?> paramKey : data.paramTypes) { // Wrap in a Provider to cover null, and to prevent Guice from injecting the // parameter binder.bind((Key) paramKey).toProvider(Providers.of(args[p++])); } } else { for (Key<?> paramKey : data.paramTypes) { // Bind to our ThreadLocalProviders. binder.bind((Key) paramKey).toProvider(data.providers.get(p++)); } } Constructor constructor = data.constructor; // Constructor *should* always be non-null here, // but if it isn't, we'll end up throwing a fairly good error // message for the user. if (constructor != null) { binder .bind(returnKey) .toConstructor(constructor, (TypeLiteral) data.implementationType) .in(Scopes.NO_SCOPE); // make sure we erase any scope on the implementation type } } }; Injector forCreate = injector.createChildInjector(assistedModule); Binding<?> binding = forCreate.getBinding(returnKey); // If we have providers cached in data, cache the binding for future optimizations. if (data.optimized) { data.cachedBinding = binding; } return binding; }
java
{ "resource": "" }
q170467
FactoryProvider2.invoke
test
@Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { // If we setup a method handle earlier for this method, call it. // This is necessary for default methods that java8 creates, so we // can call the default method implementation (and not our proxied version of it). if (methodHandleByMethod.containsKey(method)) { return methodHandleByMethod.get(method).invokeWithArguments(args); } if (method.getDeclaringClass().equals(Object.class)) { if ("equals".equals(method.getName())) { return proxy == args[0]; } else if ("hashCode".equals(method.getName())) { return System.identityHashCode(proxy); } else { return method.invoke(this, args); } } AssistData data = assistDataByMethod.get(method); checkState(data != null, "No data for method: %s", method); Provider<?> provider; if (data.cachedBinding != null) { // Try to get optimized form... provider = data.cachedBinding.getProvider(); } else { provider = getBindingFromNewInjector(method, args, data).getProvider(); } try { int p = 0; for (ThreadLocalProvider tlp : data.providers) { tlp.set(args[p++]); } return provider.get(); } catch (ProvisionException e) { // if this is an exception declared by the factory method, throw it as-is if (e.getErrorMessages().size() == 1) { Message onlyError = getOnlyElement(e.getErrorMessages()); Throwable cause = onlyError.getCause(); if (cause != null && canRethrow(method, cause)) { throw cause; } } throw e; } finally { for (ThreadLocalProvider tlp : data.providers) { tlp.remove(); } } }
java
{ "resource": "" }
q170468
Errors.missingImplementationWithHint
test
<T> Errors missingImplementationWithHint(Key<T> key, Injector injector) { StringBuilder sb = new StringBuilder(); sb.append(format("No implementation for %s was bound.", key)); // Keys which have similar strings as the desired key List<String> possibleMatches = new ArrayList<>(); // Check for other keys that may have the same type, // but not the same annotation TypeLiteral<T> type = key.getTypeLiteral(); List<Binding<T>> sameTypes = injector.findBindingsByType(type); if (!sameTypes.isEmpty()) { sb.append(format("%n Did you mean?")); int howMany = Math.min(sameTypes.size(), MAX_MATCHING_TYPES_REPORTED); for (int i = 0; i < howMany; ++i) { // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the given annotation vs actual annotation. sb.append(format("%n * %s", sameTypes.get(i).getKey())); } int remaining = sameTypes.size() - MAX_MATCHING_TYPES_REPORTED; if (remaining > 0) { String plural = (remaining == 1) ? "" : "s"; sb.append(format("%n %d more binding%s with other annotations.", remaining, plural)); } } else { // For now, do a simple substring search for possibilities. This can help spot // issues when there are generics being used (such as a wrapper class) and the // user has forgotten they need to bind based on the wrapper, not the underlying // class. In the future, consider doing a strict in-depth type search. // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the type literal strings. String want = type.toString(); Map<Key<?>, Binding<?>> bindingMap = injector.getAllBindings(); for (Key<?> bindingKey : bindingMap.keySet()) { String have = bindingKey.getTypeLiteral().toString(); if (have.contains(want) || want.contains(have)) { Formatter fmt = new Formatter(); Messages.formatSource(fmt, bindingMap.get(bindingKey).getSource()); String match = String.format("%s bound%s", convert(bindingKey), fmt.toString()); possibleMatches.add(match); // TODO: Consider a check that if there are more than some number of results, // don't suggest any. if (possibleMatches.size() > MAX_RELATED_TYPES_REPORTED) { // Early exit if we have found more than we need. break; } } } if ((possibleMatches.size() > 0) && (possibleMatches.size() <= MAX_RELATED_TYPES_REPORTED)) { sb.append(format("%n Did you mean?")); for (String possibleMatch : possibleMatches) { sb.append(format("%n %s", possibleMatch)); } } } // If where are no possibilities to suggest, then handle the case of missing // annotations on simple types. This is usually a bad idea. if (sameTypes.isEmpty() && possibleMatches.isEmpty() && key.getAnnotation() == null && COMMON_AMBIGUOUS_TYPES.contains(key.getTypeLiteral().getRawType())) { // We don't recommend using such simple types without annotations. sb.append(format("%nThe key seems very generic, did you forget an annotation?")); } return addMessage(sb.toString()); }
java
{ "resource": "" }
q170469
RealMultibinder.newRealSetBinder
test
public static <T> RealMultibinder<T> newRealSetBinder(Binder binder, Key<T> key) { binder = binder.skipSources(RealMultibinder.class); RealMultibinder<T> result = new RealMultibinder<>(binder, key); binder.install(result); return result; }
java
{ "resource": "" }
q170470
RealMultibinder.getKeyForNewItem
test
Key<T> getKeyForNewItem() { checkConfiguration(!bindingSelection.isInitialized(), "Multibinder was already initialized"); return Key.get( bindingSelection.getElementTypeLiteral(), new RealElement(bindingSelection.getSetName(), MULTIBINDER, "")); }
java
{ "resource": "" }
q170471
FilterChainInvocation.findNextFilter
test
private Filter findNextFilter(HttpServletRequest request) { while (++index < filterDefinitions.length) { Filter filter = filterDefinitions[index].getFilterIfMatching(request); if (filter != null) { return filter; } } return null; }
java
{ "resource": "" }
q170472
ConstructorBindingImpl.hasAtInject
test
private static boolean hasAtInject(Constructor cxtor) { return cxtor.isAnnotationPresent(Inject.class) || cxtor.isAnnotationPresent(javax.inject.Inject.class); }
java
{ "resource": "" }
q170473
ConstructorBindingImpl.getInternalConstructor
test
InjectionPoint getInternalConstructor() { if (factory.constructorInjector != null) { return factory.constructorInjector.getConstructionProxy().getInjectionPoint(); } else { return constructorInjectionPoint; } }
java
{ "resource": "" }
q170474
ConstructorBindingImpl.getInternalDependencies
test
Set<Dependency<?>> getInternalDependencies() { ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder(); if (factory.constructorInjector == null) { builder.add(constructorInjectionPoint); // If the below throws, it's OK -- we just ignore those dependencies, because no one // could have used them anyway. try { builder.addAll( InjectionPoint.forInstanceMethodsAndFields( constructorInjectionPoint.getDeclaringType())); } catch (ConfigurationException ignored) { } } else { builder.add(getConstructor()).addAll(getInjectableMembers()); } return Dependency.forInjectionPoints(builder.build()); }
java
{ "resource": "" }
q170475
ProviderMethodsModule.forModule
test
public static Module forModule(Object module, ModuleAnnotatedMethodScanner scanner) { return forObject(module, false, scanner); }
java
{ "resource": "" }
q170476
ProviderMethodsModule.getAnnotation
test
private Annotation getAnnotation(Binder binder, Method method) { if (method.isBridge() || method.isSynthetic()) { return null; } Annotation annotation = null; for (Class<? extends Annotation> annotationClass : scanner.annotationClasses()) { Annotation foundAnnotation = method.getAnnotation(annotationClass); if (foundAnnotation != null) { if (annotation != null) { binder.addError( "More than one annotation claimed by %s on method %s." + " Methods can only have one annotation claimed per scanner.", scanner, method); return null; } annotation = foundAnnotation; } } return annotation; }
java
{ "resource": "" }
q170477
LineNumbers.getLineNumber
test
public Integer getLineNumber(Member member) { Preconditions.checkArgument( type == member.getDeclaringClass(), "Member %s belongs to %s, not %s", member, member.getDeclaringClass(), type); return lines.get(memberKey(member)); }
java
{ "resource": "" }
q170478
DeferredLookups.initialize
test
void initialize(Errors errors) { injector.lookups = injector; new LookupProcessor(errors).process(injector, lookups); }
java
{ "resource": "" }
q170479
ServletScopes.continueRequest
test
@Deprecated public static <T> Callable<T> continueRequest(Callable<T> callable, Map<Key<?>, Object> seedMap) { return wrap(callable, continueRequest(seedMap)); }
java
{ "resource": "" }
q170480
ServletScopes.transferRequest
test
public static <T> Callable<T> transferRequest(Callable<T> callable) { return wrap(callable, transferRequest()); }
java
{ "resource": "" }
q170481
ServletScopes.validateAndCanonicalizeValue
test
private static Object validateAndCanonicalizeValue(Key<?> key, Object object) { if (object == null || object == NullObject.INSTANCE) { return NullObject.INSTANCE; } if (!key.getTypeLiteral().getRawType().isInstance(object)) { throw new IllegalArgumentException( "Value[" + object + "] of type[" + object.getClass().getName() + "] is not compatible with key[" + key + "]"); } return object; }
java
{ "resource": "" }
q170482
MembersInjectorStore.get
test
@SuppressWarnings("unchecked") // the MembersInjector type always agrees with the passed type public <T> MembersInjectorImpl<T> get(TypeLiteral<T> key, Errors errors) throws ErrorsException { return (MembersInjectorImpl<T>) cache.get(key, errors); }
java
{ "resource": "" }
q170483
MembersInjectorStore.createWithListeners
test
private <T> MembersInjectorImpl<T> createWithListeners(TypeLiteral<T> type, Errors errors) throws ErrorsException { int numErrorsBefore = errors.size(); Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(type); } catch (ConfigurationException e) { errors.merge(e.getErrorMessages()); injectionPoints = e.getPartialValue(); } ImmutableList<SingleMemberInjector> injectors = getInjectors(injectionPoints, errors); errors.throwIfNewErrors(numErrorsBefore); EncounterImpl<T> encounter = new EncounterImpl<>(errors, injector.lookups); Set<TypeListener> alreadySeenListeners = Sets.newHashSet(); for (TypeListenerBinding binding : typeListenerBindings) { TypeListener typeListener = binding.getListener(); if (!alreadySeenListeners.contains(typeListener) && binding.getTypeMatcher().matches(type)) { alreadySeenListeners.add(typeListener); try { typeListener.hear(type, encounter); } catch (RuntimeException e) { errors.errorNotifyingTypeListener(binding, type, e); } } } encounter.invalidate(); errors.throwIfNewErrors(numErrorsBefore); return new MembersInjectorImpl<T>(injector, type, encounter, injectors); }
java
{ "resource": "" }
q170484
MembersInjectorStore.getInjectors
test
ImmutableList<SingleMemberInjector> getInjectors( Set<InjectionPoint> injectionPoints, Errors errors) { List<SingleMemberInjector> injectors = Lists.newArrayList(); for (InjectionPoint injectionPoint : injectionPoints) { try { Errors errorsForMember = injectionPoint.isOptional() ? new Errors(injectionPoint) : errors.withSource(injectionPoint); SingleMemberInjector injector = injectionPoint.getMember() instanceof Field ? new SingleFieldInjector(this.injector, injectionPoint, errorsForMember) : new SingleMethodInjector(this.injector, injectionPoint, errorsForMember); injectors.add(injector); } catch (ErrorsException ignoredForNow) { // ignored for now } } return ImmutableList.copyOf(injectors); }
java
{ "resource": "" }
q170485
Key.get
test
static <T> Key<T> get(Class<T> type, AnnotationStrategy annotationStrategy) { return new Key<T>(type, annotationStrategy); }
java
{ "resource": "" }
q170486
Key.strategyFor
test
static AnnotationStrategy strategyFor(Annotation annotation) { checkNotNull(annotation, "annotation"); Class<? extends Annotation> annotationType = annotation.annotationType(); ensureRetainedAtRuntime(annotationType); ensureIsBindingAnnotation(annotationType); if (Annotations.isMarker(annotationType)) { return new AnnotationTypeStrategy(annotationType, annotation); } return new AnnotationInstanceStrategy(Annotations.canonicalizeIfNamed(annotation)); }
java
{ "resource": "" }
q170487
Key.strategyFor
test
static AnnotationStrategy strategyFor(Class<? extends Annotation> annotationType) { annotationType = Annotations.canonicalizeIfNamed(annotationType); if (isAllDefaultMethods(annotationType)) { return strategyFor(generateAnnotation(annotationType)); } checkNotNull(annotationType, "annotation type"); ensureRetainedAtRuntime(annotationType); ensureIsBindingAnnotation(annotationType); return new AnnotationTypeStrategy(annotationType, null); }
java
{ "resource": "" }
q170488
InterceptorStackCallback.pruneStacktrace
test
private void pruneStacktrace(Throwable throwable) { for (Throwable t = throwable; t != null; t = t.getCause()) { StackTraceElement[] stackTrace = t.getStackTrace(); List<StackTraceElement> pruned = Lists.newArrayList(); for (StackTraceElement element : stackTrace) { String className = element.getClassName(); if (!AOP_INTERNAL_CLASSES.contains(className) && !className.contains("$EnhancerByGuice$")) { pruned.add(element); } } t.setStackTrace(pruned.toArray(new StackTraceElement[pruned.size()])); } }
java
{ "resource": "" }
q170489
DependencyAndSource.getBindingSource
test
public String getBindingSource() { if (source instanceof Class) { return StackTraceElements.forType((Class) source).toString(); } else if (source instanceof Member) { return StackTraceElements.forMember((Member) source).toString(); } else { return source.toString(); } }
java
{ "resource": "" }
q170490
Messages.formatMessages
test
public static String formatMessages(String heading, Collection<Message> errorMessages) { Formatter fmt = new Formatter().format(heading).format(":%n%n"); int index = 1; boolean displayCauses = getOnlyCause(errorMessages) == null; Map<Equivalence.Wrapper<Throwable>, Integer> causes = Maps.newHashMap(); for (Message errorMessage : errorMessages) { int thisIdx = index++; fmt.format("%s) %s%n", thisIdx, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); formatSource(fmt, source); } Throwable cause = errorMessage.getCause(); if (displayCauses && cause != null) { Equivalence.Wrapper<Throwable> causeEquivalence = ThrowableEquivalence.INSTANCE.wrap(cause); if (!causes.containsKey(causeEquivalence)) { causes.put(causeEquivalence, thisIdx); fmt.format("Caused by: %s", Throwables.getStackTraceAsString(cause)); } else { int causeIdx = causes.get(causeEquivalence); fmt.format( "Caused by: %s (same stack trace as error #%s)", cause.getClass().getName(), causeIdx); } } fmt.format("%n"); } if (errorMessages.size() == 1) { fmt.format("1 error"); } else { fmt.format("%s errors", errorMessages.size()); } return fmt.toString(); }
java
{ "resource": "" }
q170491
Messages.create
test
public static Message create(String messageFormat, Object... arguments) { return create(null, messageFormat, arguments); }
java
{ "resource": "" }
q170492
Messages.create
test
public static Message create(Throwable cause, String messageFormat, Object... arguments) { return create(cause, ImmutableList.of(), messageFormat, arguments); }
java
{ "resource": "" }
q170493
Messages.create
test
public static Message create( Throwable cause, List<Object> sources, String messageFormat, Object... arguments) { String message = format(messageFormat, arguments); return new Message(sources, message, cause); }
java
{ "resource": "" }
q170494
Messages.convert
test
static Object convert(Object o) { ElementSource source = null; if (o instanceof ElementSource) { source = (ElementSource) o; o = source.getDeclaringSource(); } return convert(o, source); }
java
{ "resource": "" }
q170495
SourceProvider.shouldBeSkipped
test
private boolean shouldBeSkipped(String className) { return (parent != null && parent.shouldBeSkipped(className)) || classNamesToSkip.contains(className); }
java
{ "resource": "" }
q170496
SourceProvider.getFromClassNames
test
public Object getFromClassNames(List<String> moduleClassNames) { Preconditions.checkNotNull(moduleClassNames, "The list of module class names cannot be null."); for (final String moduleClassName : moduleClassNames) { if (!shouldBeSkipped(moduleClassName)) { return new StackTraceElement(moduleClassName, "configure", null, -1); } } return UNKNOWN_SOURCE; }
java
{ "resource": "" }
q170497
Manager.main
test
public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println( "Usage: java -Dcom.sun.management.jmxremote " + Manager.class.getName() + " [module class name]"); System.err.println("Then run 'jconsole' to connect."); System.exit(1); } Module module = (Module) Class.forName(args[0]).newInstance(); Injector injector = Guice.createInjector(module); manage(args[0], injector); System.out.println("Press Ctrl+C to exit..."); // Sleep forever. Thread.sleep(Long.MAX_VALUE); }
java
{ "resource": "" }
q170498
InternalContext.pushDependency
test
Dependency<?> pushDependency(Dependency<?> dependency, Object source) { Dependency<?> previous = this.dependency; this.dependency = dependency; doPushState(dependency, source); return previous; }
java
{ "resource": "" }
q170499
InternalContext.pushState
test
void pushState(com.google.inject.Key<?> key, Object source) { doPushState(key, source); }
java
{ "resource": "" }