idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
19,600 | public synchronized static void enableLogging ( ) { if ( SplitlogLoggerFactory . state == SplitlogLoggingState . ON ) { return ; } SplitlogLoggerFactory . messageCounter . set ( 0 ) ; SplitlogLoggerFactory . state = SplitlogLoggingState . ON ; LoggerFactory . getLogger ( SplitlogLoggerFactory . class ) . info ( "Forcibly enabled Splitlog's internal logging." ) ; } | Force Splitlog s internal logging to be enabled . |
19,601 | 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 . |
19,602 | public synchronized static void silenceLogging ( ) { if ( SplitlogLoggerFactory . state == SplitlogLoggingState . OFF ) { return ; } SplitlogLoggerFactory . state = SplitlogLoggingState . OFF ; SplitlogLoggerFactory . messageCounter . set ( 0 ) ; LoggerFactory . getLogger ( SplitlogLoggerFactory . class ) . info ( "Forcibly disabled Splitlog's internal logging." ) ; } | Force Splitlog s internal logging to be disabled . |
19,603 | 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 . |
19,604 | public static void remove ( ) { final String current = System . getProperties ( ) . getProperty ( HANDLER_PKGS , "" ) ; if ( current . equals ( PKG ) ) { System . getProperties ( ) . put ( HANDLER_PKGS , "" ) ; return ; } 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 ; } token = PKG + "|" ; idx = current . indexOf ( token ) ; if ( idx > - 1 ) { final String removed = current . substring ( idx + token . length ( ) ) ; System . getProperties ( ) . put ( HANDLER_PKGS , removed ) ; return ; } 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 . |
19,605 | 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 |
19,606 | 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 . |
19,607 | 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 . |
19,608 | 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 . |
19,609 | 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 . |
19,610 | protected URL [ ] getCompileClasspathElementURLs ( ) throws DependencyResolutionRequiredException { 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 . |
19,611 | 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 . |
19,612 | 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 . |
19,613 | public String getExtendsInterface ( ) { if ( this . getExtendsInterfaces ( ) . isEmpty ( ) ) { return this . getInstanceType ( ) ; } else { String tName = this . getExtendsInterfaces ( ) . get ( 0 ) . replaceAll ( "\\W+" , "" ) ; return tName ; } } | will have issues!!!!! |
19,614 | public static String escapeTitle ( final String title ) { final String escapedTitle = title . replaceAll ( "^[^" + UNICODE_TITLE_START_CHAR + "]*" , "" ) . replaceAll ( "[^" + UNICODE_WORD + ". -]" , "" ) ; if ( isNullOrEmpty ( escapedTitle ) ) { return "" ; } else { 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 . |
19,615 | public static String escapeForXML ( final String content ) { if ( content == null ) return "" ; String fixedContent = XMLUtilities . STANDALONE_AMPERSAND_PATTERN . matcher ( content ) . replaceAll ( "&" ) ; 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 ( endIndex == - 1 || ( nextIndex != - 1 && nextIndex < endIndex ) ) { continue ; } else if ( index + 1 == endIndex ) { continue ; } else { elements . add ( fixedContent . substring ( index , endIndex + 1 ) ) ; } } } String escapedTitle = fixedContent ; for ( int count = 0 ; count < elements . size ( ) ; count ++ ) { escapedTitle = escapedTitle . replace ( elements . get ( count ) , "###" + count + "###" ) ; } escapedTitle = escapedTitle . replace ( "<" , "<" ) . replace ( ">" , ">" ) . replace ( "\"" , """ ) ; 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 . |
19,616 | 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 . |
19,617 | public static boolean validateTableGroup ( final Element tgroup ) { assert tgroup != null ; assert tgroup . getNodeName ( ) . equals ( "tgroup" ) ; final Integer numColumns = Integer . parseInt ( tgroup . getAttribute ( "cols" ) ) ; final List < Node > nodes = XMLUtilities . getDirectChildNodes ( tgroup , "thead" , "tbody" , "tfoot" ) ; for ( final Node ele : nodes ) { 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 . |
19,618 | 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 . |
19,619 | 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 . |
19,620 | 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 . |
19,621 | private static String cleanTranslationText ( final String input , final boolean removeWhitespaceFromStart , final boolean removeWhitespaceFromEnd ) { String retValue = XMLUtilities . cleanText ( input ) ; retValue = retValue . trim ( ) ; 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 |
19,622 | 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 . |
19,623 | public static void wrapForRendering ( final Document xmlDoc ) { 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 . |
19,624 | 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 . |
19,625 | 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 |
19,626 | public static String validateRevisionHistory ( final Document doc , final String [ ] dateFormats ) { final List < String > invalidRevNumbers = new ArrayList < String > ( ) ; 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 ; if ( revnumber != null && ! revnumber . getTextContent ( ) . matches ( "^([0-9.]*)-([0-9.]*)$" ) ) { invalidRevNumbers . add ( revnumber . getTextContent ( ) ) ; } else if ( revnumber == null ) { return "Invalid revision, missing <revnumber> element." ; } 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 ) { 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 <date> element." ; } } if ( ! invalidRevNumbers . isEmpty ( ) ) { return "Revision History has invalid <revnumber> 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 . |
19,627 | 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 . |
19,628 | 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 . |
19,629 | 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 |
19,630 | 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 . |
19,631 | 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 . |
19,632 | private Source register ( Source source ) { for ( Resolver resolver : resolvers ) { resolver . register ( source ) ; } return source ; } | Registers a source of instances with all the internal resolvers . |
19,633 | 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 . |
19,634 | 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 |
19,635 | 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 |
19,636 | 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 ; } 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 |
19,637 | 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 . |
19,638 | 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 |
19,639 | 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 . |
19,640 | public Logger getLogger ( Class < ? > clazz ) { if ( clazz == null ) { return getGlobalLogger ( ) ; } return getLogger ( clazz . getName ( ) ) ; } | Gets the logger for the given class . |
19,641 | public Logger getGlobalLogger ( ) { return new Logger ( java . util . logging . Logger . getLogger ( java . util . logging . Logger . GLOBAL_LOGGER_NAME ) ) ; } | Gets the global Logger |
19,642 | public List < String > getLoggerNames ( ) { return Collections . list ( java . util . logging . LogManager . getLogManager ( ) . getLoggerNames ( ) ) ; } | Gets an Enumeration of all of the current loggers . |
19,643 | 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 |
19,644 | 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 . |
19,645 | 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 . |
19,646 | 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 |
19,647 | 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 . |
19,648 | 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 . |
19,649 | 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 . |
19,650 | 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 . |
19,651 | 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 ( 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 . |
19,652 | 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 . |
19,653 | public boolean setProperty ( String propertyName , String value ) throws NullPointerException { return setValue ( propertyName , value , false ) ; } | Set a new value for the given property . |
19,654 | 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 . |
19,655 | public boolean resetToDefault ( String propertyName ) { gatekeeper . signIn ( ) ; try { String defaultValue = getDefaultValue ( propertyName ) ; if ( defaultValue == null ) { return properties . remove ( propertyName ) != null ; } return properties . get ( propertyName ) . push ( defaultValue ) ; } finally { gatekeeper . signOut ( ) ; } } | Reset the value associated with specified property to its default value . |
19,656 | 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 . |
19,657 | 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 . |
19,658 | 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 . |
19,659 | 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 . |
19,660 | 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 . |
19,661 | public static Resource temporaryFile ( String name , String extension ) throws IOException { return new FileResource ( File . createTempFile ( name , extension ) ) ; } | Creates a resource wrapping a temporary file |
19,662 | 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 . |
19,663 | 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 . |
19,664 | 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 . |
19,665 | 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 . |
19,666 | public Regex then ( Regex regex ) { if ( regex == null ) { return this ; } return re ( this . pattern + regex . pattern ) ; } | Concatenates the given regex with this one . |
19,667 | 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 . |
19,668 | 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 |
19,669 | 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 . |
19,670 | 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 . |
19,671 | 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 . |
19,672 | 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 ) { taskCanceled ( task ) ; } else { 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 |
19,673 | 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 . |
19,674 | 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 . |
19,675 | public static String toUnix ( String spec ) { if ( spec == null ) { return StringUtils . EMPTY ; } return spec . replaceAll ( "\\\\+" , "/" ) ; } | Converts file spec to unix path separators |
19,676 | public static String toWindows ( String spec ) { if ( spec == null ) { return StringUtils . EMPTY ; } return spec . replaceAll ( "/+" , "\\\\" ) ; } | Converts file spec to windows path separators |
19,677 | 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 . |
19,678 | 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 . |
19,679 | 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 . |
19,680 | 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 . |
19,681 | 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 |
19,682 | 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 . |
19,683 | public boolean nonConsumingMatch ( ParserTokenType rhs ) { ParserToken token = lookAhead ( 0 ) ; return token != null && token . type . isInstance ( rhs ) ; } | Determines if the token at the front of the stream is a match for a given type without consuming the token . |
19,684 | public boolean match ( ParserTokenType expected ) { ParserToken next = lookAhead ( 0 ) ; if ( next == null || ! next . type . isInstance ( expected ) ) { return false ; } consume ( ) ; return true ; } | Determines if the next token in the stream is of an expected type and consumes it if it is |
19,685 | public static void main ( String [ ] args ) { JFrame frame ; App biorhythm = new App ( ) ; try { frame = new JFrame ( "Biorhythm" ) ; frame . addWindowListener ( new AppCloser ( frame , biorhythm ) ) ; } catch ( java . lang . Throwable ivjExc ) { frame = null ; System . out . println ( ivjExc . getMessage ( ) ) ; ivjExc . printStackTrace ( ) ; } frame . getContentPane ( ) . add ( BorderLayout . CENTER , biorhythm ) ; Dimension size = biorhythm . getSize ( ) ; if ( ( size == null ) || ( ( size . getHeight ( ) < 100 ) | ( size . getWidth ( ) < 100 ) ) ) size = new Dimension ( 640 , 400 ) ; frame . setSize ( size ) ; biorhythm . init ( ) ; frame . setTitle ( "Sample java application" ) ; biorhythm . start ( ) ; frame . setVisible ( true ) ; } | main entrypoint - starts the applet when it is run as an application |
19,686 | public void init ( ) { JPanel view = new JPanel ( ) ; view . setLayout ( new BorderLayout ( ) ) ; label = new JLabel ( INITIAL_TEXT ) ; Font font = new Font ( Font . SANS_SERIF , Font . BOLD , 32 ) ; label . setFont ( font ) ; view . add ( BorderLayout . CENTER , label ) ; this . getContentPane ( ) . add ( BorderLayout . CENTER , view ) ; this . startRollingText ( ) ; } | Initialize this applet . |
19,687 | public String replicateTable ( String tableName , boolean toCopyData ) throws SQLException { String tempTableName = MySqlCommunication . getTempTableName ( tableName ) ; LOG . debug ( "Replicate table {} into {}" , tableName , tempTableName ) ; if ( this . tableExists ( tempTableName ) ) { this . truncateTempTable ( tempTableName ) ; } else { this . createTempTable ( tableName ) ; } if ( toCopyData ) { final String sql = "INSERT INTO " + tempTableName + " SELECT * FROM " + tableName + ";" ; this . executeUpdate ( sql ) ; } return tempTableName ; } | Replicates table structure and data from source to temporary table . |
19,688 | public void restoreTable ( String tableName , String tempTableName ) throws SQLException { LOG . debug ( "Restore table {} from {}" , tableName , tempTableName ) ; try { this . setForeignKeyCheckEnabled ( false ) ; this . truncateTable ( tableName ) ; final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";" ; this . executeUpdate ( sql ) ; } finally { this . setForeignKeyCheckEnabled ( true ) ; } } | Restores table content . |
19,689 | public void removeTempTable ( String tempTableName ) throws SQLException { if ( tempTableName == null ) { return ; } if ( ! tempTableName . contains ( TEMP_TABLE_NAME_SUFFIX ) ) { throw new SQLException ( tempTableName + " is not a valid temp table name" ) ; } try ( Connection conn = this . getConn ( ) ; Statement stmt = conn . createStatement ( ) ) { final String sql = "DROP TABLE " + tempTableName + ";" ; LOG . debug ( "{} executing update: {}" , this . dbInfo , sql ) ; int row = stmt . executeUpdate ( sql ) ; } } | Drops a temporary table . |
19,690 | public final void addParser ( final ParserConfig parser ) { Contract . requireArgNotNull ( "parser" , parser ) ; if ( list == null ) { list = new ArrayList < > ( ) ; } list . add ( parser ) ; } | Adds a parser to the list . If the list does not exist it s created . |
19,691 | private String setXmlPreambleAndDTD ( final String xml , final String dtdFileName , final String entities , final String dtdRootEleName ) { final Matcher matcher = DOCTYPE_PATTERN . matcher ( xml ) ; if ( matcher . find ( ) ) { String preamble = matcher . group ( "Preamble" ) ; String name = matcher . group ( "Name" ) ; String systemId = matcher . group ( "SystemId" ) ; String declaredEntities = matcher . group ( "Entities" ) ; String doctype = matcher . group ( ) ; String newDoctype = doctype . replace ( name , dtdRootEleName ) ; if ( systemId != null ) { newDoctype = newDoctype . replace ( systemId , dtdFileName ) ; } if ( declaredEntities != null ) { newDoctype = newDoctype . replace ( declaredEntities , " [\n" + entities + "\n]" ) ; } else { newDoctype = newDoctype . substring ( 0 , newDoctype . length ( ) - 1 ) + " [\n" + entities + "\n]>" ; } if ( preamble == null ) { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; output . append ( xml . replace ( doctype , newDoctype ) ) ; return output . toString ( ) ; } else { return xml . replace ( doctype , newDoctype ) ; } } else { final String preamble = XMLUtilities . findPreamble ( xml ) ; if ( preamble != null ) { final StringBuilder doctype = new StringBuilder ( ) ; doctype . append ( preamble ) ; appendDoctype ( doctype , dtdRootEleName , dtdFileName , entities ) ; return xml . replace ( preamble , doctype . toString ( ) ) ; } else { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; appendDoctype ( output , dtdRootEleName , dtdFileName , entities ) ; output . append ( xml ) ; return output . toString ( ) ; } } } | Sets the DTD for an xml file . If there are any entities then they are removed . This function will also add the preamble to the XML if it doesn t exist . |
19,692 | public int process ( ) { if ( leftOperation != null ) { leftOperand = leftOperation . process ( ) ; } if ( rightOperation != null ) { rightOperand = rightOperation . process ( ) ; } return calculate ( ) ; } | Process the operation and take care about the composition of the operations |
19,693 | public void executeAction ( ShanksSimulation simulation , ShanksAgent agent , List < NetworkElement > arguments ) throws ShanksException { for ( NetworkElement ne : arguments ) { this . addAffectedElement ( ne ) ; } this . launchEvent ( ) ; } | Method called when the action has to be performed . |
19,694 | public synchronized boolean stopFollowing ( final Follower follower ) { if ( ! this . isFollowedBy ( follower ) ) { return false ; } this . stopConsuming ( follower ) ; DefaultLogWatch . LOGGER . info ( "Unregistered {} for {}." , follower , this ) ; return true ; } | Is synchronized since we want to prevent multiple stops of the same follower . |
19,695 | public void progress ( ) { count ++ ; if ( count % period == 0 && LOG . isInfoEnabled ( ) ) { final double percent = 100 * ( count / ( double ) totalIterations ) ; final long tock = System . currentTimeMillis ( ) ; final long timeInterval = tock - tick ; final long linesPerSec = ( count - prevCount ) * 1000 / timeInterval ; tick = tock ; prevCount = count ; final int etaSeconds = ( int ) ( ( totalIterations - count ) / linesPerSec ) ; final long hours = SECONDS . toHours ( etaSeconds ) ; final long minutes = SECONDS . toMinutes ( etaSeconds - HOURS . toSeconds ( hours ) ) ; final long seconds = SECONDS . toSeconds ( etaSeconds - MINUTES . toSeconds ( minutes ) ) ; LOG . info ( String . format ( "[%3.0f%%] Completed %d iterations of %d total input. %d iters/s. ETA %02d:%02d:%02d" , percent , count , totalIterations , linesPerSec , hours , minutes , seconds ) ) ; } } | Logs the progress . |
19,696 | public void writeEntries ( JarFile jarFile ) throws IOException { Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream ( jarFile . getInputStream ( entry ) ) ; try { if ( inputStream . hasZipHeader ( ) && entry . getMethod ( ) != ZipEntry . STORED ) { new CrcAndSize ( inputStream ) . setupStoredEntry ( entry ) ; inputStream . close ( ) ; inputStream = new ZipHeaderPeekInputStream ( jarFile . getInputStream ( entry ) ) ; } EntryWriter entryWriter = new InputStreamEntryWriter ( inputStream , true ) ; writeEntry ( entry , entryWriter ) ; } finally { inputStream . close ( ) ; } } } | Write all entries from the specified jar file . |
19,697 | public void afterProjectsRead ( final MavenSession session ) throws MavenExecutionException { boolean anyProject = false ; for ( MavenProject project : session . getProjects ( ) ) { if ( project . getPlugin ( "ceylon" ) != null || project . getPlugin ( "ceylon-maven-plugin" ) != null || "ceylon" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || "car" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || "ceylon-jar" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || usesCeylonRepo ( project ) ) { anyProject = true ; } } if ( anyProject ) { logger . info ( "At least one project is using the Ceylon plugin. Preparing." ) ; findCeylonRepo ( session ) ; } logger . info ( "Adding Ceylon repositories to build" ) ; session . getRequest ( ) . setWorkspaceReader ( new CeylonWorkspaceReader ( session . getRequest ( ) . getWorkspaceReader ( ) , logger ) ) ; } | Interception after projects are known . |
19,698 | private boolean usesCeylonRepo ( final MavenProject project ) { for ( Repository repo : project . getRepositories ( ) ) { if ( "ceylon" . equals ( repo . getLayout ( ) ) ) { return true ; } } for ( Artifact ext : project . getPluginArtifacts ( ) ) { if ( ext . getArtifactId ( ) . startsWith ( "ceylon" ) ) { return true ; } } return false ; } | Checks that a project use the Ceylon Maven plugin . |
19,699 | public void stream ( InputStream inputStream , MediaType mediaType ) { try { OutputStream outputStream = exchange . getOutputStream ( ) ; setResponseMediaType ( mediaType ) ; byte [ ] buffer = new byte [ 10240 ] ; int len ; while ( ( len = inputStream . read ( buffer ) ) != - 1 ) { outputStream . write ( buffer , 0 , len ) ; } } catch ( Exception ex ) { throw new RuntimeException ( "Error transferring data" , ex ) ; } } | Transfers blocking the bytes from a given InputStream to this response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.