idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
143,000
public boolean complete ( UUID value ) { return root . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
If not already completed sets the value to the given UUID .
29
13
143,001
public boolean complete ( InetAddress value ) { return root . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
If not already completed sets the value to the given InetAddress .
30
14
143,002
public static final Promise race ( Promise ... promises ) { if ( promises == null || promises . length == 0 ) { return Promise . resolve ( ) ; } @ SuppressWarnings ( "unchecked" ) CompletableFuture < Tree > [ ] futures = new CompletableFuture [ promises . length ] ; for ( int i = 0 ; i < promises . length ; i ++ ) { futures [ i ] = promises [ i ] . future ; } CompletableFuture < Object > any = CompletableFuture . anyOf ( futures ) ; return new Promise ( r -> { any . whenComplete ( ( object , error ) -> { try { if ( error != null ) { r . reject ( error ) ; return ; } r . resolve ( ( Tree ) object ) ; } catch ( Throwable cause ) { r . reject ( cause ) ; } } ) ; } ) ; }
Returns a new Promise that is completed when any of the given Promises complete with the same result . Otherwise if it completed exceptionally the returned Promise also does so with a CompletionException holding this exception as its cause .
187
43
143,003
@ SuppressWarnings ( "unchecked" ) protected static final Tree toTree ( Object object ) { if ( object == null ) { return new Tree ( ( Tree ) null , null , null ) ; } if ( object instanceof Tree ) { return ( Tree ) object ; } if ( object instanceof Map ) { return new Tree ( ( Map < String , Object > ) object ) ; } return new Tree ( ( Tree ) null , null , object ) ; }
Converts an Object to a Tree .
99
8
143,004
public Object addingService ( ServiceReference reference ) { HttpService httpService = ( HttpService ) context . getService ( reference ) ; this . properties = this . updateDictionaryConfig ( this . properties , true ) ; try { String alias = this . getAlias ( ) ; String servicePid = this . properties . get ( BundleConstants . SERVICE_PID ) ; if ( servlet == null ) { servlet = this . makeServlet ( alias , this . properties ) ; if ( servlet instanceof WebappServlet ) ( ( WebappServlet ) servlet ) . init ( context , servicePid , this . properties ) ; } else if ( servlet instanceof WebappServlet ) ( ( WebappServlet ) servlet ) . setProperties ( properties ) ; if ( servicePid != null ) // Listen for configuration changes serviceRegistration = context . registerService ( ManagedService . class . getName ( ) , new HttpConfigurator ( context , servicePid ) , this . properties ) ; httpService . registerServlet ( alias , servlet , this . properties , httpContext ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return httpService ; }
Http Service is up add my servlets .
263
9
143,005
public Servlet makeServlet ( String alias , Dictionary < String , String > dictionary ) { String servletClass = dictionary . get ( BundleConstants . SERVICE_CLASS ) ; return ( Servlet ) ClassServiceUtility . getClassService ( ) . makeObjectFromClassName ( servletClass ) ; }
Create the servlet . The SERVLET_CLASS property must be supplied .
65
15
143,006
public void removeService ( ServiceReference reference , Object service ) { if ( serviceRegistration != null ) { serviceRegistration . unregister ( ) ; serviceRegistration = null ; } String alias = this . getAlias ( ) ; ( ( HttpService ) service ) . unregister ( alias ) ; if ( servlet instanceof WebappServlet ) ( ( WebappServlet ) servlet ) . free ( ) ; servlet = null ; }
Http Service is down remove my servlet .
92
9
143,007
public String getAlias ( ) { String alias = this . properties . get ( BaseWebappServlet . ALIAS ) ; if ( alias == null ) alias = this . properties . get ( BaseWebappServlet . ALIAS . substring ( BaseWebappServlet . PROPERTY_PREFIX . length ( ) ) ) ; return HttpServiceTracker . addURLPath ( null , alias ) ; }
Get the web context path from the service name .
88
10
143,008
public String calculateWebAlias ( Dictionary < String , String > dictionary ) { String alias = dictionary . get ( BaseWebappServlet . ALIAS ) ; if ( alias == null ) alias = dictionary . get ( BaseWebappServlet . ALIAS . substring ( BaseWebappServlet . PROPERTY_PREFIX . length ( ) ) ) ; if ( alias == null ) alias = this . getAlias ( ) ; if ( alias == null ) alias = context . getProperty ( BaseWebappServlet . ALIAS ) ; if ( alias == null ) alias = context . getProperty ( BaseWebappServlet . ALIAS . substring ( BaseWebappServlet . PROPERTY_PREFIX . length ( ) ) ) ; if ( alias == null ) alias = DEFAULT_WEB_ALIAS ; return alias ; }
Figure out the correct web alias .
180
7
143,009
public void configPropertiesUpdated ( Dictionary < String , String > properties ) { if ( HttpServiceTracker . propertiesEqual ( properties , configProperties ) ) return ; configProperties = properties ; ServiceReference reference = context . getServiceReference ( HttpService . class . getName ( ) ) ; if ( reference == null ) return ; HttpService httpService = ( HttpService ) context . getService ( reference ) ; String oldAlias = this . getAlias ( ) ; this . changeServletProperties ( servlet , properties ) ; String alias = properties . get ( BaseWebappServlet . ALIAS ) ; boolean restartRequired = false ; if ( ! oldAlias . equals ( alias ) ) restartRequired = true ; else if ( servlet instanceof WebappServlet ) restartRequired = ( ( WebappServlet ) servlet ) . restartRequired ( ) ; if ( ! restartRequired ) return ; try { httpService . unregister ( oldAlias ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; // Should not happen } this . properties . put ( BaseWebappServlet . ALIAS , alias ) ; if ( servlet instanceof WebappServlet ) if ( ( ( WebappServlet ) servlet ) . restartRequired ( ) ) { ( ( WebappServlet ) servlet ) . free ( ) ; servlet = null ; } this . addingService ( reference ) ; // Start it back up }
Update the servlet s properties . Called when the configuration changes .
310
13
143,010
public boolean changeServletProperties ( Servlet servlet , Dictionary < String , String > properties ) { if ( servlet instanceof WebappServlet ) { Dictionary < String , String > dictionary = ( ( WebappServlet ) servlet ) . getProperties ( ) ; properties = BaseBundleActivator . putAll ( properties , dictionary ) ; } return this . setServletProperties ( servlet , properties ) ; }
Change the servlet properties to these properties .
92
9
143,011
public boolean setServletProperties ( Servlet servlet , Dictionary < String , String > properties ) { this . properties = properties ; if ( servlet instanceof WebappServlet ) return ( ( WebappServlet ) servlet ) . setProperties ( properties ) ; return true ; // Success }
Set the serlvlet s properties .
64
8
143,012
public static boolean propertiesEqual ( Dictionary < String , String > properties , Dictionary < String , String > dictionary ) { Enumeration < String > props = properties . keys ( ) ; while ( props . hasMoreElements ( ) ) { String key = props . nextElement ( ) ; if ( ! properties . get ( key ) . equals ( dictionary . get ( key ) ) ) return false ; } props = dictionary . keys ( ) ; while ( props . hasMoreElements ( ) ) { String key = props . nextElement ( ) ; if ( ! dictionary . get ( key ) . equals ( properties . get ( key ) ) ) return false ; } return true ; }
Are these properties equal .
142
5
143,013
private String buildLogPath ( File bootstrapLogDir , String logFileName ) { return new File ( bootstrapLogDir , logFileName ) . getAbsolutePath ( ) ; }
Constructs a path of a file under the bootstrap log directory .
40
14
143,014
private void executeGalaxyScript ( final String scriptName ) { final String bashScript = String . format ( "cd %s; if [ -d .venv ]; then . .venv/bin/activate; fi; %s" , getPath ( ) , scriptName ) ; IoUtils . executeAndWait ( "bash" , "-c" , bashScript ) ; }
Executes a script within the Galaxy root directory .
81
10
143,015
public void stateMachine ( ShanksSimulation sim ) throws Exception { logger . fine ( "Using default state machine for ScenarioManager" ) ; // switch (this.simulationStateMachineStatus) { // case CHECK_FAILURES: // this.checkFailures(sim); // this.simulationStateMachineStatus = GENERATE_FAILURES; // break; // case GENERATE_FAILURES: // this.generateFailures(sim); // this.simulationStateMachineStatus = CHECK_PERIODIC_; // break; // case GENERATE_PERIODIC_EVENTS: // this.generatePeriodicEvents(sim); // this.simulationStateMachineStatus = CHECK_FAILURES; // break; // case GENERATE_RANDOM_EVENTS: // this.generateRandomEvents(sim); // this.simulationStateMachineStatus = CHECK_FAILURES; // break; // } this . checkFailures ( sim ) ; this . generateFailures ( sim ) ; this . generateScenarioEvents ( sim ) ; this . generateNetworkElementEvents ( sim ) ; long step = sim . getSchedule ( ) . getSteps ( ) ; if ( step % 500 == 0 ) { logger . info ( "Step: " + step ) ; logger . finest ( "In step " + step + ", there are " + sim . getScenario ( ) . getCurrentFailures ( ) . size ( ) + " current failures." ) ; logger . finest ( "In step " + step + ", there are " + sim . getNumOfResolvedFailures ( ) + " resolved failures." ) ; } }
This method implements the state machine of the scenario manager
363
10
143,016
public EmbedVaadinComponent withTheme ( String theme ) { assertNotNull ( theme , "theme could not be null." ) ; getConfig ( ) . setTheme ( theme ) ; return self ( ) ; }
Specifies the vaadin theme to use for the application .
45
12
143,017
public synchronized static void enableLogging ( ) { if ( SplitlogLoggerFactory . state == SplitlogLoggingState . ON ) { return ; } SplitlogLoggerFactory . messageCounter . set ( 0 ) ; SplitlogLoggerFactory . state = SplitlogLoggingState . ON ; /* * intentionally using the original logger so that this message can not * be silenced */ LoggerFactory . getLogger ( SplitlogLoggerFactory . class ) . info ( "Forcibly enabled Splitlog's internal logging." ) ; }
Force Splitlog s internal logging to be enabled .
112
10
143,018
public synchronized static boolean isLoggingEnabled ( ) { switch ( SplitlogLoggerFactory . state ) { case ON : return true ; case OFF : return false ; default : final String propertyValue = System . getProperty ( SplitlogLoggerFactory . LOGGING_PROPERTY_NAME , SplitlogLoggerFactory . OFF_STATE ) ; return propertyValue . equals ( SplitlogLoggerFactory . ON_STATE ) ; } }
Whether or not Splitlog internals will log if logging is requested at this time .
92
17
143,019
public synchronized static void silenceLogging ( ) { if ( SplitlogLoggerFactory . state == SplitlogLoggingState . OFF ) { return ; } SplitlogLoggerFactory . state = SplitlogLoggingState . OFF ; SplitlogLoggerFactory . messageCounter . set ( 0 ) ; /* * intentionally using the original logger so that this message can not * be silenced */ LoggerFactory . getLogger ( SplitlogLoggerFactory . class ) . info ( "Forcibly disabled Splitlog's internal logging." ) ; }
Force Splitlog s internal logging to be disabled .
112
10
143,020
public static void add ( ) { String current = System . getProperties ( ) . getProperty ( HANDLER_PKGS , "" ) ; if ( current . length ( ) > 0 ) { if ( current . contains ( PKG ) ) { return ; } current = current + "|" ; } System . getProperties ( ) . put ( HANDLER_PKGS , current + PKG ) ; }
Adds the protocol handler .
89
5
143,021
public static void remove ( ) { final String current = System . getProperties ( ) . getProperty ( HANDLER_PKGS , "" ) ; // Only one if ( current . equals ( PKG ) ) { System . getProperties ( ) . put ( HANDLER_PKGS , "" ) ; return ; } // Middle String token = "|" + PKG + "|" ; int idx = current . indexOf ( token ) ; if ( idx > - 1 ) { final String removed = current . substring ( 0 , idx ) + "|" + current . substring ( idx + token . length ( ) ) ; System . getProperties ( ) . put ( HANDLER_PKGS , removed ) ; return ; } // Beginning token = PKG + "|" ; idx = current . indexOf ( token ) ; if ( idx > - 1 ) { final String removed = current . substring ( idx + token . length ( ) ) ; System . getProperties ( ) . put ( HANDLER_PKGS , removed ) ; return ; } // End token = "|" + PKG ; idx = current . indexOf ( token ) ; if ( idx > - 1 ) { final String removed = current . substring ( 0 , idx ) ; System . getProperties ( ) . put ( HANDLER_PKGS , removed ) ; return ; } }
Removes the protocol handler .
306
6
143,022
public boolean pauseQuartzJob ( String jobName , String jobGroupName ) { try { this . scheduler . pauseJob ( new JobKey ( jobName , jobGroupName ) ) ; return true ; } catch ( SchedulerException e ) { logger . error ( "error pausing job: " + jobName + " in group: " + jobGroupName , e ) ; } return false ; }
Pause the job with given name in given group
85
9
143,023
public boolean pauseQuartzScheduler ( ) { try { this . scheduler . standby ( ) ; return true ; } catch ( SchedulerException e ) { logger . error ( "error pausing quartz scheduler" , e ) ; } return false ; }
Pause the Quartz scheduler .
55
6
143,024
public Boolean isSchedulerPaused ( ) { try { return this . scheduler . isInStandbyMode ( ) ; } catch ( SchedulerException e ) { logger . error ( "error retrieveing scheduler condition" , e ) ; } return null ; }
Check if scheduler is paused or not .
57
9
143,025
public boolean executeJob ( String jobName , String jobGroupName ) { try { this . scheduler . triggerJob ( new JobKey ( jobName , jobGroupName ) ) ; return true ; } catch ( SchedulerException e ) { logger . error ( "error executing job: " + jobName + " in group: " + jobGroupName , e ) ; } return false ; }
Fire the given job in given group .
82
8
143,026
public void log ( Level level , String message , Object ... args ) { if ( logger . isLoggable ( level ) ) { String errorMessage = "" ; Throwable thrown = null ; Object [ ] params = null ; if ( args == null || args . length == 0 ) { errorMessage = message ; } else if ( args [ 0 ] instanceof Throwable ) { thrown = ( Throwable ) args [ 0 ] ; if ( args . length > 1 ) { params = new Object [ args . length - 1 ] ; System . arraycopy ( args , 1 , params , 0 , args . length - 1 ) ; } } else if ( args [ args . length - 1 ] instanceof Throwable ) { params = new Object [ args . length - 1 ] ; System . arraycopy ( args , 0 , params , 0 , args . length - 1 ) ; thrown = ( Throwable ) args [ args . length - 1 ] ; } else { params = new Object [ args . length ] ; System . arraycopy ( args , 0 , params , 0 , args . length ) ; } if ( params != null ) { errorMessage = MessageFormat . format ( message , params ) ; } LogRecord record = new LogRecord ( level , errorMessage ) ; record . setLoggerName ( logger . getName ( ) ) ; record . setThrown ( thrown ) ; record . setParameters ( args ) ; logger . log ( record ) ; } }
Logs a message at a given level .
305
9
143,027
protected URL [ ] getCompileClasspathElementURLs ( ) throws DependencyResolutionRequiredException { // build class loader to get classes to generate resources for return project . getCompileClasspathElements ( ) . stream ( ) . map ( path -> { try { return new File ( path ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException ex ) { throw new RuntimeException ( ex ) ; } } ) . toArray ( size -> new URL [ size ] ) ; }
Get a List of URLs of all compile dependencies of this project .
111
13
143,028
protected File getGeneratedResourcesDirectory ( ) { if ( generatedResourcesFolder == null ) { String generatedResourcesFolderAbsolutePath = this . project . getBuild ( ) . getDirectory ( ) + "/" + getGeneratedResourcesDirectoryPath ( ) ; generatedResourcesFolder = new File ( generatedResourcesFolderAbsolutePath ) ; if ( ! generatedResourcesFolder . exists ( ) ) { generatedResourcesFolder . mkdirs ( ) ; } } return generatedResourcesFolder ; }
Get folder to temporarily generate the resources to .
98
9
143,029
public static String getAPIVersion ( final String resourceFileName , final String versionProperty ) { final Properties props = new Properties ( ) ; final URL url = ClassLoader . getSystemResource ( resourceFileName ) ; if ( url != null ) { InputStream is = null ; try { is = url . openStream ( ) ; props . load ( is ) ; } catch ( IOException ex ) { LOG . debug ( "Unable to open resource file" , ex ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { } } } } String version = props . getProperty ( versionProperty , "unknown" ) ; return version ; }
Get the Version Number from a properties file in the Application Classpath .
150
14
143,030
public String getExtendsInterface ( ) { if ( this . getExtendsInterfaces ( ) . isEmpty ( ) ) { // return "Empty"; return this . getInstanceType ( ) ; } else { String tName = this . getExtendsInterfaces ( ) . get ( 0 ) . replaceAll ( "\\W+" , "" ) ; return tName ; } }
will have issues!!!!!
81
4
143,031
public static String escapeTitle ( final String title ) { final String escapedTitle = title . replaceAll ( "^[^" + UNICODE_TITLE_START_CHAR + "]*" , "" ) . replaceAll ( "[^" + UNICODE_WORD + ". -]" , "" ) ; if ( isNullOrEmpty ( escapedTitle ) ) { return "" ; } else { // Remove whitespace return escapedTitle . replaceAll ( "\\s+" , "_" ) . replaceAll ( "(^_+)|(_+$)" , "" ) . replaceAll ( "__" , "_" ) ; } }
Escapes a title so that it is alphanumeric or has a fullstop underscore or hyphen only . It also removes anything from the front of the title that isn t alphanumeric .
136
39
143,032
public static String escapeForXML ( final String content ) { if ( content == null ) return "" ; /* * Note: The following characters should be escaped: & < > " ' * * However, all but ampersand pose issues when other elements are included in the title. * * eg <title>Product A > Product B<phrase condition="beta">-Beta</phrase></title> * * should become * * <title>Product A &gt; Product B<phrase condition="beta">-Beta</phrase></title> */ String fixedContent = XMLUtilities . STANDALONE_AMPERSAND_PATTERN . matcher ( content ) . replaceAll ( "&amp;" ) ; // Loop over and find all the XML Elements as they should remain untouched. final LinkedList < String > elements = new LinkedList < String > ( ) ; if ( fixedContent . indexOf ( ' ' ) != - 1 ) { int index = - 1 ; while ( ( index = fixedContent . indexOf ( ' ' , index + 1 ) ) != - 1 ) { int endIndex = fixedContent . indexOf ( ' ' , index ) ; int nextIndex = fixedContent . indexOf ( ' ' , index + 1 ) ; /* * If the next opening tag is less than the next ending tag, than the current opening tag isn't a match for the next * ending tag, so continue to the next one */ if ( endIndex == - 1 || ( nextIndex != - 1 && nextIndex < endIndex ) ) { continue ; } else if ( index + 1 == endIndex ) { // This is a <> sequence, so it should be ignored as well. continue ; } else { elements . add ( fixedContent . substring ( index , endIndex + 1 ) ) ; } } } // Find all the elements and replace them with a marker String escapedTitle = fixedContent ; for ( int count = 0 ; count < elements . size ( ) ; count ++ ) { escapedTitle = escapedTitle . replace ( elements . get ( count ) , "###" + count + "###" ) ; } // Perform the replacements on what's left escapedTitle = escapedTitle . replace ( "<" , "&lt;" ) . replace ( ">" , "&gt;" ) . replace ( "\"" , "&quot;" ) ; // Replace the markers for ( int count = 0 ; count < elements . size ( ) ; count ++ ) { escapedTitle = escapedTitle . replace ( "###" + count + "###" , elements . get ( count ) ) ; } return escapedTitle ; }
Escapes a String so that it can be used in a Docbook Element ensuring that any entities or elements are maintained .
547
24
143,033
public static boolean validateTableRows ( final Element table ) { assert table != null ; assert table . getNodeName ( ) . equals ( "table" ) || table . getNodeName ( ) . equals ( "informaltable" ) ; final NodeList tgroups = table . getElementsByTagName ( "tgroup" ) ; for ( int i = 0 ; i < tgroups . getLength ( ) ; i ++ ) { final Element tgroup = ( Element ) tgroups . item ( i ) ; if ( ! validateTableGroup ( tgroup ) ) return false ; } return true ; }
Check to ensure that a table isn t missing any entries in its rows .
129
15
143,034
public static boolean validateTableGroup ( final Element tgroup ) { assert tgroup != null ; assert tgroup . getNodeName ( ) . equals ( "tgroup" ) ; final Integer numColumns = Integer . parseInt ( tgroup . getAttribute ( "cols" ) ) ; // Check that all the thead, tbody and tfoot elements have the correct number of entries. final List < Node > nodes = XMLUtilities . getDirectChildNodes ( tgroup , "thead" , "tbody" , "tfoot" ) ; for ( final Node ele : nodes ) { // Find all child nodes that are a row final NodeList children = ele . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node node = children . item ( i ) ; if ( node . getNodeName ( ) . equals ( "row" ) || node . getNodeName ( ) . equals ( "tr" ) ) { if ( ! validateTableRow ( node , numColumns ) ) return false ; } } } return true ; }
Check to ensure that a Docbook tgroup isn t missing an row entries using number of cols defined for the tgroup .
238
26
143,035
public static boolean validateTableRow ( final Node row , final int numColumns ) { assert row != null ; assert row . getNodeName ( ) . equals ( "row" ) || row . getNodeName ( ) . equals ( "tr" ) ; if ( row . getNodeName ( ) . equals ( "row" ) ) { final List < Node > entries = XMLUtilities . getDirectChildNodes ( row , "entry" ) ; final List < Node > entryTbls = XMLUtilities . getDirectChildNodes ( row , "entrytbl" ) ; if ( ( entries . size ( ) + entryTbls . size ( ) ) <= numColumns ) { for ( final Node entryTbl : entryTbls ) { if ( ! validateEntryTbl ( ( Element ) entryTbl ) ) return false ; } return true ; } else { return false ; } } else { final List < Node > nodes = XMLUtilities . getDirectChildNodes ( row , "td" , "th" ) ; return nodes . size ( ) <= numColumns ; } }
Check to ensure that a docbook row has the required number of columns for a table .
237
18
143,036
public static List < StringToNodeCollection > getTranslatableStringsV3 ( final Document xml , final boolean allowDuplicates ) { if ( xml == null ) return null ; return getTranslatableStringsV3 ( xml . getDocumentElement ( ) , allowDuplicates ) ; }
Get the Translatable Strings from an XML Document . This method will return of Translation strings to XML DOM nodes within the XML Document .
62
27
143,037
public static List < StringToNodeCollection > getTranslatableStringsV3 ( final Node node , final boolean allowDuplicates ) { if ( node == null ) return null ; final List < StringToNodeCollection > retValue = new LinkedList < StringToNodeCollection > ( ) ; final NodeList nodes = node . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; ++ i ) { final Node childNode = nodes . item ( i ) ; getTranslatableStringsFromNodeV3 ( childNode , retValue , allowDuplicates , new XMLProperties ( ) ) ; } return retValue ; }
Get the Translatable Strings from an XML Node . This method will return of Translation strings to XML DOM nodes within the XML Document .
143
27
143,038
private static String cleanTranslationText ( final String input , final boolean removeWhitespaceFromStart , final boolean removeWhitespaceFromEnd ) { String retValue = XMLUtilities . cleanText ( input ) ; retValue = retValue . trim ( ) ; /* * When presenting the contents of a childless XML node to the translator, there is no need for white space padding. * When building up a translatable string from a succession of text nodes, whitespace becomes important. */ if ( ! removeWhitespaceFromStart ) { if ( PRECEEDING_WHITESPACE_SIMPLE_RE_PATTERN . matcher ( input ) . matches ( ) ) { retValue = " " + retValue ; } } if ( ! removeWhitespaceFromEnd ) { if ( TRAILING_WHITESPACE_SIMPLE_RE_PATTERN . matcher ( input ) . matches ( ) ) { retValue += " " ; } } return retValue ; }
Cleans a string for presentation to a translator
211
9
143,039
public static Pair < String , String > wrapForValidation ( final DocBookVersion docBookVersion , final String xml ) { final String rootEleName = XMLUtilities . findRootElementName ( xml ) ; if ( docBookVersion == DocBookVersion . DOCBOOK_50 ) { if ( rootEleName . equals ( "abstract" ) || rootEleName . equals ( "legalnotice" ) || rootEleName . equals ( "authorgroup" ) ) { final String preamble = XMLUtilities . findPreamble ( xml ) ; final StringBuilder buffer = new StringBuilder ( "<book><info><title />" ) ; if ( preamble != null ) { buffer . append ( xml . replace ( preamble , "" ) ) ; } else { buffer . append ( xml ) ; } buffer . append ( "</info></book>" ) ; return new Pair < String , String > ( "book" , DocBookUtilities . addDocBook50Namespace ( buffer . toString ( ) ) ) ; } else if ( rootEleName . equals ( "info" ) ) { final String preamble = XMLUtilities . findPreamble ( xml ) ; final StringBuilder buffer = new StringBuilder ( "<book>" ) ; if ( preamble != null ) { buffer . append ( xml . replace ( preamble , "" ) ) ; } else { buffer . append ( xml ) ; } buffer . append ( "</book>" ) ; return new Pair < String , String > ( "book" , DocBookUtilities . addDocBook50Namespace ( buffer . toString ( ) ) ) ; } } return new Pair < String , String > ( rootEleName , xml ) ; }
Wraps the xml if required so that validation can be performed . An example of where this is required is if you are validating against Abstracts Author Groups or Legal Notices for DocBook 5 . 0 .
365
42
143,040
public static void wrapForRendering ( final Document xmlDoc ) { // Some topics need to be wrapped up to be rendered properly final String documentElementNodeName = xmlDoc . getDocumentElement ( ) . getNodeName ( ) ; if ( documentElementNodeName . equals ( "authorgroup" ) || documentElementNodeName . equals ( "legalnotice" ) ) { final Element currentChild = xmlDoc . createElement ( documentElementNodeName ) ; xmlDoc . renameNode ( xmlDoc . getDocumentElement ( ) , xmlDoc . getNamespaceURI ( ) , "book" ) ; final Element bookInfo = xmlDoc . createElement ( "bookinfo" ) ; xmlDoc . getDocumentElement ( ) . appendChild ( bookInfo ) ; bookInfo . appendChild ( currentChild ) ; final NodeList existingChildren = xmlDoc . getDocumentElement ( ) . getChildNodes ( ) ; for ( int childIndex = 0 ; childIndex < existingChildren . getLength ( ) ; ++ childIndex ) { final Node child = existingChildren . item ( childIndex ) ; if ( child != bookInfo ) { currentChild . appendChild ( child ) ; } } } }
Some docbook elements need to be wrapped up so they can be properly transformed by the docbook XSL .
248
22
143,041
public static boolean validateTables ( final Document doc ) { final NodeList tables = doc . getElementsByTagName ( "table" ) ; for ( int i = 0 ; i < tables . getLength ( ) ; i ++ ) { final Element table = ( Element ) tables . item ( i ) ; if ( ! validateTableRows ( table ) ) { return false ; } } final NodeList informalTables = doc . getElementsByTagName ( "informaltable" ) ; for ( int i = 0 ; i < informalTables . getLength ( ) ; i ++ ) { final Element informalTable = ( Element ) informalTables . item ( i ) ; if ( ! validateTableRows ( informalTable ) ) { return false ; } } return true ; }
Checks to see if the Rows in XML Tables exceed the maximum number of columns .
167
18
143,042
public static boolean checkForInvalidInfoElements ( final Document doc ) { final List < Node > invalidElements = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , "title" , "subtitle" , "titleabbrev" ) ; return invalidElements != null && ! invalidElements . isEmpty ( ) ; }
Checks that the
77
4
143,043
public static String validateRevisionHistory ( final Document doc , final String [ ] dateFormats ) { final List < String > invalidRevNumbers = new ArrayList < String > ( ) ; // Find each <revnumber> element and make sure it matches the publican regex final NodeList revisions = doc . getElementsByTagName ( "revision" ) ; Date previousDate = null ; for ( int i = 0 ; i < revisions . getLength ( ) ; i ++ ) { final Element revision = ( Element ) revisions . item ( i ) ; final NodeList revnumbers = revision . getElementsByTagName ( "revnumber" ) ; final Element revnumber = revnumbers . getLength ( ) == 1 ? ( Element ) revnumbers . item ( 0 ) : null ; final NodeList dates = revision . getElementsByTagName ( "date" ) ; final Element date = dates . getLength ( ) == 1 ? ( Element ) dates . item ( 0 ) : null ; // Make sure the rev number is valid and the order is correct if ( revnumber != null && ! revnumber . getTextContent ( ) . matches ( "^([0-9.]*)-([0-9.]*)$" ) ) { invalidRevNumbers . add ( revnumber . getTextContent ( ) ) ; } else if ( revnumber == null ) { return "Invalid revision, missing &lt;revnumber&gt; element." ; } // Check the dates are in chronological order if ( date != null ) { try { final Date revisionDate = DateUtils . parseDateStrictly ( cleanDate ( date . getTextContent ( ) ) , Locale . ENGLISH , dateFormats ) ; if ( previousDate != null && revisionDate . after ( previousDate ) ) { return "The revisions in the Revision History are not in descending chronological order, " + "starting from \"" + date . getTextContent ( ) + "\"." ; } previousDate = revisionDate ; } catch ( Exception e ) { // Check that it is an invalid format or just an incorrect date (ie the day doesn't match) try { DateUtils . parseDate ( cleanDate ( date . getTextContent ( ) ) , Locale . ENGLISH , dateFormats ) ; return "Invalid revision, the name of the day specified in \"" + date . getTextContent ( ) + "\" doesn't match the " + "date." ; } catch ( Exception ex ) { return "Invalid revision, the date \"" + date . getTextContent ( ) + "\" is not in a valid format." ; } } } else { return "Invalid revision, missing &lt;date&gt; element." ; } } if ( ! invalidRevNumbers . isEmpty ( ) ) { return "Revision History has invalid &lt;revnumber&gt; values: " + CollectionUtilities . toSeperatedString ( invalidRevNumbers , ", " ) + ". The revnumber must match \"^([0-9.]*)-([0-9.]*)$\" to be valid." ; } else { return null ; } }
Validates a Revision History XML DOM Document to ensure that the content is valid for use with Publican .
663
21
143,044
private static String cleanDate ( final String dateString ) { if ( dateString == null ) { return dateString ; } String retValue = dateString ; retValue = THURSDAY_DATE_RE . matcher ( retValue ) . replaceAll ( "Thu" ) ; retValue = TUESDAY_DATE_RE . matcher ( retValue ) . replaceAll ( "Tue" ) ; return retValue ; }
Basic method to clean a date string to fix any partial day names . It currently cleans Thur Thurs and Tues .
92
22
143,045
public static Object get ( final Object bean , final String property ) { try { if ( property . indexOf ( "." ) >= 0 ) { final Object subBean = ClassMockUtils . get ( bean , property . substring ( 0 , property . indexOf ( "." ) ) ) ; if ( subBean == null ) { return null ; } final String newProperty = property . substring ( property . indexOf ( "." ) + 1 ) ; return ClassMockUtils . get ( subBean , newProperty ) ; } Method method = null ; try { method = bean . getClass ( ) . getMethod ( ClassMockUtils . propertyToGetter ( property ) , new Class [ ] { } ) ; } catch ( final NoSuchMethodException e ) { method = bean . getClass ( ) . getMethod ( ClassMockUtils . propertyToGetter ( property , true ) , new Class [ ] { } ) ; } return method . invoke ( bean , new Object [ ] { } ) ; } catch ( final Exception e ) { throw new RuntimeException ( "Can't get property " + property + " in the class " + bean . getClass ( ) . getName ( ) , e ) ; } }
Access the value in the property of the bean .
266
10
143,046
public static Object newInstance ( final IClassWriter classMock ) { try { final Class < ? > clazz = classMock . build ( ) ; return clazz . newInstance ( ) ; } catch ( final Exception e ) { throw new RuntimeException ( "Can't intanciate class" , e ) ; } }
Creates a new instance from class generated by IClassWriter
70
12
143,047
public LogWatchBuilder withDelayBetweenReads ( final int length , final TimeUnit unit ) { this . delayBetweenReads = LogWatchBuilder . getDelay ( length , unit ) ; return this ; }
Specify the delay between attempts to read the file .
45
11
143,048
public LogWatchBuilder withDelayBetweenSweeps ( final int length , final TimeUnit unit ) { this . delayBetweenSweeps = LogWatchBuilder . getDelay ( length , unit ) ; return this ; }
Specify the delay between attempts to sweep the log watch from unreachable messages .
45
16
143,049
private Source register ( Source source ) { /** * As promised, the registrar simply abstracts away internal resolvers * by iterating over them during the registration process. */ for ( Resolver resolver : resolvers ) { resolver . register ( source ) ; } return source ; }
Registers a source of instances with all the internal resolvers .
61
14
143,050
private void checkForCycles ( Class < ? > target , Class < ? > in , Stack < Class < ? > > trace ) { for ( Field field : in . getDeclaredFields ( ) ) { if ( field . getAnnotation ( Autowired . class ) != null ) { Class < ? > type = field . getType ( ) ; trace . push ( type ) ; if ( type . equals ( target ) ) { throw new DependencyCycleException ( trace ) ; } else { checkForCycles ( target , type , trace ) ; } trace . pop ( ) ; } } }
A simple recursive cycle - checker implementation that records the current stack trace as an argument parameter for the purpose of producing an accurate error message in the case of an error .
129
34
143,051
public static SimpleModule getTupleMapperModule ( ) { SimpleModule module = new SimpleModule ( "1" , Version . unknownVersion ( ) ) ; SimpleAbstractTypeResolver resolver = getTupleTypeResolver ( ) ; module . setAbstractTypes ( resolver ) ; module . setKeyDeserializers ( new SimpleKeyDeserializers ( ) ) ; return module ; }
Returns the default mapping for all the possible TupleN
82
11
143,052
public void addSparseConstraint ( int component , int index , double value ) { constraints . add ( new Constraint ( component , index , value ) ) ; }
This adds a constraint on the weight vector that a certain component must be set to a sparse index = value
37
21
143,053
private static boolean isInheritIOBroken ( ) { if ( ! System . getProperty ( "os.name" , "none" ) . toLowerCase ( ) . contains ( "windows" ) ) { return false ; } String runtime = System . getProperty ( "java.runtime.version" ) ; if ( ! runtime . startsWith ( "1.7" ) ) { return false ; } String [ ] tokens = runtime . split ( "_" ) ; if ( tokens . length < 2 ) { return true ; // No idea actually, shouldn't happen } try { Integer build = Integer . valueOf ( tokens [ 1 ] . split ( "[^0-9]" ) [ 0 ] ) ; if ( build < 60 ) { return true ; } } catch ( Exception ex ) { return true ; } return false ; }
that means we need to avoid inheritIO
176
8
143,054
public synchronized static void setFormatter ( Formatter formatter ) { java . util . logging . Logger root = java . util . logging . LogManager . getLogManager ( ) . getLogger ( StringUtils . EMPTY ) ; for ( Handler h : root . getHandlers ( ) ) { h . setFormatter ( formatter ) ; } }
Sets the formatter to use for all handlers .
77
11
143,055
public synchronized static void clearHandlers ( ) { java . util . logging . Logger root = java . util . logging . LogManager . getLogManager ( ) . getLogger ( StringUtils . EMPTY ) ; Handler [ ] handlers = root . getHandlers ( ) ; for ( Handler h : handlers ) { root . removeHandler ( h ) ; } }
Clears all handlers from the logger
78
7
143,056
public synchronized static void addHandler ( Handler handler ) { java . util . logging . Logger root = java . util . logging . LogManager . getLogManager ( ) . getLogger ( StringUtils . EMPTY ) ; root . addHandler ( handler ) ; }
Adds a handler to the root .
57
7
143,057
public Logger getLogger ( Class < ? > clazz ) { if ( clazz == null ) { return getGlobalLogger ( ) ; } return getLogger ( clazz . getName ( ) ) ; }
Gets the logger for the given class .
47
9
143,058
public Logger getGlobalLogger ( ) { return new Logger ( java . util . logging . Logger . getLogger ( java . util . logging . Logger . GLOBAL_LOGGER_NAME ) ) ; }
Gets the global Logger
49
6
143,059
public List < String > getLoggerNames ( ) { return Collections . list ( java . util . logging . LogManager . getLogManager ( ) . getLoggerNames ( ) ) ; }
Gets an Enumeration of all of the current loggers .
41
14
143,060
public void setLevel ( String logger , Level level ) { Logger log = getLogger ( logger ) ; log . setLevel ( level ) ; for ( String loggerName : getLoggerNames ( ) ) { if ( loggerName . startsWith ( logger ) && ! loggerName . equals ( logger ) ) { getLogger ( loggerName ) . setLevel ( level ) ; } } }
Sets the level of a logger
83
7
143,061
public String renderServiceHtml ( io . wcm . caravan . hal . docs . impl . model . Service service ) throws IOException { Map < String , Object > model = ImmutableMap . < String , Object > builder ( ) . put ( "service" , service ) . build ( ) ; return render ( service , model , serviceTemplate ) ; }
Generate HTML file for service .
75
7
143,062
public String renderLinkRelationHtml ( io . wcm . caravan . hal . docs . impl . model . Service service , LinkRelation linkRelation ) throws IOException { Map < String , Object > model = ImmutableMap . < String , Object > builder ( ) . put ( "service" , service ) . put ( "linkRelation" , linkRelation ) . build ( ) ; return render ( service , model , linkRelationTemplate ) ; }
Generate HTML file for link relation .
99
8
143,063
private String render ( io . wcm . caravan . hal . docs . impl . model . Service service , Map < String , Object > model , Template template ) throws IOException { Map < String , Object > mergedModel = ImmutableMap . < String , Object > builder ( ) . putAll ( model ) . put ( "docsContext" , ImmutableMap . < String , Object > builder ( ) . put ( "baseUrl" , DocsPath . get ( service . getServiceId ( ) ) + "/" ) . put ( "resourcesPath" , HalDocsBundleTracker . DOCS_RESOURCES_URI_PREFIX ) . build ( ) ) . build ( ) ; return template . apply ( mergedModel ) ; }
Generate templated file with handlebars
159
9
143,064
public boolean start ( ) { if ( ! this . isStarted . compareAndSet ( false , true ) ) { return false ; } final long delay = this . delayBetweenSweeps ; this . timer . scheduleWithFixedDelay ( this , delay , delay , TimeUnit . MILLISECONDS ) ; LogWatchStorageSweeper . LOGGER . info ( "Scheduled automated unreachable message sweep in {} to run every {} millisecond(s)." , this . messaging . getLogWatch ( ) , delay ) ; return true ; }
Start the sweeping if not started already .
115
8
143,065
public boolean stop ( ) { if ( ! this . isStarted . get ( ) || ! this . isStopped . compareAndSet ( false , true ) ) { return false ; } this . timer . shutdown ( ) ; LogWatchStorageSweeper . LOGGER . info ( "Cancelled automated unreachable message sweep in {}." , this . messaging . getLogWatch ( ) ) ; return true ; }
Stop the sweeping if not stopped already .
87
8
143,066
private Properties copyProperties ( Properties source ) { Properties copy = new Properties ( ) ; if ( source != null ) { copy . putAll ( source ) ; } return copy ; }
Copy the given properties to a new object .
38
9
143,067
public void save ( File file , String comment , boolean saveDefaults ) throws IOException { save ( file , comment , saveDefaults , null ) ; }
Save the current state of the properties within this instance to the given file .
33
15
143,068
public void save ( File file , String comment , boolean saveDefaults , String propertyName ) throws IOException { gatekeeper . lock ( ) ; try { File parent = file . getParentFile ( ) ; if ( ! parent . exists ( ) && ! parent . mkdirs ( ) ) { throw new IOException ( "Directory at \"" + parent . getAbsolutePath ( ) + "\" does not exist and cannot be created" ) ; } FileOutputStream outputStream = new FileOutputStream ( file ) ; try { Properties tmpProperties = getProperties ( saveDefaults , propertyName ) ; tmpProperties . store ( outputStream , comment ) ; /* * If we only saved a single property, only that property should * be marked synced. */ if ( propertyName != null ) { properties . get ( propertyName ) . synced ( ) ; } else { for ( ChangeStack < String > stack : properties . values ( ) ) { stack . synced ( ) ; } } } finally { outputStream . close ( ) ; } } finally { gatekeeper . unlock ( ) ; } }
Save the current state of the given property to the given file without saving all of the other properties within this instance .
233
23
143,069
public String getProperty ( String propertyName ) { ChangeStack < String > stack = properties . get ( propertyName ) ; if ( stack == null ) { return null ; } return stack . getCurrentValue ( ) ; }
Retrieve the value associated with the given property .
46
10
143,070
public boolean setProperty ( String propertyName , String value ) throws NullPointerException { return setValue ( propertyName , value , false ) ; }
Set a new value for the given property .
31
9
143,071
private boolean setValue ( String propertyName , String value , boolean sync ) throws NullPointerException { gatekeeper . signIn ( ) ; try { ChangeStack < String > stack = properties . get ( propertyName ) ; if ( stack == null ) { ChangeStack < String > newStack = new ChangeStack < String > ( value , sync ) ; stack = properties . putIfAbsent ( propertyName , newStack ) ; if ( stack == null ) { return true ; } } return sync ? stack . sync ( value ) : stack . push ( value ) ; } finally { gatekeeper . signOut ( ) ; } }
Push or sync the given value to the appropriate stack . This method will create a new stack if this property has never had a value before .
131
28
143,072
public boolean resetToDefault ( String propertyName ) { gatekeeper . signIn ( ) ; try { /* * If this property was added with no default value, all we can do * is remove the property entirely. */ String defaultValue = getDefaultValue ( propertyName ) ; if ( defaultValue == null ) { return properties . remove ( propertyName ) != null ; } /* * Every property with a default value is guaranteed to have a * stack. Since we just confirmed the existence of a default value, * we know the stack is available. */ return properties . get ( propertyName ) . push ( defaultValue ) ; } finally { gatekeeper . signOut ( ) ; } }
Reset the value associated with specified property to its default value .
141
13
143,073
public void resetToDefaults ( ) { gatekeeper . signIn ( ) ; try { for ( Iterator < Entry < String , ChangeStack < String > > > iter = properties . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Entry < String , ChangeStack < String > > entry = iter . next ( ) ; String defaultValue = getDefaultValue ( entry . getKey ( ) ) ; if ( defaultValue == null ) { iter . remove ( ) ; continue ; } entry . getValue ( ) . push ( defaultValue ) ; } } finally { gatekeeper . signOut ( ) ; } }
Reset all values to the default values .
135
9
143,074
public boolean isModified ( String propertyName ) { gatekeeper . signIn ( ) ; try { ChangeStack < String > stack = properties . get ( propertyName ) ; if ( stack == null ) { return false ; } return stack . isModified ( ) ; } finally { gatekeeper . signOut ( ) ; } }
Determine whether or not the given property has been modified since it was last load or saved .
69
20
143,075
public boolean isModified ( ) { gatekeeper . signIn ( ) ; try { for ( ChangeStack < String > stack : properties . values ( ) ) { if ( stack . isModified ( ) ) { return true ; } } return false ; } finally { gatekeeper . signOut ( ) ; } }
Determine whether or not any property has been modified since the last load or save .
66
18
143,076
public static Resource from ( String resource ) { if ( StringUtils . isNullOrBlank ( resource ) ) { return new StringResource ( ) ; } Matcher matcher = protocolPattern . matcher ( resource ) ; if ( matcher . find ( ) ) { String schema = matcher . group ( "PROTOCOL" ) ; String options = matcher . group ( "OPTIONS" ) ; String path = matcher . group ( "PATH" ) ; if ( StringUtils . isNullOrBlank ( options ) ) { options = "" ; } else { options = options . replaceFirst ( "\\[" , "" ) . replaceFirst ( "\\]$" , "" ) ; } ResourceProvider provider = resourceProviders . get ( schema . toLowerCase ( ) ) ; if ( provider == null ) { try { return new URIResource ( new URI ( resource ) ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( schema + " is an unknown protocol." ) ; } } if ( provider . requiresProtocol ( ) ) { path = schema + ":" + path ; } return provider . createResource ( path , Val . of ( options ) . asMap ( String . class , String . class ) ) ; } return new FileResource ( resource ) ; }
Constructs a resource from a string representation . Defaults to a file based resource if no schema is present .
281
22
143,077
public static Resource temporaryDirectory ( ) { File tempDir = new File ( SystemInfo . JAVA_IO_TMPDIR ) ; String baseName = System . currentTimeMillis ( ) + "-" ; for ( int i = 0 ; i < 1_000_000 ; i ++ ) { File tmp = new File ( tempDir , baseName + i ) ; if ( tmp . mkdir ( ) ) { return new FileResource ( tmp ) ; } } throw new RuntimeException ( "Unable to create temp directory" ) ; }
Creates a new Resource that points to a temporary directory .
115
12
143,078
public static Resource temporaryFile ( String name , String extension ) throws IOException { return new FileResource ( File . createTempFile ( name , extension ) ) ; }
Creates a resource wrapping a temporary file
34
8
143,079
public synchronized Future < Message > setExpectation ( final C condition , final MessageAction < P > action ) { if ( this . isStopped ( ) ) { throw new IllegalStateException ( "Already stopped." ) ; } final AbstractExpectation < C , P > expectation = this . createExpectation ( condition , action ) ; final Future < Message > future = AbstractExpectationManager . EXECUTOR . submit ( expectation ) ; this . expectations . put ( expectation , future ) ; AbstractExpectationManager . LOGGER . info ( "Registered expectation {} with action {}." , expectation , action ) ; return future ; }
The resulting future will only return after such a message is received that makes the condition true .
135
18
143,080
protected synchronized boolean unsetExpectation ( final AbstractExpectation < C , P > expectation ) { if ( this . expectations . containsKey ( expectation ) ) { this . expectations . remove ( expectation ) ; AbstractExpectationManager . LOGGER . info ( "Unregistered expectation {}." , expectation ) ; return true ; } return false ; }
Stop tracking this expectation . Calls from the internal code only .
73
12
143,081
@ Api public < T > void setOption ( GestureOption < T > option , T value ) { if ( value == null ) { throw new IllegalArgumentException ( "Null value passed." ) ; } if ( value instanceof Boolean ) { setOption ( this , ( Boolean ) value , option . getName ( ) ) ; } else if ( value instanceof Integer ) { setOption ( this , ( Integer ) value , option . getName ( ) ) ; } else if ( value instanceof Double ) { setOption ( this , ( Double ) value , option . getName ( ) ) ; } else if ( value instanceof String ) { setOption ( this , String . valueOf ( value ) , option . getName ( ) ) ; } }
Change the initial settings of hammer Gwt .
160
9
143,082
static String toChars ( String p ) { if ( p . length ( ) >= 3 && p . charAt ( 0 ) == ' ' && p . charAt ( p . length ( ) - 1 ) == ' ' ) { return p . substring ( 1 , p . length ( ) - 1 ) ; } return p ; }
To chars string .
71
4
143,083
public Regex then ( Regex regex ) { if ( regex == null ) { return this ; } return re ( this . pattern + regex . pattern ) ; }
Concatenates the given regex with this one .
34
11
143,084
public Regex group ( String name ) { return re ( "(" + ( StringUtils . isNotNullOrBlank ( name ) ? "?<" + name + ">" : StringUtils . EMPTY ) + pattern + ")" ) ; }
Converts the regex into a group . If the supplied name is not null or blank the group will be named .
55
23
143,085
public Regex not ( ) { if ( this . pattern . length ( ) > 0 ) { if ( this . pattern . charAt ( 0 ) == ' ' && this . pattern . length ( ) > 1 ) { return re ( "[^" + this . pattern . substring ( 1 ) ) ; } return re ( "^" + this . pattern ) ; } return this ; }
Negates the regex
82
4
143,086
public Regex range ( int min , int max ) { return re ( this . pattern + "{" + Integer . toString ( min ) + "," + Integer . toString ( max ) + "}" ) ; }
Specifies the minimum and maximum times for this regex to repeat .
46
13
143,087
public static ListMultimap < String , Link > getAllLinks ( HalResource hal , Predicate < Pair < String , Link > > predicate ) { return getAllLinks ( hal , "self" , predicate ) ; }
Returns all links in a HAL resource and its embedded resources except CURI links fitting the given predicate .
47
20
143,088
public static List < Link > getAllLinksForRelation ( HalResource hal , String relation ) { List < Link > links = Lists . newArrayList ( hal . getLinks ( relation ) ) ; List < Link > embeddedLinks = hal . getEmbedded ( ) . values ( ) . stream ( ) . flatMap ( embedded -> getAllLinksForRelation ( embedded , relation ) . stream ( ) ) . collect ( Collectors . toList ( ) ) ; links . addAll ( embeddedLinks ) ; return links ; }
Returns all links in a HAL resource and its embedded resources fitting the supplied relation .
111
16
143,089
private void cleanup ( boolean atStartup ) { boolean allTasksIdle = false ; while ( ! allTasksIdle ) { int activeCount = 0 ; for ( Task task : taskDao . listTasks ( ) ) { if ( ! task . getState ( ) . equals ( Task . IDLE ) ) { activeCount ++ ; if ( ! task . getState ( ) . equals ( Task . CANCELING ) ) { logger . info ( "Auto-canceling task " + task . getId ( ) + " (" + task . getName ( ) + ")" ) ; taskDao . setTaskState ( task . getId ( ) , Task . CANCELING ) ; task . setState ( Task . CANCELING ) ; } if ( atStartup ) { // We're cleaning up after an unclean shutdown. // Since the TaskRunner isn't actually running, we make // the direct call here to clean up the state in the // database, marking it as canceled. taskCanceled ( task ) ; } else { // In the normal case, the TaskRunner is running in a // separate thread and we just need to request that // it cancel at the next available opportunity. cancelTask ( task ) ; } } } if ( activeCount == 0 || atStartup ) { allTasksIdle = true ; } else { logger . info ( "Waiting for " + activeCount + " task(s) to go idle." ) ; sleepSeconds ( 1 ) ; } } }
Cancel any non - idle tasks and wait for them to go idle
325
14
143,090
public static Pattern createFilePattern ( String filePattern ) { filePattern = StringUtils . isNullOrBlank ( filePattern ) ? "\\*" : filePattern ; filePattern = filePattern . replaceAll ( "\\." , "\\." ) ; filePattern = filePattern . replaceAll ( "\\*" , ".*" ) ; return Pattern . compile ( "^" + filePattern + "$" ) ; }
Create file pattern pattern .
91
5
143,091
public static boolean isCompressed ( PushbackInputStream pushbackInputStream ) throws IOException { if ( pushbackInputStream == null ) { return false ; } byte [ ] buffer = new byte [ 2 ] ; int read = pushbackInputStream . read ( buffer ) ; boolean isCompressed = false ; if ( read == 2 ) { isCompressed = ( ( buffer [ 0 ] == ( byte ) ( GZIPInputStream . GZIP_MAGIC ) ) && ( buffer [ 1 ] == ( byte ) ( GZIPInputStream . GZIP_MAGIC >> 8 ) ) ) ; } if ( read != - 1 ) { pushbackInputStream . unread ( buffer , 0 , read ) ; } return isCompressed ; }
Is compressed boolean .
161
4
143,092
public static String toUnix ( String spec ) { if ( spec == null ) { return StringUtils . EMPTY ; } return spec . replaceAll ( "\\\\+" , "/" ) ; }
Converts file spec to unix path separators
42
10
143,093
public static String toWindows ( String spec ) { if ( spec == null ) { return StringUtils . EMPTY ; } return spec . replaceAll ( "/+" , "\\\\" ) ; }
Converts file spec to windows path separators
42
9
143,094
public static String addTrailingSlashIfNeeded ( String directory ) { if ( StringUtils . isNullOrBlank ( directory ) ) { return StringUtils . EMPTY ; } int separator = indexOfLastSeparator ( directory ) ; String slash = SystemInfo . isUnix ( ) ? Character . toString ( UNIX_SEPARATOR ) : Character . toString ( WINDOWS_SEPARATOR ) ; if ( separator != - 1 ) { slash = Character . toString ( directory . charAt ( separator ) ) ; } return directory . endsWith ( slash ) ? directory : directory + slash ; }
Adds a trailing slash if its needed . Tries to determine the slash style but defaults to unix . Assumes that what is passed in is a directory .
136
32
143,095
public static String parent ( String file ) { if ( StringUtils . isNullOrBlank ( file ) ) { return StringUtils . EMPTY ; } file = StringUtils . trim ( file ) ; String path = path ( file ) ; int index = indexOfLastSeparator ( path ) ; if ( index <= 0 ) { return SystemInfo . isUnix ( ) ? Character . toString ( UNIX_SEPARATOR ) : Character . toString ( WINDOWS_SEPARATOR ) ; } return path . substring ( 0 , index ) ; }
Returns the parent directory for the given file . If the file passed in is actually a directory it will get the directory s parent .
122
26
143,096
private static boolean openBrowserJava6 ( String url ) throws Exception { final Class < ? > desktopClass ; try { desktopClass = Class . forName ( "java.awt.Desktop" ) ; } catch ( ClassNotFoundException e ) { return false ; } Boolean supported = ( Boolean ) desktopClass . getMethod ( "isDesktopSupported" , new Class [ 0 ] ) . invoke ( null ) ; if ( supported ) { Object desktop = desktopClass . getMethod ( "getDesktop" , new Class [ 0 ] ) . invoke ( null ) ; desktopClass . getMethod ( "browse" , new Class [ ] { URI . class } ) . invoke ( desktop , new URI ( url ) ) ; return true ; } return false ; }
Tries to open the browser using java . awt . Desktop .
158
14
143,097
private static String [ ] getOpenBrowserCommand ( String url ) throws IOException , InterruptedException { if ( IS_WINDOWS ) { return new String [ ] { "rundll32" , "url.dll,FileProtocolHandler" , url } ; } else if ( IS_MAC ) { return new String [ ] { "/usr/bin/open" , url } ; } else if ( IS_LINUX ) { String [ ] browsers = { "google-chrome" , "firefox" , "opera" , "konqueror" , "epiphany" , "mozilla" , "netscape" } ; for ( String browser : browsers ) { if ( Runtime . getRuntime ( ) . exec ( new String [ ] { "which" , browser } ) . waitFor ( ) == 0 ) { return new String [ ] { browser , url } ; } } throw new UnsupportedOperationException ( "Cannot find a browser" ) ; } else { throw new UnsupportedOperationException ( "Opening browser is not implemented for your OS (" + OS_NAME + ")" ) ; } }
Returns the command to execute to open the specified URL according to the current OS .
236
16
143,098
public ParserToken lookAhead ( int distance ) { while ( distance >= buffer . size ( ) && tokenIterator . hasNext ( ) ) { buffer . addLast ( tokenIterator . next ( ) ) ; } return buffer . size ( ) > distance ? buffer . getLast ( ) : null ; }
Looks ahead in the token stream
64
6
143,099
public ParserTokenType lookAheadType ( int distance ) { ParserToken token = lookAhead ( distance ) ; return token == null ? null : token . type ; }
Looks ahead to determine the type of the token a given distance from the front of the stream .
38
19