idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
13,900 | public static Config getConfig ( ) { final Configuration systemConfig = new SystemConfiguration ( ) ; final String configName = systemConfig . getString ( CONFIG_PROPERTY_NAME ) ; final String configLocation = systemConfig . getString ( CONFIG_LOCATION_PROPERTY_NAME ) ; Preconditions . checkState ( configLocation != null , "Config location must be set!" ) ; final ConfigFactory configFactory = new ConfigFactory ( URI . create ( configLocation ) , configName ) ; return new Config ( configFactory . load ( ) ) ; } | Loads the configuration . The no - args method uses system properties to determine which configurations to load . |
13,901 | public static Config getConfig ( final URI configLocation , final String configName ) { final ConfigFactory configFactory = new ConfigFactory ( configLocation , configName ) ; return new Config ( configFactory . load ( ) ) ; } | Load Configuration using the supplied URI as base . The loaded configuration can be overridden using system properties . |
13,902 | public static Config getOverriddenConfig ( final Config config , final AbstractConfiguration ... overrideConfigurations ) { if ( overrideConfigurations == null || overrideConfigurations . length == 0 ) { return config ; } final CombinedConfiguration cc = new CombinedConfiguration ( new OverrideCombiner ( ) ) ; int index = 0 ; final AbstractConfiguration first = config . config . getNumberOfConfigurations ( ) > 0 ? AbstractConfiguration . class . cast ( config . config . getConfiguration ( index ) ) : null ; if ( first != null && first . getClass ( ) == SystemConfiguration . class ) { cc . addConfiguration ( first ) ; index ++ ; } else { for ( AbstractConfiguration c : overrideConfigurations ) { if ( c . getClass ( ) == SystemConfiguration . class ) { cc . addConfiguration ( c ) ; } } } for ( AbstractConfiguration c : overrideConfigurations ) { if ( c . getClass ( ) != SystemConfiguration . class ) { cc . addConfiguration ( c ) ; } } while ( index < config . config . getNumberOfConfigurations ( ) ) { final AbstractConfiguration c = AbstractConfiguration . class . cast ( config . config . getConfiguration ( index ++ ) ) ; if ( c . getClass ( ) != SystemConfiguration . class ) { cc . addConfiguration ( c ) ; } } return new Config ( cc ) ; } | Create a new configuration object from an existing object using overrides . If no overrides are passed in the same object is returned . |
13,903 | public int start ( ) throws Exception { if ( isStarted . compareAndSet ( false , true ) ) { try { for ( Reporter reporter : reporters ) { reporter . start ( ) ; } } catch ( Exception e ) { stop ( ) ; throw e ; } } return reporters . size ( ) ; } | Starts all reporters . |
13,904 | public void stop ( ) { if ( isStarted . compareAndSet ( true , false ) ) { for ( Reporter reporter : reporters ) { reporter . stop ( ) ; } } } | Stops all reporting . |
13,905 | public static < T > T xmlNodeToObject ( final Node node , final Class < T > valueType , final JAXBContext jaxbContext ) throws JAXBException { if ( node == null ) { return null ; } Validate . notNull ( valueType , "valueType must not be null" ) ; if ( jaxbContext == null ) { return valueType . cast ( getJaxbContext ( valueType ) . createUnmarshaller ( ) . unmarshal ( node ) ) ; } return valueType . cast ( jaxbContext . createUnmarshaller ( ) . unmarshal ( node ) ) ; } | Transforms a XML node into an object . |
13,906 | public static < T > T jsonMapToObject ( final Map < String , Object > map , final Class < T > valueType , final ObjectMapper objectMapper ) throws IOException { if ( map == null ) { return null ; } Validate . notNull ( valueType , "valueType must not be null" ) ; if ( objectMapper == null ) { return DEFAULT_OBJECT_MAPPER . readValue ( DEFAULT_OBJECT_MAPPER . writeValueAsBytes ( map ) , valueType ) ; } return objectMapper . readValue ( objectMapper . writeValueAsBytes ( map ) , valueType ) ; } | Transforms a JSON map into an object . |
13,907 | static < T > ArraySet < T > fromArray ( List < T > aArray , Boolean aAllowDuplicates ) { ArraySet < T > set = new ArraySet < > ( ) ; for ( int i = 0 , len = aArray . size ( ) ; i < len ; i ++ ) { set . add ( aArray . get ( i ) , aAllowDuplicates ) ; } return set ; } | Static method for creating ArraySet instances from an existing array . |
13,908 | Integer indexOf ( T t ) { if ( t == null ) { return null ; } Integer i = _set . get ( t ) ; if ( i == null ) { return - 1 ; } return i ; } | What is the index of the given string in the array? |
13,909 | T at ( Integer i ) { if ( i == null ) { return null ; } if ( i >= _array . size ( ) ) { return null ; } return _array . get ( i ) ; } | What is the element at the given index? |
13,910 | public int read ( ) throws IOException { synchronized ( file ) { while ( true ) { long len = file . getLength ( ) ; if ( len >= 1 ) { long pos = file . getFirstIndex ( ) ; file . file . seek ( pos + 16 ) ; int b = file . file . read ( ) ; if ( b == - 1 ) throw new EOFException ( "Unexpected EOF" ) ; addStats ( 1 ) ; long newFirstIndex = pos + 1 ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( len - 1 ) ; file . notify ( ) ; return b ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } } | Reads data from the file blocks until the data is available . |
13,911 | public int read ( byte [ ] b , int off , int len ) throws IOException { synchronized ( file ) { while ( true ) { long fileLen = file . getLength ( ) ; if ( fileLen >= 1 ) { long pos = file . getFirstIndex ( ) ; file . file . seek ( pos + 16 ) ; int readSize = fileLen > len ? len : ( int ) fileLen ; if ( ( pos + readSize ) > file . maxFifoLength ) readSize = ( int ) ( file . maxFifoLength - pos ) ; int totalRead = file . file . read ( b , off , readSize ) ; if ( totalRead == - 1 ) throw new EOFException ( "Unexpected EOF" ) ; addStats ( totalRead ) ; long newFirstIndex = pos + totalRead ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( fileLen - totalRead ) ; file . notify ( ) ; return totalRead ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } } | Reads data from the file blocks until at least one byte is available . |
13,912 | public long skip ( long n ) throws IOException { synchronized ( file ) { while ( true ) { long fileLen = file . getLength ( ) ; if ( fileLen >= 1 ) { long pos = file . getFirstIndex ( ) ; long skipSize = fileLen > n ? n : fileLen ; if ( ( pos + skipSize ) > file . maxFifoLength ) skipSize = file . maxFifoLength - pos ; long totalSkipped = skipSize ; long newFirstIndex = pos + skipSize ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( fileLen - skipSize ) ; file . notify ( ) ; return totalSkipped ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } } | Skips data in the queue blocks until at least one byte is skipped . |
13,913 | public int available ( ) throws IOException { synchronized ( file ) { long len = file . getLength ( ) ; return len > Integer . MAX_VALUE ? Integer . MAX_VALUE : ( int ) len ; } } | Determines the number of bytes that may be read without blocking . |
13,914 | protected void init ( final String name , final Properties props ) { init = new InitUtil ( "" , props , false ) ; this . name = name ; } | Initialize the properties . |
13,915 | public List < GeneratedPosition > allGeneratedPositionsFor ( int line , Integer column , String source ) { ParsedMapping needle = new ParsedMapping ( null , null , line , column == null ? 0 : column , null , null ) ; if ( this . sourceRoot != null ) { source = Util . relative ( this . sourceRoot , source ) ; } if ( ! this . _sources . has ( source ) ) { return Collections . emptyList ( ) ; } needle . source = this . _sources . indexOf ( source ) ; List < GeneratedPosition > mappings = new ArrayList < > ( ) ; int index = _findMapping ( needle , this . _originalMappings ( ) , "originalLine" , "originalColumn" , ( mapping1 , mapping2 ) -> Util . compareByOriginalPositions ( mapping1 , mapping2 , true ) , BinarySearch . Bias . LEAST_UPPER_BOUND ) ; if ( index >= 0 ) { ParsedMapping mapping = this . _originalMappings ( ) . get ( index ) ; if ( column == null ) { int originalLine = mapping . originalLine ; while ( mapping != null && mapping . originalLine == originalLine ) { mappings . add ( new GeneratedPosition ( mapping . generatedLine , mapping . generatedColumn , mapping . lastGeneratedColumn ) ) ; index ++ ; if ( index >= this . _originalMappings ( ) . size ( ) ) { mapping = null ; } else { mapping = this . _originalMappings ( ) . get ( index ) ; } } } else { int originalColumn = mapping . originalColumn ; while ( mapping != null && mapping . originalLine == line && mapping . originalColumn == originalColumn ) { mappings . add ( new GeneratedPosition ( mapping . generatedLine , mapping . generatedColumn , mapping . lastGeneratedColumn ) ) ; index ++ ; if ( index >= this . _originalMappings ( ) . size ( ) ) { mapping = null ; } else { mapping = this . _originalMappings ( ) . get ( index ) ; } } } } return mappings ; } | Returns all generated line and column information for the original source line and column provided . If no column is provided returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings . Otherwise returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets . |
13,916 | < T > int _findMapping ( T aNeedle , List < T > aMappings , Object aLineName , Object aColumnName , BinarySearch . Comparator < T > aComparator , BinarySearch . Bias aBias ) { return BinarySearch . search ( aNeedle , aMappings , aComparator , aBias ) ; } | Find the mapping that best matches the hypothetical needle mapping that we are searching for in the given haystack of mappings . |
13,917 | public static InputStream getHTMLInputStream ( Class < ? > clazz ) throws IOException { return HTMLInputStreamPage . class . getResourceAsStream ( '/' + clazz . getName ( ) . replace ( '.' , '/' ) + ".html" ) ; } | Gets the HTML file with the same name as the provided Class . |
13,918 | public void save ( ProbeTestRun probeTestRun ) throws IOException { OutputStreamWriter osw = new OutputStreamWriter ( new FileOutputStream ( new File ( getTmpDir ( probeTestRun ) , UUID . randomUUID ( ) . toString ( ) ) ) , Charset . forName ( Constants . ENCODING ) . newEncoder ( ) ) ; serializer . serializePayload ( osw , probeTestRun , true ) ; } | Save a payload |
13,919 | void onClose ( AbstractSocket socket ) { synchronized ( sockets ) { if ( sockets . remove ( socket . getId ( ) ) == null ) throw new AssertionError ( "Socket not part of this context. onClose called twice?" ) ; } } | Called by a socket when it is closed . This will only be called once . |
13,920 | protected void addSocket ( final S newSocket ) { if ( isClosed ( ) ) throw new IllegalStateException ( "SocketContext is closed" ) ; Future < ? > future ; synchronized ( sockets ) { Identifier id = newSocket . getId ( ) ; if ( sockets . containsKey ( id ) ) throw new IllegalStateException ( "Socket with the same ID has already been added" ) ; sockets . put ( id , newSocket ) ; future = listenerManager . enqueueEvent ( new ConcurrentListenerManager . Event < SocketContextListener > ( ) { public Runnable createCall ( final SocketContextListener listener ) { return new Runnable ( ) { public void run ( ) { listener . onNewSocket ( AbstractSocketContext . this , newSocket ) ; } } ; } } ) ; } try { future . get ( ) ; } catch ( ExecutionException e ) { logger . log ( Level . SEVERE , null , e ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , null , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } } | Adds a new socket to this context sockets must be added to the context before they create any of their own events . This gives context listeners a chance to register per - socket listeners in onNewSocket . |
13,921 | public void writeCompressedUTF ( String str , int slot ) throws IOException { if ( slot < 0 || slot > 0x3f ) throw new IOException ( "Slot out of range (0-63): " + slot ) ; if ( lastStrings == null ) lastStrings = new String [ 64 ] ; String last = lastStrings [ slot ] ; if ( last == null ) last = "" ; int strLen = str . length ( ) ; int lastLen = last . length ( ) ; int maxCommon = Math . min ( strLen , lastLen ) ; int common = 0 ; for ( ; common < maxCommon ; common ++ ) { if ( str . charAt ( common ) != last . charAt ( common ) ) break ; } if ( lastCommonLengths == null ) lastCommonLengths = new int [ 64 ] ; int commonDifference = common - lastCommonLengths [ slot ] ; out . write ( ( commonDifference == 0 ? 0 : 0x80 ) | ( common == strLen ? 0 : 0x40 ) | slot ) ; if ( commonDifference > 0 ) writeCompressedInt ( commonDifference - 1 ) ; else if ( commonDifference < 0 ) writeCompressedInt ( commonDifference ) ; if ( common != strLen ) writeUTF ( str . substring ( common ) ) ; lastStrings [ slot ] = str ; lastCommonLengths [ slot ] = common ; } | Writes a String to the stream while using prefix compression . |
13,922 | public void writeLongUTF ( String str ) throws IOException { int length = str . length ( ) ; writeCompressedInt ( length ) ; for ( int position = 0 ; position < length ; position += 20480 ) { int blockLength = length - position ; if ( blockLength > 20480 ) blockLength = 20480 ; String block = str . substring ( position , position + blockLength ) ; writeUTF ( block ) ; } } | Writes a string of any length . |
13,923 | public static void printPageList ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , WebPage [ ] pages , WebPageLayout layout ) throws IOException , SQLException { int len = pages . length ; for ( int c = 0 ; c < len ; c ++ ) { WebPage page = pages [ c ] ; out . print ( " <tr>\n" + " <td style='white-space:nowrap'><a class='aoLightLink' href='" ) . encodeXmlAttribute ( req == null ? "" : resp . encodeURL ( req . getContextPath ( ) + req . getURL ( page ) ) ) . print ( "'>" ) . encodeXhtml ( page . getShortTitle ( ) ) . print ( "</a>\n" + " </td>\n" + " <td style='width:12px; white-space:nowrap'> </td>\n" + " <td style='white-space:nowrap'>" ) . encodeXhtml ( page . getDescription ( ) ) . print ( "</td>\n" + " </tr>\n" ) ; } } | Prints a list of pages . |
13,924 | public static void printPageList ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , WebPage parent , WebPageLayout layout ) throws IOException , SQLException { printPageList ( out , req , resp , parent . getCachedPages ( req ) , layout ) ; } | Prints an unordered list of the available pages . |
13,925 | private boolean generatedPositionAfter ( Mapping mappingA , Mapping mappingB ) { int lineA = mappingA . generated . line ; int lineB = mappingB . generated . line ; int columnA = mappingA . generated . column ; int columnB = mappingB . generated . column ; return lineB > lineA || lineB == lineA && columnB >= columnA || Util . compareByGeneratedPositionsInflated ( mappingA , mappingB ) <= 0 ; } | Determine whether mappingB is after mappingA with respect to generated position . |
13,926 | void add ( Mapping aMapping ) { if ( generatedPositionAfter ( this . _last , aMapping ) ) { this . _last = aMapping ; this . _array . add ( aMapping ) ; } else { this . _sorted = false ; this . _array . add ( aMapping ) ; } } | Add the given source mapping . |
13,927 | List < Mapping > toArray ( ) { if ( ! this . _sorted ) { Collections . sort ( this . _array , Util :: compareByGeneratedPositionsInflated ) ; this . _sorted = true ; } return this . _array ; } | Returns the flat sorted array of mappings . The mappings are sorted by generated position . |
13,928 | private static void loadDriver ( String classname ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { if ( ! driversLoaded . containsKey ( classname ) ) { Object O = Class . forName ( classname ) . newInstance ( ) ; driversLoaded . putIfAbsent ( classname , O ) ; } } | Loads a driver at most once . |
13,929 | protected void ensureCapacity ( long capacity ) throws IOException { long curCapacity = pbuffer . capacity ( ) ; if ( curCapacity < capacity ) expandCapacity ( curCapacity , capacity ) ; } | This class takes a lazy approach on allocating buffer space . It will allocate additional space as needed here rounding up to the next 4096 - byte boundary . |
13,930 | private static String getRelativePath ( File file , FilesystemIterator iterator ) throws IOException { String path = file . getPath ( ) ; String prefix = iterator . getStartPath ( ) ; if ( ! path . startsWith ( prefix ) ) throw new IOException ( "path doesn't start with prefix: path=\"" + path + "\", prefix=\"" + prefix + "\"" ) ; return path . substring ( prefix . length ( ) ) ; } | Gets the relative path for the provided file from the provided iterator . |
13,931 | private String toLabel ( final TimeUnit unit ) { switch ( unit ) { case DAYS : return "day" ; case HOURS : return "hour" ; case MINUTES : return "minute" ; case SECONDS : return "second" ; case MILLISECONDS : return "ms" ; case MICROSECONDS : return "us" ; case NANOSECONDS : return "ns" ; default : return "" ; } } | Converts a time unit to a label . |
13,932 | public void connect ( final String endpoint , final Callback < ? super HttpSocket > onConnect , final Callback < ? super Exception > onError ) { executors . getUnbounded ( ) . submit ( new Runnable ( ) { public void run ( ) { try { AoByteArrayOutputStream bout = new AoByteArrayOutputStream ( ) ; try { try ( DataOutputStream out = new DataOutputStream ( bout ) ) { out . writeBytes ( "action=connect" ) ; } } finally { bout . close ( ) ; } long connectTime = System . currentTimeMillis ( ) ; URL endpointURL = new URL ( endpoint ) ; HttpURLConnection conn = ( HttpURLConnection ) endpointURL . openConnection ( ) ; conn . setAllowUserInteraction ( false ) ; conn . setConnectTimeout ( CONNECT_TIMEOUT ) ; conn . setDoOutput ( true ) ; conn . setFixedLengthStreamingMode ( bout . size ( ) ) ; conn . setInstanceFollowRedirects ( false ) ; conn . setReadTimeout ( CONNECT_TIMEOUT ) ; conn . setRequestMethod ( "POST" ) ; conn . setUseCaches ( false ) ; OutputStream out = conn . getOutputStream ( ) ; try { out . write ( bout . getInternalByteArray ( ) , 0 , bout . size ( ) ) ; out . flush ( ) ; } finally { out . close ( ) ; } int responseCode = conn . getResponseCode ( ) ; if ( responseCode != 200 ) throw new IOException ( "Unexpect response code: " + responseCode ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: got connection" ) ; DocumentBuilder builder = builderFactory . newDocumentBuilder ( ) ; Element document = builder . parse ( conn . getInputStream ( ) ) . getDocumentElement ( ) ; if ( ! "connection" . equals ( document . getNodeName ( ) ) ) throw new IOException ( "Unexpected root node name: " + document . getNodeName ( ) ) ; Identifier id = Identifier . valueOf ( document . getAttribute ( "id" ) ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: got id=" + id ) ; HttpSocket httpSocket = new HttpSocket ( HttpSocketClient . this , id , connectTime , endpointURL ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: adding socket" ) ; addSocket ( httpSocket ) ; if ( onConnect != null ) { if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: calling onConnect" ) ; onConnect . call ( httpSocket ) ; } } catch ( Exception exc ) { if ( onError != null ) { if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: calling onError" ) ; onError . call ( exc ) ; } } } } ) ; } | Asynchronously connects . |
13,933 | static final String encode ( int aValue ) { String encoded = "" ; int digit ; int vlq = toVLQSigned ( aValue ) ; do { digit = vlq & VLQ_BASE_MASK ; vlq >>>= VLQ_BASE_SHIFT ; if ( vlq > 0 ) { digit |= VLQ_CONTINUATION_BIT ; } encoded += Base64 . encode ( digit ) ; } while ( vlq > 0 ) ; return encoded ; } | Returns the base 64 VLQ encoded value . |
13,934 | static Base64VLQResult decode ( String aStr , int aIndex ) { int strLen = aStr . length ( ) ; int result = 0 ; int shift = 0 ; boolean continuation ; int digit ; do { if ( aIndex >= strLen ) { throw new Error ( "Expected more digits in base 64 VLQ value." ) ; } digit = Base64 . decode ( aStr . charAt ( aIndex ++ ) ) ; if ( digit == - 1 ) { throw new Error ( "Invalid base64 digit: " + aStr . charAt ( aIndex - 1 ) ) ; } continuation = ( digit & VLQ_CONTINUATION_BIT ) != 0 ; digit &= VLQ_BASE_MASK ; result = result + ( digit << shift ) ; shift += VLQ_BASE_SHIFT ; } while ( continuation ) ; return new Base64VLQResult ( fromVLQSigned ( result ) , aIndex ) ; } | Decodes the next base 64 VLQ value from the given string and returns the value and the rest of the string via the out parameter . |
13,935 | public static StringBuilder generateIdPrefix ( String template , String prefix ) { NullArgumentException . checkNotNull ( template , "template" ) ; NullArgumentException . checkNotNull ( prefix , "prefix" ) ; assert isValidId ( prefix ) ; final int len = template . length ( ) ; int pos = 0 ; while ( pos < len ) { char ch = template . charAt ( pos ) ; if ( ( ch >= 'A' && ch <= 'Z' ) || ( ch >= 'a' && ch <= 'z' ) ) { break ; } pos ++ ; } StringBuilder idPrefix ; if ( pos == len ) { idPrefix = new StringBuilder ( prefix ) ; } else { idPrefix = new StringBuilder ( len - pos ) ; while ( pos < len ) { char ch = template . charAt ( pos ) ; pos ++ ; if ( ch == ' ' ) { idPrefix . append ( '-' ) ; } else if ( ( ch >= 'A' && ch <= 'Z' ) || ( ch >= 'a' && ch <= 'z' ) || ( ch >= '0' && ch <= '9' ) || ch == ':' || ch == '_' || ch == '.' || ch == '-' ) { if ( ch >= 'A' && ch <= 'Z' ) { ch = ( char ) ( ch + ( 'a' - 'A' ) ) ; } idPrefix . append ( ch ) ; } } } assert isValidId ( idPrefix . toString ( ) ) ; return idPrefix ; } | Generates a valid ID from an arbitrary string . |
13,936 | void setPage ( Page page ) { synchronized ( lock ) { checkNotFrozen ( ) ; if ( this . page != null ) throw new IllegalStateException ( "element already has a page: " + this ) ; this . page = page ; } assert checkPageAndParentElement ( ) ; } | This is set when the element is associated with the page . |
13,937 | public String getId ( ) { if ( id == null ) { synchronized ( lock ) { if ( id == null ) { if ( page != null ) { Map < String , Element > elementsById = page . getElementsById ( ) ; String template = getElementIdTemplate ( ) ; if ( template == null ) { throw new IllegalStateException ( "null from getElementIdTemplate" ) ; } StringBuilder possId = Element . generateIdPrefix ( template , getDefaultIdPrefix ( ) ) ; int possIdLen = possId . length ( ) ; for ( int i = 1 ; i <= Integer . MAX_VALUE ; i ++ ) { if ( i == Integer . MAX_VALUE ) throw new IllegalStateException ( "ID not generated" ) ; if ( i > 1 ) possId . append ( '-' ) . append ( i ) ; String newId = possId . toString ( ) ; if ( elementsById == null || ! elementsById . containsKey ( newId ) ) { setId ( newId , true ) ; break ; } possId . setLength ( possIdLen ) ; } } } } } return id ; } | When inside a page every element must have a per - page unique ID when one is not provided it will be generated . When not inside a page no missing ID is generated and it will remain null . |
13,938 | public ElementRef getElementRef ( ) throws IllegalStateException { Page p = page ; if ( p == null ) throw new IllegalStateException ( "page not set" ) ; PageRef pageRef = p . getPageRef ( ) ; String i = getId ( ) ; if ( i == null ) throw new IllegalStateException ( "page not set so no id generated" ) ; ElementRef er = elementRef ; if ( er == null || ! er . getPageRef ( ) . equals ( pageRef ) || ! er . getId ( ) . equals ( i ) ) { er = new ElementRef ( pageRef , i ) ; elementRef = er ; } return er ; } | Gets an ElementRef for this element . Must have a page set . If id has not yet been set one will be generated . |
13,939 | private void setParentElement ( Element parentElement ) { synchronized ( lock ) { checkNotFrozen ( ) ; if ( this . parentElement != null ) throw new IllegalStateException ( "parentElement already set" ) ; this . parentElement = parentElement ; } assert checkPageAndParentElement ( ) ; } | Sets the parent element of this element . |
13,940 | public Long addChildElement ( Element childElement , ElementWriter elementWriter ) { Long elementKey = super . addChildElement ( childElement , elementWriter ) ; childElement . setParentElement ( this ) ; return elementKey ; } | Adds a child element to this element . |
13,941 | private static void log ( File logFile , long connectionId , char separator , String line ) { synchronized ( logFile ) { try { try ( Writer out = new FileWriter ( logFile , true ) ) { out . write ( Long . toString ( connectionId ) ) ; out . write ( separator ) ; out . write ( ' ' ) ; out . write ( line ) ; out . write ( '\n' ) ; } } catch ( IOException e ) { e . printStackTrace ( System . err ) ; } } } | Writes one line to the given file synchronizes on the file object . |
13,942 | public static Optional < Object > tryValue ( ReadableRepresentation representation , String name ) { try { return Optional . fromNullable ( representation . getValue ( name ) ) ; } catch ( RepresentationException e ) { return Optional . absent ( ) ; } } | Returns a property from the Representation . |
13,943 | private static final int intcmp ( Integer i1 , Integer i2 ) { if ( i1 == null && i2 == null ) { return 0 ; } if ( i1 == null ) { return - i2 ; } if ( i2 == null ) { return i1 ; } return i1 - i2 ; } | mimic the behaviour of i1 - i2 in JS |
13,944 | public int compareTo ( News o ) { int diff = o . getPubDate ( ) . compareTo ( getPubDate ( ) ) ; if ( diff != 0 ) return diff ; return getPage ( ) . compareTo ( o . getPage ( ) ) ; } | Ordered by pubDate desc page |
13,945 | public static JmxExporterConfig defaultJmxExporterConfig ( final InetAddress hostname , final Integer rmiRegistryPort , final Integer rmiServerPort , final boolean useRandomIds ) throws IOException { return new JmxExporterConfig ( ( hostname != null ) ? hostname : InetAddress . getByName ( null ) , ( rmiRegistryPort != null ) ? rmiRegistryPort : NetUtils . findUnusedPort ( ) , ( rmiServerPort != null ) ? rmiServerPort : NetUtils . findUnusedPort ( ) , useRandomIds ) ; } | Creates a default configuration object . |
13,946 | public static Writer getInstance ( Writer out ) { if ( UNIX_EOL . equals ( EOL ) ) return out ; return new FindReplaceWriter ( out , EOL , UNIX_EOL ) ; } | Gets an instance of the Writer that performs the conversion . The implementation may be optimized for common platforms . |
13,947 | public static int [ ] getRGB ( BufferedImage image ) { int [ ] pixels = getRGBArray ( image ) ; getRGB ( image , pixels ) ; return pixels ; } | Gets the RGB pixels for the given image into a new array . |
13,948 | public static Image getImageFromResources ( Class < ? > clazz , String name ) throws IOException { return getImageFromResources ( clazz , name , Toolkit . getDefaultToolkit ( ) ) ; } | Loads an image from a resource using the default toolkit . |
13,949 | public static Image getImageFromResources ( Class < ? > clazz , String name , Toolkit toolkit ) throws IOException { byte [ ] imageData ; InputStream in = clazz . getResourceAsStream ( name ) ; if ( in == null ) throw new IOException ( "Unable to find resource: " + name ) ; try { imageData = IoUtils . readFully ( in ) ; } finally { in . close ( ) ; } return toolkit . createImage ( imageData ) ; } | Loads an image from a resource using the provided toolkit . |
13,950 | public void printLoginForm ( WebPage page , LoginException loginException , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { getParent ( ) . printLoginForm ( page , loginException , req , resp ) ; } | Prints the form that is used to login . |
13,951 | public void printUnauthorizedPage ( WebPage page , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { getParent ( ) . printUnauthorizedPage ( page , req , resp ) ; } | Prints the unauthorized page message . |
13,952 | protected final long getClassLastModified ( ) throws IOException , SQLException { String dir = getServletContext ( ) . getRealPath ( "/WEB-INF/classes" ) ; if ( dir != null && dir . length ( ) > 0 ) { long lastMod = new File ( dir , getClass ( ) . getName ( ) . replace ( '.' , File . separatorChar ) + ".class" ) . lastModified ( ) ; if ( lastMod != 0 && lastMod != - 1 ) return lastMod ; } return getUptime ( ) ; } | Gets the last modified time of the java class file . If the class file is unavailable it defaults to the time the servlets were loaded . |
13,953 | public long getWebPageAndChildrenLastModified ( WebSiteRequest req ) throws IOException , SQLException { WebPage [ ] myPages = getCachedPages ( req ) ; int len = myPages . length ; long mostRecent = getClassLastModified ( ) ; if ( mostRecent == - 1 ) return - 1 ; for ( int c = 0 ; c < len ; c ++ ) { long time = myPages [ c ] . getLastModified ( req ) ; if ( time == - 1 ) return - 1 ; if ( time > mostRecent ) mostRecent = time ; } return mostRecent ; } | Gets the most recent last modified time of this page and its immediate children . |
13,954 | final public long getLastModifiedRecursive ( WebSiteRequest req ) throws IOException , SQLException { long time = getLastModified ( req ) ; WebPage [ ] myPages = getCachedPages ( req ) ; int len = myPages . length ; for ( int c = 0 ; c < len ; c ++ ) { long time2 = myPages [ c ] . getLastModifiedRecursive ( req ) ; if ( time2 > time ) time = time2 ; } return time ; } | Recursively gets the most recent modification time . |
13,955 | public static long getLastModifiedRecursive ( File file ) { long time = file . lastModified ( ) ; if ( file . isDirectory ( ) ) { String [ ] list = file . list ( ) ; if ( list != null ) { int len = list . length ; for ( int c = 0 ; c < len ; c ++ ) { long time2 = getLastModifiedRecursive ( new File ( file , list [ c ] ) ) ; if ( time2 > time ) time = time2 ; } } } return time ; } | Recursively gets the most recent modification time of a file or directory . |
13,956 | public void doGet ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { } | By default GET provides no content . |
13,957 | public final WebPage getRootPage ( ) throws IOException , SQLException { WebPage page = this ; WebPage parent ; while ( ( parent = page . getParent ( ) ) != null ) page = parent ; return page ; } | Gets the root page in the web page hierarchy . The root page has no parent . |
13,958 | public String getNavImageURL ( WebSiteRequest req , HttpServletResponse resp , Object params ) throws IOException , SQLException { return resp . encodeURL ( req . getContextPath ( ) + req . getURL ( this , params ) ) ; } | Gets the URL associated with a nav image . |
13,959 | final public int getPageIndexInParent ( WebSiteRequest req ) throws IOException , SQLException { WebPage [ ] myPages = getParent ( ) . getCachedPages ( req ) ; int len = myPages . length ; for ( int c = 0 ; c < len ; c ++ ) if ( myPages [ c ] . equals ( this ) ) return c ; throw new RuntimeException ( "Unable to find page index in parent." ) ; } | Gets the index of this page in the parents list of children pages . |
13,960 | public static Class < ? extends WebPage > loadClass ( String className ) throws ClassNotFoundException { return Class . forName ( className ) . asSubclass ( WebPage . class ) ; } | Dynamically loads new classes based on the source . class file s modified time . |
13,961 | public String getCopyright ( WebSiteRequest req , HttpServletResponse resp , WebPage requestPage ) throws IOException , SQLException { return getParent ( ) . getCopyright ( req , resp , requestPage ) ; } | Gets the copyright information for this page . Defaults to the copyright of the parent page . |
13,962 | public static String join ( Iterable < ? > objects , String delimiter ) throws ConcurrentModificationException { int delimiterLength = delimiter . length ( ) ; int totalLength = 0 ; boolean didOne = false ; for ( Object obj : objects ) { if ( didOne ) totalLength += delimiterLength ; else didOne = true ; totalLength += String . valueOf ( obj ) . length ( ) ; } StringBuilder sb = new StringBuilder ( totalLength ) ; didOne = false ; for ( Object obj : objects ) { if ( didOne ) sb . append ( delimiter ) ; else didOne = true ; sb . append ( obj ) ; } if ( totalLength != sb . length ( ) ) throw new ConcurrentModificationException ( ) ; return sb . toString ( ) ; } | Joins the string representation of objects on the provided delimiter . The iteration will be performed twice . Once to compute the total length of the resulting string and the second to build the result . |
13,963 | public static < A extends Appendable > A join ( Iterable < ? > objects , String delimiter , A out ) throws IOException { boolean didOne = false ; for ( Object obj : objects ) { if ( didOne ) out . append ( delimiter ) ; else didOne = true ; out . append ( String . valueOf ( obj ) ) ; } return out ; } | Joins the string representation of objects on the provided delimiter . |
13,964 | public static int compareToDDMMYYYY ( String date1 , String date2 ) { if ( date1 . length ( ) != 8 || date2 . length ( ) != 8 ) return 0 ; return compareToDDMMYYYY0 ( date1 ) - compareToDDMMYYYY0 ( date2 ) ; } | Compare one date to another must be in the DDMMYYYY format . |
13,965 | public static int indexOf ( String S , char [ ] chars , int start ) { int Slen = S . length ( ) ; int clen = chars . length ; for ( int c = start ; c < Slen ; c ++ ) { char ch = S . charAt ( c ) ; for ( int d = 0 ; d < clen ; d ++ ) if ( ch == chars [ d ] ) return c ; } return - 1 ; } | Finds the first occurrence of any of the supplied characters starting at the specified index . |
13,966 | public static String replace ( final String string , final String find , final String replacement ) { int pos = string . indexOf ( find ) ; if ( pos == - 1 ) return string ; StringBuilder SB = new StringBuilder ( ) ; int lastpos = 0 ; final int findLen = find . length ( ) ; do { SB . append ( string , lastpos , pos ) . append ( replacement ) ; lastpos = pos + findLen ; pos = string . indexOf ( find , lastpos ) ; } while ( pos != - 1 ) ; int len = string . length ( ) ; if ( lastpos < len ) SB . append ( string , lastpos , len ) ; return SB . toString ( ) ; } | Replaces all occurrences of a String with a String Please consider the variant with the Appendable for higher performance . |
13,967 | public static void replace ( final StringBuffer sb , final String find , final String replacement ) { int pos = 0 ; while ( pos < sb . length ( ) ) { pos = sb . indexOf ( find , pos ) ; if ( pos == - 1 ) break ; sb . replace ( pos , pos + find . length ( ) , replacement ) ; pos += replacement . length ( ) ; } } | Replaces all occurrences of a String with a String . |
13,968 | public static List < String > splitLines ( String S ) { List < String > V = new ArrayList < > ( ) ; int start = 0 ; int pos ; while ( ( pos = S . indexOf ( '\n' , start ) ) != - 1 ) { String line ; if ( pos > start && S . charAt ( pos - 1 ) == '\r' ) line = S . substring ( start , pos - 1 ) ; else line = S . substring ( start , pos ) ; V . add ( line ) ; start = pos + 1 ; } int slen = S . length ( ) ; if ( start < slen ) { if ( S . charAt ( slen - 1 ) == '\r' ) slen -- ; String line = S . substring ( start , slen ) ; V . add ( line ) ; } return V ; } | Splits a String into lines on any \ n characters . Also removes any ending \ r characters if present |
13,969 | public static List < String > splitStringCommaSpace ( String line ) { List < String > words = new ArrayList < > ( ) ; int len = line . length ( ) ; int pos = 0 ; while ( pos < len ) { char ch ; while ( pos < len && ( ( ch = line . charAt ( pos ) ) <= ' ' || ch == ',' ) ) pos ++ ; int start = pos ; while ( pos < len && ( ch = line . charAt ( pos ) ) > ' ' && ch != ',' ) pos ++ ; if ( pos > start ) words . add ( line . substring ( start , pos ) ) ; } return words ; } | Splits a string into multiple words on either whitespace or commas |
13,970 | public static void convertToHex ( int value , Appendable out ) throws IOException { out . append ( getHexChar ( value >>> 28 ) ) ; out . append ( getHexChar ( value >>> 24 ) ) ; out . append ( getHexChar ( value >>> 20 ) ) ; out . append ( getHexChar ( value >>> 16 ) ) ; out . append ( getHexChar ( value >>> 12 ) ) ; out . append ( getHexChar ( value >>> 8 ) ) ; out . append ( getHexChar ( value >>> 4 ) ) ; out . append ( getHexChar ( value ) ) ; } | Converts an int to a full 8 - character hex code . |
13,971 | public static int compareToIgnoreCaseCarefulEquals ( String S1 , String S2 ) { int diff = S1 . compareToIgnoreCase ( S2 ) ; if ( diff == 0 ) diff = S1 . compareTo ( S2 ) ; return diff ; } | Compares two strings in a case insensitive manner . However if they are considered equals in the case - insensitive manner the case sensitive comparison is done . |
13,972 | public static int indexOf ( String source , String target , int fromIndex , int toIndex ) { if ( fromIndex > toIndex ) throw new IllegalArgumentException ( "fromIndex>toIndex: fromIndex=" + fromIndex + ", toIndex=" + toIndex ) ; int sourceCount = source . length ( ) ; if ( toIndex < sourceCount ) sourceCount = toIndex ; int targetCount = target . length ( ) ; if ( fromIndex >= sourceCount ) { return ( targetCount == 0 ? sourceCount : - 1 ) ; } if ( fromIndex < 0 ) { fromIndex = 0 ; } if ( targetCount == 0 ) { return fromIndex ; } char first = target . charAt ( 0 ) ; int max = sourceCount - targetCount ; for ( int i = fromIndex ; i <= max ; i ++ ) { if ( source . charAt ( i ) != first ) { while ( ++ i <= max && source . charAt ( i ) != first ) { } } if ( i <= max ) { int j = i + 1 ; int end = j + targetCount - 1 ; for ( int k = 1 ; j < end && source . charAt ( j ) == target . charAt ( k ) ; j ++ , k ++ ) { } if ( j == end ) { return i ; } } } return - 1 ; } | Finds the next of a substring like regular String . indexOf but stops at a certain maximum index . Like substring will look up to the character one before toIndex . |
13,973 | public static String nullIfEmpty ( String value ) { return value == null || value . isEmpty ( ) ? null : value ; } | Returns null if the string is null or empty . |
13,974 | public boolean isEmpty ( ) { for ( List < ? extends Method < ? extends E > > methods : methodsByClass . values ( ) ) { for ( Method < ? extends E > method : methods ) { E singleton = method . getSingleton ( target ) ; if ( singleton != null ) return false ; Set < ? extends E > set = method . getSet ( target ) ; if ( set != null && ! set . isEmpty ( ) ) return false ; } } return true ; } | Checks if this set is empty . This can be an expensive method since it can potentially call all methods . |
13,975 | @ SuppressWarnings ( "unchecked" ) public boolean addAll ( Collection < ? extends E > c ) { if ( c . isEmpty ( ) ) return false ; if ( c instanceof Set ) return addAll ( ( Set < ? extends E > ) c ) ; else throw new UnsupportedOperationException ( "May only add sets" ) ; } | Must be a set . |
13,976 | public TempFile createTempFile ( ) throws IOException { TempFile tempFile = new TempFile ( prefix , suffix , directory ) ; synchronized ( tempFiles ) { tempFiles . add ( new WeakReference < > ( tempFile ) ) ; } return tempFile ; } | Creates a new temp file while adding it to the list of files that will be explicitly deleted when this list is deleted . |
13,977 | public void delete ( ) throws IOException { synchronized ( tempFiles ) { for ( WeakReference < TempFile > tempFileRef : tempFiles ) { TempFile tempFile = tempFileRef . get ( ) ; if ( tempFile != null ) tempFile . delete ( ) ; } tempFiles . clear ( ) ; } } | Deletes all of the underlying temp files immediately . |
13,978 | private static File getFileUploadDirectory ( ServletContext servletContext ) throws FileNotFoundException { File uploadDir = new File ( ( File ) servletContext . getAttribute ( ServletContext . TEMPDIR ) , "uploads" ) ; if ( ! uploadDir . exists ( ) && ! uploadDir . mkdirs ( ) && ! uploadDir . exists ( ) ) { throw new FileNotFoundException ( uploadDir . getPath ( ) ) ; } return uploadDir ; } | Gets the upload directory . |
13,979 | protected static boolean appendParams ( StringBuilder SB , Object optParam , List < String > finishedParams , boolean alreadyAppended ) { if ( optParam != null ) { if ( optParam instanceof String ) { List < String > nameValuePairs = StringUtility . splitString ( ( String ) optParam , '&' ) ; int len = nameValuePairs . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { SB . append ( alreadyAppended ? '&' : '?' ) ; String S = nameValuePairs . get ( i ) ; int pos = S . indexOf ( '=' ) ; if ( pos == - 1 ) { SB . append ( S ) ; alreadyAppended = true ; } else { String name = S . substring ( 0 , pos ) ; if ( ! finishedParams . contains ( name ) ) { SB . append ( S ) ; finishedParams . add ( name ) ; alreadyAppended = true ; } } } } else if ( optParam instanceof String [ ] ) { String [ ] SA = ( String [ ] ) optParam ; int len = SA . length ; for ( int c = 0 ; c < len ; c += 2 ) { String name = SA [ c ] ; if ( ! finishedParams . contains ( name ) ) { SB . append ( alreadyAppended ? '&' : '?' ) . append ( name ) . append ( '=' ) . append ( SA [ c + 1 ] ) ; finishedParams . add ( name ) ; alreadyAppended = true ; } } } else throw new IllegalArgumentException ( "Unsupported type for optParam: " + optParam . getClass ( ) . getName ( ) ) ; } return alreadyAppended ; } | Appends the parameters to a URL . Parameters should already be URL encoded but not XML encoded . |
13,980 | public String getURL ( String classAndParams ) throws IOException , SQLException { String className , params ; int pos = classAndParams . indexOf ( '?' ) ; if ( pos == - 1 ) { className = classAndParams ; params = null ; } else { className = classAndParams . substring ( 0 , pos ) ; params = classAndParams . substring ( pos + 1 ) ; } return getURL ( className , params ) ; } | Gets a relative URL from a String containing a classname and optional parameters . Parameters should already be URL encoded but not XML encoded . |
13,981 | public String getURL ( String classname , String params ) throws IOException , SQLException { try { Class < ? extends WebPage > clazz = Class . forName ( classname ) . asSubclass ( WebPage . class ) ; return getURL ( clazz , params ) ; } catch ( ClassNotFoundException err ) { throw new IOException ( "Unable to load class: " + classname , err ) ; } } | Gets a relative URL given its classname and optional parameters . Parameters should already be URL encoded but not XML encoded . |
13,982 | public String getURL ( String url , Object optParam , boolean keepSettings ) throws IOException { StringBuilder SB = new StringBuilder ( ) ; SB . append ( url ) ; List < String > finishedParams = new SortedArrayList < > ( ) ; boolean alreadyAppended = appendParams ( SB , optParam , finishedParams , false ) ; if ( keepSettings ) appendSettings ( finishedParams , alreadyAppended , SB ) ; return SB . toString ( ) ; } | Gets the context - relative URL optionally with the settings embedded . Parameters should already be URL encoded but not XML encoded . |
13,983 | public String getURL ( WebPage page ) throws IOException , SQLException { return getURL ( page , ( Object ) null ) ; } | Gets the context - relative URL to a web page . |
13,984 | public String getURL ( String url , Object optParam ) throws IOException { return getURL ( url , optParam , true ) ; } | Gets the URL String with the given parameters embedded keeping the current settings . |
13,985 | public boolean isLynx ( ) { if ( ! isLynxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLynx = agent != null && agent . toLowerCase ( Locale . ROOT ) . contains ( "lynx" ) ; isLynxDone = true ; } return isLynx ; } | Determines if the request is for a Lynx browser |
13,986 | public boolean isBlackBerry ( ) { if ( ! isBlackBerryDone ) { String agent = req . getHeader ( "user-agent" ) ; isBlackBerry = agent != null && agent . startsWith ( "BlackBerry" ) ; isBlackBerryDone = true ; } return isBlackBerry ; } | Determines if the request is for a BlackBerry browser |
13,987 | public boolean isLinux ( ) { if ( ! isLinuxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLinux = agent == null || agent . toLowerCase ( Locale . ROOT ) . contains ( "linux" ) ; isLinuxDone = true ; } return isLinux ; } | Determines if the request is for a Linux browser |
13,988 | public static String addParams ( String href , HttpParameters params , String encoding ) throws UnsupportedEncodingException { if ( params != null ) { StringBuilder sb = new StringBuilder ( href ) ; int anchorStart = href . lastIndexOf ( '#' ) ; String anchor ; boolean hasQuestion ; if ( anchorStart == - 1 ) { anchor = null ; hasQuestion = href . lastIndexOf ( '?' ) != - 1 ; } else { anchor = href . substring ( anchorStart ) ; sb . setLength ( anchorStart ) ; hasQuestion = href . lastIndexOf ( '?' , anchorStart - 1 ) != - 1 ; } for ( Map . Entry < String , List < String > > entry : params . getParameterMap ( ) . entrySet ( ) ) { String encodedName = URLEncoder . encode ( entry . getKey ( ) , encoding ) ; for ( String value : entry . getValue ( ) ) { if ( hasQuestion ) sb . append ( '&' ) ; else { sb . append ( '?' ) ; hasQuestion = true ; } sb . append ( encodedName ) ; assert value != null : "null values no longer supported to be consistent with servlet environment" ; sb . append ( '=' ) . append ( URLEncoder . encode ( value , encoding ) ) ; } } if ( anchor != null ) sb . append ( anchor ) ; href = sb . toString ( ) ; } return href ; } | Adds all of the parameters to a URL . |
13,989 | public static String toJSONString ( Object o ) { try { return objectMapper . writer ( ) . without ( SerializationFeature . INDENT_OUTPUT ) . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } } | A not - pretty printed JSON string . Returns a portable JSON string . |
13,990 | final public void beginLightArea ( WebSiteRequest req , HttpServletResponse resp , ChainWriter out ) throws IOException { beginLightArea ( req , resp , out , null , false ) ; } | Begins a lighter colored area of the site . |
13,991 | private void makeNewFile ( ) throws IOException { String filename = prefix + ( files . size ( ) + 1 ) + suffix ; File file = new File ( parent , filename ) ; out = new FileOutputStream ( file ) ; bytesOut = 0 ; files . add ( file ) ; } | All accesses are already synchronized . |
13,992 | public static FileMessage decode ( String encodedMessage , File file ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) , file ) ; } | base - 64 decodes the message into the provided file . |
13,993 | public static FileMessage decode ( String encodedMessage ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) ) ; } | base - 64 decodes the message into a temp file . |
13,994 | public static FileMessage decode ( ByteArray encodedMessage , File file ) throws IOException { try ( OutputStream out = new FileOutputStream ( file ) ) { out . write ( encodedMessage . array , 0 , encodedMessage . size ) ; } return new FileMessage ( true , file ) ; } | Restores this message into the provided file . |
13,995 | public static FileMessage decode ( ByteArray encodedMessage ) throws IOException { File file = File . createTempFile ( "FileMessage." , null ) ; file . deleteOnExit ( ) ; return decode ( encodedMessage , file ) ; } | Restores this message into a temp file . |
13,996 | public static Registry createRegistry ( int port , RMIClientSocketFactory csf , RMIServerSocketFactory ssf ) throws RemoteException { synchronized ( registryCache ) { Integer portObj = port ; Registry registry = registryCache . get ( portObj ) ; if ( registry == null ) { registry = LocateRegistry . createRegistry ( port , csf , ssf ) ; registryCache . put ( portObj , registry ) ; } return registry ; } } | Creates a registry or returns the registry that is already using the port . |
13,997 | final public void close ( ) { List < C > connsToClose ; synchronized ( poolLock ) { isClosed = true ; connsToClose = new ArrayList < > ( availableConnections . size ( ) ) ; for ( PooledConnection < C > availableConnection : availableConnections ) { synchronized ( availableConnection ) { C conn = availableConnection . connection ; if ( conn != null ) { availableConnection . connection = null ; connsToClose . add ( conn ) ; } } } poolLock . notifyAll ( ) ; } for ( C conn : connsToClose ) { try { close ( conn ) ; } catch ( Exception err ) { logger . log ( Level . WARNING , null , err ) ; } } } | Shuts down the pool exceptions during close will be logged as a warning and not thrown . |
13,998 | final public int getConnectionCount ( ) { int total = 0 ; synchronized ( poolLock ) { for ( PooledConnection < C > pooledConnection : allConnections ) { if ( pooledConnection . connection != null ) total ++ ; } } return total ; } | Gets the number of connections currently connected . |
13,999 | private void release ( PooledConnection < C > pooledConnection ) { long currentTime = System . currentTimeMillis ( ) ; long useTime ; synchronized ( pooledConnection ) { pooledConnection . releaseTime = currentTime ; useTime = currentTime - pooledConnection . startTime ; if ( useTime > 0 ) pooledConnection . totalTime . addAndGet ( useTime ) ; pooledConnection . allocateStackTrace = null ; } synchronized ( poolLock ) { try { if ( busyConnections . remove ( pooledConnection ) ) availableConnections . add ( pooledConnection ) ; } finally { poolLock . notify ( ) ; } } } | Releases a PooledConnection . It is safe to release it multiple times . The connection should have either been closed or reset before this is called because this makes the connection available for the next request . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.