idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
137,200 | public static Document createEmptyDocument ( ) { Document output = null ; try { final DocumentBuilder db = FACTORY . newDocumentBuilder ( ) ; db . setErrorHandler ( new ParserErrorHandler ( ) ) ; output = db . newDocument ( ) ; } catch ( final Exception ex ) { LOGGER . error ( "Problem creating empty XML document." , ex ) ; } return output ; } | Create an empty XML structure . | 84 | 6 |
137,201 | public static boolean validate ( final Source input , final Source [ ] schemas ) { boolean isValid = true ; try { final SchemaFactory factory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; factory . setResourceResolver ( new SchemaLSResourceResolver ( ) ) ; final Validator val = factory . newSchema ( schemas ) . newValidator ( ) ; final ParserErrorHandler eh = new ParserErrorHandler ( ) ; val . setErrorHandler ( eh ) ; val . validate ( input ) ; if ( eh . didErrorOccur ( ) ) { isValid = false ; eh . logErrors ( LOGGER ) ; } } catch ( final Exception ex ) { LOGGER . error ( "Problem validating the given process definition." , ex ) ; isValid = false ; } return isValid ; } | Validate an XML document against an XML Schema definition . | 193 | 12 |
137,202 | public static void transform ( final Source input , final Source sheet , final Result output ) { try { final DOMResult intermediate = new DOMResult ( createEmptyDocument ( ) ) ; // Transform. createTransformer ( sheet ) . transform ( input , intermediate ) ; // Format. format ( new DOMSource ( intermediate . getNode ( ) ) , output ) ; } catch ( final Exception ex ) { LOGGER . error ( "Problem transforming XML file." , ex ) ; } } | Transform an XML document according to an XSL style sheet . | 98 | 12 |
137,203 | static Document loadDefinition ( final File def ) { // Parse the jDPL definition into a DOM tree. final Document document = XmlUtils . parseFile ( def ) ; if ( document == null ) { return null ; } // Log the jPDL version from the process definition (if applicable and available). final Node xmlnsNode = document . getFirstChild ( ) . getAttributes ( ) . getNamedItem ( "xmlns" ) ; if ( xmlnsNode != null && StringUtils . isNotBlank ( xmlnsNode . getNodeValue ( ) ) && xmlnsNode . getNodeValue ( ) . contains ( "jpdl" ) ) { final String version = xmlnsNode . getNodeValue ( ) . substring ( xmlnsNode . getNodeValue ( ) . length ( ) - 3 ) ; LOGGER . info ( "jPDL version == " + version ) ; } return document ; } | Load a process definition from file . | 198 | 7 |
137,204 | private static void transform ( final String xmlFileName , final String xsltFileName , final String outputFileName ) { Source xsltSource = null ; if ( StringUtils . isNotBlank ( xsltFileName ) ) { // Use the given stylesheet. xsltSource = new StreamSource ( new File ( xsltFileName ) ) ; } else { // Use the default stylesheet. xsltSource = new StreamSource ( Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( DEFAULT_XSLT_SHEET ) ) ; } // Transform the given input file and put the result in the given output file. final Source xmlSource = new StreamSource ( new File ( xmlFileName ) ) ; final Result xmlResult = new StreamResult ( new File ( outputFileName ) ) ; XmlUtils . transform ( xmlSource , xsltSource , xmlResult ) ; } | Perform the transformation called from the main method . | 204 | 10 |
137,205 | private static Version parseVersion ( String version ) { String [ ] parts = version . split ( "\\." ) ; int nbParts = parts . length ; int majorIndex = nbParts > 1 ? 1 : 0 ; int major = Integer . parseInt ( parts [ majorIndex ] ) ; return new Version ( major ) ; } | Parse Java version number . | 70 | 6 |
137,206 | @ Override public void initialize ( URL location , ResourceBundle resources ) { // Add an event handler to automatically close the stage in the event of // any exception encountered. addEventHandler ( WindowEvent . ANY , new EventHandler < WindowEvent > ( ) { @ Override public void handle ( WindowEvent window ) { Platform . runLater ( new Runnable ( ) { @ Override public void run ( ) { if ( isLoadingError ) { close ( ) ; } } } ) ; } } ) ; // Set default focus to the appropriate UI component Platform . runLater ( new Runnable ( ) { @ Override public void run ( ) { switch ( dialogType ) { case INFORMATION : okButton . requestFocus ( ) ; break ; case CONFIRMATION : yesButton . requestFocus ( ) ; break ; case CONFIRMATION_ALT1 : okButton . requestFocus ( ) ; break ; case CONFIRMATION_ALT2 : yesButton . requestFocus ( ) ; break ; case WARNING : okButton . requestFocus ( ) ; break ; case ERROR : okButton . requestFocus ( ) ; break ; case EXCEPTION : okButton . requestFocus ( ) ; break ; case INPUT_TEXT : inputTextField . requestFocus ( ) ; break ; case GENERIC_OK : okButton . requestFocus ( ) ; break ; case GENERIC_OK_CANCEL : okButton . requestFocus ( ) ; break ; case GENERIC_YES_NO : yesButton . requestFocus ( ) ; break ; case GENERIC_YES_NO_CANCEL : yesButton . requestFocus ( ) ; break ; } } } ) ; this . detailsLabel . setWrapText ( true ) ; this . headerLabel . setText ( getHeader ( ) ) ; this . detailsLabel . setText ( getDetails ( ) ) ; // Filter behaviour for exception dialog if ( dialogType == DialogType . EXCEPTION ) { this . exceptionArea . clear ( ) ; if ( this . exception != null ) { this . exceptionArea . appendText ( Arrays . toString ( this . exception . getStackTrace ( ) ) ) ; } else { this . exceptionArea . appendText ( DialogText . NO_EXCEPTION_TRACE . getText ( ) ) ; } this . exceptionArea . setWrapText ( true ) ; this . exceptionArea . setEditable ( false ) ; } // Filter whether it headless or not if ( this . dialogStyle == DialogStyle . HEADLESS ) { this . topBoxContainer . getChildren ( ) . remove ( this . headContainer ) ; this . setHeadlessPadding ( ) ; } // Apply Header CSS style color this . setHeaderColorStyle ( this . headerColorStyle ) ; } | Initializes the dialog . Sets default focus to OK button . Wraps the text for details message label and apply the user - defined header and details . Filter the behavior for the exception dialog for a null and non - null exception object given . Applies corresponding header background css style . | 590 | 57 |
137,207 | private void setHeadlessPadding ( ) { if ( dialogType == DialogType . INPUT_TEXT ) { bodyContainer . setStyle ( PreDefinedStyle . INPUT_DIALOG_HEADLESS_PADDING . getStyle ( ) ) ; } else if ( dialogType == DialogType . EXCEPTION ) { bodyContainer . setStyle ( PreDefinedStyle . EXCEPTION_DIALOG_HEADLESS_PADDING . getStyle ( ) ) ; } else { bodyContainer . setStyle ( PreDefinedStyle . HEADLESS_PADDING . getStyle ( ) ) ; } } | Sets the padding for a headless dialog | 133 | 9 |
137,208 | public final void setHeaderColorStyle ( HeaderColorStyle headerColorStyle ) { this . headerColorStyle = headerColorStyle ; if ( ! headerColorStyle . getColorStyle ( ) . isEmpty ( ) ) { this . getHeaderLabel ( ) . setStyle ( headerColorStyle . getColorStyle ( ) ) ; // It's either DEFAULT or CUSTOM value (all empty values) // If it is DEFAULT, it sets the default style color // Otherwise if it is CUSTOM, by default no style is applied // (default css "generic" color is in play), user has // to manually set it via setCustomHeaderColorStyle(String colorStyle) } else { if ( headerColorStyle == HeaderColorStyle . DEFAULT ) { switch ( this . dialogType ) { case INFORMATION : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_INFO ) ; break ; case ERROR : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_ERROR ) ; break ; case WARNING : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_WARNING ) ; break ; case CONFIRMATION : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_CONFIRM ) ; break ; case CONFIRMATION_ALT1 : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_CONFIRM ) ; break ; case CONFIRMATION_ALT2 : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_CONFIRM ) ; break ; case EXCEPTION : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_EXCEPTION ) ; break ; case INPUT_TEXT : this . updateHeaderColorStyle ( HeaderColorStyle . GLOSS_INPUT ) ; break ; default : this . updateHeaderColorStyle ( HeaderColorStyle . GENERIC ) ; break ; } } } } | Applies a predefined JavaFX CSS background color style for the header label | 396 | 15 |
137,209 | public void setFont ( String header_font_family , int header_font_size , String details_font_family , int details_font_size ) { this . headerLabel . setStyle ( "-fx-font-family: \"" + header_font_family + "\";" + "-fx-font-size:" + Integer . toString ( header_font_size ) + "px;" ) ; this . detailsLabel . setStyle ( "-fx-font-family: \"" + details_font_family + "\";" + "-fx-font-size:" + Integer . toString ( details_font_size ) + "px;" ) ; } | Sets the font sizes and the font families for the header and details label . | 141 | 16 |
137,210 | public void setHeaderFont ( String font_family , int font_size ) { this . headerLabel . setStyle ( "-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer . toString ( font_size ) + "px;" ) ; } | Sets both header label s font family and size . | 67 | 11 |
137,211 | public void setDetailsFont ( String font_family , int font_size ) { this . detailsLabel . setStyle ( "-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer . toString ( font_size ) + "px;" ) ; } | Sets both details label s font family and size . | 67 | 11 |
137,212 | @ FXML private void send_btn_on_click ( ActionEvent event ) { // Future proof for other uses of send event handler if ( this . dialogType == DialogType . INPUT_TEXT ) { this . textEntry = this . inputTextField . getText ( ) ; } setResponse ( DialogResponse . SEND ) ; close ( ) ; } | Event handler when sendButton is pressed . Sets response to SEND and closes the dialog window . | 78 | 19 |
137,213 | public static String fingerprint ( String str ) { try { MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; return byteArrayToHexString ( md . digest ( str . getBytes ( ) ) ) ; } catch ( NoSuchAlgorithmException nsae ) { LOGGER . warning ( "Unable to calculate the fingerprint for string [" + str + "]." ) ; return null ; } } | Generate a fingerprint for a given string | 90 | 8 |
137,214 | public static String fingerprint ( Class cl , Method m ) { return fingerprint ( cl , m . getName ( ) ) ; } | Generate a fingerprint based on class and method | 26 | 9 |
137,215 | public static String fingerprint ( Class cl , String methodName ) { return fingerprint ( cl . getCanonicalName ( ) + "." + methodName ) ; } | Generate a fingerprint based on class and method name | 34 | 10 |
137,216 | public static Set < String > getContributors ( Set < String > baseContributors , ProbeTest methodAnnotation , ProbeTestClass classAnnotation ) { Set < String > contributors ; if ( baseContributors == null ) { contributors = new HashSet <> ( ) ; } else { contributors = populateContributors ( baseContributors , new HashSet < String > ( ) ) ; } if ( classAnnotation != null && classAnnotation . contributors ( ) != null ) { contributors = populateContributors ( new HashSet <> ( Arrays . asList ( classAnnotation . contributors ( ) ) ) , contributors ) ; } if ( methodAnnotation != null && methodAnnotation . contributors ( ) != null ) { contributors = populateContributors ( new HashSet <> ( Arrays . asList ( methodAnnotation . contributors ( ) ) ) , contributors ) ; } return contributors ; } | Retrieve the contributors and compile them from the different sources | 187 | 11 |
137,217 | private static Set < String > populateContributors ( Set < String > source , Set < String > destination ) { for ( String contributor : source ) { if ( ! emailPattern . matcher ( contributor ) . matches ( ) ) { LOGGER . warning ( "The contributor '" + contributor + "' does not respect the email pattern " + emailPattern . pattern ( ) + " and is ignored" ) ; } else if ( destination . contains ( contributor ) ) { LOGGER . info ( "The contributor '" + contributor + "' is already present in the collection and is ignored" ) ; } else { destination . add ( contributor ) ; } } return destination ; } | Populate the source with the destination contributors only if they match the pattern rules for the contributors | 138 | 18 |
137,218 | protected int binarySearchHashCode ( int elemHash ) { int left = 0 ; int right = size ( ) - 1 ; while ( left <= right ) { int mid = ( left + right ) >> 1 ; int midHash = get ( mid ) . hashCode ( ) ; if ( elemHash == midHash ) return mid ; if ( elemHash < midHash ) right = mid - 1 ; else left = mid + 1 ; } return - ( left + 1 ) ; } | Performs a binary search on hashCode values only . It will return any matching element not necessarily the first or the last . | 103 | 25 |
137,219 | public int indexOf ( int hashCode ) { int pos = binarySearchHashCode ( hashCode ) ; if ( pos < 0 ) return - 1 ; // Try backwards until different hashCode while ( pos > 0 && get ( pos - 1 ) . hashCode ( ) == hashCode ) pos -- ; return pos ; } | Finds the first index where the object has the provided hashCode | 67 | 13 |
137,220 | @ Override public boolean add ( E o ) { // Shortcut for empty int size = size ( ) ; if ( size == 0 ) { super . add ( o ) ; } else { int Ohash = o . hashCode ( ) ; // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if ( Ohash >= get ( size - 1 ) . hashCode ( ) ) { super . add ( o ) ; } else { int index = binarySearchHashCode ( Ohash ) ; if ( index < 0 ) { // Not found in list super . add ( - ( index + 1 ) , o ) ; } else { // Add after the last item with matching hashCodes while ( index < ( size - 1 ) && get ( index + 1 ) . hashCode ( ) == Ohash ) index ++ ; super . add ( index + 1 , o ) ; } } } return true ; } | Adds the specified element in sorted position within this list . When two elements have the same hashCode the new item is added at the end of the list of matching hashCodes . | 206 | 36 |
137,221 | public static HttpParameters wrap ( HttpParameters wrapped ) { // null remains null if ( wrapped == null ) return null ; // Empty are unmodifiable if ( wrapped == EmptyParameters . getInstance ( ) ) return wrapped ; // ServletRequest parameters are unmodifiable already if ( wrapped instanceof ServletRequestParameters ) return wrapped ; // Already wrapped if ( wrapped instanceof UnmodifiableHttpParameters ) return wrapped ; // Wrapping necessary return new UnmodifiableHttpParameters ( wrapped ) ; } | Wraps the given parameters to ensure they are unmodifiable . | 103 | 13 |
137,222 | public static boolean isRssEnabled ( ServletContext servletContext ) { // Note: no locking performed since it's ok for two threads to do the work concurrently at first Boolean isRssEnabled = ( Boolean ) servletContext . getAttribute ( ISS_RSS_ENABLED_CACHE_KEY ) ; if ( isRssEnabled == null ) { try { Class . forName ( RSS_SERVLET_CLASSNAME ) ; isRssEnabled = true ; } catch ( ClassNotFoundException e ) { isRssEnabled = false ; } servletContext . setAttribute ( ISS_RSS_ENABLED_CACHE_KEY , isRssEnabled ) ; } return isRssEnabled ; } | Checks if the RSS module is installed . This is done by checking for the existence of the servlet class . This is cached in application scope to avoid throwing and catching ClassNotFoundException repeatedly . | 156 | 40 |
137,223 | public static boolean isProtectedExtension ( String path ) { for ( String extension : PROTECTED_EXTENSIONS ) { if ( path . endsWith ( extension ) ) return true ; } return false ; } | Checks that the given resource should not be included under any circumstances . | 45 | 14 |
137,224 | public static String getRssServletPath ( PageRef pageRef ) { String servletPath = pageRef . getBookRef ( ) . getPrefix ( ) + pageRef . getPath ( ) ; for ( String extension : RESOURCE_EXTENSIONS ) { if ( servletPath . endsWith ( extension ) ) { servletPath = servletPath . substring ( 0 , servletPath . length ( ) - extension . length ( ) ) ; break ; } } return servletPath + EXTENSION ; } | Gets the servletPath to the RSS feed for the give page ref . | 112 | 16 |
137,225 | public int compareTo ( BookRef o ) { int diff = domain . compareTo ( o . domain ) ; if ( diff != 0 ) return diff ; return path . compareTo ( o . path ) ; } | Ordered by domain path . | 44 | 6 |
137,226 | @ Override public List < String > sources ( ) { List < String > sources = new ArrayList <> ( ) ; for ( int i = 0 ; i < this . _sections . size ( ) ; i ++ ) { for ( int j = 0 ; j < this . _sections . get ( i ) . consumer . sources ( ) . size ( ) ; j ++ ) { sources . add ( this . _sections . get ( i ) . consumer . sources ( ) . get ( j ) ) ; } } return sources ; } | The list of original sources . | 113 | 6 |
137,227 | public static long syncFile ( InputStream in , RandomAccessFile out ) throws IOException { byte [ ] inBuff = new byte [ BLOCK_SIZE ] ; byte [ ] outBuff = new byte [ BLOCK_SIZE ] ; long pos = 0 ; long bytesWritten = 0 ; int numBytes ; while ( ( numBytes = in . read ( inBuff , 0 , BLOCK_SIZE ) ) != - 1 ) { if ( DEBUG ) System . err . println ( pos + ": Read " + numBytes + " bytes of input" ) ; out . seek ( pos ) ; long blockEnd = pos + numBytes ; if ( out . length ( ) >= blockEnd ) { // Read block from out if ( DEBUG ) System . err . println ( pos + ": Reading " + numBytes + " bytes of output" ) ; out . readFully ( outBuff , 0 , numBytes ) ; if ( ! AoArrays . equals ( inBuff , outBuff , 0 , numBytes ) ) { if ( DEBUG ) System . err . println ( pos + ": Updating " + numBytes + " bytes of output" ) ; out . seek ( pos ) ; if ( ! DRY_RUN ) out . write ( inBuff , 0 , numBytes ) ; bytesWritten += numBytes ; } else { if ( DEBUG ) System . err . println ( pos + ": Data matches, not writing" ) ; } } else { // At end, write entire block if ( DEBUG ) System . err . println ( pos + ": Appending " + numBytes + " bytes to output" ) ; if ( ! DRY_RUN ) out . write ( inBuff , 0 , numBytes ) ; bytesWritten += numBytes ; } pos = blockEnd ; } if ( out . length ( ) != pos ) { if ( DEBUG ) System . err . println ( pos + ": Truncating output to " + pos + " bytes" ) ; assert out . length ( ) > pos ; if ( ! DRY_RUN ) { try { out . setLength ( pos ) ; } catch ( IOException e ) { System . err . println ( "Warning: Unable to truncate output to " + pos + " bytes" ) ; } } } return bytesWritten ; } | Synchronized the input to the provided output only writing data that doesn t already match the input . Returns the number of bytes written . | 484 | 27 |
137,228 | protected void evaluateAttributes ( E element , ELContext elContext ) throws JspTagException , IOException { String idStr = nullIfEmpty ( resolveValue ( id , String . class , elContext ) ) ; if ( idStr != null ) element . setId ( idStr ) ; } | Resolves all attributes setting into the created element as appropriate This is only called for captureLevel > = META . Attributes are resolved before the element is added to any parent node . Typically deferred expressions will be evaluated here . Overriding methods must call this implementation . | 61 | 53 |
137,229 | protected void doBody ( E element , CaptureLevel captureLevel ) throws JspException , IOException { JspFragment body = getJspBody ( ) ; if ( body != null ) { if ( captureLevel == CaptureLevel . BODY ) { final PageContext pageContext = ( PageContext ) getJspContext ( ) ; // Invoke tag body, capturing output BufferWriter capturedOut = AutoEncodingBufferedTag . newBufferWriter ( pageContext . getRequest ( ) ) ; try { body . invoke ( capturedOut ) ; } finally { capturedOut . close ( ) ; } element . setBody ( capturedOut . getResult ( ) . trim ( ) ) ; } else if ( captureLevel == CaptureLevel . META ) { // Invoke body for any meta data, but discard any output body . invoke ( NullWriter . getInstance ( ) ) ; } else { throw new AssertionError ( ) ; } } } | This is only called for captureLevel > = META . | 197 | 12 |
137,230 | public static Properties loadFromResource ( ServletContext servletContext , String resource ) throws IOException { Properties props = new Properties ( ) ; InputStream in = servletContext . getResourceAsStream ( resource ) ; if ( in == null ) throw new LocalizedIOException ( accessor , "PropertiesUtils.readProperties.resourceNotFound" , resource ) ; try { props . load ( in ) ; } finally { in . close ( ) ; } return props ; } | Loads properties from a web resource . | 102 | 8 |
137,231 | public static Map . Entry < String , String > match ( Map < String , String > categoriesByPackage , String pkg ) { if ( categoriesByPackage != null && pkg != null ) { for ( Map . Entry < String , String > e : categoriesByPackage . entrySet ( ) ) { if ( Minimatch . minimatch ( pkg . replaceAll ( "\\." , "/" ) , e . getKey ( ) . replaceAll ( "\\." , "/" ) ) ) { return e ; } } } return null ; } | Check if there is a pattern in the map that match the given package | 116 | 14 |
137,232 | private static long getCachedLastModified ( ServletContext servletContext , HeaderAndPath hap ) { // Get the cache @ SuppressWarnings ( "unchecked" ) Map < HeaderAndPath , GetLastModifiedCacheValue > cache = ( Map < HeaderAndPath , GetLastModifiedCacheValue > ) servletContext . getAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME ) ; if ( cache == null ) { // Create new cache cache = new HashMap <> ( ) ; servletContext . setAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME , cache ) ; } GetLastModifiedCacheValue cacheValue ; synchronized ( cache ) { // Get the cache entry cacheValue = cache . get ( hap ) ; if ( cacheValue == null ) { cacheValue = new GetLastModifiedCacheValue ( ) ; cache . put ( hap , cacheValue ) ; } } synchronized ( cacheValue ) { final long currentTime = System . currentTimeMillis ( ) ; if ( cacheValue . isValid ( currentTime ) ) { return cacheValue . lastModified ; } else { ServletContextCache servletContextCache = ServletContextCache . getCache ( servletContext ) ; long lastModified = 0 ; String realPath = servletContextCache . getRealPath ( hap . path ) ; if ( realPath != null ) { // Use File first lastModified = new File ( realPath ) . lastModified ( ) ; } if ( lastModified == 0 ) { // Try URL try { URL resourceUrl = servletContextCache . getResource ( hap . path ) ; if ( resourceUrl != null ) { URLConnection conn = resourceUrl . openConnection ( ) ; conn . setAllowUserInteraction ( false ) ; conn . setConnectTimeout ( 10 ) ; conn . setDoInput ( false ) ; conn . setDoOutput ( false ) ; conn . setReadTimeout ( 10 ) ; conn . setUseCaches ( false ) ; lastModified = conn . getLastModified ( ) ; } } catch ( IOException e ) { // lastModified stays unmodified } } // Store in cache cacheValue . cacheTime = currentTime ; cacheValue . lastModified = lastModified ; return lastModified ; } } } | Gets a modified time from either a file or URL . Caches results for up to a second . | 506 | 21 |
137,233 | public static long getLastModified ( ServletContext servletContext , HttpServletRequest request , String path ) { return getLastModified ( servletContext , request , path , FileUtils . getExtension ( path ) ) ; } | Automatically determines extension from path . | 53 | 7 |
137,234 | @ Override protected long getLastModified ( HttpServletRequest req ) { try { ReadableInstant mostRecent = null ; for ( Tuple2 < Book , ReadableInstant > sitemapBook : getSitemapBooks ( getServletContext ( ) , req , ( HttpServletResponse ) req . getAttribute ( RESPONSE_IN_REQUEST_ATTRIBUTE ) ) ) { ReadableInstant lastModified = sitemapBook . getElement2 ( ) ; // If any single book is unknown, the overall result is unknown if ( lastModified == null ) { mostRecent = null ; break ; } if ( mostRecent == null || ( lastModified . compareTo ( mostRecent ) > 0 ) ) { mostRecent = lastModified ; } } return mostRecent == null ? - 1 : mostRecent . getMillis ( ) ; } catch ( ServletException | IOException e ) { log ( "getLastModified failed" , e ) ; return - 1 ; } } | Last modified is known only when the last modified is known for all books and it is the most recent of all the per - book last modified . | 218 | 29 |
137,235 | private static boolean hasSiteMapUrl ( final ServletContext servletContext , final HttpServletRequest req , final HttpServletResponse resp , final SortedSet < View > views , final Book book , PageRef pageRef ) throws ServletException , IOException { Boolean result = CapturePage . traversePagesAnyOrder ( servletContext , req , resp , pageRef , CaptureLevel . META , new CapturePage . PageHandler < Boolean > ( ) { @ Override public Boolean handlePage ( Page page ) throws ServletException , IOException { // TODO: Chance for more concurrency here by view? for ( View view : views ) { if ( view . getAllowRobots ( servletContext , req , resp , page ) && view . isApplicable ( servletContext , req , resp , page ) ) { return true ; } } return null ; } } , new CapturePage . TraversalEdges ( ) { @ Override public Set < ChildRef > getEdges ( Page page ) { return page . getChildRefs ( ) ; } } , new CapturePage . EdgeFilter ( ) { @ Override public boolean applyEdge ( PageRef childPage ) { return book . getBookRef ( ) . equals ( childPage . getBookRef ( ) ) ; } } ) ; assert result == null || result : "Should always be null or true" ; return result != null ; } | Checks if the sitemap has at least one page . This version implemented as a traversal . | 299 | 21 |
137,236 | protected String getMessageType ( final String message ) { if ( StringUtils . isBlank ( defaultMessageType ) || MESSAGE_TYPE_TEXT_VALUE . equalsIgnoreCase ( defaultMessageType ) || MESSAGE_TYPE_LONG_TEXT_VALUE . equalsIgnoreCase ( defaultMessageType ) ) { return message . length ( ) > getMaxLengthOfOneSms ( ) ? MESSAGE_TYPE_LONG_TEXT_VALUE : MESSAGE_TYPE_TEXT_VALUE ; } return defaultMessageType ; } | Returns the message type . | 121 | 5 |
137,237 | protected String createSendTime ( final Date sendTime ) { if ( sendTime == null || new Date ( System . currentTimeMillis ( ) + 1000L * 60L ) . after ( sendTime ) ) { return null ; } String customSendTimePattern = StringUtils . isBlank ( this . sendTimePattern ) ? DEFAULT_SEND_TIME_PATTERN : this . sendTimePattern ; SimpleDateFormat sdf = new SimpleDateFormat ( customSendTimePattern , Locale . GERMANY ) ; sdf . setTimeZone ( TimeZone . getTimeZone ( "Europe/Berlin" ) ) ; return sdf . format ( sendTime ) ; } | Creates the send time URL parameter value . | 146 | 9 |
137,238 | protected TrustManager [ ] createTrustAllManagers ( ) { return new TrustManager [ ] { new X509TrustManager ( ) { @ Override public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } @ Override public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } @ Override public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } ; } | Creates an array of trust managers which trusts all X509 certificates . | 102 | 14 |
137,239 | private String encode ( final String value , final Charset charset ) { if ( StringUtils . isBlank ( value ) ) { return "" ; } try { return URLEncoder . encode ( value , charset . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { return value ; } } | Encode query parameter . | 70 | 5 |
137,240 | public static SourceMapGenerator fromSourceMap ( SourceMapConsumer aSourceMapConsumer ) { String sourceRoot = aSourceMapConsumer . sourceRoot ; SourceMapGenerator generator = new SourceMapGenerator ( aSourceMapConsumer . file , sourceRoot ) ; aSourceMapConsumer . eachMapping ( ) . forEach ( mapping -> { Mapping newMapping = new Mapping ( mapping . generated ) ; if ( mapping . source != null ) { newMapping . source = mapping . source ; if ( sourceRoot != null ) { newMapping . source = Util . relative ( sourceRoot , newMapping . source ) ; } newMapping . original = mapping . original ; if ( mapping . name != null ) { newMapping . name = mapping . name ; } } generator . addMapping ( newMapping ) ; } ) ; aSourceMapConsumer . sources ( ) . stream ( ) . forEach ( sourceFile -> { String content = aSourceMapConsumer . sourceContentFor ( sourceFile , null ) ; if ( content != null ) { generator . setSourceContent ( sourceFile , content ) ; } } ) ; return generator ; } | Creates a new SourceMapGenerator based on a SourceMapConsumer | 245 | 14 |
137,241 | public void setSourceContent ( String aSourceFile , String aSourceContent ) { String source = aSourceFile ; if ( this . _sourceRoot != null ) { source = Util . relative ( this . _sourceRoot , source ) ; } if ( aSourceContent != null ) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if ( this . _sourcesContents == null ) { this . _sourcesContents = new HashMap <> ( ) ; } this . _sourcesContents . put ( source , aSourceContent ) ; } else if ( this . _sourcesContents != null ) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. this . _sourcesContents . remove ( source ) ; if ( this . _sourcesContents . isEmpty ( ) ) { this . _sourcesContents = null ; } } } | Set the source content for a source file . | 214 | 9 |
137,242 | private String serializeMappings ( ) { int previousGeneratedColumn = 0 ; int previousGeneratedLine = 1 ; int previousOriginalColumn = 0 ; int previousOriginalLine = 0 ; int previousName = 0 ; int previousSource = 0 ; String result = "" ; Mapping mapping ; int nameIdx ; int sourceIdx ; List < Mapping > mappings = this . _mappings . toArray ( ) ; for ( int i = 0 , len = mappings . size ( ) ; i < len ; i ++ ) { mapping = mappings . get ( i ) ; if ( mapping . generated . line != previousGeneratedLine ) { previousGeneratedColumn = 0 ; while ( mapping . generated . line != previousGeneratedLine ) { result += ' ' ; previousGeneratedLine ++ ; } } else { if ( i > 0 ) { if ( Util . compareByGeneratedPositionsInflated ( mapping , mappings . get ( i - 1 ) ) == 0 ) { continue ; } result += ' ' ; } } result += Base64VLQ . encode ( mapping . generated . column - previousGeneratedColumn ) ; previousGeneratedColumn = mapping . generated . column ; if ( mapping . source != null ) { sourceIdx = this . _sources . indexOf ( mapping . source ) ; result += Base64VLQ . encode ( sourceIdx - previousSource ) ; previousSource = sourceIdx ; // lines are stored 0-based in SourceMap spec version 3 result += Base64VLQ . encode ( mapping . original . line - 1 - previousOriginalLine ) ; previousOriginalLine = mapping . original . line - 1 ; result += Base64VLQ . encode ( mapping . original . column - previousOriginalColumn ) ; previousOriginalColumn = mapping . original . column ; if ( mapping . name != null ) { nameIdx = this . _names . indexOf ( mapping . name ) ; result += Base64VLQ . encode ( nameIdx - previousName ) ; previousName = nameIdx ; } } } return result ; } | Serialize the accumulated mappings in to the stream of base 64 VLQs specified by the source map format . | 438 | 24 |
137,243 | public SourceMap toJSON ( ) { SourceMap map = new SourceMap ( ) ; map . version = this . _version ; map . sources = this . _sources . toArray ( ) ; map . names = this . _names . toArray ( ) ; map . mappings = serializeMappings ( ) ; map . file = this . _file ; map . sourceRoot = this . _sourceRoot ; if ( this . _sourcesContents != null ) { map . sourcesContent = _generateSourcesContent ( map . sources , this . _sourceRoot ) ; } return map ; } | Externalize the source map . | 127 | 6 |
137,244 | public Result < V , E > get ( K key , Refresher < ? super K , ? extends V , ? extends E > refresher ) { Result < V , E > result = get ( key ) ; if ( result == null ) result = put ( key , refresher ) ; return result ; } | Gets the value if currently in the cache . If not Runs the refresher immediately to obtain the result then places an entry into the cache . | 65 | 29 |
137,245 | public Result < V , E > get ( K key ) { CacheEntry entry = map . get ( key ) ; if ( entry == null ) { return null ; } else { return entry . getResult ( ) ; } } | Gets a cached result for the given key null if not cached . Extends the expiration of the cache entry . | 47 | 23 |
137,246 | public Result < V , E > put ( K key , Refresher < ? super K , ? extends V , ? extends E > refresher ) { Result < V , E > result = runRefresher ( refresher , key ) ; put ( key , refresher , result ) ; return result ; } | Runs the refresher immediately to obtain the result then places an entry into the cache replacing any existing entry under this key . | 65 | 25 |
137,247 | public void put ( K key , Refresher < ? super K , ? extends V , ? extends E > refresher , V value ) { put ( key , refresher , new Result < V , E > ( value ) ) ; } | Places a result into the cache replacing any existing entry under this key . | 50 | 15 |
137,248 | @ Override public void doTag ( ) throws JspTagException , IOException { try { final PageContext pageContext = ( PageContext ) getJspContext ( ) ; NavigationTreeRenderer . writeNavigationTree ( pageContext . getServletContext ( ) , pageContext . getELContext ( ) , ( HttpServletRequest ) pageContext . getRequest ( ) , ( HttpServletResponse ) pageContext . getResponse ( ) , pageContext . getOut ( ) , root , skipRoot , yuiConfig , includeElements , target , thisDomain , thisBook , thisPage , linksToDomain , linksToBook , linksToPage , maxDepth ) ; } catch ( ServletException e ) { throw new JspTagException ( e ) ; } } | Creates the nested < ; ul> ; and < ; li> ; tags used by TreeView . The first level is expanded . | 166 | 31 |
137,249 | public static BasicSourceMapConsumer fromSourceMap ( SourceMapGenerator aSourceMap ) { BasicSourceMapConsumer smc = new BasicSourceMapConsumer ( ) ; ArraySet < String > names = smc . _names = ArraySet . fromArray ( aSourceMap . _names . toArray ( ) , true ) ; ArraySet < String > sources = smc . _sources = ArraySet . fromArray ( aSourceMap . _sources . toArray ( ) , true ) ; smc . sourceRoot = aSourceMap . _sourceRoot ; smc . sourcesContent = aSourceMap . _generateSourcesContent ( smc . _sources . toArray ( ) , smc . sourceRoot ) ; smc . file = aSourceMap . _file ; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. List < Mapping > generatedMappings = new ArrayList <> ( aSourceMap . _mappings . toArray ( ) ) ; List < ParsedMapping > destGeneratedMappings = smc . __generatedMappings = new ArrayList <> ( ) ; List < ParsedMapping > destOriginalMappings = smc . __originalMappings = new ArrayList <> ( ) ; for ( int i = 0 , length = generatedMappings . size ( ) ; i < length ; i ++ ) { Mapping srcMapping = generatedMappings . get ( i ) ; ParsedMapping destMapping = new ParsedMapping ( ) ; destMapping . generatedLine = srcMapping . generated . line ; destMapping . generatedColumn = srcMapping . generated . column ; if ( srcMapping . source != null ) { destMapping . source = sources . indexOf ( srcMapping . source ) ; destMapping . originalLine = srcMapping . original . line ; destMapping . originalColumn = srcMapping . original . column ; if ( srcMapping . name != null ) { destMapping . name = names . indexOf ( srcMapping . name ) ; } destOriginalMappings . add ( destMapping ) ; } destGeneratedMappings . add ( destMapping ) ; } Collections . sort ( smc . __originalMappings , Util :: compareByOriginalPositions ) ; return smc ; } | Create a BasicSourceMapConsumer from a SourceMapGenerator . | 536 | 13 |
137,250 | void computeColumnSpans ( ) { for ( int index = 0 ; index < _generatedMappings ( ) . size ( ) ; ++ index ) { ParsedMapping mapping = _generatedMappings ( ) . get ( index ) ; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if ( index + 1 < _generatedMappings ( ) . size ( ) ) { ParsedMapping nextMapping = _generatedMappings ( ) . get ( index + 1 ) ; if ( mapping . generatedLine == nextMapping . generatedLine ) { mapping . lastGeneratedColumn = nextMapping . generatedColumn - 1 ; continue ; } } // The last mapping for each line spans the entire line. mapping . lastGeneratedColumn = Integer . MAX_VALUE ; } } | Compute the last column for each generated mapping . The last column is inclusive . | 210 | 16 |
137,251 | @ Override public boolean hasContentsOfAllSources ( ) { if ( sourcesContent == null ) { return false ; } return this . sourcesContent . size ( ) >= this . _sources . size ( ) && ! this . sourcesContent . stream ( ) . anyMatch ( sc -> sc == null ) ; } | Return true if we have the source content for every source in the source map false otherwise . | 66 | 18 |
137,252 | public static String createFingerprint ( Class cl , Method m ) { return FingerprintGenerator . fingerprint ( cl , m ) ; } | Create fingerprint for java test method | 29 | 6 |
137,253 | public static void enrichContext ( Context context ) { context . setPostProperty ( Context . MEMORY_TOTAL , Runtime . getRuntime ( ) . totalMemory ( ) ) ; context . setPostProperty ( Context . MEMORY_FREE , Runtime . getRuntime ( ) . freeMemory ( ) ) ; context . setPostProperty ( Context . MEMORY_USED , Runtime . getRuntime ( ) . totalMemory ( ) - Runtime . getRuntime ( ) . freeMemory ( ) ) ; } | Enrich a context | 103 | 4 |
137,254 | public Version getVersion ( String product ) throws IllegalArgumentException { String three = properties . getProperty ( product ) ; if ( three == null ) throw new IllegalArgumentException ( accessor . getMessage ( "PropertiesVersions.getVersion.productNotFound" , product ) ) ; return Version . valueOf ( three + "." + getBuild ( ) ) ; } | Gets the version number for the provided product . | 79 | 10 |
137,255 | public int getBuild ( ) throws IllegalArgumentException { String build = properties . getProperty ( "build.number" ) ; if ( build == null ) throw new IllegalArgumentException ( accessor . getMessage ( "PropertiesVersions.getVersion.buildNotFound" ) ) ; return Integer . parseInt ( build ) ; } | Gets the build number that is applied to all products . | 71 | 12 |
137,256 | public int getNextFiles ( final File [ ] files , final int batchSize ) throws IOException { int c = 0 ; while ( c < batchSize ) { File file = getNextFile ( ) ; if ( file == null ) break ; files [ c ++ ] = file ; } return c ; } | Gets the next files up to batchSize . | 64 | 10 |
137,257 | protected boolean isFilesystemRoot ( String filename ) throws IOException { String [ ] roots = getFilesystemRoots ( ) ; for ( int c = 0 , len = roots . length ; c < len ; c ++ ) { if ( roots [ c ] . equals ( filename ) ) return true ; } return false ; } | Determines if a path is a possible file system root | 68 | 12 |
137,258 | private FilesystemIteratorRule getBestRule ( final String filename ) { String longestPrefix = null ; FilesystemIteratorRule rule = null ; // First search the path and all of its parents for the first regular rule String path = filename ; while ( true ) { // Check the current path for an exact match //System.out.println("DEBUG: Checking "+path); rule = rules . get ( path ) ; if ( rule != null ) { longestPrefix = path ; break ; } // If done, break the loop int pathLen = path . length ( ) ; if ( pathLen == 0 ) break ; int lastSlashPos = path . lastIndexOf ( File . separatorChar ) ; if ( lastSlashPos == - 1 ) { path = "" ; } else if ( lastSlashPos == ( pathLen - 1 ) ) { // If ends with a slash, remove that slash path = path . substring ( 0 , lastSlashPos ) ; } else { // Otherwise, remove and leave the last slash path = path . substring ( 0 , lastSlashPos + 1 ) ; } } if ( prefixRules != null ) { // TODO: If there are many more prefix rules than the length of this filename, it will at some threshold // be faster to do a map lookup for each possible length of the string. // Would also only need to look down to longestPrefix for ( Map . Entry < String , FilesystemIteratorRule > entry : prefixRules . entrySet ( ) ) { String prefix = entry . getKey ( ) ; if ( ( longestPrefix == null || prefix . length ( ) > longestPrefix . length ( ) ) && filename . startsWith ( prefix ) ) { //System.err.println("DEBUG: FilesystemIterator: getBestRule: filename="+filename+", prefix="+prefix+", longestPrefix="+longestPrefix); longestPrefix = prefix ; rule = entry . getValue ( ) ; } } } return rule ; } | Gets the rule that best suits the provided filename . The rule is the longer rule between the regular rules and the prefix rules . | 421 | 26 |
137,259 | public static ServletContextCache getCache ( ServletContext servletContext ) { ServletContextCache cache = ( ServletContextCache ) servletContext . getAttribute ( ATTRIBUTE_KEY ) ; if ( cache == null ) { // It is possible this is called during context initialization before the listener cache = new ServletContextCache ( servletContext ) ; servletContext . setAttribute ( ATTRIBUTE_KEY , cache ) ; //throw new IllegalStateException("ServletContextCache not active in the provided ServletContext. Add context listener to web.xml?"); } else { assert cache . servletContext == servletContext ; } return cache ; } | Gets or creates the cache for the provided servlet context . | 142 | 13 |
137,260 | public URL getResource ( String path ) throws MalformedURLException { Result < URL , MalformedURLException > result = getResourceCache . get ( path , getResourceRefresher ) ; MalformedURLException exception = result . getException ( ) ; if ( exception != null ) throw exception ; return result . getValue ( ) ; } | Gets the possibly cached URL . This URL is not copied and caller should not fiddle with its state . Thank you Java for this not being immutable . | 77 | 31 |
137,261 | protected int binarySearch ( int value ) { int left = 0 ; int right = size - 1 ; while ( left <= right ) { int mid = ( left + right ) >> 1 ; int midValue = elementData [ mid ] ; if ( value == midValue ) return mid ; if ( value < midValue ) right = mid - 1 ; else left = mid + 1 ; } return - ( left + 1 ) ; } | Performs a binary search for the provide value . It will return any matching element not necessarily the first or the last . | 89 | 24 |
137,262 | @ Override public int indexOf ( int elem ) { // Find the location to insert the object at int pos = binarySearch ( elem ) ; // Not found if ( pos < 0 ) return - 1 ; // Found one, iterate backwards to the first one while ( pos > 0 && elementData [ pos - 1 ] == elem ) pos -- ; return pos ; } | Searches for the first occurrence of the given value . | 80 | 12 |
137,263 | @ Override public boolean add ( int o ) { // Shortcut for empty int mySize = size ( ) ; if ( mySize == 0 ) { super . add ( o ) ; } else { // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if ( o >= elementData [ mySize - 1 ] ) { super . add ( o ) ; } else { int index = binarySearch ( o ) ; if ( index < 0 ) { // Not found in list super . add ( - ( index + 1 ) , o ) ; } else { // Add after existing super . add ( index + 1 , o ) ; } } } return true ; } | Adds the specified element in sorted position within this list . | 155 | 11 |
137,264 | @ Override public boolean addAll ( Collection < ? extends Integer > c ) { Iterator < ? extends Integer > iter = c . iterator ( ) ; boolean didOne = false ; while ( iter . hasNext ( ) ) { add ( iter . next ( ) . intValue ( ) ) ; didOne = true ; } return didOne ; } | Adds all of the elements in the specified Collection and sorts during the add . This may operate slowly as it is the same as individual calls to the add method . | 73 | 32 |
137,265 | @ XmlElement ( name = "successfullySent" , required = true ) @ JsonProperty ( value = "successfullySent" , required = true ) public boolean isSuccessfullySent ( ) { return successfullySent ; } | Is successfully sent boolean . | 46 | 5 |
137,266 | @ Override // @NotThreadSafe public byte get ( long position ) throws IOException { return mappedBuffers . get ( getBufferNum ( position ) ) . get ( getIndex ( position ) ) ; } | Gets a single byte from the buffer . | 44 | 9 |
137,267 | public static void dispatchInclude ( RequestDispatcher dispatcher , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SkipPageException { final boolean isOutmostInclude = request . getAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) == null ; if ( logger . isLoggable ( Level . FINE ) ) logger . log ( Level . FINE , "request={0}, isOutmostInclude={1}" , new Object [ ] { request , isOutmostInclude } ) ; try { if ( isOutmostInclude ) request . setAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME , true ) ; dispatcher . include ( request , response ) ; if ( isOutmostInclude ) { // Set location header if set in attribute String location = ( String ) request . getAttribute ( LOCATION_REQUEST_ATTRIBUTE_NAME ) ; if ( location != null ) response . setHeader ( "Location" , location ) ; // Call sendError from here if set in attributes Integer status = ( Integer ) request . getAttribute ( STATUS_REQUEST_ATTRIBUTE_NAME ) ; if ( status != null ) { String message = ( String ) request . getAttribute ( MESSAGE_REQUEST_ATTRIBUTE_NAME ) ; if ( message == null ) { response . sendError ( status ) ; } else { response . sendError ( status , message ) ; } } } // Propagate effects of SkipPageException if ( request . getAttribute ( PAGE_SKIPPED_REQUEST_ATTRIBUTE_NAME ) != null ) throw ServletUtil . SKIP_PAGE_EXCEPTION ; } finally { if ( isOutmostInclude ) { request . removeAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) ; request . removeAttribute ( LOCATION_REQUEST_ATTRIBUTE_NAME ) ; request . removeAttribute ( STATUS_REQUEST_ATTRIBUTE_NAME ) ; request . removeAttribute ( MESSAGE_REQUEST_ATTRIBUTE_NAME ) ; // PAGE_SKIPPED_REQUEST_ATTRIBUTE_NAME not removed to propagate fully up the stack } } } | Performs the actual include supporting propagation of SkipPageException and sendError . | 497 | 15 |
137,268 | public static void setLocation ( HttpServletRequest request , HttpServletResponse response , String location ) { if ( request . getAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) == null ) { // Not included, setHeader directly response . setHeader ( "Location" , location ) ; } else { // Is included, set attribute so top level tag can perform actual setHeader call request . setAttribute ( LOCATION_REQUEST_ATTRIBUTE_NAME , location ) ; } } | Sets a Location header . When not in an included page calls setHeader directly . When inside of an include will set request attribute so outermost include can call setHeader . | 112 | 35 |
137,269 | public static void sendError ( HttpServletRequest request , HttpServletResponse response , int status , String message ) throws IOException { if ( request . getAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) == null ) { // Not included, sendError directly if ( message == null ) { response . sendError ( status ) ; } else { response . sendError ( status , message ) ; } } else { // Is included, set attributes so top level tag can perform actual sendError call request . setAttribute ( STATUS_REQUEST_ATTRIBUTE_NAME , status ) ; request . setAttribute ( MESSAGE_REQUEST_ATTRIBUTE_NAME , message ) ; } } | Sends an error . When not in an included page calls sendError directly . When inside of an include will set request attribute so outermost include can call sendError . | 158 | 34 |
137,270 | protected String createAndlogStackTrace ( Failure failure ) { StringBuilder sb = new StringBuilder ( ) ; if ( failure . getMessage ( ) != null && ! failure . getMessage ( ) . isEmpty ( ) ) { sb . append ( "Failure message: " ) . append ( failure . getMessage ( ) ) ; } if ( failure . getException ( ) != null ) { sb . append ( "\n\n" ) ; sb . append ( failure . getException ( ) . getClass ( ) . getCanonicalName ( ) ) . append ( ": " ) . append ( failure . getMessage ( ) ) . append ( "\n" ) ; for ( StackTraceElement ste : failure . getException ( ) . getStackTrace ( ) ) { sb . append ( "\tat " ) . append ( ste . getClassName ( ) ) . append ( "." ) . append ( ste . getMethodName ( ) ) . append ( "(" ) . append ( ste . getFileName ( ) ) . append ( ":" ) . append ( ste . getLineNumber ( ) ) . append ( ")\n" ) ; if ( ! fullStackTraces && ste . getClassName ( ) . equals ( failure . getDescription ( ) . getClassName ( ) ) ) { sb . append ( "\t...\n" ) ; break ; } } if ( fullStackTraces && failure . getException ( ) . getCause ( ) != null ) { sb . append ( "Cause: " ) . append ( failure . getException ( ) . getCause ( ) . getMessage ( ) ) . append ( "\n" ) ; for ( StackTraceElement ste : failure . getException ( ) . getCause ( ) . getStackTrace ( ) ) { sb . append ( "\tat " ) . append ( ste . getClassName ( ) ) . append ( "." ) . append ( ste . getMethodName ( ) ) . append ( "(" ) . append ( ste . getFileName ( ) ) . append ( ":" ) . append ( ste . getLineNumber ( ) ) . append ( ")\n" ) ; } } LOGGER . info ( "\n" + failure . getTestHeader ( ) + "\n" + sb . toString ( ) ) ; } return sb . toString ( ) ; } | Build a stack trace string | 512 | 5 |
137,271 | protected final String getFingerprint ( Description description ) { return TestResultDataUtils . getFingerprint ( description . getTestClass ( ) , description . getMethodName ( ) ) ; } | Retrieve the fingerprint of a test based on its description | 42 | 11 |
137,272 | protected final String getPackage ( Class cls ) { return cls . getPackage ( ) != null ? cls . getPackage ( ) . getName ( ) : "defaultPackage" ; } | Retrieve the package name if available if not default package name is used . | 41 | 15 |
137,273 | public static String getHumanName ( String methodName ) { char [ ] name = methodName . toCharArray ( ) ; StringBuilder humanName = new StringBuilder ( ) ; boolean digit = false ; boolean upper = true ; int upCount = 0 ; for ( int i = 0 ; i < name . length ; i ++ ) { if ( i == 0 ) { humanName . append ( Character . toUpperCase ( name [ i ] ) ) ; } else { humanName . append ( Character . toLowerCase ( name [ i ] ) ) ; } if ( i < name . length - 1 ) { if ( ! digit && Character . isDigit ( name [ i + 1 ] ) ) { digit = true ; humanName . append ( " " ) ; } else if ( digit && ! Character . isDigit ( name [ i + 1 ] ) ) { digit = false ; humanName . append ( " " ) ; } else if ( upper && ! Character . isUpperCase ( name [ i + 1 ] ) ) { if ( upCount == 2 ) { humanName . insert ( humanName . length ( ) - 2 , " " ) ; } upper = false ; upCount = 0 ; humanName . insert ( humanName . length ( ) - 1 , " " ) ; } else if ( Character . isUpperCase ( name [ i + 1 ] ) ) { upCount ++ ; upper = true ; } } } return humanName . toString ( ) . replaceAll ( "^ " , "" ) ; } | Create a human name from a method name | 325 | 8 |
137,274 | private static void waitForAll ( Iterable < ? extends Future < ? > > futures ) throws InterruptedException , ExecutionException { for ( Future < ? > future : futures ) { future . get ( ) ; } } | Waits for all futures to complete discarding any results . | 46 | 12 |
137,275 | public static StringMessage decode ( ByteArray encodedMessage ) { if ( encodedMessage . size == 0 ) return EMPTY_STRING_MESSAGE ; return new StringMessage ( new String ( encodedMessage . array , 0 , encodedMessage . size , CHARSET ) ) ; } | UTF - 8 decodes the message . | 60 | 8 |
137,276 | @ Override public ByteArray encodeAsByteArray ( ) { if ( message . isEmpty ( ) ) return ByteArray . EMPTY_BYTE_ARRAY ; return new ByteArray ( message . getBytes ( CHARSET ) ) ; } | UTF - 8 encodes the message . | 52 | 8 |
137,277 | public static int readCompressedInt ( InputStream in ) throws IOException { int b1 = in . read ( ) ; if ( b1 == - 1 ) throw new EOFException ( ) ; if ( ( b1 & 0x80 ) != 0 ) { // 31 bit int b2 = in . read ( ) ; if ( b2 == - 1 ) throw new EOFException ( ) ; int b3 = in . read ( ) ; if ( b3 == - 1 ) throw new EOFException ( ) ; int b4 = in . read ( ) ; if ( b4 == - 1 ) throw new EOFException ( ) ; return ( ( b1 & 0x40 ) == 0 ? 0 : 0xc0000000 ) | ( ( b1 & 0x3f ) << 24 ) | ( b2 << 16 ) | ( b3 << 8 ) | b4 ; } else if ( ( b1 & 0x40 ) != 0 ) { // 22 bit int b2 = in . read ( ) ; if ( b2 == - 1 ) throw new EOFException ( ) ; int b3 = in . read ( ) ; if ( b3 == - 1 ) throw new EOFException ( ) ; return ( ( b1 & 0x20 ) == 0 ? 0 : 0xffe00000 ) | ( ( b1 & 0x1f ) << 16 ) | ( b2 << 8 ) | b3 ; } else if ( ( b1 & 0x20 ) != 0 ) { // 13 bit int b2 = in . read ( ) ; if ( b2 == - 1 ) throw new EOFException ( ) ; return ( ( b1 & 0x10 ) == 0 ? 0 : 0xfffff000 ) | ( ( b1 & 0x0f ) << 8 ) | b2 ; } else { // 5 bit return ( ( b1 & 0x10 ) == 0 ? 0 : 0xfffffff0 ) | ( b1 & 0x0f ) ; } } | Reads a compressed integer from the stream . | 428 | 9 |
137,278 | public String readLongUTF ( ) throws IOException { int length = readCompressedInt ( ) ; StringBuilder SB = new StringBuilder ( length ) ; for ( int position = 0 ; position < length ; position += 20480 ) { int expectedLen = length - position ; if ( expectedLen > 20480 ) expectedLen = 20480 ; String block = readUTF ( ) ; if ( block . length ( ) != expectedLen ) throw new IOException ( "Block has unexpected length: expected " + expectedLen + ", got " + block . length ( ) ) ; SB . append ( block ) ; } if ( SB . length ( ) != length ) throw new IOException ( "StringBuilder has unexpected length: expected " + length + ", got " + SB . length ( ) ) ; return SB . toString ( ) ; } | Reads a string of any length . | 173 | 8 |
137,279 | public void synchronize ( DefaultTreeModel treeModel , Tree < E > tree ) throws IOException , SQLException { assert SwingUtilities . isEventDispatchThread ( ) : ApplicationResources . accessor . getMessage ( "assert.notRunningInSwingEventThread" ) ; synchronize ( treeModel , tree . getRootNodes ( ) ) ; } | Synchronizes the children of this node with the roots of the provided tree while adding and removing only a minimum number of nodes . Comparisons are performed using equals on the value objects . This must be called from the Swing event dispatch thread . | 77 | 48 |
137,280 | @ SuppressWarnings ( "unchecked" ) public void synchronize ( DefaultTreeModel treeModel , List < Node < E > > children ) throws IOException , SQLException { assert SwingUtilities . isEventDispatchThread ( ) : ApplicationResources . accessor . getMessage ( "assert.notRunningInSwingEventThread" ) ; if ( children == null ) { // No children allowed while ( getChildCount ( ) > 0 ) treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( getChildCount ( ) - 1 ) ) ; if ( getAllowsChildren ( ) ) { setAllowsChildren ( false ) ; treeModel . reload ( this ) ; } } else { // Children allowed if ( ! getAllowsChildren ( ) ) { setAllowsChildren ( true ) ; treeModel . reload ( this ) ; } // Update the children minimally int size = children . size ( ) ; for ( int index = 0 ; index < size ; index ++ ) { Node < E > child = children . get ( index ) ; E value = child . getValue ( ) ; SynchronizingMutableTreeNode < E > synchronizingNode ; if ( index >= getChildCount ( ) ) { synchronizingNode = new SynchronizingMutableTreeNode <> ( value ) ; treeModel . insertNodeInto ( synchronizingNode , this , index ) ; } else { synchronizingNode = ( SynchronizingMutableTreeNode < E > ) getChildAt ( index ) ; if ( ! synchronizingNode . getUserObject ( ) . equals ( value ) ) { // Objects don't match // If this object is found further down the list, then delete up to that object int foundIndex = - 1 ; for ( int searchIndex = index + 1 , count = getChildCount ( ) ; searchIndex < count ; searchIndex ++ ) { synchronizingNode = ( SynchronizingMutableTreeNode < E > ) getChildAt ( searchIndex ) ; if ( synchronizingNode . getUserObject ( ) . equals ( value ) ) { foundIndex = searchIndex ; break ; } } if ( foundIndex != - 1 ) { for ( int removeIndex = foundIndex - 1 ; removeIndex >= index ; removeIndex -- ) { treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( removeIndex ) ) ; } // synchronizingNode already contains the right node } else { // Otherwise, insert in the current index synchronizingNode = new SynchronizingMutableTreeNode <> ( value ) ; treeModel . insertNodeInto ( synchronizingNode , this , index ) ; } } } // Recursively synchronize the children synchronizingNode . synchronize ( treeModel , child . getChildren ( ) ) ; } // Remove any extra children while ( getChildCount ( ) > size ) { treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( getChildCount ( ) - 1 ) ) ; } } } | Synchronizes the children of this node with the provided children while adding and removing only a minimum number of nodes . Comparisons are performed using equals on the value objects . This must be called from the Swing event dispatch thread . | 634 | 45 |
137,281 | private void checkDates ( ) { DateTime created = this . dateCreated ; DateTime published = this . datePublished ; DateTime modified = this . dateModified ; DateTime reviewed = this . dateReviewed ; if ( created != null && published != null && published . compareTo ( created ) < 0 ) throw new IllegalArgumentException ( "published may not be before created" ) ; if ( created != null && modified != null && modified . compareTo ( created ) < 0 ) throw new IllegalArgumentException ( "modified may not be before created" ) ; if ( created != null && reviewed != null && reviewed . compareTo ( created ) < 0 ) throw new IllegalArgumentException ( "reviewed may not be before created" ) ; } | Checks the dates for consistency . | 157 | 7 |
137,282 | public Map < String , Element > getElementsById ( ) { synchronized ( lock ) { if ( elementsById == null ) return Collections . emptyMap ( ) ; if ( frozen ) return elementsById ; return AoCollections . unmodifiableCopyMap ( elementsById ) ; } } | Gets the elements indexed by id in no particular order . Note while the page is being created elements with automatic IDs will not be in this map . However once frozen every element will have an ID . | 59 | 40 |
137,283 | public Set < String > getGeneratedIds ( ) { synchronized ( lock ) { if ( generatedIds == null ) return Collections . emptySet ( ) ; if ( frozen ) return generatedIds ; return AoCollections . unmodifiableCopySet ( generatedIds ) ; } } | Gets which element IDs were generated . | 61 | 8 |
137,284 | public void addElement ( Element element ) { synchronized ( lock ) { checkNotFrozen ( ) ; element . setPage ( this ) ; // elements if ( elements == null ) elements = new ArrayList <> ( ) ; elements . add ( element ) ; // elementsById addToElementsById ( element , false ) ; } } | Adds an element to this page . | 70 | 7 |
137,285 | public static void closeQuietly ( final MessageConsumer consumer ) { if ( consumer != null ) { try { consumer . close ( ) ; } catch ( JMSException je ) { if ( je . getCause ( ) instanceof InterruptedException ) { LOG . trace ( "ActiveMQ caught and wrapped InterruptedException" ) ; } if ( je . getCause ( ) instanceof InterruptedIOException ) { LOG . trace ( "ActiveMQ caught and wrapped InterruptedIOException" ) ; } else { LOG . warnDebug ( je , "While closing consumer" ) ; } } } } | Close a message consumer . | 124 | 5 |
137,286 | public static void closeQuietly ( final MessageProducer producer ) { if ( producer != null ) { try { producer . close ( ) ; } catch ( JMSException je ) { if ( je . getCause ( ) instanceof InterruptedException ) { LOG . trace ( "ActiveMQ caught and wrapped InterruptedException" ) ; } if ( je . getCause ( ) instanceof InterruptedIOException ) { LOG . trace ( "ActiveMQ caught and wrapped InterruptedIOException" ) ; } else { LOG . warnDebug ( je , "While closing producer" ) ; } } } } | Close a message producer . | 125 | 5 |
137,287 | public static ByteArrayMessage decode ( String encodedMessage ) { if ( encodedMessage . isEmpty ( ) ) return EMPTY_BYTE_ARRAY_MESSAGE ; return new ByteArrayMessage ( Base64Coder . decode ( encodedMessage ) ) ; } | base - 64 decodes the message . | 56 | 8 |
137,288 | public static String encode ( String value ) { if ( value == null ) return null ; StringBuilder encoded = null ; int len = value . length ( ) ; for ( int c = 0 ; c < len ; c ++ ) { char ch = value . charAt ( c ) ; if ( ( ch < ' ' && ch != ' ' && ch != ' ' ) || ch == ' ' ) { if ( encoded == null ) { encoded = new StringBuilder ( ) ; if ( c > 0 ) encoded . append ( value , 0 , c ) ; } if ( ch == ' ' ) encoded . append ( "\\\\" ) ; else if ( ch == ' ' ) encoded . append ( "\\b" ) ; else if ( ch == ' ' ) encoded . append ( "\\f" ) ; else if ( ch == ' ' ) encoded . append ( "\\t" ) ; else { int ich = ch ; encoded . append ( "\\u" ) . append ( hexChars [ ( ich >>> 12 ) & 15 ] ) . append ( hexChars [ ( ich >>> 8 ) & 15 ] ) . append ( hexChars [ ( ich >>> 4 ) & 15 ] ) . append ( hexChars [ ich & 15 ] ) ; } } else { if ( encoded != null ) encoded . append ( ch ) ; } } return encoded == null ? value : encoded . toString ( ) ; } | Encodes string for binary transparency over SOAP . | 303 | 10 |
137,289 | public static DescriptionDescriptor createDescription ( DescriptionType descriptionType , Store store ) { DescriptionDescriptor descriptionDescriptor = store . create ( DescriptionDescriptor . class ) ; descriptionDescriptor . setLang ( descriptionType . getLang ( ) ) ; descriptionDescriptor . setValue ( descriptionType . getValue ( ) ) ; return descriptionDescriptor ; } | Create a description descriptor . | 82 | 5 |
137,290 | public static IconDescriptor createIcon ( IconType iconType , Store store ) { IconDescriptor iconDescriptor = store . create ( IconDescriptor . class ) ; iconDescriptor . setLang ( iconType . getLang ( ) ) ; PathType largeIcon = iconType . getLargeIcon ( ) ; if ( largeIcon != null ) { iconDescriptor . setLargeIcon ( largeIcon . getValue ( ) ) ; } PathType smallIcon = iconType . getSmallIcon ( ) ; if ( smallIcon != null ) { iconDescriptor . setSmallIcon ( smallIcon . getValue ( ) ) ; } return iconDescriptor ; } | Create an icon descriptor . | 147 | 5 |
137,291 | public static DisplayNameDescriptor createDisplayName ( DisplayNameType displayNameType , Store store ) { DisplayNameDescriptor displayNameDescriptor = store . create ( DisplayNameDescriptor . class ) ; displayNameDescriptor . setLang ( displayNameType . getLang ( ) ) ; displayNameDescriptor . setValue ( displayNameType . getValue ( ) ) ; return displayNameDescriptor ; } | Create a display name descriptor . | 94 | 6 |
137,292 | public static String getRequestEncoding ( ServletRequest request ) { String requestEncoding = request . getCharacterEncoding ( ) ; return requestEncoding != null ? requestEncoding : DEFAULT_REQUEST_ENCODING ; } | Gets the request encoding or ISO - 8859 - 1 when not available . | 50 | 16 |
137,293 | public static void getAbsoluteURL ( HttpServletRequest request , String relPath , Appendable out ) throws IOException { out . append ( request . isSecure ( ) ? "https://" : "http://" ) ; out . append ( request . getServerName ( ) ) ; int port = request . getServerPort ( ) ; if ( port != ( request . isSecure ( ) ? 443 : 80 ) ) out . append ( ' ' ) . append ( Integer . toString ( port ) ) ; out . append ( request . getContextPath ( ) ) ; out . append ( relPath ) ; } | Gets an absolute URL for the given context - relative path . This includes protocol port context path and relative path . No URL rewriting is performed . | 132 | 29 |
137,294 | public static String getRedirectLocation ( HttpServletRequest request , HttpServletResponse response , String servletPath , String href ) throws MalformedURLException , UnsupportedEncodingException { // Convert page-relative paths to context-relative path, resolving ./ and ../ href = getAbsolutePath ( servletPath , href ) ; // Encode URL path elements (like Japanese filenames) href = UrlUtils . encodeUrlPath ( href , response . getCharacterEncoding ( ) ) ; // Perform URL rewriting href = response . encodeRedirectURL ( href ) ; // Convert to absolute URL if needed. This will also add the context path. if ( href . startsWith ( "/" ) ) href = getAbsoluteURL ( request , href ) ; return href ; } | Gets the absolute URL that should be used for a redirect . | 170 | 13 |
137,295 | public static void sendRedirect ( HttpServletResponse response , String location , int status ) throws IllegalStateException , IOException { // Response must not be committed if ( response . isCommitted ( ) ) throw new IllegalStateException ( "Unable to redirect: Response already committed" ) ; response . setHeader ( "Location" , location ) ; response . sendError ( status ) ; } | Sends a redirect to the provided absolute URL location . | 83 | 11 |
137,296 | public static void sendRedirect ( HttpServletRequest request , HttpServletResponse response , String href , int status ) throws IllegalStateException , IOException { sendRedirect ( response , getRedirectLocation ( request , response , request . getServletPath ( ) , href ) , status ) ; } | Sends a redirect with relative paths determined from the request servlet path . | 66 | 15 |
137,297 | public static String getContextRequestUri ( HttpServletRequest request ) { String requestUri = request . getRequestURI ( ) ; String contextPath = request . getContextPath ( ) ; int cpLen = contextPath . length ( ) ; if ( cpLen > 0 ) { assert requestUri . startsWith ( contextPath ) ; return requestUri . substring ( cpLen ) ; } else { return requestUri ; } } | Gets the current request URI in context - relative form . The contextPath stripped . | 95 | 17 |
137,298 | public static < S extends HttpServlet > void doOptions ( HttpServletResponse response , Class < S > stopClass , Class < ? extends S > thisClass , String doGet , String doPost , String doPut , String doDelete , Class < ? > [ ] paramTypes ) { boolean ALLOW_GET = false ; boolean ALLOW_HEAD = false ; boolean ALLOW_POST = false ; boolean ALLOW_PUT = false ; boolean ALLOW_DELETE = false ; boolean ALLOW_TRACE = true ; boolean ALLOW_OPTIONS = true ; for ( Method method : getAllDeclaredMethods ( stopClass , thisClass ) ) { if ( Arrays . equals ( paramTypes , method . getParameterTypes ( ) ) ) { String methodName = method . getName ( ) ; if ( doGet . equals ( methodName ) ) { ALLOW_GET = true ; ALLOW_HEAD = true ; } else if ( doPost . equals ( methodName ) ) { ALLOW_POST = true ; } else if ( doPut . equals ( methodName ) ) { ALLOW_PUT = true ; } else if ( doDelete . equals ( methodName ) ) { ALLOW_DELETE = true ; } } } StringBuilder allow = new StringBuilder ( ) ; if ( ALLOW_GET ) { // if(allow.length() != 0) allow.append(", "); allow . append ( METHOD_GET ) ; } if ( ALLOW_HEAD ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_HEAD ) ; } if ( ALLOW_POST ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_POST ) ; } if ( ALLOW_PUT ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_PUT ) ; } if ( ALLOW_DELETE ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_DELETE ) ; } if ( ALLOW_TRACE ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_TRACE ) ; } if ( ALLOW_OPTIONS ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_OPTIONS ) ; } response . setHeader ( "Allow" , allow . toString ( ) ) ; } | A reusable doOptions implementation for servlets . | 564 | 9 |
137,299 | public int getPort ( ) { if ( port != 0 ) { return port ; } else { final Connector connector = connectorHolder . get ( ) ; if ( connector != null ) { Preconditions . checkState ( connector . getLocalPort ( ) > 0 , "no port was set and the connector is not yet started!" ) ; return connector . getLocalPort ( ) ; } else { return 0 ; } } } | Returns the system port for this connector . | 90 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.