idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,300 | public static void assertCauseMessage ( final Throwable ex , final String expectedMessage ) { assertThat ( ex . getCause ( ) ) . isNotNull ( ) ; assertThat ( ex . getCause ( ) . getMessage ( ) ) . isEqualTo ( expectedMessage ) ; } | Verifies that the cause of an exception contains an expected message . |
21,301 | public static void assertCauseCauseMessage ( final Throwable ex , final String expectedMessage ) { assertThat ( ex . getCause ( ) ) . isNotNull ( ) ; assertThat ( ex . getCause ( ) . getCause ( ) ) . isNotNull ( ) ; assertThat ( ex . getCause ( ) . getCause ( ) . getMessage ( ) ) . isEqualTo ( expectedMessage ) ; } | Verifies that the cause of a cause of an exception contains an expected message . |
21,302 | public static Set < ConstraintViolation < Object > > validate ( final Object obj , final Class < ? > ... scopes ) { if ( scopes == null ) { return validator ( ) . validate ( obj , Default . class ) ; } return validator ( ) . validate ( obj , scopes ) ; } | Validates the given object by using a newly created validator . |
21,303 | public static List < File > findFilesRecursive ( final File dir , final String extension ) { final String dotExtension = "." + extension ; final List < File > files = new ArrayList < > ( ) ; final FileProcessor fileProcessor = new FileProcessor ( new FileHandler ( ) { public final FileHandlerResult handleFile ( final File file ) { if ( file . isDirectory ( ) ) { return FileHandlerResult . CONTINUE ; } final String name = file . getName ( ) ; if ( name . endsWith ( dotExtension ) ) { files . add ( file ) ; } return FileHandlerResult . CONTINUE ; } } ) ; fileProcessor . process ( dir ) ; return files ; } | Returns a list of files with a given extension . |
21,304 | public static final Index indexAllClasses ( final List < File > classFiles ) { final Indexer indexer = new Indexer ( ) ; indexAllClasses ( indexer , classFiles ) ; return indexer . complete ( ) ; } | Creates an index for all class files in the given list . |
21,305 | public static final void indexAllClasses ( final Indexer indexer , final List < File > classFiles ) { classFiles . forEach ( file -> { try { final InputStream in = new FileInputStream ( file ) ; try { indexer . index ( in ) ; } finally { in . close ( ) ; } } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } ) ; } | Index all class files in the given list . |
21,306 | public static ClassInfo classInfo ( final ClassLoader cl , final Class < ? > clasz ) { return classInfo ( cl , clasz . getName ( ) ) ; } | Loads a class and creates a Jandex class information for it . |
21,307 | public static ClassInfo classInfo ( final ClassLoader cl , final String className ) { final Index index = index ( cl , className ) ; return index . getClassByName ( DotName . createSimple ( className ) ) ; } | Loads a class by it s name and creates a Jandex class information for it . |
21,308 | public static Index index ( final ClassLoader cl , final String className ) { final Indexer indexer = new Indexer ( ) ; index ( indexer , cl , className ) ; return indexer . complete ( ) ; } | Returns a Jandex index for a class by it s name . |
21,309 | public static void index ( final Indexer indexer , final ClassLoader cl , final String className ) { final InputStream stream = cl . getResourceAsStream ( className . replace ( '.' , '/' ) + ".class" ) ; try { indexer . index ( stream ) ; } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } | Indexes a class by it s name . |
21,310 | public static String replaceXmlAttr ( final String xml , final KV ... keyValues ) { final List < String > searchList = new ArrayList < String > ( ) ; final List < String > replacementList = new ArrayList < String > ( ) ; for ( final KV kv : keyValues ) { final String tag = kv . getKey ( ) + "=\"" ; int pa = xml . indexOf ( tag ) ; while ( pa > - 1 ) { final int s = pa + tag . length ( ) ; final int pe = xml . indexOf ( "\"" , s ) ; if ( pe > - 1 ) { final String str = xml . substring ( pa , pe + 1 ) ; searchList . add ( str ) ; final String repl = xml . substring ( pa , pa + tag . length ( ) ) + kv . getValue ( ) + "\"" ; replacementList . add ( repl ) ; } pa = xml . indexOf ( tag , s ) ; } } final String [ ] searchArray = searchList . toArray ( new String [ searchList . size ( ) ] ) ; final String [ ] replacementArray = replacementList . toArray ( new String [ replacementList . size ( ) ] ) ; return StringUtils . replaceEachRepeatedly ( xml , searchArray , replacementArray ) ; } | Replaces the content of one or more XML attributes . |
21,311 | public static boolean isExpectedType ( final Class < ? > expectedClass , final Object obj ) { final Class < ? > actualClass ; if ( obj == null ) { actualClass = null ; } else { actualClass = obj . getClass ( ) ; } return Objects . equals ( expectedClass , actualClass ) ; } | Determines if an object has an expected type in a null - safe way . |
21,312 | public static boolean isExpectedException ( final Class < ? extends Exception > expectedClass , final String expectedMessage , final Exception ex ) { if ( ! isExpectedType ( expectedClass , ex ) ) { return false ; } if ( ( expectedClass != null ) && ( expectedMessage != null ) && ( ex != null ) ) { return Objects . equals ( expectedMessage , ex . getMessage ( ) ) ; } return true ; } | Determines if an exception has an expected type and message in a null - safe way . |
21,313 | public final boolean isAlwaysAllowed ( final String packageName ) { if ( packageName . equals ( "java.lang" ) ) { return true ; } return Utils . findAllowedByName ( getAlwaysAllowed ( ) , packageName ) != null ; } | Checks if the package is always OK . |
21,314 | public final void validate ( ) throws InvalidDependenciesDefinitionException { int errorCount = 0 ; final StringBuilder sb = new StringBuilder ( "Duplicate package entries in 'allowed' and 'forbidden': " ) ; final List < Package < NotDependsOn > > list = getForbidden ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { final String name = list . get ( i ) . getName ( ) ; final Package < DependsOn > dep = new Package < DependsOn > ( name ) ; if ( getAllowed ( ) . indexOf ( dep ) > - 1 ) { if ( errorCount > 0 ) { sb . append ( ", " ) ; } sb . append ( name ) ; errorCount ++ ; } } if ( errorCount > 0 ) { throw new InvalidDependenciesDefinitionException ( this , sb . toString ( ) ) ; } } | Checks if the definition is valid - Especially if no package is in both lists . |
21,315 | public final Package < DependsOn > findAllowedByName ( final String packageName ) { final List < Package < DependsOn > > list = getAllowed ( ) ; for ( final Package < DependsOn > pkg : list ) { if ( pkg . getName ( ) . equals ( packageName ) ) { return pkg ; } } return null ; } | Find an entry in the allowed list by package name . |
21,316 | public final Package < NotDependsOn > findForbiddenByName ( final String packageName ) { final List < Package < NotDependsOn > > list = getForbidden ( ) ; for ( final Package < NotDependsOn > pkg : list ) { if ( pkg . getName ( ) . equals ( packageName ) ) { return pkg ; } } return null ; } | Find an entry in the forbidden list by package name . |
21,317 | public static XStream createXStream ( ) { final Class < ? > [ ] classes = new Class [ ] { Dependencies . class , Package . class , DependsOn . class , NotDependsOn . class , Dependency . class } ; final XStream xstream = new XStream ( ) ; XStream . setupDefaultSecurity ( xstream ) ; xstream . allowTypes ( classes ) ; xstream . alias ( "dependencies" , Dependencies . class ) ; xstream . alias ( "package" , Package . class ) ; xstream . alias ( "dependsOn" , DependsOn . class ) ; xstream . alias ( "notDependsOn" , NotDependsOn . class ) ; xstream . aliasField ( "package" , Dependency . class , "packageName" ) ; xstream . useAttributeFor ( Package . class , "name" ) ; xstream . useAttributeFor ( Package . class , "comment" ) ; xstream . useAttributeFor ( Dependency . class , "packageName" ) ; xstream . useAttributeFor ( Dependency . class , "includeSubPackages" ) ; xstream . useAttributeFor ( NotDependsOn . class , "comment" ) ; xstream . addImplicitCollection ( Package . class , "dependencies" ) ; return xstream ; } | Creates a ready configured XStream instance . |
21,318 | public static Dependencies load ( final File file ) { Utils4J . checkNotNull ( "file" , file ) ; Utils4J . checkValidFile ( file ) ; try { final InputStream inputStream = new BufferedInputStream ( new FileInputStream ( file ) ) ; try { return load ( inputStream ) ; } finally { inputStream . close ( ) ; } } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } | Load dependencies from a file . |
21,319 | public static Dependencies load ( final InputStream inputStream ) { Utils4J . checkNotNull ( "inputStream" , inputStream ) ; final XStream xstream = createXStream ( ) ; final Reader reader = new InputStreamReader ( inputStream ) ; return ( Dependencies ) xstream . fromXML ( reader ) ; } | Load dependencies from an input stream . |
21,320 | public static Dependencies load ( final Class < ? > clasz , final String resourcePathAndName ) { Utils4J . checkNotNull ( "clasz" , clasz ) ; Utils4J . checkNotNull ( "resourcePathAndName" , resourcePathAndName ) ; try { final URL url = clasz . getResource ( resourcePathAndName ) ; if ( url == null ) { throw new RuntimeException ( "Resource '" + resourcePathAndName + "' not found!" ) ; } final InputStream in = url . openStream ( ) ; try { return load ( in ) ; } finally { in . close ( ) ; } } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } | Load dependencies from a resource . |
21,321 | public static void save ( final File file , final Dependencies dependencies ) { Utils4J . checkNotNull ( "file" , file ) ; Utils4J . checkValidFile ( file ) ; final XStream xstream = createXStream ( ) ; try { final Writer writer = new FileWriter ( file ) ; try { xstream . toXML ( dependencies , writer ) ; } finally { writer . close ( ) ; } } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } | Write the dependencies to a file . |
21,322 | public final void findCallingMethodsInJar ( final File file ) throws IOException { try ( final JarFile jarFile = new JarFile ( file ) ) { final Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { final JarEntry entry = entries . nextElement ( ) ; if ( entry . getName ( ) . endsWith ( ".class" ) ) { final InputStream in = new BufferedInputStream ( jarFile . getInputStream ( entry ) , 1024 ) ; try { new ClassReader ( in ) . accept ( cv , 0 ) ; } finally { in . close ( ) ; } } } } } | Locate method calls in classes of a JAR file . |
21,323 | public final void findCallingMethodsInDir ( final File dir , final FileFilter filter ) { final FileProcessor fileProcessor = new FileProcessor ( new FileHandler ( ) { public final FileHandlerResult handleFile ( final File file ) { if ( file . isDirectory ( ) ) { return FileHandlerResult . CONTINUE ; } if ( file . getName ( ) . endsWith ( ".class" ) && ( filter == null || filter . accept ( file ) ) ) { handleClass ( file ) ; } return FileHandlerResult . CONTINUE ; } } ) ; fileProcessor . process ( dir ) ; } | Locate method calls in classes of a directory . |
21,324 | public final void addCall ( final MCAMethod found , final int line ) { calls . add ( new MCAMethodCall ( found , className , methodName , methodDescr , source , line ) ) ; } | Adds the current method to the list of callers . |
21,325 | private void createDefaultExtractOperation ( ) { this . currentStreamOperation = new DStreamOperation ( this . operationIdCounter ++ ) ; this . currentStreamOperation . addStreamOperationFunction ( Ops . extract . name ( ) , s -> s ) ; } | Will create an operation named extract with a pass - thru function |
21,326 | public static File toJar ( File sourceDir , String jarName ) { if ( ! sourceDir . isAbsolute ( ) ) { throw new IllegalArgumentException ( "Source must be expressed through absolute path" ) ; } Manifest manifest = new Manifest ( ) ; manifest . getMainAttributes ( ) . put ( Attributes . Name . MANIFEST_VERSION , "1.0" ) ; File jarFile = new File ( jarName ) ; try { JarOutputStream target = new JarOutputStream ( new FileOutputStream ( jarFile ) , manifest ) ; add ( sourceDir , sourceDir . getAbsolutePath ( ) . length ( ) , target ) ; target . close ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Failed to create JAR file '" + jarName + "' from " + sourceDir . getAbsolutePath ( ) , e ) ; } return jarFile ; } | Will create a JAR file from base dir |
21,327 | private String installConfiguration ( String configurationName , InputStream confFileInputStream ) { String outputPath ; try { File confDir = new File ( System . getProperty ( "java.io.tmpdir" ) + "/dstream_" + UUID . randomUUID ( ) ) ; confDir . mkdirs ( ) ; File executionConfig = new File ( confDir , configurationName ) ; executionConfig . deleteOnExit ( ) ; FileOutputStream confFileOs = new FileOutputStream ( executionConfig ) ; Properties configurationProperties = new Properties ( ) ; configurationProperties . load ( confFileInputStream ) ; configurationProperties . store ( confFileOs , configurationName + " configuration" ) ; this . addToClassPath ( confDir ) ; outputPath = configurationProperties . containsKey ( DStreamConstants . OUTPUT ) ? configurationProperties . getProperty ( DStreamConstants . OUTPUT ) : configurationName . split ( "\\." ) [ 0 ] + "/out" ; } catch ( Exception e ) { throw new IllegalStateException ( "Failed to generate execution config" , e ) ; } return outputPath ; } | Will generate execution configuration and add it to the classpath |
21,328 | public static < T , U , E extends Exception > BiConsumer < T , U > sneaked ( SneakyBiConsumer < T , U , E > biConsumer ) { return ( t , u ) -> { @ SuppressWarnings ( "unchecked" ) SneakyBiConsumer < T , U , RuntimeException > castedBiConsumer = ( SneakyBiConsumer < T , U , RuntimeException > ) biConsumer ; castedBiConsumer . accept ( t , u ) ; } ; } | Sneaky throws a BiConsumer lambda . |
21,329 | public static < T , U , R , E extends Exception > BiFunction < T , U , R > sneaked ( SneakyBiFunction < T , U , R , E > biFunction ) { return ( t , u ) -> { @ SuppressWarnings ( "unchecked" ) SneakyBiFunction < T , U , R , RuntimeException > castedBiFunction = ( SneakyBiFunction < T , U , R , RuntimeException > ) biFunction ; return castedBiFunction . apply ( t , u ) ; } ; } | Sneaky throws a BiFunction lambda . |
21,330 | public static < T , E extends Exception > BinaryOperator < T > sneaked ( SneakyBinaryOperator < T , E > binaryOperator ) { return ( t1 , t2 ) -> { @ SuppressWarnings ( "unchecked" ) SneakyBinaryOperator < T , RuntimeException > castedBinaryOperator = ( SneakyBinaryOperator < T , RuntimeException > ) binaryOperator ; return castedBinaryOperator . apply ( t1 , t2 ) ; } ; } | Sneaky throws a BinaryOperator lambda . |
21,331 | public static < T , U , E extends Exception > BiPredicate < T , U > sneaked ( SneakyBiPredicate < T , U , E > biPredicate ) { return ( t , u ) -> { @ SuppressWarnings ( "unchecked" ) SneakyBiPredicate < T , U , RuntimeException > castedBiPredicate = ( SneakyBiPredicate < T , U , RuntimeException > ) biPredicate ; return castedBiPredicate . test ( t , u ) ; } ; } | Sneaky throws a BiPredicate lambda . |
21,332 | public static < T , E extends Exception > Consumer < T > sneaked ( SneakyConsumer < T , E > consumer ) { return t -> { @ SuppressWarnings ( "unchecked" ) SneakyConsumer < T , RuntimeException > casedConsumer = ( SneakyConsumer < T , RuntimeException > ) consumer ; casedConsumer . accept ( t ) ; } ; } | Sneaky throws a Consumer lambda . |
21,333 | public static < T , R , E extends Exception > Function < T , R > sneaked ( SneakyFunction < T , R , E > function ) { return t -> { @ SuppressWarnings ( "unchecked" ) SneakyFunction < T , R , RuntimeException > f1 = ( SneakyFunction < T , R , RuntimeException > ) function ; return f1 . apply ( t ) ; } ; } | Sneaky throws a Function lambda . |
21,334 | public static < T , E extends Exception > Predicate < T > sneaked ( SneakyPredicate < T , E > predicate ) { return t -> { @ SuppressWarnings ( "unchecked" ) SneakyPredicate < T , RuntimeException > castedSneakyPredicate = ( SneakyPredicate < T , RuntimeException > ) predicate ; return castedSneakyPredicate . test ( t ) ; } ; } | Sneaky throws a Predicate lambda . |
21,335 | public static < E extends Exception > Runnable sneaked ( SneakyRunnable < E > runnable ) { return ( ) -> { @ SuppressWarnings ( "unchecked" ) SneakyRunnable < RuntimeException > castedRunnable = ( SneakyRunnable < RuntimeException > ) runnable ; castedRunnable . run ( ) ; } ; } | Sneaky throws a Runnable lambda . |
21,336 | public static < T , E extends Exception > Supplier < T > sneaked ( SneakySupplier < T , E > supplier ) { return ( ) -> { @ SuppressWarnings ( "unchecked" ) SneakySupplier < T , RuntimeException > castedSupplier = ( SneakySupplier < T , RuntimeException > ) supplier ; return castedSupplier . get ( ) ; } ; } | Sneaky throws a Supplier lambda . |
21,337 | public static < T , E extends Exception > UnaryOperator < T > sneaked ( SneakyUnaryOperator < T , E > unaryOperator ) { return t -> { @ SuppressWarnings ( "unchecked" ) SneakyUnaryOperator < T , RuntimeException > castedUnaryOperator = ( SneakyUnaryOperator < T , RuntimeException > ) unaryOperator ; return castedUnaryOperator . apply ( t ) ; } ; } | Sneaky throws a UnaryOperator lambda . |
21,338 | public static String [ ] split ( String input , char delimiter ) { if ( input == null ) throw new NullPointerException ( "input cannot be null" ) ; final int len = input . length ( ) ; int nSplits = 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { nSplits ++ ; } } String [ ] result = new String [ nSplits ] ; int lastMark = 0 ; int lastSplit = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { result [ lastSplit ] = input . substring ( lastMark , i ) ; lastSplit ++ ; lastMark = i + 1 ; } } result [ lastSplit ] = input . substring ( lastMark , len ) ; return result ; } | Splits a string into an array using a provided delimiter . The split chunks are also trimmed . |
21,339 | public static void split ( String input , char delimiter , Consumer < String > callbackPerSubstring ) { if ( input == null ) throw new NullPointerException ( "input cannot be null" ) ; final int len = input . length ( ) ; int lastMark = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { callbackPerSubstring . accept ( input . substring ( lastMark , i ) ) ; lastMark = i + 1 ; } } callbackPerSubstring . accept ( input . substring ( lastMark , len ) ) ; } | Splits a string into an array using a provided delimiter . The callback will be invoked once per each found substring |
21,340 | public static String firstPartOfCamelCase ( String camelcased ) { int end = 0 ; while ( ++ end < camelcased . length ( ) ) { if ( Character . isUpperCase ( camelcased . charAt ( end ) ) ) break ; } return camelcased . substring ( 0 , end ) ; } | Extracts the first part of a camel_cased string . |
21,341 | public static String decapitalize ( String word ) { return Character . toLowerCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ; } | Decapitalizes a word - only the first character is converted to lower case . |
21,342 | private < I , D extends Descriptor > boolean satisfies ( ScannerPlugin < I , D > selectedPlugin , D descriptor ) { return ! ( selectedPlugin . getClass ( ) . isAnnotationPresent ( Requires . class ) && descriptor == null ) ; } | Verifies if the selected plugin requires a descriptor . |
21,343 | protected < I > boolean accepts ( ScannerPlugin < I , ? > selectedPlugin , I item , String path , Scope scope ) { boolean accepted = false ; try { accepted = selectedPlugin . accepts ( item , path , scope ) ; } catch ( IOException e ) { LOGGER . error ( "Plugin " + selectedPlugin + " failed to check whether it can accept item " + path , e ) ; } return accepted ; } | Checks whether a plugin accepts an item . |
21,344 | private < D extends Descriptor > void pushDesriptor ( Class < D > type , D descriptor ) { if ( descriptor != null ) { scannerContext . push ( type , descriptor ) ; scannerContext . setCurrentDescriptor ( descriptor ) ; } } | Push the given descriptor with all it s types to the context . |
21,345 | private < D extends Descriptor > void popDescriptor ( Class < D > type , D descriptor ) { if ( descriptor != null ) { scannerContext . setCurrentDescriptor ( null ) ; scannerContext . pop ( type ) ; } } | Pop the given descriptor from the context . |
21,346 | private List < ScannerPlugin < ? , ? > > getScannerPluginsForType ( final Class < ? > type ) { List < ScannerPlugin < ? , ? > > plugins = scannerPluginsPerType . get ( type ) ; if ( plugins == null ) { final List < ScannerPlugin < ? , ? > > candidates = new LinkedList < > ( ) ; final Map < Class < ? extends Descriptor > , Set < ScannerPlugin < ? , ? > > > pluginsByDescriptor = new HashMap < > ( ) ; for ( ScannerPlugin < ? , ? > scannerPlugin : scannerPlugins . values ( ) ) { Class < ? > scannerPluginType = scannerPlugin . getType ( ) ; if ( scannerPluginType . isAssignableFrom ( type ) ) { Class < ? extends Descriptor > descriptorType = scannerPlugin . getDescriptorType ( ) ; Set < ScannerPlugin < ? , ? > > pluginsForDescriptorType = pluginsByDescriptor . get ( descriptorType ) ; if ( pluginsForDescriptorType == null ) { pluginsForDescriptorType = new HashSet < > ( ) ; pluginsByDescriptor . put ( descriptorType , pluginsForDescriptorType ) ; } pluginsForDescriptorType . add ( scannerPlugin ) ; candidates . add ( scannerPlugin ) ; } } plugins = DependencyResolver . newInstance ( candidates , new DependencyProvider < ScannerPlugin < ? , ? > > ( ) { public Set < ScannerPlugin < ? , ? > > getDependencies ( ScannerPlugin < ? , ? > dependent ) { Set < ScannerPlugin < ? , ? > > dependencies = new HashSet < > ( ) ; Requires annotation = dependent . getClass ( ) . getAnnotation ( Requires . class ) ; if ( annotation != null ) { for ( Class < ? extends Descriptor > descriptorType : annotation . value ( ) ) { Set < ScannerPlugin < ? , ? > > pluginsByDescriptorType = pluginsByDescriptor . get ( descriptorType ) ; if ( pluginsByDescriptorType != null ) { for ( ScannerPlugin < ? , ? > scannerPlugin : pluginsByDescriptorType ) { if ( ! scannerPlugin . equals ( dependent ) ) { dependencies . add ( scannerPlugin ) ; } } } } } return dependencies ; } } ) . resolve ( ) ; scannerPluginsPerType . put ( type , plugins ) ; } return plugins ; } | Determine the list of scanner plugins that handle the given type . |
21,347 | private < T > List < ? super T > bind ( final ResultSet results , final Class < T > klass , final List < ? super T > instances ) throws SQLException { if ( results == null ) { throw new NullPointerException ( "results is null" ) ; } if ( klass == null ) { throw new NullPointerException ( "klass is null" ) ; } if ( instances == null ) { throw new NullPointerException ( "instances is null" ) ; } while ( results . next ( ) ) { final T instance ; try { instance = klass . newInstance ( ) ; } catch ( final ReflectiveOperationException roe ) { logger . log ( SEVERE , format ( "failed to create new instance of %s" , klass ) , roe ) ; continue ; } instances . add ( bind ( results , klass , instance ) ) ; } return instances ; } | Binds all records as given type and add them to specified list . |
21,348 | public MetadataContext addSuppressionPaths ( final String suppressionPath , final String ... otherPaths ) { addSuppressionPath ( suppressionPath ) ; for ( final String otherPath : otherPaths ) { addSuppressionPath ( otherPath ) ; } return this ; } | Adds suppression paths and returns this instance . |
21,349 | public void stop ( ) { CompletableFuture . runAsync ( ( ) -> { try { bootstrap . getInjector ( ) . getInstance ( Server . class ) . stop ( ) ; } catch ( Exception ignore ) { } bootstrap . shutdown ( ) ; } ) ; } | Asynchronously shutdowns the server |
21,350 | public Jawn onStartup ( Runnable callback ) { Objects . requireNonNull ( callback ) ; bootstrapper . onStartup ( callback ) ; return this ; } | Run the tasks as a part of the start up process . |
21,351 | public Jawn onShutdown ( Runnable callback ) { Objects . requireNonNull ( callback ) ; bootstrapper . onShutdown ( callback ) ; return this ; } | Run the tasks as a part of the shut down process . |
21,352 | public String asText ( ) throws ParsableException { try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( request . getInputStream ( ) ) ) ) { return reader . lines ( ) . collect ( Collectors . joining ( ) ) ; } catch ( IOException e ) { throw new ParsableException ( "Reading the input failed" ) ; } } | Conveniently converts any input in the request into a string |
21,353 | public byte [ ] asBytes ( ) throws IOException { try ( ServletInputStream stream = request . getInputStream ( ) ) { ByteArrayOutputStream array = new ByteArrayOutputStream ( stream . available ( ) ) ; return array . toByteArray ( ) ; } } | Reads entire request data as byte array . Do not use for large data sets to avoid memory issues . |
21,354 | private void executeGroup ( RuleSet ruleSet , Group group , Severity parentSeverity ) throws RuleException { if ( ! executedGroups . contains ( group ) ) { ruleVisitor . beforeGroup ( group , getEffectiveSeverity ( group , parentSeverity , parentSeverity ) ) ; for ( Map . Entry < String , Severity > conceptEntry : group . getConcepts ( ) . entrySet ( ) ) { applyConcepts ( ruleSet , conceptEntry . getKey ( ) , parentSeverity , conceptEntry . getValue ( ) ) ; } for ( Map . Entry < String , Severity > groupEntry : group . getGroups ( ) . entrySet ( ) ) { executeGroups ( ruleSet , groupEntry . getKey ( ) , parentSeverity , groupEntry . getValue ( ) ) ; } Map < String , Severity > constraints = group . getConstraints ( ) ; for ( Map . Entry < String , Severity > constraintEntry : constraints . entrySet ( ) ) { validateConstraints ( ruleSet , constraintEntry . getKey ( ) , parentSeverity , constraintEntry . getValue ( ) ) ; } ruleVisitor . afterGroup ( group ) ; executedGroups . add ( group ) ; } } | Executes the given group . |
21,355 | private Severity getEffectiveSeverity ( SeverityRule rule , Severity parentSeverity , Severity requestedSeverity ) { Severity effectiveSeverity = requestedSeverity != null ? requestedSeverity : parentSeverity ; return effectiveSeverity != null ? effectiveSeverity : rule . getSeverity ( ) ; } | Determines the effective severity for a rule to be executed . |
21,356 | private void validateConstraint ( RuleSet ruleSet , Constraint constraint , Severity severity ) throws RuleException { if ( ! executedConstraints . contains ( constraint ) ) { if ( applyRequiredConcepts ( ruleSet , constraint ) ) { ruleVisitor . visitConstraint ( constraint , severity ) ; } else { ruleVisitor . skipConstraint ( constraint , severity ) ; } executedConstraints . add ( constraint ) ; } } | Validates the given constraint . |
21,357 | private boolean applyConcept ( RuleSet ruleSet , Concept concept , Severity severity ) throws RuleException { Boolean result = executedConcepts . get ( concept ) ; if ( result == null ) { if ( applyRequiredConcepts ( ruleSet , concept ) ) { result = ruleVisitor . visitConcept ( concept , severity ) ; } else { ruleVisitor . skipConcept ( concept , severity ) ; result = false ; } executedConcepts . put ( concept , result ) ; } return result ; } | Applies the given concept . |
21,358 | private boolean isSuppressedRow ( String ruleId , Map < String , Object > row , String primaryColumn ) { Object primaryValue = row . get ( primaryColumn ) ; if ( primaryValue != null && Suppress . class . isAssignableFrom ( primaryValue . getClass ( ) ) ) { Suppress suppress = ( Suppress ) primaryValue ; for ( String suppressId : suppress . getSuppressIds ( ) ) { if ( ruleId . equals ( suppressId ) ) { return true ; } } } return false ; } | Verifies if the given row shall be suppressed . |
21,359 | protected < T extends ExecutableRule < ? > > Status getStatus ( T executableRule , List < String > columnNames , List < Map < String , Object > > rows , AnalyzerContext context ) throws RuleException { return context . verify ( executableRule , columnNames , rows ) ; } | Evaluate the status of the result may be overridden by sub - classes . |
21,360 | private static < T > T getAnnotationValue ( Annotation annotation , String value , Class < T > expectedType ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; Method valueMethod ; try { valueMethod = annotationType . getDeclaredMethod ( value ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( "Cannot resolve required method '" + value + "()' for '" + annotationType + "'." ) ; } Object elementValue ; try { elementValue = valueMethod . invoke ( annotation ) ; } catch ( ReflectiveOperationException e ) { throw new IllegalStateException ( "Cannot invoke method value() for " + annotationType ) ; } return elementValue != null ? expectedType . cast ( elementValue ) : null ; } | Return a value from an annotation . |
21,361 | private int verifyRuleResults ( Collection < ? extends Result < ? extends ExecutableRule > > results , Severity warnOnSeverity , Severity failOnSeverity , String type , String header , boolean logResult ) { int violations = 0 ; for ( Result < ? > result : results ) { if ( Result . Status . FAILURE . equals ( result . getStatus ( ) ) ) { ExecutableRule rule = result . getRule ( ) ; String severityInfo = rule . getSeverity ( ) . getInfo ( result . getSeverity ( ) ) ; List < String > resultRows = getResultRows ( result , logResult ) ; boolean warn = warnOnSeverity != null && result . getSeverity ( ) . getLevel ( ) <= warnOnSeverity . getLevel ( ) ; boolean fail = failOnSeverity != null && result . getSeverity ( ) . getLevel ( ) <= failOnSeverity . getLevel ( ) ; LoggingStrategy loggingStrategy ; if ( fail ) { violations ++ ; loggingStrategy = errorLogger ; } else if ( warn ) { loggingStrategy = warnLogger ; } else { loggingStrategy = debugLogger ; } log ( loggingStrategy , rule , resultRows , severityInfo , type , header ) ; } } return violations ; } | Verifies the given results and logs messages . |
21,362 | private List < String > getResultRows ( Result < ? > result , boolean logResult ) { List < String > rows = new ArrayList < > ( ) ; if ( logResult ) { for ( Map < String , Object > columns : result . getRows ( ) ) { StringBuilder row = new StringBuilder ( ) ; for ( Map . Entry < String , Object > entry : columns . entrySet ( ) ) { if ( row . length ( ) > 0 ) { row . append ( ", " ) ; } row . append ( entry . getKey ( ) ) ; row . append ( '=' ) ; String stringValue = getLabel ( entry . getValue ( ) ) ; row . append ( stringValue ) ; } rows . add ( " " + row . toString ( ) ) ; } } return rows ; } | Convert the result rows into a string representation . |
21,363 | private void logDescription ( LoggingStrategy loggingStrategy , Rule rule ) { String description = rule . getDescription ( ) ; StringTokenizer tokenizer = new StringTokenizer ( description , "\n" ) ; while ( tokenizer . hasMoreTokens ( ) ) { loggingStrategy . log ( tokenizer . nextToken ( ) . replaceAll ( "(\\r|\\n|\\t)" , "" ) ) ; } } | Log the description of a rule . |
21,364 | public static String escapeRuleId ( Rule rule ) { return rule != null ? rule . getId ( ) . replaceAll ( "\\:" , "_" ) : null ; } | Escape the id of the given rule in a way such that it can be used as file name . |
21,365 | public static String getLabel ( Object value ) { if ( value != null ) { if ( value instanceof CompositeObject ) { CompositeObject descriptor = ( CompositeObject ) value ; String label = getLanguageLabel ( descriptor ) ; return label != null ? label : descriptor . toString ( ) ; } else if ( value . getClass ( ) . isArray ( ) ) { Object [ ] objects = ( Object [ ] ) value ; return getLabel ( Arrays . asList ( objects ) ) ; } else if ( value instanceof Iterable ) { StringBuilder sb = new StringBuilder ( ) ; for ( Object o : ( ( Iterable ) value ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( getLabel ( o ) ) ; } return "[" + sb . toString ( ) + "]" ; } else if ( value instanceof Map ) { StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < String , Object > entry : ( ( Map < String , Object > ) value ) . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( entry . getKey ( ) ) ; sb . append ( ":" ) ; sb . append ( getLabel ( entry . getValue ( ) ) ) ; } return "{" + sb . toString ( ) + "}" ; } return value . toString ( ) ; } return null ; } | Converts a value to its string representation . |
21,366 | public final static Class < ? > getCompiledClass ( String className , boolean useCache ) throws CompilationException , ClassLoadException { try { if ( ! useCache ) { DynamicClassLoader dynamicClassLoader = new DynamicClassLoader ( DynamicClassFactory . class . getClassLoader ( ) ) ; return dynamicClassLoader . loadClass ( className ) ; } else { return CACHED_CONTROLLERS . computeIfAbsent ( className , WRAP_FORNAME ) ; } } catch ( CompilationException e ) { throw e ; } catch ( Exception e ) { throw new ClassLoadException ( e ) ; } } | Handles caching of classes if not active_reload |
21,367 | public final Result json ( Object obj ) { final Result response = ok ( ) . contentType ( MediaType . APPLICATION_JSON ) . renderable ( obj ) ; holder . setControllerResult ( response ) ; return response ; } | This method will send a JSON response to the client . It will not use any layouts . Use it to build app . services and to support AJAX . |
21,368 | public Result xml ( Object obj ) { Result response = ok ( ) ; holder . setControllerResult ( response ) ; response . contentType ( MediaType . APPLICATION_XML ) . renderable ( obj ) ; return response ; } | This method will send a XML response to the client . It will not use any layouts . Use it to build app . services . |
21,369 | private void extractRules ( RuleSource ruleSource , Collection < ? > blocks , RuleSetBuilder builder ) throws RuleException { for ( Object element : blocks ) { if ( element instanceof AbstractBlock ) { AbstractBlock block = ( AbstractBlock ) element ; if ( EXECUTABLE_RULE_TYPES . contains ( block . getRole ( ) ) ) { extractExecutableRule ( ruleSource , block , builder ) ; } else if ( GROUP . equals ( block . getRole ( ) ) ) { extractGroup ( ruleSource , block , builder ) ; } extractRules ( ruleSource , block . getBlocks ( ) , builder ) ; } else if ( element instanceof Collection < ? > ) { extractRules ( ruleSource , ( Collection < ? > ) element , builder ) ; } } } | Find all content parts representing source code listings with a role that represents a rule . |
21,370 | private Map < String , Boolean > getRequiresConcepts ( RuleSource ruleSource , String id , Attributes attributes ) throws RuleException { Map < String , String > requiresDeclarations = getReferences ( attributes , REQUIRES_CONCEPTS ) ; Map < String , Boolean > required = new HashMap < > ( ) ; for ( Map . Entry < String , String > requiresEntry : requiresDeclarations . entrySet ( ) ) { String conceptId = requiresEntry . getKey ( ) ; String dependencyAttribute = requiresEntry . getValue ( ) ; Boolean optional = dependencyAttribute != null ? OPTIONAL . equals ( dependencyAttribute . toLowerCase ( ) ) : null ; required . put ( conceptId , optional ) ; } return required ; } | Evaluates required concepts of a rule . |
21,371 | private Map < String , String > getReferences ( Attributes attributes , String attributeName ) { String attribute = attributes . getString ( attributeName ) ; Set < String > references = new HashSet < > ( ) ; if ( attribute != null && ! attribute . trim ( ) . isEmpty ( ) ) { references . addAll ( asList ( attribute . split ( "\\s*,\\s*" ) ) ) ; } Map < String , String > rules = new HashMap < > ( ) ; for ( String reference : references ) { Matcher matcher = DEPENDENCY_PATTERN . matcher ( reference ) ; if ( matcher . matches ( ) ) { String id = matcher . group ( 1 ) ; String referenceValue = matcher . group ( 3 ) ; rules . put ( id , referenceValue ) ; } } return rules ; } | Get reference declarations for an attribute from a map of attributes . |
21,372 | private Severity getSeverity ( Attributes attributes , Severity defaultSeverity ) throws RuleException { String severity = attributes . getString ( SEVERITY ) ; if ( severity == null ) { return defaultSeverity ; } Severity value = Severity . fromValue ( severity . toLowerCase ( ) ) ; return value != null ? value : defaultSeverity ; } | Extract the optional severity of a rule . |
21,373 | private String unescapeHtml ( Object content ) { return content != null ? content . toString ( ) . replace ( "<" , "<" ) . replace ( ">" , ">" ) : "" ; } | Unescapes the content of a rule . |
21,374 | private Report getReport ( AbstractBlock part ) { Object primaryReportColum = part . getAttributes ( ) . get ( PRIMARY_REPORT_COLUM ) ; Object reportType = part . getAttributes ( ) . get ( REPORT_TYPE ) ; Properties reportProperties = parseProperties ( part , REPORT_PROPERTIES ) ; Report . ReportBuilder reportBuilder = Report . builder ( ) ; if ( reportType != null ) { reportBuilder . selectedTypes ( Report . selectTypes ( reportType . toString ( ) ) ) ; } if ( primaryReportColum != null ) { reportBuilder . primaryColumn ( primaryReportColum . toString ( ) ) ; } return reportBuilder . properties ( reportProperties ) . build ( ) ; } | Create the report part of a rule . |
21,375 | private Properties parseProperties ( AbstractBlock part , String attributeName ) { Properties properties = new Properties ( ) ; Object attribute = part . getAttributes ( ) . get ( attributeName ) ; if ( attribute == null ) { return properties ; } Scanner propertiesScanner = new Scanner ( attribute . toString ( ) ) ; propertiesScanner . useDelimiter ( ";" ) ; while ( propertiesScanner . hasNext ( ) ) { String next = propertiesScanner . next ( ) . trim ( ) ; if ( next . length ( ) > 0 ) { Scanner propertyScanner = new Scanner ( next ) ; propertyScanner . useDelimiter ( "=" ) ; String key = propertyScanner . next ( ) . trim ( ) ; String value = propertyScanner . next ( ) . trim ( ) ; properties . setProperty ( key , value ) ; } } return properties ; } | Parse properties from an attribute . |
21,376 | public final static Class < ? > getCompiledClass ( String fullClassName , boolean useCache ) throws Err . Compilation , Err . UnloadableClass { try { if ( ! useCache ) { DynamicClassLoader dynamicClassLoader = new DynamicClassLoader ( fullClassName . substring ( 0 , fullClassName . lastIndexOf ( '.' ) ) ) ; Class < ? > cl = dynamicClassLoader . loadClass ( fullClassName ) ; dynamicClassLoader = null ; return cl ; } else { return CACHED_CONTROLLERS . computeIfAbsent ( fullClassName , WRAP_FORNAME ) ; } } catch ( Exception e ) { throw new Err . UnloadableClass ( e ) ; } } | Handles caching of classes if not useCache |
21,377 | public String getKeyOrDefault ( String key ) { if ( StringUtils . isBlank ( key ) ) { if ( this . hasDefaultEnvironment ( ) ) { return defaultEnvironment ; } else { throw new MultiEnvSupportException ( "[environment] property is mandatory and can't be empty" ) ; } } if ( map . containsKey ( key ) ) { return key ; } if ( this . hasTemplateEnvironment ( ) ) { return this . templateEnvironment ; } LOG . error ( "Failed to find environment [{}] in {}" , key , this . keySet ( ) ) ; throw new MultiEnvSupportException ( String . format ( "Failed to find configuration for environment %s" , key ) ) ; } | Returns the key if that specified key is mapped to something |
21,378 | public T get ( Object key ) { String sKey = ( String ) key ; if ( StringUtils . isBlank ( sKey ) && this . hasDefaultEnvironment ( ) ) { sKey = defaultEnvironment ; } else if ( StringUtils . isBlank ( sKey ) ) { throw new MultiEnvSupportException ( "[environment] property is mandatory and can't be empty" ) ; } T value = map . get ( sKey ) ; if ( value == null ) { if ( creationFunction != null ) { value = creationFunction . apply ( sKey ) ; } else { value = resolve ( sKey , getTemplate ( ) ) ; } if ( value != null ) { map . put ( sKey , value ) ; } } return value ; } | Returns the value to which the specified key is mapped and adds it to the internal map if it wasn t previously present . |
21,379 | protected T resolve ( String sKey , T value ) { LOG . error ( "Fail to find environment [{}] in {}" , sKey , this . keySet ( ) ) ; throw new MultiEnvSupportException ( String . format ( "Fail to find configuration for environment %s" , sKey ) ) ; } | By default we don t try to resolve anything but others can extend this behavior if they d like to try to resolve not found values differently . |
21,380 | public ImageHandlerBuilder resize ( int width , int height ) { BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_EXACT , width , height ) ; image . flush ( ) ; image = resize ; return this ; } | Resize the image to the given width and height |
21,381 | public ImageHandlerBuilder resizeToHeight ( int size ) { if ( image . getHeight ( ) < size ) return this ; BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_TO_HEIGHT , Math . min ( size , image . getHeight ( ) ) ) ; image . flush ( ) ; image = resize ; return this ; } | Resize the image to a given height maintaining the original proportions of the image and setting the width accordingly . If the height of the image is smaller than the provided size then the image is not scaled . |
21,382 | public ImageHandlerBuilder resizeToWidth ( int size ) { if ( image . getWidth ( ) < size ) return this ; BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_TO_WIDTH , size ) ; image . flush ( ) ; image = resize ; return this ; } | Resize the image to a given width maintaining the original proportions of the image and setting the height accordingly . If the width of the image is smaller than the provided size then the image is not scaled . |
21,383 | public String save ( String uploadFolder ) throws ControllerException { String realPath = info . getRealPath ( uploadFolder ) ; fn . sanitise ( ) ; String imagename = uniqueImagename ( realPath , fn . fullPath ( ) ) ; try { ImageIO . write ( image , fn . extension ( ) , new File ( realPath , imagename ) ) ; image . flush ( ) ; } catch ( IOException e ) { throw new ControllerException ( e ) ; } return uploadFolder + File . separatorChar + imagename ; } | Saves the file on the server in the folder given |
21,384 | String uniqueImagename ( String folder , String filename ) { String buildFileName = filename ; while ( ( new File ( folder , buildFileName ) ) . exists ( ) ) buildFileName = fn . increment ( ) ; return buildFileName ; } | Calculates a unique filename located in the image upload folder . |
21,385 | private List < JqassistantRules > readXmlSource ( RuleSource ruleSource ) { List < JqassistantRules > rules = new ArrayList < > ( ) ; try ( InputStream inputStream = ruleSource . getInputStream ( ) ) { JqassistantRules jqassistantRules = jaxbUnmarshaller . unmarshal ( inputStream ) ; rules . add ( jqassistantRules ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Cannot read rules from '" + ruleSource . getId ( ) + "'." , e ) ; } return rules ; } | Read rules from XML documents . |
21,386 | private Report getReport ( ReportType reportType ) { String type = null ; String primaryColumn = null ; Properties properties = new Properties ( ) ; if ( reportType != null ) { type = reportType . getType ( ) ; primaryColumn = reportType . getPrimaryColumn ( ) ; for ( PropertyType propertyType : reportType . getProperty ( ) ) { properties . setProperty ( propertyType . getName ( ) , propertyType . getValue ( ) ) ; } } Report . ReportBuilder reportBuilder = Report . builder ( ) . primaryColumn ( primaryColumn ) . properties ( properties ) ; if ( type != null ) { reportBuilder . selectedTypes ( Report . selectTypes ( type ) ) ; } return reportBuilder . build ( ) ; } | Read the report definition . |
21,387 | private Verification getVerification ( VerificationType verificationType ) throws RuleException { if ( verificationType != null ) { RowCountVerificationType rowCountVerificationType = verificationType . getRowCount ( ) ; AggregationVerificationType aggregationVerificationType = verificationType . getAggregation ( ) ; if ( aggregationVerificationType != null ) { return AggregationVerification . builder ( ) . column ( aggregationVerificationType . getColumn ( ) ) . min ( aggregationVerificationType . getMin ( ) ) . max ( aggregationVerificationType . getMax ( ) ) . build ( ) ; } else if ( rowCountVerificationType != null ) { return RowCountVerification . builder ( ) . min ( rowCountVerificationType . getMin ( ) ) . max ( rowCountVerificationType . getMax ( ) ) . build ( ) ; } else { throw new RuleException ( "Unsupported verification " + verificationType ) ; } } return null ; } | Read the verification definition . |
21,388 | private Severity getSeverity ( SeverityEnumType severityType , Severity defaultSeverity ) throws RuleException { return severityType == null ? defaultSeverity : Severity . fromValue ( severityType . value ( ) ) ; } | Get the severity . |
21,389 | public void printScopes ( Map < String , Scope > scopes ) { logger . info ( "Scopes [" + scopes . size ( ) + "]" ) ; for ( String scopeName : scopes . keySet ( ) ) { logger . info ( "\t" + scopeName ) ; } } | Print a list of available scopes to the console . |
21,390 | private void shutdownGracefully ( final Iterator < EventExecutorGroup > iterator ) { if ( iterator . hasNext ( ) ) { EventExecutorGroup group = iterator . next ( ) ; if ( ! group . isShuttingDown ( ) ) { group . shutdownGracefully ( ) . addListener ( future -> { if ( ! future . isSuccess ( ) ) { } shutdownGracefully ( iterator ) ; } ) ; } } } | Shutdown executor in order . |
21,391 | public static void decode ( final Map < String , String > map , final String data ) { StringUtil . split ( data , '&' , keyValue -> { final int indexOfSeperator = keyValue . indexOf ( '=' ) ; if ( indexOfSeperator > - 1 ) { if ( indexOfSeperator == keyValue . length ( ) - 1 ) { map . put ( URLCodec . decode ( keyValue . substring ( 0 , indexOfSeperator ) , StandardCharsets . UTF_8 ) , "" ) ; } else { final String first = keyValue . substring ( 0 , indexOfSeperator ) , second = keyValue . substring ( indexOfSeperator + 1 ) ; map . put ( URLCodec . decode ( first , StandardCharsets . UTF_8 ) , URLCodec . decode ( second , StandardCharsets . UTF_8 ) ) ; } } } ) ; } | A faster decode than the original from Play Framework but still equivalent in output |
21,392 | public static < T > T selectValue ( T defaultValue , T ... overrides ) { for ( T override : overrides ) { if ( override != null ) { return override ; } } return defaultValue ; } | Determine a value from given options . |
21,393 | public static < T > void verifyDeprecatedOption ( String deprecatedOption , T value , String option ) { if ( value != null ) { LOGGER . warn ( "The option '" + deprecatedOption + "' is deprecated, use '" + option + "' instead." ) ; } } | Verify if a deprecated option has been used and emit a warning . |
21,394 | < T > Deque < T > getValues ( Class < T > key ) { Deque < T > values = ( Deque < T > ) contextValuesPerKey . get ( key ) ; if ( values == null ) { values = new LinkedList < > ( ) ; contextValuesPerKey . put ( key , values ) ; } return values ; } | Determine the stack for the given key . |
21,395 | public void apply ( UnaryOperator < String > function ) { this . filename = function . apply ( this . filename ) ; if ( path != null && ! path . isEmpty ( ) ) this . path = function . apply ( this . path ) ; } | Apply the function to all string |
21,396 | public String increment ( ) { int count = 0 ; String newFilename , altered = filename ( ) ; if ( altered . charAt ( altered . length ( ) - 1 ) == RIGHT ) { int rightBracket = altered . length ( ) - 1 , leftBracket = altered . lastIndexOf ( LEFT ) ; try { count = Integer . parseInt ( altered . substring ( leftBracket + 1 , rightBracket ) ) ; } catch ( NumberFormatException | IndexOutOfBoundsException ignore ) { newFilename = altered + LEFT ; } newFilename = altered . substring ( 0 , leftBracket + 1 ) ; } else { newFilename = altered + LEFT ; } newFilename += ( count + 1 ) ; newFilename += RIGHT ; updateName ( newFilename ) ; return newFilename + EXTENSION_SEPERATOR + ext ; } | filename . jpg - > ; filename_1v . jpg - > ; filename_2v . jpg |
21,397 | public static < T > Supplier < T > memoizeLock ( Supplier < T > delegate ) { AtomicReference < T > value = new AtomicReference < > ( ) ; return ( ) -> { T val = value . get ( ) ; if ( val == null ) { synchronized ( value ) { val = value . get ( ) ; if ( val == null ) { val = Objects . requireNonNull ( delegate . get ( ) ) ; value . set ( val ) ; } } } return val ; } ; } | Stolen from Googles Guava Suppliers . java |
21,398 | public static String getControllerForResult ( Route route ) { if ( route == null || route . getController ( ) == null ) return Constants . ROOT_CONTROLLER_NAME ; return RouterHelper . getReverseRouteFast ( route . getController ( ) ) . substring ( 1 ) ; } | Getting the controller from the route |
21,399 | private < T , U > T [ ] locateAll ( final ClassLocator locator , final Class < T > clazz , final Consumer < T > bootstrapper ) { Set < Class < ? extends T > > set = locator . subtypeOf ( clazz ) ; if ( ! set . isEmpty ( ) ) { @ SuppressWarnings ( "unchecked" ) T [ ] all = ( T [ ] ) Array . newInstance ( clazz , set . size ( ) ) ; int index = 0 ; Iterator < Class < ? extends T > > iterator = set . iterator ( ) ; while ( iterator . hasNext ( ) ) { Class < ? extends T > c = iterator . next ( ) ; try { T locatedImplementation = DynamicClassFactory . createInstance ( c , clazz ) ; bootstrapper . accept ( locatedImplementation ) ; logger . debug ( "Loaded configuration from: " + c ) ; all [ index ++ ] = locatedImplementation ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { logger . debug ( "Error reading custom configuration. Going with built in defaults. The error was: " + getCauseMessage ( e ) ) ; } } return all ; } else { logger . debug ( "Did not find custom configuration for {}. Going with built in defaults " , clazz ) ; } return null ; } | Locates an implementation of the given type and executes the consumer if a class of the given type is found |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.