code
stringlengths
73
34.1k
label
stringclasses
1 value
public static Type capture(Type type) { VarMap varMap = new VarMap(); List<CaptureTypeImpl> toInit = new ArrayList<>(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType)type; Class<?> clazz = (Class<?>)pType.getRawType(); Type[] arguments = pType.getActualTypeArgument...
java
public static String getTypeName(Type type) { if(type instanceof Class) { Class<?> clazz = (Class<?>) type; return clazz.isArray() ? (getTypeName(clazz.getComponentType()) + "[]") : clazz.getName(); } else { return type.toString(); } }
java
private static void buildUpperBoundClassAndInterfaces(Type type, Set<Class<?>> result) { if (type instanceof ParameterizedType || type instanceof Class<?>) { result.add(erase(type)); return; } for (Type superType: getExactDirectSuperTypes(type)) { buildUpperBoundClassAndInterfaces(superType, result); ...
java
@Beta public <T> T Mock( @NamedParams({ @NamedParam(value = "name", type = String.class), @NamedParam(value = "additionalInterfaces", type = List.class), @NamedParam(value = "defaultResponse", type = IDefaultResponse.class), @NamedParam(value = "verified", type = Boolean.class), @Nam...
java
@Beta public <T> T Mock(Map<String, Object> options, Closure interactions) { invalidMockCreation(); return null; }
java
@Override @Beta public <T> T Stub(Class<T> type) { invalidMockCreation(); return null; }
java
@Override @Beta public <T> T Spy(Class<T> type) { invalidMockCreation(); return null; }
java
private boolean hasExpandableVarArgs(IMockMethod method, List<Object> args) { List<Class<?>> paramTypes = method.getParameterTypes(); return !paramTypes.isEmpty() && CollectionUtil.getLastElement(paramTypes).isArray() && CollectionUtil.getLastElement(args) != null; }
java
public void load(@Language("Groovy") String sourceText) throws CompilationFailedException { reset(); try { classLoader.parseClass(sourceText); } catch (AstSuccessfullyCaptured e) { indexAstNodes(); return; } throw new AstInspectorException("internal error"); }
java
public void load(File sourceFile) throws CompilationFailedException { reset(); try { classLoader.parseClass(sourceFile); } catch (IOException e) { throw new AstInspectorException("cannot read source file", e); } catch (AstSuccessfullyCaptured e) { indexAstNodes(); return; } ...
java
private int estimateNumIterations(Object[] dataProviders) { if (runStatus != OK) return -1; if (dataProviders.length == 0) return 1; int result = Integer.MAX_VALUE; for (Object prov : dataProviders) { if (prov instanceof Iterator) // unbelievably, DGM provides a size() method for Iterator...
java
private Object[] nextArgs(Iterator[] iterators) { if (runStatus != OK) return null; Object[] next = new Object[iterators.length]; for (int i = 0; i < iterators.length; i++) try { next[i] = iterators[i].next(); } catch (Throwable t) { runStatus = supervisor.error( new...
java
@Override public <T> T Mock(Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.MOCK, Collections.<String, Object>emptyMap()); }
java
@Override public <T> T Mock(Map<String, Object> options, Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.MOCK, options); }
java
@Override public <T> T Stub(Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.STUB, Collections.<String, Object>emptyMap()); }
java
@Override public <T> T Stub(Map<String, Object> options, Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.STUB, options); }
java
@Override public <T> T Spy(Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.SPY, Collections.<String, Object>emptyMap()); }
java
@Override public <T> T Spy(Map<String, Object> options, Class<T> type) { return createMock(inferNameFromType(type), type, MockNature.SPY, options); }
java
public static int getFeatureCount(Class<?> spec) { checkIsSpec(spec); int count = 0; do { for (Method method : spec.getDeclaredMethods()) if (method.isAnnotationPresent(FeatureMetadata.class)) count++; spec = spec.getSuperclass(); } while (spec != null && isSpec(spec)); ...
java
public boolean hasBytecodeName(String name) { if (featureMethod.hasBytecodeName(name)) return true; if (dataProcessorMethod != null && dataProcessorMethod.hasBytecodeName(name)) return true; for (DataProviderInfo provider : dataProviders) if (provider.getDataProviderMethod().hasBytecodeName(name)) ret...
java
@SuppressWarnings("unchecked") public static List<Statement> getStatements(MethodNode method) { Statement code = method.getCode(); if (!(code instanceof BlockStatement)) { // null or single statement BlockStatement block = new BlockStatement(); if (code != null) block.addStatement(code); met...
java
public static void fixUpLocalVariables(List<? extends Variable> localVariables, VariableScope scope, boolean isClosureScope) { for (Variable localVar : localVariables) { Variable scopeVar = scope.getReferencedClassVariable(localVar.getName()); if (scopeVar instanceof DynamicVariable) { scope.rem...
java
private void beforeKey() throws JSONException { Scope context = peek(); if (context == Scope.NONEMPTY_OBJECT) { // first in object out.append(','); } else if (context != Scope.EMPTY_OBJECT) { // not in an object! throw new JSONException("Nesting problem"); } ...
java
@Override public String getAuthorizationHeader(HttpRequest req) { return generateAuthorizationHeader(req.getMethod().name(), req.getURL(), req.getParameters(), oauthToken); }
java
StatusStream getSampleStream() throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.get(conf.getStreamBaseURL() + "statuses/sample.json?" + stallWarningsGetParam, null, auth, null), conf); } catch (IOExcep...
java
private void setHeaders(HttpRequest req, HttpURLConnection connection) { if (logger.isDebugEnabled()) { logger.debug("Request: "); logger.debug(req.getMethod().name() + " ", req.getURL()); } String authorizationHeader; if (req.getAuthorization() != null && (autho...
java
public static List<HttpParameter> decodeParameters(String queryParameters) { List<HttpParameter> result=new ArrayList<HttpParameter>(); for (String pair : queryParameters.split("&")) { String[] parts=pair.split("=", 2); if(parts.length == 2) { String name=decode(p...
java
@Override public void getOAuthRequestTokenAsync() { getDispatcher().invokeLater(new AsyncTask(OAUTH_REQUEST_TOKEN, listeners) { @Override public void invoke(List<TwitterListener> listeners) throws TwitterException { RequestToken token = twitter.getOAuthRequestToken();...
java
public static Status createStatus(String rawJSON) throws TwitterException { try { return new StatusJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static User createUser(String rawJSON) throws TwitterException { try { return new UserJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static AccountTotals createAccountTotals(String rawJSON) throws TwitterException { try { return new AccountTotalsJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Relationship createRelationship(String rawJSON) throws TwitterException { try { return new RelationshipJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Place createPlace(String rawJSON) throws TwitterException { try { return new PlaceJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static SavedSearch createSavedSearch(String rawJSON) throws TwitterException { try { return new SavedSearchJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Trend createTrend(String rawJSON) throws TwitterException { try { return new TrendJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Map<String, RateLimitStatus> createRateLimitStatus(String rawJSON) throws TwitterException { try { return RateLimitStatusJSONImpl.createRateLimitStatuses(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Category createCategory(String rawJSON) throws TwitterException { try { return new CategoryJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static DirectMessage createDirectMessage(String rawJSON) throws TwitterException { try { return new DirectMessageJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static Location createLocation(String rawJSON) throws TwitterException { try { return new LocationJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static UserList createUserList(String rawJSON) throws TwitterException { try { return new UserListJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
public static OEmbed createOEmbed(String rawJSON) throws TwitterException { try { return new OEmbedJSONImpl(new JSONObject(rawJSON)); } catch (JSONException e) { throw new TwitterException(e); } }
java
protected final void setHttpProxyHost(String proxyHost) { httpConf = new MyHttpClientConfiguration(proxyHost , httpConf.getHttpProxyUser() , httpConf.getHttpProxyPassword() , httpConf.getHttpProxyPort() , httpConf.isHttpProxySocks() ...
java
public Dispatcher getInstance() { try { return (Dispatcher) Class.forName(dispatcherImpl) .getConstructor(Configuration.class).newInstance(conf); } catch (InstantiationException e) { throw new AssertionError(e); } catch (IllegalAccessException e) { ...
java
static double checkDouble(double d) throws JSONException { if (Double.isInfinite(d) || Double.isNaN(d)) { throw new JSONException("Forbidden numeric value: " + d); } return d; }
java
@Override public Configuration getInstance(String configTreePath) { PropertyConfiguration conf = new PropertyConfiguration(configTreePath); conf.dumpConfiguration(); return conf; }
java
private UploadedMedia uploadMediaChunkedFinalize(long mediaId) throws TwitterException { int tries = 0; int maxTries = 20; int lastProgressPercent = 0; int currentProgressPercent = 0; UploadedMedia uploadedMedia = uploadMediaChunkedFinalize0(mediaId); while (tries < maxTries) { if(lastProgressPercent == ...
java
private void checkFileValidity(File image) throws TwitterException { if (!image.exists()) { //noinspection ThrowableInstanceNeverThrown throw new TwitterException(new FileNotFoundException(image + " is not found.")); } if (!image.isFile()) { //noinspection Thr...
java
@Override public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret) { if (null == consumerKey) { throw new NullPointerException("consumer key is null"); } if (null == consumerSecret) { throw new NullPointerException("consumer secret is null"...
java
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize, int maxLines, float precision) { if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) { // Don't auto-size since there's no limit on lines. return; } int targetWi...
java
private static float getAutofitTextSize(CharSequence text, TextPaint paint, float targetWidth, int maxLines, float low, float high, float precision, DisplayMetrics displayMetrics) { float mid = (low + high) / 2.0f; int lineCount = 1; StaticLayout layout = null; p...
java
public AutofitHelper setMinTextSize(int unit, float size) { Context context = mTextView.getContext(); Resources r = Resources.getSystem(); if (context != null) { r = context.getResources(); } setRawMinTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetric...
java
public AutofitHelper setMaxTextSize(int unit, float size) { Context context = mTextView.getContext(); Resources r = Resources.getSystem(); if (context != null) { r = context.getResources(); } setRawMaxTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetric...
java
public AutofitHelper setEnabled(boolean enabled) { if (mEnabled != enabled) { mEnabled = enabled; if (enabled) { mTextView.addTextChangedListener(mTextWatcher); mTextView.addOnLayoutChangeListener(mOnLayoutChangeListener); autofit(); ...
java
public static <T> List<Field> getDeclaredFields(T type) { return new ArrayList<>(asList(type.getClass().getDeclaredFields())); }
java
public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = sup...
java
public Class<?> getWrapperType(Class<?> primitiveType) { for(PrimitiveEnum p : PrimitiveEnum.values()) { if(p.getType().equals(primitiveType)) { return p.getClazz(); } } return primitiveType; // if not primitive, return it as is }
java
public static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (!fieldType.isPrimitive()) { return false; } Object fieldValue = getFieldValue(object, field); if (f...
java
public static boolean isCollectionType(final Type type) { return isParameterizedType(type) && isCollectionType((Class<?>) ((ParameterizedType) type).getRawType()); }
java
public static boolean isPopulatable(final Type type) { return !isWildcardType(type) && !isTypeVariable(type) && !isCollectionType(type) && !isParameterizedType(type); }
java
public static boolean isIntrospectable(final Class<?> type) { return !isEnumType(type) && !isArrayType(type) && !(isCollectionType(type) && isJdkBuiltIn(type)) && !(isMapType(type) && isJdkBuiltIn(type)); }
java
public static boolean isParameterizedType(final Type type) { return type != null && type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length > 0; }
java
public static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type) { if (type instanceof ParameterizedType) { Type[] fieldArugmentTypes = ((ParameterizedType) type).getActualTypeArguments(); List<Class<?>> typesWithSameParameterizedTypes = new ArrayLis...
java
public static <T extends Annotation> T getAnnotation(Field field, Class<T> annotationType) { return field.getAnnotation(annotationType) == null ? getAnnotationFromReadMethod(getReadMethod(field).orElse(null), annotationType) : field.getAnnotation(annotationType); }
java
public static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType) { final Optional<Method> readMethod = getReadMethod(field); return field.isAnnotationPresent(annotationType) || readMethod.isPresent() && readMethod.get().isAnnotationPresent(annotationType); }
java
public static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize) { rejectUnsupportedTypes(fieldType); Collection<?> collection; try { collection = (Collection<?>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e)...
java
public static Optional<Method> getReadMethod(Field field) { String fieldName = field.getName(); Class<?> fieldClass = field.getDeclaringClass(); String capitalizedFieldName = fieldName.substring(0, 1).toUpperCase(ENGLISH) + fieldName.substring(1); // try to find getProperty Optio...
java
@Override public Randomizer<?> getRandomizer(Field field) { if (field.isAnnotationPresent(org.jeasy.random.annotation.Randomizer.class)) { org.jeasy.random.annotation.Randomizer randomizer = field.getAnnotation(org.jeasy.random.annotation.Randomizer.class); Class<?> type = randomizer...
java
protected double nextDouble(final double min, final double max) { double value = min + (random.nextDouble() * (max - min)); if (value < min) { return min; } else if (value > max) { return max; } else { return value; } // NB: ThreadLocal...
java
public static Predicate<Class<?>> named(final String name) { return clazz -> clazz.getName().equals(name); }
java
public static Predicate<Class<?>> inPackage(final String packageNamePrefix) { return clazz -> clazz.getPackage().getName().startsWith(packageNamePrefix); }
java
public static Predicate<Class<?>> isAnnotatedWith(Class<? extends Annotation>... annotations) { return clazz -> { for (Class<? extends Annotation> annotation : annotations) { if (clazz.isAnnotationPresent(annotation)) { return true; } }...
java
public static Predicate<Class<?>> hasModifiers(final Integer modifiers) { return clazz -> (modifiers & clazz.getModifiers()) == modifiers; }
java
public <T> EasyRandomParameters randomize(Class<T> type, Randomizer<T> randomizer) { Objects.requireNonNull(type, "Type must not be null"); Objects.requireNonNull(randomizer, "Randomizer must not be null"); customRandomizerRegistry.registerRandomizer(type, randomizer); return this; }
java
public EasyRandomParameters excludeField(Predicate<Field> predicate) { Objects.requireNonNull(predicate, "Predicate must not be null"); fieldExclusionPredicates.add(predicate); exclusionRandomizerRegistry.addFieldPredicate(predicate); return this; }
java
public EasyRandomParameters excludeType(Predicate<Class<?>> predicate) { Objects.requireNonNull(predicate, "Predicate must not be null"); typeExclusionPredicates.add(predicate); exclusionRandomizerRegistry.addTypePredicate(predicate); return this; }
java
public EasyRandomParameters collectionSizeRange(final int minCollectionSize, final int maxCollectionSize) { if (minCollectionSize < 0) { throw new IllegalArgumentException("minCollectionSize must be >= 0"); } if (minCollectionSize > maxCollectionSize) { throw new IllegalA...
java
public EasyRandomParameters stringLengthRange(final int minStringLength, final int maxStringLength) { if (minStringLength < 0) { throw new IllegalArgumentException("minStringLength must be >= 0"); } if (minStringLength > maxStringLength) { throw new IllegalArgumentExcepti...
java
public EasyRandomParameters dateRange(final LocalDate min, final LocalDate max) { if (min.isAfter(max)) { throw new IllegalArgumentException("Min date should be before max date"); } setDateRange(new Range<>(min, max)); return this; }
java
public EasyRandomParameters timeRange(final LocalTime min, final LocalTime max) { if (min.isAfter(max)) { throw new IllegalArgumentException("Min time should be before max time"); } setTimeRange(new Range<>(min, max)); return this; }
java
public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : ...
java
public boolean shouldBeExcluded(final Class<?> type, final RandomizerContext context) { Set<Predicate<Class<?>>> typeExclusionPredicates = context.getParameters().getTypeExclusionPredicates(); for (Predicate<Class<?>> typeExclusionPredicate : typeExclusionPredicates) { if (typeExclusionPredi...
java
public static List<Character> collectPrintableCharactersOf(Charset charset) { List<Character> chars = new ArrayList<>(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { char character = (char) i; if (isPrintable(character)) { String characterAsSt...
java
public static List<Character> filterLetters(List<Character> characters) { return characters.stream().filter(Character::isLetter).collect(toList()); }
java
public static Predicate<Field> named(final String name) { return field -> Pattern.compile(name).matcher(field.getName()).matches(); }
java
public static Predicate<Field> ofType(Class<?> type) { return field -> field.getType().equals(type); }
java
public static Predicate<Field> inClass(Class<?> clazz) { return field -> field.getDeclaringClass().equals(clazz); }
java
public static Predicate<Field> isAnnotatedWith(Class<? extends Annotation>... annotations) { return field -> { for (Class<? extends Annotation> annotation : annotations) { if (field.isAnnotationPresent(annotation)) { return true; } } ...
java
public static Predicate<Field> hasModifiers(final Integer modifiers) { return field -> (modifiers & field.getModifiers()) == modifiers; }
java
public static <T> T randomElementOf(final List<T> list) { if (list.isEmpty()) { return null; } return list.get(nextInt(0, list.size())); }
java
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
java
public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); }
java
private List<E> getFilteredList(Class<E> enumeration, E... excludedValues) { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); if (excludedValues != null) { for (E element : excludedValues) { filteredValues...
java
@PublicAPI(usage = ACCESS) public void accept(Predicate<? super JavaClass> predicate, ClassVisitor visitor) { for (JavaClass javaClass : getClassesWith(predicate)) { visitor.visit(javaClass); } for (JavaPackage subPackage : getSubPackages()) { subPackage.accept(predic...
java
@PublicAPI(usage = ACCESS) public void accept(Predicate<? super JavaPackage> predicate, PackageVisitor visitor) { if (predicate.apply(this)) { visitor.visit(this); } for (JavaPackage subPackage : getSubPackages()) { subPackage.accept(predicate, visitor); } ...
java
public void printToStandardStream() throws FileNotFoundException { System.out.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams System.err.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams new SomeCus...
java
public void back() throws JSONException { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } this.decrementIndexes(); this.usePrevious = true; this.eof = false; }
java
private void incrementIndexes(int c) { if(c > 0) { this.index++; if(c=='\r') { this.line++; this.characterPreviousLine = this.character; this.character=0; }else if (c=='\n') { if(this.previous != '\r') { ...
java
public JSONException syntaxError(String message, Throwable causedBy) { return new JSONException(message + this.toString(), causedBy); }
java
private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { try { int index = Integer.parseInt(indexToken); JSONArray currentArr = (JSONArray) current; if (index >= currentArr.length()) { throw new JSONPointerException(form...
java
public String toURIFragment() { try { StringBuilder rval = new StringBuilder("#"); for (String token : this.refTokens) { rval.append('/').append(URLEncoder.encode(token, ENCODING)); } return rval.toString(); } catch (UnsupportedEncodingExce...
java