idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
13,800
public static HttpParameters wrap ( HttpParameters wrapped ) { if ( wrapped == null ) return null ; if ( wrapped == EmptyParameters . getInstance ( ) ) return wrapped ; if ( wrapped instanceof ServletRequestParameters ) return wrapped ; if ( wrapped instanceof UnmodifiableHttpParameters ) return wrapped ; return new UnmodifiableHttpParameters ( wrapped ) ; }
Wraps the given parameters to ensure they are unmodifiable .
13,801
public static boolean isRssEnabled ( ServletContext servletContext ) { 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 .
13,802
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 .
13,803
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 .
13,804
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 .
13,805
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 .
13,806
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 ) { 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 { 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 .
13,807
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 .
13,808
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 ( ) ; BufferWriter capturedOut = AutoEncodingBufferedTag . newBufferWriter ( pageContext . getRequest ( ) ) ; try { body . invoke ( capturedOut ) ; } finally { capturedOut . close ( ) ; } element . setBody ( capturedOut . getResult ( ) . trim ( ) ) ; } else if ( captureLevel == CaptureLevel . META ) { body . invoke ( NullWriter . getInstance ( ) ) ; } else { throw new AssertionError ( ) ; } } }
This is only called for captureLevel > = META .
13,809
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 .
13,810
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
13,811
private static long getCachedLastModified ( ServletContext servletContext , HeaderAndPath hap ) { @ SuppressWarnings ( "unchecked" ) Map < HeaderAndPath , GetLastModifiedCacheValue > cache = ( Map < HeaderAndPath , GetLastModifiedCacheValue > ) servletContext . getAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME ) ; if ( cache == null ) { cache = new HashMap < > ( ) ; servletContext . setAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME , cache ) ; } GetLastModifiedCacheValue cacheValue ; synchronized ( cache ) { 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 ) { lastModified = new File ( realPath ) . lastModified ( ) ; } if ( lastModified == 0 ) { 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 ) { } } 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 .
13,812
public static long getLastModified ( ServletContext servletContext , HttpServletRequest request , String path ) { return getLastModified ( servletContext , request , path , FileUtils . getExtension ( path ) ) ; }
Automatically determines extension from path .
13,813
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 ( 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 .
13,814
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 > ( ) { public Boolean handlePage ( Page page ) throws ServletException , IOException { for ( View view : views ) { if ( view . getAllowRobots ( servletContext , req , resp , page ) && view . isApplicable ( servletContext , req , resp , page ) ) { return true ; } } return null ; } } , new CapturePage . TraversalEdges ( ) { public Set < ChildRef > getEdges ( Page page ) { return page . getChildRefs ( ) ; } } , new CapturePage . EdgeFilter ( ) { 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 .
13,815
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 .
13,816
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 .
13,817
protected TrustManager [ ] createTrustAllManagers ( ) { return new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } ; }
Creates an array of trust managers which trusts all X509 certificates .
13,818
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 .
13,819
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
13,820
public void setSourceContent ( String aSourceFile , String aSourceContent ) { String source = aSourceFile ; if ( this . _sourceRoot != null ) { source = Util . relative ( this . _sourceRoot , source ) ; } if ( aSourceContent != null ) { if ( this . _sourcesContents == null ) { this . _sourcesContents = new HashMap < > ( ) ; } this . _sourcesContents . put ( source , aSourceContent ) ; } else if ( this . _sourcesContents != null ) { this . _sourcesContents . remove ( source ) ; if ( this . _sourcesContents . isEmpty ( ) ) { this . _sourcesContents = null ; } } }
Set the source content for a source file .
13,821
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 ; 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 .
13,822
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 .
13,823
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 .
13,824
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 .
13,825
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 .
13,826
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 .
13,827
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 &lt ; ul&gt ; and &lt ; li&gt ; tags used by TreeView . The first level is expanded .
13,828
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 ; 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 .
13,829
void computeColumnSpans ( ) { for ( int index = 0 ; index < _generatedMappings ( ) . size ( ) ; ++ index ) { ParsedMapping mapping = _generatedMappings ( ) . get ( index ) ; if ( index + 1 < _generatedMappings ( ) . size ( ) ) { ParsedMapping nextMapping = _generatedMappings ( ) . get ( index + 1 ) ; if ( mapping . generatedLine == nextMapping . generatedLine ) { mapping . lastGeneratedColumn = nextMapping . generatedColumn - 1 ; continue ; } } mapping . lastGeneratedColumn = Integer . MAX_VALUE ; } }
Compute the last column for each generated mapping . The last column is inclusive .
13,830
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 .
13,831
public static String createFingerprint ( Class cl , Method m ) { return FingerprintGenerator . fingerprint ( cl , m ) ; }
Create fingerprint for java test method
13,832
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
13,833
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 .
13,834
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 .
13,835
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 .
13,836
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
13,837
private FilesystemIteratorRule getBestRule ( final String filename ) { String longestPrefix = null ; FilesystemIteratorRule rule = null ; String path = filename ; while ( true ) { rule = rules . get ( path ) ; if ( rule != null ) { longestPrefix = path ; break ; } int pathLen = path . length ( ) ; if ( pathLen == 0 ) break ; int lastSlashPos = path . lastIndexOf ( File . separatorChar ) ; if ( lastSlashPos == - 1 ) { path = "" ; } else if ( lastSlashPos == ( pathLen - 1 ) ) { path = path . substring ( 0 , lastSlashPos ) ; } else { path = path . substring ( 0 , lastSlashPos + 1 ) ; } } if ( prefixRules != null ) { for ( Map . Entry < String , FilesystemIteratorRule > entry : prefixRules . entrySet ( ) ) { String prefix = entry . getKey ( ) ; if ( ( longestPrefix == null || prefix . length ( ) > longestPrefix . length ( ) ) && filename . startsWith ( prefix ) ) { 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 .
13,838
public static ServletContextCache getCache ( ServletContext servletContext ) { ServletContextCache cache = ( ServletContextCache ) servletContext . getAttribute ( ATTRIBUTE_KEY ) ; if ( cache == null ) { cache = new ServletContextCache ( servletContext ) ; servletContext . setAttribute ( ATTRIBUTE_KEY , cache ) ; } else { assert cache . servletContext == servletContext ; } return cache ; }
Gets or creates the cache for the provided servlet context .
13,839
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 .
13,840
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 .
13,841
public int indexOf ( int elem ) { int pos = binarySearch ( elem ) ; if ( pos < 0 ) return - 1 ; while ( pos > 0 && elementData [ pos - 1 ] == elem ) pos -- ; return pos ; }
Searches for the first occurrence of the given value .
13,842
public boolean add ( int o ) { int mySize = size ( ) ; if ( mySize == 0 ) { super . add ( o ) ; } else { if ( o >= elementData [ mySize - 1 ] ) { super . add ( o ) ; } else { int index = binarySearch ( o ) ; if ( index < 0 ) { super . add ( - ( index + 1 ) , o ) ; } else { super . add ( index + 1 , o ) ; } } } return true ; }
Adds the specified element in sorted position within this list .
13,843
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 .
13,844
@ XmlElement ( name = "successfullySent" , required = true ) @ JsonProperty ( value = "successfullySent" , required = true ) public boolean isSuccessfullySent ( ) { return successfullySent ; }
Is successfully sent boolean .
13,845
public byte get ( long position ) throws IOException { return mappedBuffers . get ( getBufferNum ( position ) ) . get ( getIndex ( position ) ) ; }
Gets a single byte from the buffer .
13,846
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 ) { String location = ( String ) request . getAttribute ( LOCATION_REQUEST_ATTRIBUTE_NAME ) ; if ( location != null ) response . setHeader ( "Location" , location ) ; 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 ) ; } } } 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 ) ; } } }
Performs the actual include supporting propagation of SkipPageException and sendError .
13,847
public static void setLocation ( HttpServletRequest request , HttpServletResponse response , String location ) { if ( request . getAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) == null ) { response . setHeader ( "Location" , location ) ; } else { 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 .
13,848
public static void sendError ( HttpServletRequest request , HttpServletResponse response , int status , String message ) throws IOException { if ( request . getAttribute ( IS_INCLUDED_REQUEST_ATTRIBUTE_NAME ) == null ) { if ( message == null ) { response . sendError ( status ) ; } else { response . sendError ( status , message ) ; } } else { 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 .
13,849
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
13,850
protected final String getFingerprint ( Description description ) { return TestResultDataUtils . getFingerprint ( description . getTestClass ( ) , description . getMethodName ( ) ) ; }
Retrieve the fingerprint of a test based on its description
13,851
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 .
13,852
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
13,853
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 .
13,854
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 .
13,855
public ByteArray encodeAsByteArray ( ) { if ( message . isEmpty ( ) ) return ByteArray . EMPTY_BYTE_ARRAY ; return new ByteArray ( message . getBytes ( CHARSET ) ) ; }
UTF - 8 encodes the message .
13,856
public static int readCompressedInt ( InputStream in ) throws IOException { int b1 = in . read ( ) ; if ( b1 == - 1 ) throw new EOFException ( ) ; if ( ( b1 & 0x80 ) != 0 ) { 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 ) { 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 ) { int b2 = in . read ( ) ; if ( b2 == - 1 ) throw new EOFException ( ) ; return ( ( b1 & 0x10 ) == 0 ? 0 : 0xfffff000 ) | ( ( b1 & 0x0f ) << 8 ) | b2 ; } else { return ( ( b1 & 0x10 ) == 0 ? 0 : 0xfffffff0 ) | ( b1 & 0x0f ) ; } }
Reads a compressed integer from the stream .
13,857
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 .
13,858
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 .
13,859
@ 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 ) { while ( getChildCount ( ) > 0 ) treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( getChildCount ( ) - 1 ) ) ; if ( getAllowsChildren ( ) ) { setAllowsChildren ( false ) ; treeModel . reload ( this ) ; } } else { if ( ! getAllowsChildren ( ) ) { setAllowsChildren ( true ) ; treeModel . reload ( this ) ; } 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 ) ) { 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 ) ) ; } } else { synchronizingNode = new SynchronizingMutableTreeNode < > ( value ) ; treeModel . insertNodeInto ( synchronizingNode , this , index ) ; } } } synchronizingNode . synchronize ( treeModel , child . getChildren ( ) ) ; } 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 .
13,860
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 .
13,861
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 .
13,862
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 .
13,863
public void addElement ( Element element ) { synchronized ( lock ) { checkNotFrozen ( ) ; element . setPage ( this ) ; if ( elements == null ) elements = new ArrayList < > ( ) ; elements . add ( element ) ; addToElementsById ( element , false ) ; } }
Adds an element to this page .
13,864
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 .
13,865
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 .
13,866
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 .
13,867
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 != '\n' && ch != '\r' ) || ch == '\\' ) { if ( encoded == null ) { encoded = new StringBuilder ( ) ; if ( c > 0 ) encoded . append ( value , 0 , c ) ; } if ( ch == '\\' ) encoded . append ( "\\\\" ) ; else if ( ch == '\b' ) encoded . append ( "\\b" ) ; else if ( ch == '\f' ) encoded . append ( "\\f" ) ; else if ( ch == '\t' ) 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 .
13,868
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 .
13,869
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 .
13,870
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 .
13,871
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 .
13,872
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 .
13,873
public static String getRedirectLocation ( HttpServletRequest request , HttpServletResponse response , String servletPath , String href ) throws MalformedURLException , UnsupportedEncodingException { href = getAbsolutePath ( servletPath , href ) ; href = UrlUtils . encodeUrlPath ( href , response . getCharacterEncoding ( ) ) ; href = response . encodeRedirectURL ( href ) ; if ( href . startsWith ( "/" ) ) href = getAbsoluteURL ( request , href ) ; return href ; }
Gets the absolute URL that should be used for a redirect .
13,874
public static void sendRedirect ( HttpServletResponse response , String location , int status ) throws IllegalStateException , IOException { 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 .
13,875
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 .
13,876
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 .
13,877
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 ) { 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 .
13,878
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 .
13,879
public static boolean isAllowed ( ServletContext servletContext , ServletRequest request ) { return Boolean . parseBoolean ( servletContext . getInitParameter ( ENABLE_INIT_PARAM ) ) && isAllowedAddr ( request . getRemoteAddr ( ) ) ; }
Checks if the given request is allowed to open files on the server . The servlet init param must have it enabled as well as be from an allowed IP .
13,880
public static void addFileOpener ( ServletContext servletContext , FileOpener fileOpener , String ... extensions ) { synchronized ( fileOpenersLock ) { @ SuppressWarnings ( "unchecked" ) Map < String , FileOpener > fileOpeners = ( Map < String , FileOpener > ) servletContext . getAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; if ( fileOpeners == null ) { fileOpeners = new HashMap < > ( ) ; servletContext . setAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME , fileOpeners ) ; } for ( String extension : extensions ) { if ( fileOpeners . containsKey ( extension ) ) throw new IllegalStateException ( "File opener already registered: " + extension ) ; fileOpeners . put ( extension , fileOpener ) ; } } }
Registers a file opener .
13,881
public static void removeFileOpener ( ServletContext servletContext , String ... extensions ) { synchronized ( fileOpenersLock ) { @ SuppressWarnings ( "unchecked" ) Map < String , FileOpener > fileOpeners = ( Map < String , FileOpener > ) servletContext . getAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; if ( fileOpeners != null ) { for ( String extension : extensions ) { fileOpeners . remove ( extension ) ; } if ( fileOpeners . isEmpty ( ) ) { servletContext . removeAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; } } } }
Removes file openers .
13,882
public static void addCookie ( HttpServletRequest request , HttpServletResponse response , String cookieName , String value , String comment , int maxAge , boolean secure , boolean contextOnlyPath ) { Cookie newCookie = new Cookie ( cookieName , value ) ; if ( comment != null ) newCookie . setComment ( comment ) ; newCookie . setMaxAge ( maxAge ) ; newCookie . setSecure ( secure && request . isSecure ( ) ) ; String path ; if ( contextOnlyPath ) { path = request . getContextPath ( ) + "/" ; } else { path = "/" ; } newCookie . setPath ( path ) ; response . addCookie ( newCookie ) ; }
Adds a cookie .
13,883
public static void removeCookie ( HttpServletRequest request , HttpServletResponse response , String cookieName , boolean secure , boolean contextOnlyPath ) { addCookie ( request , response , cookieName , "Removed" , null , 0 , secure , contextOnlyPath ) ; }
Removes a cookie by adding it with maxAge of zero .
13,884
public int compareTo ( Column o ) { int diff = name . compareToIgnoreCase ( o . name ) ; if ( diff != 0 ) return diff ; return name . compareTo ( o . name ) ; }
Ordered by column name only .
13,885
public int read ( ) throws IOException { int c = in . read ( ) ; if ( c == - 1 ) return - 1 ; md5 . Update ( c ) ; return c ; }
Read a byte of data .
13,886
public int read ( byte bytes [ ] , int offset , int length ) throws IOException { int r ; if ( ( r = in . read ( bytes , offset , length ) ) == - 1 ) return - 1 ; md5 . Update ( bytes , offset , r ) ; return r ; }
Reads into an array of bytes .
13,887
void addBundle ( EditableResourceBundle bundle ) { Locale locale = bundle . getBundleLocale ( ) ; if ( ! locales . contains ( locale ) ) throw new AssertionError ( "locale not in locales: " + locale ) ; bundles . put ( locale , bundle ) ; }
The constructor of EditableResourceBundle adds itself here .
13,888
public EditableResourceBundle getResourceBundle ( Locale locale ) { EditableResourceBundle localeBundle = bundles . get ( locale ) ; if ( localeBundle == null ) { ResourceBundle resourceBundle = ResourceBundle . getBundle ( baseName , locale ) ; if ( ! resourceBundle . getLocale ( ) . equals ( locale ) ) throw new AssertionError ( "ResourceBundle not for this locale: " + locale ) ; if ( ! ( resourceBundle instanceof EditableResourceBundle ) ) throw new AssertionError ( "ResourceBundle is not a EditableResourceBundle: " + resourceBundle ) ; localeBundle = ( EditableResourceBundle ) resourceBundle ; if ( localeBundle . getBundleSet ( ) != this ) throw new AssertionError ( "EditableResourceBundle not for this EditableResourceBundleSet: " + localeBundle ) ; if ( ! localeBundle . getBundleLocale ( ) . equals ( locale ) ) throw new AssertionError ( "EditableResourceBundle not for this locale: " + locale ) ; } return localeBundle ; }
Gets the editable bundle for the provided locale .
13,889
public static Boolean getEnvironmentBoolean ( String name , Boolean defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentBoolean." ) ; } String value = getEnvironmentString ( name , null ) ; if ( value == null ) { return defaultValue ; } else { return BOOLEAN_PATTERN . matcher ( value ) . matches ( ) ; } }
Retrieve boolean value for the environment variable name
13,890
public static Integer getEnvironmentInteger ( String name , Integer defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentInteger." ) ; } String value = getEnvironmentString ( name , null ) ; if ( value == null ) { return defaultValue ; } else { return Integer . parseInt ( value ) ; } }
Retrieve integer value for the environment variable name
13,891
public static String getEnvironmentString ( String name , String defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentString." ) ; } return envVars . get ( ENV_PREFIX + name ) != null ? envVars . get ( ENV_PREFIX + name ) : defaultValue ; }
Retrieve string value for the environment variable name
13,892
public String encodeAsString ( ) throws IOException { final int size = messages . size ( ) ; if ( size == 0 ) return "" ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( size ) . append ( DELIMITER ) ; int count = 0 ; for ( Message message : messages ) { count ++ ; String str = message . encodeAsString ( ) ; sb . append ( message . getMessageType ( ) . getTypeChar ( ) ) . append ( str . length ( ) ) . append ( DELIMITER ) . append ( str ) ; } if ( count != size ) throw new ConcurrentModificationException ( ) ; return sb . toString ( ) ; }
Encodes the messages into a single string .
13,893
public ByteArray encodeAsByteArray ( ) throws IOException { final int size = messages . size ( ) ; if ( size == 0 ) return ByteArray . EMPTY_BYTE_ARRAY ; AoByteArrayOutputStream bout = new AoByteArrayOutputStream ( ) ; try { try ( DataOutputStream out = new DataOutputStream ( bout ) ) { out . writeInt ( size ) ; int count = 0 ; for ( Message message : messages ) { count ++ ; ByteArray byteArray = message . encodeAsByteArray ( ) ; final int capacity = byteArray . size ; out . writeByte ( message . getMessageType ( ) . getTypeByte ( ) ) ; out . writeInt ( capacity ) ; out . write ( byteArray . array , 0 , capacity ) ; } if ( count != size ) throw new ConcurrentModificationException ( ) ; } } finally { bout . close ( ) ; } return new ByteArray ( bout . getInternalByteArray ( ) , bout . size ( ) ) ; }
Encodes the messages into a single ByteArray . There is likely a more efficient implementation that reads - through but this is a simple implementation .
13,894
protected void setLength ( long length ) throws IOException { if ( length < 0 ) throw new IllegalArgumentException ( "Invalid length: " + length ) ; synchronized ( this ) { file . seek ( 8 ) ; file . writeLong ( length ) ; if ( length == 0 ) setFirstIndex ( 0 ) ; } }
Sets the number of bytes currently contained by the FIFO .
13,895
private boolean isExcludedPath ( String requestURI ) { if ( requestURI == null ) return false ; if ( _excludedPaths != null ) { for ( String excludedPath : _excludedPaths ) { if ( requestURI . startsWith ( excludedPath ) ) { return true ; } } } if ( _excludedPathPatterns != null ) { for ( Pattern pattern : _excludedPathPatterns ) { if ( pattern . matcher ( requestURI ) . matches ( ) ) { return true ; } } } return false ; }
Checks to see if the path is excluded
13,896
@ SuppressWarnings ( "unchecked" ) public static boolean isRunnable ( Class cl , Method method , List < FilterDefinition > filters ) { ProbeTest mAnnotation = method . getAnnotation ( ProbeTest . class ) ; ProbeTestClass cAnnotation = method . getDeclaringClass ( ) . getAnnotation ( ProbeTestClass . class ) ; String fingerprint = FingerprintGenerator . fingerprint ( cl , method ) ; if ( mAnnotation != null || cAnnotation != null ) { return isRunnable ( new FilterTargetData ( fingerprint , method , mAnnotation , cAnnotation ) , filters ) ; } else { return isRunnable ( new FilterTargetData ( fingerprint , method ) , filters ) ; } }
Define if a test is runnable or not based on a method and class
13,897
private String readUid ( File uidFile ) { String uid = null ; try ( BufferedReader br = new BufferedReader ( new FileReader ( uidFile ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { uid = line ; } } catch ( IOException ioe ) { } return uid ; }
Read a UID file
13,898
public static Version getInstance ( int major , int minor , int release , int build ) { return new Version ( major , minor , release , build ) ; }
Gets a version number instance from its component parts .
13,899
public static Version valueOf ( String version ) throws IllegalArgumentException { NullArgumentException . checkNotNull ( version , "version" ) ; int dot1Pos = version . indexOf ( '.' ) ; if ( dot1Pos == - 1 ) throw new IllegalArgumentException ( version ) ; int dot2Pos = version . indexOf ( '.' , dot1Pos + 1 ) ; if ( dot2Pos == - 1 ) throw new IllegalArgumentException ( version ) ; int dot3Pos = version . indexOf ( '.' , dot2Pos + 1 ) ; if ( dot3Pos == - 1 ) throw new IllegalArgumentException ( version ) ; return getInstance ( Integer . parseInt ( version . substring ( 0 , dot1Pos ) ) , Integer . parseInt ( version . substring ( dot1Pos + 1 , dot2Pos ) ) , Integer . parseInt ( version . substring ( dot2Pos + 1 , dot3Pos ) ) , Integer . parseInt ( version . substring ( dot3Pos + 1 ) ) ) ; }
Parses a version number from its string representation .