idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
24,700 | public static UserList createUserList ( String rawJSON ) throws TwitterException { try { return new UserListJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a UserList object from rawJSON string . | 52 | 11 |
24,701 | public static OEmbed createOEmbed ( String rawJSON ) throws TwitterException { try { return new OEmbedJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs an OEmbed object from rawJSON string . | 55 | 12 |
24,702 | protected final void setHttpProxyHost ( String proxyHost ) { httpConf = new MyHttpClientConfiguration ( proxyHost , httpConf . getHttpProxyUser ( ) , httpConf . getHttpProxyPassword ( ) , httpConf . getHttpProxyPort ( ) , httpConf . isHttpProxySocks ( ) , httpConf . getHttpConnectionTimeout ( ) , httpConf . getHttpReadTimeout ( ) , httpConf . isPrettyDebugEnabled ( ) , httpConf . isGZIPEnabled ( ) ) ; } | methods for HttpClientConfiguration | 109 | 7 |
24,703 | public Dispatcher getInstance ( ) { try { return ( Dispatcher ) Class . forName ( dispatcherImpl ) . getConstructor ( Configuration . class ) . newInstance ( conf ) ; } catch ( InstantiationException e ) { throw new AssertionError ( e ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } catch ( ClassCastException e ) { throw new AssertionError ( e ) ; } catch ( NoSuchMethodException e ) { throw new AssertionError ( e ) ; } catch ( InvocationTargetException e ) { throw new AssertionError ( e ) ; } } | returns a Dispatcher instance . | 160 | 8 |
24,704 | static double checkDouble ( double d ) throws JSONException { if ( Double . isInfinite ( d ) || Double . isNaN ( d ) ) { throw new JSONException ( "Forbidden numeric value: " + d ) ; } return d ; } | Returns the input if it is a JSON - permissible value ; throws otherwise . | 54 | 15 |
24,705 | @ Override public Configuration getInstance ( String configTreePath ) { PropertyConfiguration conf = new PropertyConfiguration ( configTreePath ) ; conf . dumpConfiguration ( ) ; return conf ; } | It may be preferable to cache the config instance | 38 | 9 |
24,706 | 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 == currentProgressPercent ) { tries ++ ; } lastProgressPercent = currentProgressPercent ; String state = uploadedMedia . getProcessingState ( ) ; if ( state . equals ( "failed" ) ) { throw new TwitterException ( "Failed to finalize the chuncked upload." ) ; } if ( state . equals ( "pending" ) || state . equals ( "in_progress" ) ) { currentProgressPercent = uploadedMedia . getProgressPercent ( ) ; int waitSec = Math . max ( uploadedMedia . getProcessingCheckAfterSecs ( ) , 1 ) ; logger . debug ( "Chunked finalize, wait for:" + waitSec + " sec" ) ; try { Thread . sleep ( waitSec * 1000 ) ; } catch ( InterruptedException e ) { throw new TwitterException ( "Failed to finalize the chuncked upload." , e ) ; } } if ( state . equals ( "succeeded" ) ) { return uploadedMedia ; } uploadedMedia = uploadMediaChunkedStatus ( mediaId ) ; } throw new TwitterException ( "Failed to finalize the chuncked upload, progress has stopped, tried " + tries + 1 + " times." ) ; } | command = FINALIZE&media_id = 601413451156586496 | 342 | 17 |
24,707 | 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 ThrowableInstanceNeverThrown throw new TwitterException ( new IOException ( image + " is not a file." ) ) ; } } | Check the existence and the type of the specified file . | 99 | 11 |
24,708 | @ 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" ) ; } if ( auth instanceof NullAuthorization ) { if ( conf . isApplicationOnlyAuthEnabled ( ) ) { OAuth2Authorization oauth2 = new OAuth2Authorization ( conf ) ; oauth2 . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = oauth2 ; } else { OAuthAuthorization oauth = new OAuthAuthorization ( conf ) ; oauth . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = oauth ; } } else if ( auth instanceof BasicAuthorization ) { XAuthAuthorization xauth = new XAuthAuthorization ( ( BasicAuthorization ) auth ) ; xauth . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = xauth ; } else if ( auth instanceof OAuthAuthorization || auth instanceof OAuth2Authorization ) { throw new IllegalStateException ( "consumer key/secret pair already set." ) ; } } | methods declared in OAuthSupport interface | 266 | 8 |
24,709 | 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 targetWidth = view . getWidth ( ) - view . getPaddingLeft ( ) - view . getPaddingRight ( ) ; if ( targetWidth <= 0 ) { return ; } CharSequence text = view . getText ( ) ; TransformationMethod method = view . getTransformationMethod ( ) ; if ( method != null ) { text = method . getTransformation ( text , view ) ; } Context context = view . getContext ( ) ; Resources r = Resources . getSystem ( ) ; DisplayMetrics displayMetrics ; float size = maxTextSize ; float high = size ; float low = 0 ; if ( context != null ) { r = context . getResources ( ) ; } displayMetrics = r . getDisplayMetrics ( ) ; paint . set ( view . getPaint ( ) ) ; paint . setTextSize ( size ) ; if ( ( maxLines == 1 && paint . measureText ( text , 0 , text . length ( ) ) > targetWidth ) || getLineCount ( text , paint , size , targetWidth , displayMetrics ) > maxLines ) { size = getAutofitTextSize ( text , paint , targetWidth , maxLines , low , high , precision , displayMetrics ) ; } if ( size < minTextSize ) { size = minTextSize ; } view . setTextSize ( TypedValue . COMPLEX_UNIT_PX , size ) ; } | Re - sizes the textSize of the TextView so that the text fits within the bounds of the View . | 376 | 22 |
24,710 | 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 ; paint . setTextSize ( TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_PX , mid , displayMetrics ) ) ; if ( maxLines != 1 ) { layout = new StaticLayout ( text , paint , ( int ) targetWidth , Layout . Alignment . ALIGN_NORMAL , 1.0f , 0.0f , true ) ; lineCount = layout . getLineCount ( ) ; } if ( SPEW ) Log . d ( TAG , "low=" + low + " high=" + high + " mid=" + mid + " target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount ) ; if ( lineCount > maxLines ) { // For the case that `text` has more newline characters than `maxLines`. if ( ( high - low ) < precision ) { return low ; } return getAutofitTextSize ( text , paint , targetWidth , maxLines , low , mid , precision , displayMetrics ) ; } else if ( lineCount < maxLines ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , mid , high , precision , displayMetrics ) ; } else { float maxLineWidth = 0 ; if ( maxLines == 1 ) { maxLineWidth = paint . measureText ( text , 0 , text . length ( ) ) ; } else { for ( int i = 0 ; i < lineCount ; i ++ ) { if ( layout . getLineWidth ( i ) > maxLineWidth ) { maxLineWidth = layout . getLineWidth ( i ) ; } } } if ( ( high - low ) < precision ) { return low ; } else if ( maxLineWidth > targetWidth ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , low , mid , precision , displayMetrics ) ; } else if ( maxLineWidth < targetWidth ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , mid , high , precision , displayMetrics ) ; } else { return mid ; } } } | Recursive binary search to find the best size for the text . | 536 | 13 |
24,711 | 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 . getDisplayMetrics ( ) ) ) ; return this ; } | Set the minimum text size to a given unit and value . See TypedValue for the possible dimension units . | 89 | 22 |
24,712 | 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 . getDisplayMetrics ( ) ) ) ; return this ; } | Set the maximum text size to a given unit and value . See TypedValue for the possible dimension units . | 89 | 22 |
24,713 | public AutofitHelper setEnabled ( boolean enabled ) { if ( mEnabled != enabled ) { mEnabled = enabled ; if ( enabled ) { mTextView . addTextChangedListener ( mTextWatcher ) ; mTextView . addOnLayoutChangeListener ( mOnLayoutChangeListener ) ; autofit ( ) ; } else { mTextView . removeTextChangedListener ( mTextWatcher ) ; mTextView . removeOnLayoutChangeListener ( mOnLayoutChangeListener ) ; mTextView . setTextSize ( TypedValue . COMPLEX_UNIT_PX , mTextSize ) ; } } return this ; } | Set the enabled state of automatically resizing text . | 135 | 10 |
24,714 | public static < T > List < Field > getDeclaredFields ( T type ) { return new ArrayList <> ( asList ( type . getClass ( ) . getDeclaredFields ( ) ) ) ; } | Get declared fields of a given type . | 47 | 8 |
24,715 | 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 = superclass ; } return inheritedFields ; } | Get inherited fields of a given type . | 99 | 8 |
24,716 | 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 } | Get wrapper type of a primitive type . | 77 | 8 |
24,717 | 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 ( fieldValue == null ) { return false ; } if ( fieldType . equals ( boolean . class ) && ( boolean ) fieldValue == false ) { return true ; } if ( fieldType . equals ( byte . class ) && ( byte ) fieldValue == ( byte ) 0 ) { return true ; } if ( fieldType . equals ( short . class ) && ( short ) fieldValue == ( short ) 0 ) { return true ; } if ( fieldType . equals ( int . class ) && ( int ) fieldValue == 0 ) { return true ; } if ( fieldType . equals ( long . class ) && ( long ) fieldValue == 0L ) { return true ; } if ( fieldType . equals ( float . class ) && ( float ) fieldValue == 0.0F ) { return true ; } if ( fieldType . equals ( double . class ) && ( double ) fieldValue == 0.0D ) { return true ; } if ( fieldType . equals ( char . class ) && ( char ) fieldValue == ' ' ) { return true ; } return false ; } | Check if a field has a primitive type and matching default value which is set by the compiler . | 298 | 19 |
24,718 | public static boolean isCollectionType ( final Type type ) { return isParameterizedType ( type ) && isCollectionType ( ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } | Check if a type is a collection type . | 49 | 9 |
24,719 | public static boolean isPopulatable ( final Type type ) { return ! isWildcardType ( type ) && ! isTypeVariable ( type ) && ! isCollectionType ( type ) && ! isParameterizedType ( type ) ; } | Check if a type is populatable . | 49 | 8 |
24,720 | public static boolean isIntrospectable ( final Class < ? > type ) { return ! isEnumType ( type ) && ! isArrayType ( type ) && ! ( isCollectionType ( type ) && isJdkBuiltIn ( type ) ) && ! ( isMapType ( type ) && isJdkBuiltIn ( type ) ) ; } | Check if a type should be introspected for internal fields . | 74 | 13 |
24,721 | public static boolean isParameterizedType ( final Type type ) { return type != null && type instanceof ParameterizedType && ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) . length > 0 ; } | Check if a type is a parameterized type | 50 | 9 |
24,722 | 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 ArrayList <> ( ) ; for ( Class < ? > currentConcreteType : types ) { List < Type [ ] > actualTypeArguments = getActualTypeArgumentsOfGenericInterfaces ( currentConcreteType ) ; typesWithSameParameterizedTypes . addAll ( actualTypeArguments . stream ( ) . filter ( currentTypeArguments -> Arrays . equals ( fieldArugmentTypes , currentTypeArguments ) ) . map ( currentTypeArguments -> currentConcreteType ) . collect ( toList ( ) ) ) ; } return typesWithSameParameterizedTypes ; } return types ; } | Filters a list of types to keep only elements having the same parameterized types as the given type . | 213 | 21 |
24,723 | 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 ) ; } | Looks for given annotationType on given field or read method for field . | 72 | 14 |
24,724 | 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 ) ; } | Checks if field or corresponding read method is annotated with given annotationType . | 74 | 16 |
24,725 | public static Collection < ? > createEmptyCollectionForType ( Class < ? > fieldType , int initialSize ) { rejectUnsupportedTypes ( fieldType ) ; Collection < ? > collection ; try { collection = ( Collection < ? > ) fieldType . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { if ( fieldType . equals ( ArrayBlockingQueue . class ) ) { collection = new ArrayBlockingQueue <> ( initialSize ) ; } else { collection = ( Collection < ? > ) new ObjenesisStd ( ) . newInstance ( fieldType ) ; } } return collection ; } | Create an empty collection for the given type . | 133 | 9 |
24,726 | 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 Optional < Method > getter = getPublicMethod ( "get" + capitalizedFieldName , fieldClass ) ; if ( getter . isPresent ( ) ) { return getter ; } // try to find isProperty for boolean properties return getPublicMethod ( "is" + capitalizedFieldName , fieldClass ) ; } | Get the read method for given field . | 151 | 8 |
24,727 | @ 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 . value ( ) ; RandomizerArgument [ ] arguments = randomizer . args ( ) ; return ReflectionUtils . newInstance ( type , arguments ) ; } return null ; } | Retrieves a randomizer for the given field . | 124 | 11 |
24,728 | 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: ThreadLocalRandom.current().nextDouble(min, max)) cannot be use because the seed is not configurable // and is created per thread (see Javadoc) } | Return a random double in the given range . | 102 | 9 |
24,729 | public static Predicate < Class < ? > > named ( final String name ) { return clazz -> clazz . getName ( ) . equals ( name ) ; } | Create a predicate to check that a type has a given name . | 35 | 13 |
24,730 | public static Predicate < Class < ? > > inPackage ( final String packageNamePrefix ) { return clazz -> clazz . getPackage ( ) . getName ( ) . startsWith ( packageNamePrefix ) ; } | Create a predicate to check that a type is defined in a given package . | 48 | 15 |
24,731 | public static Predicate < Class < ? > > isAnnotatedWith ( Class < ? extends Annotation > ... annotations ) { return clazz -> { for ( Class < ? extends Annotation > annotation : annotations ) { if ( clazz . isAnnotationPresent ( annotation ) ) { return true ; } } return false ; } ; } | Create a predicate to check that a type is annotated with one of the given annotations . | 71 | 18 |
24,732 | public static Predicate < Class < ? > > hasModifiers ( final Integer modifiers ) { return clazz -> ( modifiers & clazz . getModifiers ( ) ) == modifiers ; } | Create a predicate to check that a type has a given set of modifiers . | 39 | 15 |
24,733 | 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 ; } | Register a custom randomizer for a given type . | 81 | 10 |
24,734 | public EasyRandomParameters excludeField ( Predicate < Field > predicate ) { Objects . requireNonNull ( predicate , "Predicate must not be null" ) ; fieldExclusionPredicates . add ( predicate ) ; exclusionRandomizerRegistry . addFieldPredicate ( predicate ) ; return this ; } | Exclude a field from being randomized . | 62 | 8 |
24,735 | public EasyRandomParameters excludeType ( Predicate < Class < ? > > predicate ) { Objects . requireNonNull ( predicate , "Predicate must not be null" ) ; typeExclusionPredicates . add ( predicate ) ; exclusionRandomizerRegistry . addTypePredicate ( predicate ) ; return this ; } | Exclude a type from being randomized . | 65 | 8 |
24,736 | public EasyRandomParameters collectionSizeRange ( final int minCollectionSize , final int maxCollectionSize ) { if ( minCollectionSize < 0 ) { throw new IllegalArgumentException ( "minCollectionSize must be >= 0" ) ; } if ( minCollectionSize > maxCollectionSize ) { throw new IllegalArgumentException ( format ( "minCollectionSize (%s) must be <= than maxCollectionSize (%s)" , minCollectionSize , maxCollectionSize ) ) ; } setCollectionSizeRange ( new Range <> ( minCollectionSize , maxCollectionSize ) ) ; return this ; } | Set the collection size range . | 122 | 6 |
24,737 | public EasyRandomParameters stringLengthRange ( final int minStringLength , final int maxStringLength ) { if ( minStringLength < 0 ) { throw new IllegalArgumentException ( "minStringLength must be >= 0" ) ; } if ( minStringLength > maxStringLength ) { throw new IllegalArgumentException ( format ( "minStringLength (%s) must be <= than maxStringLength (%s)" , minStringLength , maxStringLength ) ) ; } setStringLengthRange ( new Range <> ( minStringLength , maxStringLength ) ) ; return this ; } | Set the string length range . | 122 | 6 |
24,738 | 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 ; } | Set the date range . | 67 | 5 |
24,739 | 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 ; } | Set the time range . | 67 | 5 |
24,740 | 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 : fieldExclusionPredicates ) { if ( fieldExclusionPredicate . test ( field ) ) { return true ; } } return false ; } | Given the current randomization context should the field be excluded from being populated ? | 104 | 15 |
24,741 | public boolean shouldBeExcluded ( final Class < ? > type , final RandomizerContext context ) { Set < Predicate < Class < ? > > > typeExclusionPredicates = context . getParameters ( ) . getTypeExclusionPredicates ( ) ; for ( Predicate < Class < ? > > typeExclusionPredicate : typeExclusionPredicates ) { if ( typeExclusionPredicate . test ( type ) ) { return true ; } } return false ; } | Given the current randomization context should the type be excluded from being populated ? | 100 | 15 |
24,742 | 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 characterAsString = Character . toString ( character ) ; byte [ ] encoded = characterAsString . getBytes ( charset ) ; String decoded = new String ( encoded , charset ) ; if ( characterAsString . equals ( decoded ) ) { chars . add ( character ) ; } } } return chars ; } | Returns a list of all printable charaters of the given charset . | 143 | 15 |
24,743 | public static List < Character > filterLetters ( List < Character > characters ) { return characters . stream ( ) . filter ( Character :: isLetter ) . collect ( toList ( ) ) ; } | Keep only letters from a list of characters . | 41 | 9 |
24,744 | public static Predicate < Field > named ( final String name ) { return field -> Pattern . compile ( name ) . matcher ( field . getName ( ) ) . matches ( ) ; } | Create a predicate to check that a field has a certain name pattern . | 40 | 14 |
24,745 | public static Predicate < Field > ofType ( Class < ? > type ) { return field -> field . getType ( ) . equals ( type ) ; } | Create a predicate to check that a field has a certain type . | 33 | 13 |
24,746 | public static Predicate < Field > inClass ( Class < ? > clazz ) { return field -> field . getDeclaringClass ( ) . equals ( clazz ) ; } | Create a predicate to check that a field is defined in a given class . | 37 | 15 |
24,747 | public static Predicate < Field > isAnnotatedWith ( Class < ? extends Annotation > ... annotations ) { return field -> { for ( Class < ? extends Annotation > annotation : annotations ) { if ( field . isAnnotationPresent ( annotation ) ) { return true ; } } return false ; } ; } | Create a predicate to check that a field is annotated with one of the given annotations . | 66 | 18 |
24,748 | public static Predicate < Field > hasModifiers ( final Integer modifiers ) { return field -> ( modifiers & field . getModifiers ( ) ) == modifiers ; } | Create a predicate to check that a field has a given set of modifiers . | 34 | 15 |
24,749 | public static < T > T randomElementOf ( final List < T > list ) { if ( list . isEmpty ( ) ) { return null ; } return list . get ( nextInt ( 0 , list . size ( ) ) ) ; } | Get a random element from the list . | 51 | 8 |
24,750 | public < T > T nextObject ( final Class < T > type ) { return doPopulateBean ( type , new RandomizationContext ( type , parameters ) ) ; } | Generate a random instance of the given type . | 37 | 10 |
24,751 | 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 ) ; } | Generate a stream of random instances of the given type . | 71 | 12 |
24,752 | 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 . remove ( element ) ; } } return filteredValues ; } | Get a subset of enumeration . | 90 | 7 |
24,753 | @ 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 ( predicate , visitor ) ; } } | Traverses the package tree visiting each matching class . | 81 | 11 |
24,754 | @ 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 ) ; } } | Traverses the package tree visiting each matching package . | 74 | 11 |
24,755 | 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 SomeCustomException ( ) . printStackTrace ( ) ; // Violates rule not to write to standard streams new SomeCustomException ( ) . printStackTrace ( new PrintStream ( "/some/file" ) ) ; // this is okay, since it's a custom PrintStream new SomeCustomException ( ) . printStackTrace ( new PrintWriter ( "/some/file" ) ) ; // this is okay, since it's a custom PrintWriter } | Violates rules not to use java . util . logging & that loggers should be private static final | 167 | 20 |
24,756 | 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 ; } | Back up one character . This provides a sort of lookahead capability so that you can test for a digit or letter before attempting to parse the next number or identifier . | 65 | 33 |
24,757 | private void incrementIndexes ( int c ) { if ( c > 0 ) { this . index ++ ; if ( c == ' ' ) { this . line ++ ; this . characterPreviousLine = this . character ; this . character = 0 ; } else if ( c == ' ' ) { if ( this . previous != ' ' ) { this . line ++ ; this . characterPreviousLine = this . character ; } this . character = 0 ; } else { this . character ++ ; } } } | Increments the internal indexes according to the previous character read and the character passed as the current character . | 104 | 20 |
24,758 | public JSONException syntaxError ( String message , Throwable causedBy ) { return new JSONException ( message + this . toString ( ) , causedBy ) ; } | Make a JSONException to signal a syntax error . | 34 | 10 |
24,759 | 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 ( format ( "index %s is out of bounds - the array has %d elements" , indexToken , Integer . valueOf ( currentArr . length ( ) ) ) ) ; } try { return currentArr . get ( index ) ; } catch ( JSONException e ) { throw new JSONPointerException ( "Error reading value at index position " + index , e ) ; } } catch ( NumberFormatException e ) { throw new JSONPointerException ( format ( "%s is not an array index" , indexToken ) , e ) ; } } | Matches a JSONArray element by ordinal position | 183 | 10 |
24,760 | public String toURIFragment ( ) { try { StringBuilder rval = new StringBuilder ( "#" ) ; for ( String token : this . refTokens ) { rval . append ( ' ' ) . append ( URLEncoder . encode ( token , ENCODING ) ) ; } return rval . toString ( ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } | Returns a string representing the JSONPointer path value using URI fragment identifier representation | 94 | 15 |
24,761 | public static boolean executeSql ( final String sql , final Connection connection , final boolean isDebug ) throws SQLException { if ( isDebug || LOGGER . isTraceEnabled ( ) ) { LOGGER . log ( Level . INFO , "Executing SQL [" + sql + "]" ) ; } final Statement statement = connection . createStatement ( ) ; final boolean isSuccess = ! statement . execute ( sql ) ; statement . close ( ) ; return isSuccess ; } | Executes the specified SQL with the specified connection . | 99 | 10 |
24,762 | public static boolean executeSql ( final String sql , final List < Object > paramList , final Connection connection , final boolean isDebug ) throws SQLException { if ( isDebug || LOGGER . isTraceEnabled ( ) ) { LOGGER . log ( Level . INFO , "Executing SQL [" + sql + "]" ) ; } final PreparedStatement preparedStatement = connection . prepareStatement ( sql ) ; for ( int i = 1 ; i <= paramList . size ( ) ; i ++ ) { preparedStatement . setObject ( i , paramList . get ( i - 1 ) ) ; } final boolean isSuccess = preparedStatement . execute ( ) ; preparedStatement . close ( ) ; return isSuccess ; } | Executes the specified SQL with the specified params and connection ... | 151 | 12 |
24,763 | protected String genHTML ( final HttpServletRequest request , final Map < String , Object > dataModel , final Template template ) throws Exception { final StringWriter stringWriter = new StringWriter ( ) ; template . setOutputEncoding ( "UTF-8" ) ; template . process ( dataModel , stringWriter ) ; final StringBuilder pageContentBuilder = new StringBuilder ( stringWriter . toString ( ) ) ; final long endimeMillis = System . currentTimeMillis ( ) ; final String dateString = DateFormatUtils . format ( endimeMillis , "yyyy/MM/dd HH:mm:ss" ) ; final long startTimeMillis = ( Long ) request . getAttribute ( Keys . HttpRequest . START_TIME_MILLIS ) ; final String msg = String . format ( "\n<!-- Generated by Latke (https://github.com/b3log/latke) in %1$dms, %2$s -->" , endimeMillis - startTimeMillis , dateString ) ; pageContentBuilder . append ( msg ) ; return pageContentBuilder . toString ( ) ; } | Processes the specified FreeMarker template with the specified request data model . | 244 | 15 |
24,764 | public static Collection < Class < ? > > discover ( final String scanPath ) throws Exception { if ( StringUtils . isBlank ( scanPath ) ) { throw new IllegalStateException ( "Please specify the [scanPath]" ) ; } LOGGER . debug ( "scanPath[" + scanPath + "]" ) ; final Collection < Class < ? > > ret = new HashSet <> ( ) ; final String [ ] splitPaths = scanPath . split ( "," ) ; // Adds some built-in components final String [ ] paths = ArrayUtils . concatenate ( splitPaths , BUILT_IN_COMPONENT_PKGS ) ; final Set < URL > urls = new LinkedHashSet <> ( ) ; for ( String path : paths ) { /* * the being two types of the scanPath. * 1 package: org.b3log.xxx * 2 ant-style classpath: org/b3log/** /*process.class */ if ( ! AntPathMatcher . isPattern ( path ) ) { path = path . replaceAll ( "\\." , "/" ) + "/**/*.class" ; } urls . addAll ( ClassPathResolver . getResources ( path ) ) ; } for ( final URL url : urls ) { final DataInputStream classInputStream = new DataInputStream ( url . openStream ( ) ) ; final ClassFile classFile = new ClassFile ( classInputStream ) ; final String className = classFile . getName ( ) ; final AnnotationsAttribute annotationsAttribute = ( AnnotationsAttribute ) classFile . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( null == annotationsAttribute ) { LOGGER . log ( Level . TRACE , "The class [name={0}] is not a bean" , className ) ; continue ; } final ConstPool constPool = classFile . getConstPool ( ) ; final Annotation [ ] annotations = annotationsAttribute . getAnnotations ( ) ; boolean maybeBeanClass = false ; for ( final Annotation annotation : annotations ) { final String typeName = annotation . getTypeName ( ) ; if ( typeName . equals ( Singleton . class . getName ( ) ) ) { maybeBeanClass = true ; break ; } if ( typeName . equals ( RequestProcessor . class . getName ( ) ) || typeName . equals ( Service . class . getName ( ) ) || typeName . equals ( Repository . class . getName ( ) ) ) { final Annotation singletonAnnotation = new Annotation ( Singleton . class . getName ( ) , constPool ) ; annotationsAttribute . addAnnotation ( singletonAnnotation ) ; classFile . addAttribute ( annotationsAttribute ) ; classFile . setVersionToJava5 ( ) ; maybeBeanClass = true ; break ; } } if ( maybeBeanClass ) { Class < ? > clz = null ; try { clz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( final ClassNotFoundException e ) { LOGGER . log ( Level . ERROR , "Loads class [" + className + "] failed" , e ) ; } ret . add ( clz ) ; } } return ret ; } | Scans classpath to discover bean classes . | 697 | 9 |
24,765 | public static String signHmacSHA1 ( final String source , final String secret ) { try { final Mac mac = Mac . getInstance ( "HmacSHA1" ) ; mac . init ( new SecretKeySpec ( secret . getBytes ( "UTF-8" ) , "HmacSHA1" ) ) ; final byte [ ] signData = mac . doFinal ( source . getBytes ( "UTF-8" ) ) ; return new String ( Base64 . encodeBase64 ( signData ) , "UTF-8" ) ; } catch ( final Exception e ) { throw new RuntimeException ( "HMAC-SHA1 sign failed" , e ) ; } } | Signs the specified source string using the specified secret . | 142 | 11 |
24,766 | public static String encryptByAES ( final String content , final String key ) { try { final KeyGenerator kgen = KeyGenerator . getInstance ( "AES" ) ; final SecureRandom secureRandom = SecureRandom . getInstance ( "SHA1PRNG" ) ; secureRandom . setSeed ( key . getBytes ( ) ) ; kgen . init ( 128 , secureRandom ) ; final SecretKey secretKey = kgen . generateKey ( ) ; final byte [ ] enCodeFormat = secretKey . getEncoded ( ) ; final SecretKeySpec keySpec = new SecretKeySpec ( enCodeFormat , "AES" ) ; final Cipher cipher = Cipher . getInstance ( "AES" ) ; final byte [ ] byteContent = content . getBytes ( "UTF-8" ) ; cipher . init ( Cipher . ENCRYPT_MODE , keySpec ) ; final byte [ ] result = cipher . doFinal ( byteContent ) ; return Hex . encodeHexString ( result ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Encrypt failed" , e ) ; return null ; } } | Encrypts by AES . | 246 | 6 |
24,767 | public static String decryptByAES ( final String content , final String key ) { try { final byte [ ] data = Hex . decodeHex ( content . toCharArray ( ) ) ; final KeyGenerator kgen = KeyGenerator . getInstance ( "AES" ) ; final SecureRandom secureRandom = SecureRandom . getInstance ( "SHA1PRNG" ) ; secureRandom . setSeed ( key . getBytes ( ) ) ; kgen . init ( 128 , secureRandom ) ; final SecretKey secretKey = kgen . generateKey ( ) ; final byte [ ] enCodeFormat = secretKey . getEncoded ( ) ; final SecretKeySpec keySpec = new SecretKeySpec ( enCodeFormat , "AES" ) ; final Cipher cipher = Cipher . getInstance ( "AES" ) ; cipher . init ( Cipher . DECRYPT_MODE , keySpec ) ; final byte [ ] result = cipher . doFinal ( data ) ; return new String ( result , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Decrypt failed" ) ; return null ; } } | Decrypts by AES . | 246 | 6 |
24,768 | public static synchronized String genTimeMillisId ( ) { String ret ; ID_GEN_LOCK . lock ( ) ; try { ret = String . valueOf ( System . currentTimeMillis ( ) ) ; try { Thread . sleep ( ID_GEN_SLEEP_MILLIS ) ; } catch ( final InterruptedException e ) { throw new RuntimeException ( "Generates time millis id fail" ) ; } } finally { ID_GEN_LOCK . unlock ( ) ; } return ret ; } | Gets current date time string . | 108 | 7 |
24,769 | public static boolean hasLocale ( final Locale locale ) { try { ResourceBundle . getBundle ( Keys . LANGUAGE , locale ) ; return true ; } catch ( final MissingResourceException e ) { return false ; } } | Determines whether the server has the specified locale configuration or not . | 51 | 14 |
24,770 | public static void setLocale ( final HttpServletRequest request , final Locale locale ) { final HttpSession session = request . getSession ( false ) ; if ( null == session ) { LOGGER . warn ( "Ignores set locale caused by no session" ) ; return ; } session . setAttribute ( Keys . LOCALE , locale ) ; LOGGER . log ( Level . DEBUG , "Client[sessionId={0}] sets locale to [{1}]" , new Object [ ] { session . getId ( ) , locale . toString ( ) } ) ; } | Sets the specified locale into session of the specified request . | 124 | 12 |
24,771 | public static Locale getLocale ( ) { final Locale ret = LOCALE . get ( ) ; if ( null == ret ) { return Latkes . getLocale ( ) ; } return ret ; } | Gets locale . | 44 | 4 |
24,772 | public static String getCountry ( final String localeString ) { if ( localeString . length ( ) >= COUNTRY_END ) { return localeString . substring ( COUNTRY_START , COUNTRY_END ) ; } return "" ; } | Gets country from the specified locale string . | 51 | 9 |
24,773 | public static String getLanguage ( final String localeString ) { if ( localeString . length ( ) >= LANG_END ) { return localeString . substring ( LANG_START , LANG_END ) ; } return "" ; } | Gets language from the specified locale string . | 51 | 9 |
24,774 | private String createKeyDefinition ( final List < FieldDefinition > keyDefinitionList ) { final StringBuilder sql = new StringBuilder ( ) ; sql . append ( " PRIMARY KEY" ) ; boolean isFirst = true ; for ( FieldDefinition fieldDefinition : keyDefinitionList ) { if ( isFirst ) { sql . append ( "(" ) ; isFirst = false ; } else { sql . append ( "," ) ; } sql . append ( fieldDefinition . getName ( ) ) ; } sql . append ( ")" ) ; return sql . toString ( ) ; } | the keyDefinitionList tableSql . | 120 | 8 |
24,775 | public static String escape ( String string ) { char c ; String s = string . trim ( ) ; int length = s . length ( ) ; StringBuilder sb = new StringBuilder ( length ) ; for ( int i = 0 ; i < length ; i += 1 ) { c = s . charAt ( i ) ; if ( c < ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' ) { sb . append ( ' ' ) ; sb . append ( Character . forDigit ( ( char ) ( ( c >>> 4 ) & 0x0f ) , 16 ) ) ; sb . append ( Character . forDigit ( ( char ) ( c & 0x0f ) , 16 ) ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; } | Produce a copy of a string in which the characters + % = ; and control characters are replaced with %hh . This is a gentle form of URL encoding attempting to cause as little distortion to the string as possible . The characters = and ; are meta characters in cookies . By convention they are escaped using the URL - encoding . This is only a convention not a standard . Often cookies are expected to have encoded values . We encode = and ; because we must . We encode % and + because they are meta characters in URL encoding . | 186 | 107 |
24,776 | private < T > T getReference ( final Bean < T > bean ) { T ret = ( T ) beanReferences . get ( bean ) ; if ( null != ret ) { return ret ; } ret = bean . create ( ) ; if ( null != ret ) { beanReferences . put ( bean , ret ) ; return ret ; } throw new RuntimeException ( "Can't create reference for bean [" + bean + "]" ) ; } | Gets reference of the specified bean and creational context . | 91 | 12 |
24,777 | private < T > void destroyReference ( final Bean < T > bean , final T beanInstance ) { bean . destroy ( beanInstance ) ; } | Destroys the specified bean s instance . | 30 | 9 |
24,778 | public static void dispose ( ) { final JdbcTransaction jdbcTransaction = TX . get ( ) ; if ( null != jdbcTransaction && jdbcTransaction . getConnection ( ) != null ) { jdbcTransaction . dispose ( ) ; } final Connection connection = CONN . get ( ) ; if ( null != connection ) { try { connection . close ( ) ; } catch ( final SQLException e ) { throw new RuntimeException ( "Close connection failed" , e ) ; } finally { CONN . set ( null ) ; } } } | Disposes the resources . | 120 | 5 |
24,779 | private void update ( final String id , final JSONObject oldJsonObject , final JSONObject jsonObject , final List < Object > paramList , final StringBuilder sql ) throws JSONException { final JSONObject needUpdateJsonObject = getNeedUpdateJsonObject ( oldJsonObject , jsonObject ) ; if ( 0 == needUpdateJsonObject . length ( ) ) { LOGGER . log ( Level . TRACE , "Nothing to update [{0}] for repository [{1}]" , id , getName ( ) ) ; return ; } setUpdateProperties ( id , needUpdateJsonObject , paramList , sql ) ; } | Compares the specified old json object and new json object updates it if need . | 137 | 16 |
24,780 | private JSONObject getNeedUpdateJsonObject ( final JSONObject oldJsonObject , final JSONObject jsonObject ) throws JSONException { if ( null == oldJsonObject ) { return jsonObject ; } final JSONObject ret = new JSONObject ( ) ; final Iterator < String > keys = jsonObject . keys ( ) ; String key ; while ( keys . hasNext ( ) ) { key = keys . next ( ) ; if ( null == jsonObject . get ( key ) && null == oldJsonObject . get ( key ) ) { ret . put ( key , jsonObject . get ( key ) ) ; } else if ( ! jsonObject . optString ( key ) . equals ( oldJsonObject . optString ( key ) ) ) { ret . put ( key , jsonObject . get ( key ) ) ; } } return ret ; } | Compares the specified old json object and the new json object returns diff object for updating . | 180 | 18 |
24,781 | private void remove ( final String id , final StringBuilder sql ) { sql . append ( "DELETE FROM " ) . append ( getName ( ) ) . append ( " WHERE " ) . append ( JdbcRepositories . getDefaultKeyName ( ) ) . append ( " = '" ) . append ( id ) . append ( "'" ) ; } | Removes an record . | 77 | 5 |
24,782 | private Map < String , Object > buildSQLCount ( final int currentPageNum , final int pageSize , final int pageCount , final Query query , final StringBuilder sqlBuilder , final List < Object > paramList ) throws RepositoryException { final Map < String , Object > ret = new HashMap <> ( ) ; int pageCnt = pageCount ; int recordCnt = 0 ; final StringBuilder selectBuilder = new StringBuilder ( ) ; final StringBuilder whereBuilder = new StringBuilder ( ) ; final StringBuilder orderByBuilder = new StringBuilder ( ) ; buildSelect ( selectBuilder , query . getProjections ( ) ) ; buildWhere ( whereBuilder , paramList , query . getFilter ( ) ) ; buildOrderBy ( orderByBuilder , query . getSorts ( ) ) ; if ( - 1 == pageCount ) { final StringBuilder countBuilder = new StringBuilder ( "SELECT COUNT(" + JdbcRepositories . getDefaultKeyName ( ) + ") FROM " ) . append ( getName ( ) ) ; if ( StringUtils . isNotBlank ( whereBuilder . toString ( ) ) ) { countBuilder . append ( " WHERE " ) . append ( whereBuilder ) ; } recordCnt = ( int ) count ( countBuilder , paramList ) ; if ( 0 == recordCnt ) { ret . put ( Pagination . PAGINATION_PAGE_COUNT , 0 ) ; ret . put ( Pagination . PAGINATION_RECORD_COUNT , 0 ) ; return ret ; } pageCnt = ( int ) Math . ceil ( ( double ) recordCnt / ( double ) pageSize ) ; } ret . put ( Pagination . PAGINATION_PAGE_COUNT , pageCnt ) ; ret . put ( Pagination . PAGINATION_RECORD_COUNT , recordCnt ) ; final int start = ( currentPageNum - 1 ) * pageSize ; final int end = start + pageSize ; sqlBuilder . append ( JdbcFactory . getInstance ( ) . queryPage ( start , end , selectBuilder . toString ( ) , whereBuilder . toString ( ) , orderByBuilder . toString ( ) , getName ( ) ) ) ; return ret ; } | Builds query SQL and count result . | 486 | 8 |
24,783 | private void buildSelect ( final StringBuilder selectBuilder , final List < Projection > projections ) { selectBuilder . append ( "SELECT " ) ; if ( null == projections || projections . isEmpty ( ) ) { selectBuilder . append ( " * " ) ; return ; } selectBuilder . append ( projections . stream ( ) . map ( Projection :: getKey ) . collect ( Collectors . joining ( ", " ) ) ) ; } | Builds SELECT part with the specified select build and projections . | 91 | 12 |
24,784 | private void buildWhere ( final StringBuilder whereBuilder , final List < Object > paramList , final Filter filter ) throws RepositoryException { if ( null == filter ) { return ; } if ( filter instanceof PropertyFilter ) { processPropertyFilter ( whereBuilder , paramList , ( PropertyFilter ) filter ) ; } else { // CompositeFiler processCompositeFilter ( whereBuilder , paramList , ( CompositeFilter ) filter ) ; } } | Builds WHERE part with the specified where build param list and filter . | 92 | 14 |
24,785 | private void buildOrderBy ( final StringBuilder orderByBuilder , final Map < String , SortDirection > sorts ) { boolean isFirst = true ; String querySortDirection ; for ( final Map . Entry < String , SortDirection > sort : sorts . entrySet ( ) ) { if ( isFirst ) { orderByBuilder . append ( " ORDER BY " ) ; isFirst = false ; } else { orderByBuilder . append ( ", " ) ; } if ( sort . getValue ( ) . equals ( SortDirection . ASCENDING ) ) { querySortDirection = "ASC" ; } else { querySortDirection = "DESC" ; } orderByBuilder . append ( sort . getKey ( ) ) . append ( " " ) . append ( querySortDirection ) ; } } | Builds ORDER BY part with the specified order by build and sorts . | 171 | 14 |
24,786 | private Connection getConnection ( ) { final JdbcTransaction jdbcTransaction = TX . get ( ) ; if ( null != jdbcTransaction && jdbcTransaction . isActive ( ) ) { return jdbcTransaction . getConnection ( ) ; } Connection ret = CONN . get ( ) ; try { if ( null != ret && ! ret . isClosed ( ) ) { return ret ; } ret = Connections . getConnection ( ) ; } catch ( final SQLException e ) { LOGGER . log ( Level . ERROR , "Gets a connection failed" , e ) ; } CONN . set ( ret ) ; return ret ; } | getConnection . default using current JdbcTransaction s connection if null get a new one . | 141 | 19 |
24,787 | private void processPropertyFilter ( final StringBuilder whereBuilder , final List < Object > paramList , final PropertyFilter propertyFilter ) throws RepositoryException { String filterOperator ; switch ( propertyFilter . getOperator ( ) ) { case EQUAL : filterOperator = "=" ; break ; case GREATER_THAN : filterOperator = ">" ; break ; case GREATER_THAN_OR_EQUAL : filterOperator = ">=" ; break ; case LESS_THAN : filterOperator = "<" ; break ; case LESS_THAN_OR_EQUAL : filterOperator = "<=" ; break ; case NOT_EQUAL : filterOperator = "!=" ; break ; case IN : filterOperator = "IN" ; break ; case LIKE : filterOperator = "LIKE" ; break ; case NOT_LIKE : filterOperator = "NOT LIKE" ; break ; default : throw new RepositoryException ( "Unsupported filter operator [" + propertyFilter . getOperator ( ) + "]" ) ; } if ( FilterOperator . IN != propertyFilter . getOperator ( ) ) { whereBuilder . append ( propertyFilter . getKey ( ) ) . append ( " " ) . append ( filterOperator ) . append ( " ?" ) ; paramList . add ( propertyFilter . getValue ( ) ) ; } else { final Collection < Object > objects = ( Collection < Object > ) propertyFilter . getValue ( ) ; boolean isSubFist = true ; if ( objects != null && ! objects . isEmpty ( ) ) { whereBuilder . append ( propertyFilter . getKey ( ) ) . append ( " IN " ) ; final Iterator < Object > obs = objects . iterator ( ) ; while ( obs . hasNext ( ) ) { if ( isSubFist ) { whereBuilder . append ( "(" ) ; isSubFist = false ; } else { whereBuilder . append ( "," ) ; } whereBuilder . append ( "?" ) ; paramList . add ( obs . next ( ) ) ; if ( ! obs . hasNext ( ) ) { whereBuilder . append ( ") " ) ; } } } else { // in () => 1!=1 whereBuilder . append ( "1 != 1" ) ; } } } | Processes property filter . | 493 | 5 |
24,788 | private void processCompositeFilter ( final StringBuilder whereBuilder , final List < Object > paramList , final CompositeFilter compositeFilter ) throws RepositoryException { final List < Filter > subFilters = compositeFilter . getSubFilters ( ) ; if ( 2 > subFilters . size ( ) ) { throw new RepositoryException ( "At least two sub filters in a composite filter" ) ; } whereBuilder . append ( "(" ) ; final Iterator < Filter > iterator = subFilters . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Filter filter = iterator . next ( ) ; if ( filter instanceof PropertyFilter ) { processPropertyFilter ( whereBuilder , paramList , ( PropertyFilter ) filter ) ; } else { // CompositeFilter processCompositeFilter ( whereBuilder , paramList , ( CompositeFilter ) filter ) ; } if ( iterator . hasNext ( ) ) { switch ( compositeFilter . getOperator ( ) ) { case AND : whereBuilder . append ( " AND " ) ; break ; case OR : whereBuilder . append ( " OR " ) ; break ; default : throw new RepositoryException ( "Unsupported composite filter [operator=" + compositeFilter . getOperator ( ) + "]" ) ; } } } whereBuilder . append ( ")" ) ; } | Processes composite filter . | 277 | 5 |
24,789 | private static void toOracleClobEmpty ( final JSONObject jsonObject ) { final Iterator < String > keys = jsonObject . keys ( ) ; try { while ( keys . hasNext ( ) ) { final String name = keys . next ( ) ; final Object val = jsonObject . get ( name ) ; if ( val instanceof String ) { final String valStr = ( String ) val ; if ( StringUtils . isBlank ( valStr ) ) { jsonObject . put ( name , ORA_EMPTY_STR ) ; } } } } catch ( final JSONException e ) { LOGGER . log ( Level . ERROR , "Process oracle clob empty failed" , e ) ; } } | Process Oracle CLOB empty string . | 150 | 7 |
24,790 | public < T > Future < T > fireEventAsynchronously ( final Event < ? > event ) { final FutureTask < T > futureTask = new FutureTask < T > ( ( ) -> { synchronizedEventQueue . fireEvent ( event ) ; return null ; // XXX: Our future???? } ) ; Latkes . EXECUTOR_SERVICE . execute ( futureTask ) ; return futureTask ; } | Fire the specified event asynchronously . | 86 | 8 |
24,791 | public static void setRepositoriesWritable ( final boolean writable ) { for ( final Map . Entry < String , Repository > entry : REPOS_HOLDER . entrySet ( ) ) { final String repositoryName = entry . getKey ( ) ; final Repository repository = entry . getValue ( ) ; repository . setWritable ( writable ) ; LOGGER . log ( Level . INFO , "Sets repository[name={0}] writable[{1}]" , new Object [ ] { repositoryName , writable } ) ; } repositoryiesWritable = writable ; } | Sets all repositories whether is writable with the specified flag . | 126 | 13 |
24,792 | public static JSONArray getRepositoryNames ( ) { final JSONArray ret = new JSONArray ( ) ; if ( null == repositoriesDescription ) { LOGGER . log ( Level . INFO , "Not found repository description[repository.json] file under classpath" ) ; return ret ; } final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; ret . put ( repository . optString ( "name" ) ) ; } return ret ; } | Gets repository names . | 135 | 5 |
24,793 | public static JSONObject getRepositoryDef ( final String repositoryName ) { if ( StringUtils . isBlank ( repositoryName ) ) { return null ; } if ( null == repositoriesDescription ) { return null ; } final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; if ( repositoryName . equals ( repository . optString ( "name" ) ) ) { return repository ; } } throw new RuntimeException ( "Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json" ) ; } | Gets the repository definition of an repository specified by the given repository name . | 155 | 15 |
24,794 | private static void loadRepositoryDescription ( ) { LOGGER . log ( Level . INFO , "Loading repository description...." ) ; final InputStream inputStream = AbstractRepository . class . getResourceAsStream ( "/repository.json" ) ; if ( null == inputStream ) { LOGGER . log ( Level . INFO , "Not found repository description [repository.json] file under classpath" ) ; return ; } LOGGER . log ( Level . INFO , "Parsing repository description...." ) ; try { final String description = IOUtils . toString ( inputStream , "UTF-8" ) ; LOGGER . log ( Level . DEBUG , "{0}{1}" , new Object [ ] { Strings . LINE_SEPARATOR , description } ) ; repositoriesDescription = new JSONObject ( description ) ; // Repository name prefix final String tableNamePrefix = StringUtils . isNotBlank ( Latkes . getLocalProperty ( "jdbc.tablePrefix" ) ) ? Latkes . getLocalProperty ( "jdbc.tablePrefix" ) + "_" : "" ; final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; repository . put ( "name" , tableNamePrefix + repository . optString ( "name" ) ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Parses repository description failed" , e ) ; } finally { try { inputStream . close ( ) ; } catch ( final IOException e ) { LOGGER . log ( Level . ERROR , e . getMessage ( ) , e ) ; throw new RuntimeException ( e ) ; } } } | Loads repository description . | 399 | 5 |
24,795 | @ Override public void contextInitialized ( final ServletContextEvent servletContextEvent ) { servletContext = servletContextEvent . getServletContext ( ) ; Latkes . init ( ) ; LOGGER . info ( "Initializing the context...." ) ; Latkes . setLocale ( Locale . SIMPLIFIED_CHINESE ) ; LOGGER . log ( Level . INFO , "Default locale [{0}]" , Latkes . getLocale ( ) ) ; final String realPath = servletContext . getRealPath ( "/" ) ; LOGGER . log ( Level . INFO , "Server [realPath={0}, contextPath={1}]" , realPath , servletContext . getContextPath ( ) ) ; try { final Collection < Class < ? > > beanClasses = Discoverer . discover ( Latkes . getScanPath ( ) ) ; BeanManager . start ( beanClasses ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Initializes request processors failed" , e ) ; throw new IllegalStateException ( "Initializes request processors failed" ) ; } } | Initializes context locale and runtime environment . | 243 | 8 |
24,796 | private void resolveDependencies ( final Object reference ) { final Class < ? > superclass = reference . getClass ( ) . getSuperclass ( ) . getSuperclass ( ) ; // Proxy -> Orig -> Super resolveSuperclassFieldDependencies ( reference , superclass ) ; resolveCurrentclassFieldDependencies ( reference ) ; } | Resolves dependencies for the specified reference . | 71 | 8 |
24,797 | private T instantiateReference ( ) throws Exception { final T ret = proxyClass . newInstance ( ) ; ( ( ProxyObject ) ret ) . setHandler ( javassistMethodHandler ) ; LOGGER . log ( Level . TRACE , "Uses Javassist method handler for bean [class={0}]" , beanClass . getName ( ) ) ; return ret ; } | Constructs the bean object with dependencies resolved . | 81 | 9 |
24,798 | private void resolveCurrentclassFieldDependencies ( final Object reference ) { for ( final FieldInjectionPoint injectionPoint : fieldInjectionPoints ) { final Object injection = beanManager . getInjectableReference ( injectionPoint ) ; final Field field = injectionPoint . getAnnotated ( ) . getJavaMember ( ) ; try { final Field declaredField = proxyClass . getDeclaredField ( field . getName ( ) ) ; if ( declaredField . isAnnotationPresent ( Inject . class ) ) { try { declaredField . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } catch ( final NoSuchFieldException ex ) { try { field . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } } | Resolves current class field dependencies for the specified reference . | 180 | 11 |
24,799 | private void resolveSuperclassFieldDependencies ( final Object reference , final Class < ? > clazz ) { if ( clazz . equals ( Object . class ) ) { return ; } final Class < ? > superclass = clazz . getSuperclass ( ) ; resolveSuperclassFieldDependencies ( reference , superclass ) ; if ( Modifier . isAbstract ( clazz . getModifiers ( ) ) || Modifier . isInterface ( clazz . getModifiers ( ) ) ) { return ; } final Bean < ? > bean = beanManager . getBean ( clazz ) ; final Set < FieldInjectionPoint > injectionPoints = bean . fieldInjectionPoints ; for ( final FieldInjectionPoint injectionPoint : injectionPoints ) { final Object injection = beanManager . getInjectableReference ( injectionPoint ) ; final Field field = injectionPoint . getAnnotated ( ) . getJavaMember ( ) ; try { final Field declaredField = proxyClass . getDeclaredField ( field . getName ( ) ) ; if ( ! Reflections . matchInheritance ( declaredField , field ) ) { // Hide try { field . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } catch ( final NoSuchFieldException ex ) { throw new RuntimeException ( ex ) ; } } } | Resolves super class field dependencies for the specified reference . | 289 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.