idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
8,500 | private void reopen ( final ConnectionPoolConnection conn ) { if ( isActive ) { if ( conn . reopenAttempts == 0 ) { conn . reopenAttempts ++ ; reopenService . execute ( new Reopener ( conn ) ) ; } else { long delayMillis = 100L * conn . reopenAttempts ; if ( delayMillis > maxReconnectDelayMillis ) { delayMillis = maxReconnectDelayMillis ; } conn . reopenAttempts ++ ; reopenService . schedule ( new Reopener ( conn ) , delayMillis , TimeUnit . MILLISECONDS ) ; } } } | Schedule connection reopen . |
8,501 | final void close ( final ConnectionPoolConnection conn ) { if ( closeQueue != null ) { closeQueue . add ( conn ) ; } else { closer . close ( conn ) ; } } | Adds a connection to the close queue . |
8,502 | final String getPassword ( ) { if ( passwordSource == null ) { return dbConnection . password ; } else { String usePassword = passwordSource . getPassword ( dbConnection . name ) ; if ( ! Strings . isNullOrEmpty ( usePassword ) ) { return usePassword ; } else { usePassword = passwordSource . getPassword ( dbConnection . connectionString , dbConnection . user ) ; return ! Strings . isNullOrEmpty ( usePassword ) ? usePassword : dbConnection . password ; } } } | Gets the password for connection creation . |
8,503 | private Connection createRealConnection ( final long timeoutMillis ) throws SQLException { if ( timeoutMillis < 1L ) { String usePassword = getPassword ( ) ; Connection conn = dbConnection . datasource == null ? DriverManager . getConnection ( dbConnection . connectionString , dbConnection . user , usePassword ) : dbConnection . datasource . getConnection ( dbConnection . user , usePassword ) ; if ( conn != null ) { return conn ; } else { throw new SQLException ( "Unable to create connection: driver/datasource returned [null]" ) ; } } else { try { return connectionTimeLimiter . callWithTimeout ( ( ) -> createRealConnection ( 0L ) , timeoutMillis , TimeUnit . MILLISECONDS ) ; } catch ( UncheckedTimeoutException ute ) { throw new SQLException ( "Unable to create connection after waiting " + timeoutMillis + " ms" ) ; } catch ( Exception e ) { throw new SQLException ( "Unable to create connection: driver/datasource" , e ) ; } } } | Creates a real database connection failing if one is not obtained in the specified time . |
8,504 | final void activate ( ) throws SQLException { for ( ConnectionPoolConnection conn : connections ) { conn . forceRealClose ( ) ; conn . realOpen ( ) ; conn . logicalClose ( true ) ; } if ( closeQueue != null ) { closeQueue . clear ( ) ; } availableQueue . clear ( ) ; reopenExecutor . getQueue ( ) . clear ( ) ; List < ConnectionPoolConnection > connections = Lists . newArrayListWithCapacity ( this . connections . length ) ; for ( ConnectionPoolConnection connection : this . connections ) { connections . add ( connection ) ; connection . state . set ( ConnectionPoolConnection . STATE_AVAILABLE ) ; } isActive = true ; stats . activate ( ) ; availableQueue . addAll ( connections ) ; } | Activates the segment by opening and testing all connections . |
8,505 | final boolean isIdle ( ) { for ( ConnectionPoolConnection conn : connections ) { if ( conn . state . get ( ) == ConnectionPoolConnection . STATE_OPEN ) { return false ; } } return true ; } | Determine if this segment is currently idle . |
8,506 | final void deactivateNow ( ) { isActive = false ; stats . deactivate ( ) ; availableQueue . clear ( ) ; reopenExecutor . getQueue ( ) . clear ( ) ; for ( ConnectionPoolConnection conn : connections ) { conn . forceRealClose ( ) ; conn . state . set ( ConnectionPoolConnection . STATE_DISCONNECTED ) ; } } | Deactivates the pool immediately - real - closing all connections out from under the logical connections . |
8,507 | public final int getActiveConnectionCount ( ) { if ( ! isActive ) { return 0 ; } int count = 0 ; for ( ConnectionPoolConnection conn : connections ) { if ( conn . state . get ( ) != ConnectionPoolConnection . STATE_AVAILABLE ) { count ++ ; } } return count ; } | Gets the number of active connections . |
8,508 | void logError ( final String message ) { if ( logger != null ) { try { StringBuilder buf = new StringBuilder ( name ) ; buf . append ( ":" ) ; buf . append ( message ) ; logger . error ( buf . toString ( ) ) ; } catch ( Throwable t ) { } } } | Logs an error message . |
8,509 | static final String getStack ( final boolean filter ) { StringBuilder buf = new StringBuilder ( ) ; StackTraceElement [ ] stack = Thread . currentThread ( ) . getStackTrace ( ) ; for ( int i = 2 ; i < stack . length ; i ++ ) { if ( ! filter ) { buf . append ( stack [ i ] . toString ( ) ) ; buf . append ( NEW_LINE ) ; } else { String s = stack [ i ] . toString ( ) ; if ( ! s . startsWith ( "org.attribyte.sql.pool" ) ) { buf . append ( s ) ; buf . append ( NEW_LINE ) ; } } } return buf . toString ( ) ; } | Gets the current stack as a string . |
8,510 | static ThreadFactory createThreadFactoryBuilder ( final String baseName , final String componentName ) { StringBuilder buf = new StringBuilder ( "ACP:" ) ; if ( ! Strings . isNullOrEmpty ( baseName ) ) { buf . append ( baseName ) . append ( ":" ) . append ( componentName ) ; } else { buf . append ( componentName ) ; } buf . append ( "-Thread-%d" ) ; return new ThreadFactoryBuilder ( ) . setNameFormat ( buf . toString ( ) ) . build ( ) ; } | Creates a thread factory builder . |
8,511 | static final Set < String > uniquePrefixSet ( final Config config ) { Set < String > prefixSet = Sets . newHashSet ( ) ; for ( Map . Entry < String , ConfigValue > entry : config . entrySet ( ) ) { String key = entry . getKey ( ) ; int index = key . indexOf ( '.' ) ; if ( index > 0 ) { String prefix = key . substring ( 0 , index ) ; prefixSet . add ( prefix ) ; } } return prefixSet ; } | Gets all available keys in the config . |
8,512 | static final ConnectionPoolSegment . Initializer segmentFromConfig ( String poolName , String segmentName , final Config config , ConnectionPoolSegment . Initializer initializer , Map < String , JDBConnection > connectionMap ) throws InitializationException { initializer . setName ( poolName + "." + segmentName ) ; initializer . setSize ( getInt ( config , "size" , 1 ) ) ; initializer . setCloseConcurrency ( getInt ( config , "closeConcurrency" , 0 ) ) ; initializer . setTestOnLogicalOpen ( getString ( config , "testOnLogicalOpen" , "false" ) . equalsIgnoreCase ( "true" ) ) ; initializer . setTestOnLogicalClose ( getString ( config , "testOnLogicalClose" , "false" ) . equalsIgnoreCase ( "true" ) ) ; String incompleteTransactionPolicy = getString ( config , "incompleteTransactionPolicy" ) ; initializer . setIncompleteTransactionOnClosePolicy ( ConnectionPoolConnection . IncompleteTransactionPolicy . fromString ( incompleteTransactionPolicy , ConnectionPoolConnection . IncompleteTransactionPolicy . REPORT ) ) ; String openStatementPolicy = getString ( config , "openStatementPolicy" ) ; initializer . setOpenStatementOnClosePolicy ( ConnectionPoolConnection . OpenStatementPolicy . fromString ( openStatementPolicy , ConnectionPoolConnection . OpenStatementPolicy . SILENT ) ) ; String forceRealClosePolicy = getString ( config , "forceRealClosePolicy" ) ; initializer . setForceRealClosePolicy ( ConnectionPoolConnection . ForceRealClosePolicy . fromString ( forceRealClosePolicy , ConnectionPoolConnection . ForceRealClosePolicy . CONNECTION ) ) ; String activityTimeoutPolicy = getString ( config , "activityTimeoutPolicy" ) ; initializer . setActivityTimeoutPolicy ( ConnectionPoolConnection . ActivityTimeoutPolicy . fromString ( activityTimeoutPolicy , ConnectionPoolConnection . ActivityTimeoutPolicy . LOG ) ) ; initializer . setCloseTimeLimitMillis ( getMilliseconds ( config , "closeTimeLimit" ) ) ; String connectionName = getString ( config , "connectionName" , "" ) ; JDBConnection conn = null ; if ( connectionName . length ( ) > 0 ) { conn = connectionMap . get ( connectionName ) ; if ( conn == null ) { throw new InitializationException ( "No connection defined with name '" + connectionName + "'" ) ; } } if ( conn == null && ! initializer . hasConnection ( ) ) { throw new InitializationException ( "A 'connectionName' must be specified for segment, '" + segmentName + "'" ) ; } else if ( conn != null ) { initializer . setConnection ( conn ) ; } initializer . setAcquireTimeout ( getMilliseconds ( config , "acquireTimeout" ) , TimeUnit . MILLISECONDS ) ; initializer . setActiveTimeout ( getMilliseconds ( config , "activeTimeout" ) , TimeUnit . MILLISECONDS ) ; initializer . setConnectionLifetime ( getMilliseconds ( config , "connectionLifetime" ) , TimeUnit . MILLISECONDS ) ; initializer . setIdleTimeBeforeShutdown ( getMilliseconds ( config , "idleTimeBeforeShutdown" ) , TimeUnit . MILLISECONDS ) ; initializer . setMinActiveTime ( getMilliseconds ( config , "minActiveTime" ) , TimeUnit . MILLISECONDS ) ; initializer . setMaxConcurrentReconnects ( getInt ( config , "reconnectConcurrency" , 0 ) ) ; initializer . setMaxReconnectDelay ( getMilliseconds ( config , "reconnectMaxWaitTime" ) , TimeUnit . MILLISECONDS ) ; initializer . setActiveTimeoutMonitorFrequency ( getMilliseconds ( config , "activeTimeoutMonitorFrequency" ) , TimeUnit . MILLISECONDS ) ; return initializer ; } | Sets initializer properties from properties . |
8,513 | static Map < String , JDBConnection > connectionMapFromConfig ( Config config ) throws InitializationException { final Config globalPropertyConfig ; if ( config . hasPath ( "acp.property" ) ) { globalPropertyConfig = config . getObject ( "acp.property" ) . toConfig ( ) ; } else if ( config . hasPath ( "property" ) ) { globalPropertyConfig = config . getObject ( "property" ) . toConfig ( ) ; } else { globalPropertyConfig = null ; } final Config connectionsConfig ; if ( config . hasPath ( "acp.connection" ) ) { connectionsConfig = config . getObject ( "acp.connection" ) . toConfig ( ) ; } else if ( config . hasPath ( "connection" ) ) { connectionsConfig = config . getObject ( "connection" ) . toConfig ( ) ; } else { return Collections . emptyMap ( ) ; } Map < String , JDBConnection > connectionMap = Maps . newLinkedHashMap ( ) ; for ( String connectionName : uniquePrefixSet ( connectionsConfig ) ) { Config connectionConfig = connectionsConfig . getObject ( connectionName ) . toConfig ( ) ; connectionMap . put ( connectionName , createConnection ( connectionName , connectionConfig , globalPropertyConfig ) ) ; } return connectionMap ; } | Creates a map of connection vs . name from properties . |
8,514 | static JDBConnection createConnection ( final String connectionName , final Config baseConfig , final Config globalPropertyConfig ) throws InitializationException { Config connectionRef = ConfigFactory . load ( ) . getObject ( "acp.defaults.connection" ) . toConfig ( ) ; Config config = baseConfig . withFallback ( connectionRef ) ; final String user = getString ( config , "user" ) ; final String password = getString ( config , "password" ) ; final String testSQL = getString ( config , "testSQL" , "" ) ; String connectionString = getString ( config , "connectionString" ) ; final boolean debug = getString ( config , "debug" , "false" ) . equalsIgnoreCase ( "true" ) ; final long createTimeoutMillis = getMilliseconds ( config , "createTimeout" ) ; final long testIntervalMillis = getMilliseconds ( config , "testInterval" ) ; String propsRef = getString ( config , "properties" , "" ) ; Config propsConfig ; if ( propsRef . length ( ) > 0 ) { if ( globalPropertyConfig . hasPath ( propsRef ) ) { propsConfig = globalPropertyConfig . getObject ( propsRef ) . toConfig ( ) ; } else { throw new InitializationException ( "The referenced global properties, '" + propsRef + "' is not defined" ) ; } connectionString = buildConnectionString ( connectionString , propsConfig ) ; } return new JDBConnection ( connectionName , user , password , connectionString , createTimeoutMillis , testSQL . length ( ) > 0 ? testSQL : null , testIntervalMillis , debug ) ; } | Creates a connection from properties . |
8,515 | static void initDrivers ( final Config config ) throws InitializationException { for ( String driverName : uniquePrefixSet ( config ) ) { Config driverConfig = config . getObject ( driverName ) . toConfig ( ) ; if ( driverConfig . hasPath ( "class" ) ) { String className = driverConfig . getString ( "class" ) ; try { Class . forName ( className ) ; } catch ( Throwable t ) { throw new InitializationException ( "Unable to load JDBC driver, '" + className + "'" , t ) ; } } else { throw new InitializationException ( "A 'class' must be specified for JDBC driver, '" + driverName + "'" ) ; } } } | Initialize JDBC drivers from config . |
8,516 | private static String buildConnectionString ( final String connectionString , final Config config ) { if ( config == null ) { return connectionString ; } StringBuilder buf = new StringBuilder ( ) ; Iterator < Map . Entry < String , ConfigValue > > iter = config . entrySet ( ) . iterator ( ) ; if ( iter . hasNext ( ) ) { Map . Entry < String , ConfigValue > curr = iter . next ( ) ; buf . append ( curr . getKey ( ) ) . append ( "=" ) . append ( curr . getValue ( ) . unwrapped ( ) . toString ( ) ) ; } else { return connectionString ; } while ( iter . hasNext ( ) ) { Map . Entry < String , ConfigValue > curr = iter . next ( ) ; buf . append ( "&" ) . append ( curr . getKey ( ) ) . append ( "=" ) . append ( curr . getValue ( ) . unwrapped ( ) . toString ( ) ) ; } if ( connectionString . indexOf ( '?' ) > 0 ) { return connectionString + "&" + buf . toString ( ) ; } else { return connectionString + "?" + buf . toString ( ) ; } } | Builds a connection string with properties as parameters . |
8,517 | final void logicalOpen ( ) { openTime = Clock . currTimeMillis ; transactionState = TransactionState . NONE ; if ( debug ) { lastTrace = Util . getFilteredStack ( ) ; } } | Sets the connection state to open and records the open time . No tests are performed . |
8,518 | final void logicalClose ( final boolean withTest ) throws SQLException { openTime = 0L ; if ( debug ) { lastTrace = null ; } if ( logicalCloseException != null ) { Util . throwException ( logicalCloseException ) ; } if ( withTest ) { conn . setAutoCommit ( true ) ; if ( testSQL != null && testSQL . length ( ) > 0 ) { ResultSet rs = null ; Statement stmt = null ; try { stmt = conn . createStatement ( ) ; rs = stmt . executeQuery ( testSQL ) ; } finally { try { if ( rs != null ) { rs . close ( ) ; } } finally { if ( stmt != null ) { stmt . close ( ) ; } } } } } } | Prepares the connection for return to the active pool . |
8,519 | private boolean closeStatements ( ) { boolean hasUnclosed = false ; if ( openStatements . size ( ) > 0 ) { for ( Statement stmt : openStatements ) { try { if ( ! stmt . isClosed ( ) ) { stmt . close ( ) ; hasUnclosed = true ; } } catch ( SQLException e ) { hasUnclosed = true ; setLogicalCloseException ( e ) ; } catch ( Throwable t ) { hasUnclosed = true ; if ( logicalCloseException == null ) { if ( Util . isRuntimeError ( t ) ) { setLogicalCloseException ( t ) ; } else { setLogicalCloseException ( new SQLException ( t ) ) ; } } } } openStatements . clear ( ) ; } return hasUnclosed ; } | Check for unclosed statements . |
8,520 | private void setLogicalCloseException ( final Throwable t ) { if ( logicalCloseException == null ) { logicalCloseException = t ; } else if ( ! Util . isRuntimeError ( logicalCloseException ) && Util . isRuntimeError ( t ) ) { logicalCloseException = t ; } } | Sets logicalCloseException if null or replaces logicalCloseException if not null && input is a runtime error . |
8,521 | private void resolveIncompleteTransactions ( ) throws SQLException { switch ( transactionState ) { case COMPLETED : break ; case STARTED : if ( conn != null && openStatements . size ( ) > 0 ) { switch ( incompleteTransactionPolicy ) { case REPORT : throw new SQLException ( "Statement closed with incomplete transaction" , JDBConnection . SQLSTATE_INVALID_TRANSACTION_STATE ) ; case COMMIT : if ( ! conn . isClosed ( ) ) { conn . commit ( ) ; } break ; case ROLLBACK : if ( ! conn . isClosed ( ) ) { conn . rollback ( ) ; } } } break ; } } | Attempt to deal with any transaction problems . |
8,522 | public final void closeUnmanagedConnection ( final Connection conn ) throws SQLException { activeUnmanagedConnections . dec ( ) ; if ( ! conn . isClosed ( ) ) { conn . close ( ) ; } } | Closes an unumanged connection . |
8,523 | final void signalActivateSegment ( ) throws SQLException { if ( segmentSignalQueue != null ) { segmentSignalQueue . offer ( ACTIVATE_SEGMENT_SIGNAL ) ; } else if ( activeSegments == 0 ) { synchronized ( this ) { if ( activeSegments == 0 ) { segments [ 0 ] . activate ( ) ; activeSegments = 1 ; } } } } | Signals that a new segment should be activated . |
8,524 | public final void shutdownNow ( ) { if ( isShuttingDown . compareAndSet ( false , true ) ) { logInfo ( "Shutting down..." ) ; if ( idleSegmentMonitorService != null ) { logInfo ( "Shutting down idle segment monitor service..." ) ; idleSegmentMonitorService . shutdownNow ( ) ; } if ( segmentSignalQueue != null ) { segmentSignalQueue . clear ( ) ; } if ( segmentSignalMonitorThread != null ) { logInfo ( "Shutting down segment signal monitor thread..." ) ; segmentSignalMonitorThread . interrupt ( ) ; } logInfo ( "Shutting down all segments..." ) ; for ( ConnectionPoolSegment segment : segments ) { segment . shutdownNow ( ) ; } logInfo ( "Shutting down inactive monitor service..." ) ; inactiveMonitorService . shutdownNow ( ) ; Clock . shutdown ( ) ; logInfo ( "Shutdown complete!" ) ; } } | Shutdown the pool without waiting for any in - progress operations to complete . |
8,525 | final String getConnectionDescription ( ) { if ( datasource != null ) { return name ; } String description = connectionString ; int index = connectionString != null ? connectionString . indexOf ( '?' ) : 0 ; if ( index > 0 ) { description = connectionString . substring ( 0 , index ) ; } if ( ! Strings . isNullOrEmpty ( user ) ) { return user + "@" + description ; } else { return description ; } } | Gets a description of the database connection . |
8,526 | public static void doSetAscRecursively ( ComparatorItem comparatorItem , boolean asc ) { ComparatorItem tmp = comparatorItem ; while ( tmp != null ) { tmp . setAsc ( asc ) ; tmp = tmp . getNextComparatorItem ( ) ; } } | Sets the sort order of all items . |
8,527 | public static void doSetIgnoreCaseRecursively ( ComparatorItem comparatorItem , boolean ignoreCase ) { ComparatorItem tmp = comparatorItem ; while ( tmp != null ) { tmp . setIgnoreCase ( ignoreCase ) ; tmp = tmp . getNextComparatorItem ( ) ; } } | Sets whether the sort is case sensitive or not to all items . |
8,528 | public static void doSetNullIsFirstRecursively ( ComparatorItem comparatorItem , boolean nullIsFirst ) { ComparatorItem tmp = comparatorItem ; while ( tmp != null ) { tmp . setNullIsFirst ( nullIsFirst ) ; tmp = tmp . getNextComparatorItem ( ) ; } } | Sets the sort order of a null value to all items . |
8,529 | public void addGlobalVarMaskRegex ( VarMaskRegex varMaskRegex ) { if ( StringUtils . isBlank ( varMaskRegex . getRegex ( ) ) ) { LOGGER . fine ( "addGlobalVarMaskRegex NOT adding null regex" ) ; return ; } getGlobalVarMaskRegexesList ( ) . add ( varMaskRegex ) ; } | Adds a regex at the global level . |
8,530 | @ Restricted ( NoExternalUse . class ) public final synchronized void reset ( ) { clear ( ) ; addMaskedPasswordParameterDefinition ( hudson . model . PasswordParameterDefinition . class . getName ( ) ) ; addMaskedPasswordParameterDefinition ( com . michelin . cio . hudson . plugins . passwordparam . PasswordParameterDefinition . class . getName ( ) ) ; } | Resets configuration to the default state . |
8,531 | public List < VarMaskRegex > getGlobalVarMaskRegexes ( ) { List < VarMaskRegex > r = new ArrayList < VarMaskRegex > ( getGlobalVarMaskRegexesList ( ) . size ( ) ) ; for ( VarMaskRegex varMaskRegex : getGlobalVarMaskRegexesList ( ) ) { r . add ( ( VarMaskRegex ) varMaskRegex . clone ( ) ) ; } return r ; } | Returns the list of regexes defined at the global level . |
8,532 | public boolean isMasked ( final ParameterValue value , final String paramValueClassName ) { if ( value != null && value . isSensitive ( ) ) { return true ; } synchronized ( this ) { if ( paramValueCache_maskedClasses . contains ( paramValueClassName ) ) { return true ; } if ( paramValueCache_nonMaskedClasses . contains ( paramValueClassName ) ) { return false ; } boolean guessSo = guessIfShouldMask ( paramValueClassName ) ; if ( guessSo ) { paramValueCache_maskedClasses . add ( paramValueClassName ) ; return true ; } else { LOGGER . log ( Level . WARNING , "Identified the {0} class as a ParameterValue class, which does not require masking. It may be false-negative" , paramValueClassName ) ; paramValueCache_nonMaskedClasses . add ( paramValueClassName ) ; return false ; } } } | Returns true if the specified parameter value class name corresponds to a parameter definition class name selected in Jenkins main configuration screen . |
8,533 | public URI getLocationURI ( HttpRequest request , HttpResponse response , HttpContext context ) throws ProtocolException { URI uri = this . redirectStrategy . getLocationURI ( request , response , context ) ; String resultingPageUrl = uri . toString ( ) ; DriverRequest driverRequest = ( ( OutgoingRequest ) request ) . getOriginalRequest ( ) ; if ( StringUtils . startsWith ( resultingPageUrl , driverRequest . getVisibleBaseUrl ( ) ) ) { resultingPageUrl = "/" + StringUtils . stripStart ( StringUtils . replace ( resultingPageUrl , driverRequest . getVisibleBaseUrl ( ) , "" ) , "/" ) ; } resultingPageUrl = ResourceUtils . getHttpUrlWithQueryString ( resultingPageUrl , driverRequest , false ) ; return UriUtils . createURI ( ResourceUtils . getHttpUrlWithQueryString ( resultingPageUrl , driverRequest , false ) ) ; } | For local redirects converts to relative urls . |
8,534 | public boolean matches ( String schemeParam , String hostParam , String uriParam ) { if ( this . host != null && ! this . host . equalsIgnoreCase ( schemeParam + "://" + hostParam ) ) { return false ; } if ( this . extension != null && ! uriParam . endsWith ( this . extension ) ) { return false ; } if ( this . path != null && ! uriParam . startsWith ( this . path ) ) { return false ; } return true ; } | Check this matching rule against a request . |
8,535 | public void setAttribute ( String id , Object obj , boolean save ) { if ( save ) { String historyAttribute = id + "history" ; Queue < Object > history = ( Queue < Object > ) getAttribute ( historyAttribute ) ; if ( history == null ) { history = new LinkedList < > ( ) ; setAttribute ( historyAttribute , history ) ; } if ( this . getAttribute ( id ) != null ) { history . add ( getAttribute ( id ) ) ; } } setAttribute ( id , obj ) ; } | Set attribute and save previous attribute value |
8,536 | public Object removeAttribute ( String id , boolean restore ) { Object value = removeAttribute ( id ) ; if ( restore ) { String historyAttribute = id + "history" ; Queue < Object > history = ( Queue < Object > ) getAttribute ( historyAttribute ) ; if ( history != null && ! history . isEmpty ( ) ) { Object previous = history . remove ( ) ; setAttribute ( id , previous ) ; } } return value ; } | remove attribute and restore previous attribute value |
8,537 | public String rewriteReferer ( String referer , String baseUrl , String visibleBaseUrl ) { URI uri = UriUtils . createURI ( referer ) ; if ( ! baseUrl . endsWith ( "/" ) ) { baseUrl = baseUrl + "/" ; } URI baseUri = UriUtils . createURI ( baseUrl ) ; if ( ! visibleBaseUrl . endsWith ( "/" ) ) { visibleBaseUrl = visibleBaseUrl + "/" ; } URI visibleBaseUri = UriUtils . createURI ( visibleBaseUrl ) ; URI relativeUri = visibleBaseUri . relativize ( uri ) ; if ( relativeUri . equals ( uri ) ) { LOG . debug ( "url kept unchanged: [{}]" , referer ) ; return referer ; } URI result = baseUri . resolve ( relativeUri ) ; LOG . debug ( "referer fixed: [{}] -> [{}]" , referer , result ) ; return result . toString ( ) ; } | Fixes a referer url in a request . |
8,538 | public CharSequence rewriteHtml ( CharSequence input , String requestUrl , String baseUrlParam , String visibleBaseUrl , boolean absolute ) { StringBuffer result = new StringBuffer ( input . length ( ) ) ; Matcher m = URL_PATTERN . matcher ( input ) ; while ( m . find ( ) ) { String url = input . subSequence ( m . start ( 3 ) + 1 , m . end ( 3 ) - 1 ) . toString ( ) ; String tag = m . group ( 0 ) ; String quote = input . subSequence ( m . end ( 3 ) - 1 , m . end ( 3 ) ) . toString ( ) ; String trimmedUrl = StringUtils . trim ( url ) ; String rewrittenUrl = url ; trimmedUrl = unescapeHtml ( trimmedUrl ) ; if ( trimmedUrl . isEmpty ( ) ) { LOG . debug ( "empty url kept unchanged" ) ; } else if ( trimmedUrl . startsWith ( "#" ) ) { LOG . debug ( "anchor url kept unchanged: [{}]" , url ) ; } else if ( JAVASCRIPT_CONCATENATION_PATTERN . matcher ( trimmedUrl ) . find ( ) ) { LOG . debug ( "url in javascript kept unchanged: [{}]" , url ) ; } else if ( m . group ( 2 ) . equalsIgnoreCase ( "content" ) ) { if ( META_REFRESH_PATTERN . matcher ( tag ) . find ( ) ) { rewrittenUrl = rewriteRefresh ( trimmedUrl , requestUrl , baseUrlParam , visibleBaseUrl ) ; rewrittenUrl = escapeHtml ( rewrittenUrl ) ; LOG . debug ( "refresh url [{}] rewritten [{}]" , url , rewrittenUrl ) ; } else { LOG . debug ( "content attribute kept unchanged: [{}]" , url ) ; } } else { rewrittenUrl = rewriteUrl ( trimmedUrl , requestUrl , baseUrlParam , visibleBaseUrl , absolute ) ; rewrittenUrl = escapeHtml ( rewrittenUrl ) ; LOG . debug ( "url [{}] rewritten [{}]" , url , rewrittenUrl ) ; } m . appendReplacement ( result , "" ) ; result . append ( "<" ) ; result . append ( m . group ( 1 ) ) ; result . append ( m . group ( 2 ) ) ; result . append ( "=" ) ; result . append ( quote ) ; result . append ( rewrittenUrl ) ; result . append ( quote ) ; if ( m . groupCount ( ) > 3 ) { result . append ( m . group ( 4 ) ) ; } result . append ( ">" ) ; } m . appendTail ( result ) ; return result ; } | Fixes all resources urls and returns the result . |
8,539 | public static String removeSimpleQuotes ( String s ) { if ( s . startsWith ( "'" ) && s . endsWith ( "'" ) ) { return s . substring ( 1 , s . length ( ) - 1 ) ; } return s ; } | Removes simple quotes if any . |
8,540 | public static HttpHost getHost ( HttpRequest request ) { HttpHost httpHost = UriUtils . extractHost ( request . getRequestLine ( ) . getUri ( ) ) ; String scheme = httpHost . getSchemeName ( ) ; String host = httpHost . getHostName ( ) ; int port = httpHost . getPort ( ) ; Header [ ] headers = request . getHeaders ( HttpHeaders . HOST ) ; if ( headers != null && headers . length != 0 ) { String headerValue = headers [ 0 ] . getValue ( ) ; String [ ] splitted = headerValue . split ( ":" ) ; host = splitted [ 0 ] ; if ( splitted . length > 1 ) { port = Integer . parseInt ( splitted [ 1 ] ) ; } else { port = - 1 ; } } return new HttpHost ( host , port , scheme ) ; } | Returns the target host as defined in the Host header or extracted from the request URI . |
8,541 | private ClientExecChain addFetchEvent ( final ClientExecChain wrapped ) { return new ClientExecChain ( ) { public CloseableHttpResponse execute ( HttpRoute route , HttpRequestWrapper request , HttpClientContext httpClientContext , HttpExecutionAware execAware ) throws IOException , HttpException { OutgoingRequestContext context = OutgoingRequestContext . adapt ( httpClientContext ) ; FetchEvent fetchEvent = new FetchEvent ( context , request ) ; eventManager . fire ( EventManager . EVENT_FETCH_PRE , fetchEvent ) ; if ( fetchEvent . isExit ( ) ) { if ( fetchEvent . getHttpResponse ( ) == null ) { fetchEvent . setHttpResponse ( HttpErrorPage . generateHttpResponse ( HttpStatus . SC_INTERNAL_SERVER_ERROR , "An extension stopped the processing of the request without providing a response" ) ) ; } } else { try { fetchEvent . setHttpResponse ( wrapped . execute ( route , request , context , execAware ) ) ; eventManager . fire ( EventManager . EVENT_FETCH_POST , fetchEvent ) ; } catch ( IOException | HttpException e ) { fetchEvent . setHttpResponse ( HttpErrorPage . generateHttpResponse ( e ) ) ; fetchEvent . setExit ( true ) ; eventManager . fire ( EventManager . EVENT_FETCH_POST , fetchEvent ) ; if ( ! fetchEvent . isExit ( ) ) throw e ; } } return fetchEvent . getHttpResponse ( ) ; } } ; } | Decorate with fetch event managements |
8,542 | public String getRemoteUser ( ) { String user = getHeader ( "X_REMOTE_USER" ) ; if ( user != null ) { return user ; } else { return super . getRemoteUser ( ) ; } } | Returns the user defined as parameter user if present . |
8,543 | private void fixSurrogateMap ( LinkedHashMap < String , List < String > > targetCapabilities , String currentSurrogate ) { boolean esiEnabledInEsigate = false ; for ( String c : Esi . CAPABILITIES ) { if ( targetCapabilities . get ( currentSurrogate ) . contains ( c ) ) { esiEnabledInEsigate = true ; break ; } } if ( esiEnabledInEsigate ) { for ( String c : Esi . CAPABILITIES ) { for ( String device : targetCapabilities . keySet ( ) ) { if ( device . equals ( currentSurrogate ) ) { if ( ! targetCapabilities . get ( device ) . contains ( c ) ) { targetCapabilities . get ( device ) . add ( c ) ; } } else { targetCapabilities . get ( device ) . remove ( c ) ; } } } } } | The current implementation of ESI cannot execute rules partially . For instance if ESI - Inline is requested ESI ESI - Inline X - ESI - Fragment are executed . |
8,544 | private void initSurrogateMap ( Map < String , List < String > > targetCapabilities , SurrogateCapabilitiesHeader surrogateCapabilitiesHeader ) { for ( SurrogateCapabilities sc : surrogateCapabilitiesHeader . getSurrogates ( ) ) { targetCapabilities . put ( sc . getDeviceToken ( ) , new ArrayList < String > ( ) ) ; } } | Populate the Map with all current devices with empty capabilities . |
8,545 | private String getFirstSurrogateFor ( SurrogateCapabilitiesHeader surrogateCapabilitiesHeader , String capability ) { for ( SurrogateCapabilities surrogate : surrogateCapabilitiesHeader . getSurrogates ( ) ) { for ( Capability sc : surrogate . getCapabilities ( ) ) { if ( capability . equals ( sc . toString ( ) ) ) { return surrogate . getDeviceToken ( ) ; } } } return null ; } | Returns the first surrogate which supports the requested capability . |
8,546 | private static void processSurrogateControlContent ( HttpResponse response , boolean keepHeader ) { if ( ! response . containsHeader ( H_SURROGATE_CONTROL ) ) { return ; } if ( ! keepHeader ) { response . removeHeaders ( H_SURROGATE_CONTROL ) ; return ; } MoveResponseHeader . moveHeader ( response , H_X_NEXT_SURROGATE_CONTROL , H_SURROGATE_CONTROL ) ; } | Remove Surrogate - Control header or replace by its new value . |
8,547 | private static Double getOperandAsNumeric ( String op ) { Double d = null ; try { d = Double . valueOf ( op ) ; } catch ( Exception e ) { } return d ; } | Get an operand as a numeric type . |
8,548 | public static Collection < String > getPropertyValue ( Properties properties , String propertyName , Collection < String > defaultValue ) { Collection < String > result = defaultValue ; String propertyValue = properties . getProperty ( propertyName ) ; if ( propertyValue != null ) { result = toCollection ( propertyValue ) ; if ( result . contains ( "*" ) && result . size ( ) > 1 ) { throw new ConfigurationException ( propertyName + " must be a comma-separated list or *" ) ; } } return result ; } | Retrieves a property containing a comma separated list of values trim them and return them as a Collection of String . |
8,549 | static Collection < String > toCollection ( String list ) { Collection < String > result = new ArrayList < > ( ) ; if ( list != null ) { String [ ] values = list . split ( "," ) ; for ( String value : values ) { String trimmed = value . trim ( ) ; if ( ! trimmed . isEmpty ( ) ) { result . add ( trimmed ) ; } } } return result ; } | Return the provided comma - separated String as a collection . Order is maintained . |
8,550 | private static String cleanupStatusKey ( String s ) { String result = s ; if ( s . startsWith ( PREFIX_CONTEXT ) ) { result = s . substring ( PREFIX_CONTEXT . length ( ) ) ; } if ( s . startsWith ( PREFIX_THREAD_POOL ) ) { result = s . substring ( PREFIX_THREAD_POOL . length ( ) ) ; } return result ; } | Remove unnecessary prefix from Metrics meters id . |
8,551 | private void stopServer ( ) { final Server targetServer = this . getServer ( ) ; new Thread ( ) { public void run ( ) { try { targetServer . stop ( ) ; } catch ( Exception e ) { } } } . start ( ) ; } | Start a new thread to shutdown the server |
8,552 | private void instrument ( String id , int port , MetricRegistry registry ) { this . setPort ( port ) ; this . accepts = registry . meter ( id + "-accepts" ) ; this . connects = registry . meter ( id + "-connects" ) ; this . disconnects = registry . meter ( id + "-disconnects" ) ; this . connections = registry . counter ( id + "-active-connections" ) ; } | Create metrics . |
8,553 | public CloseableHttpResponse execute ( OutgoingRequest httpRequest ) throws HttpErrorPage { OutgoingRequestContext context = httpRequest . getContext ( ) ; IncomingRequest originalRequest = httpRequest . getOriginalRequest ( ) . getOriginalRequest ( ) ; if ( cookieManager != null ) { CookieStore cookieStore = new RequestCookieStore ( cookieManager , httpRequest . getOriginalRequest ( ) ) ; context . setCookieStore ( cookieStore ) ; } HttpResponse result ; FragmentEvent event = new FragmentEvent ( originalRequest , httpRequest , context ) ; eventManager . fire ( EventManager . EVENT_FRAGMENT_PRE , event ) ; if ( ! event . isExit ( ) ) { if ( event . getHttpResponse ( ) == null ) { if ( httpRequest . containsHeader ( HttpHeaders . EXPECT ) ) { event . setHttpResponse ( HttpErrorPage . generateHttpResponse ( HttpStatus . SC_EXPECTATION_FAILED , "'Expect' request header is not supported" ) ) ; } else { try { HttpHost physicalHost = context . getPhysicalHost ( ) ; result = httpClient . execute ( physicalHost , httpRequest , context ) ; } catch ( IOException e ) { result = HttpErrorPage . generateHttpResponse ( e ) ; LOG . warn ( httpRequest . getRequestLine ( ) + " -> " + result . getStatusLine ( ) . toString ( ) ) ; } event . setHttpResponse ( BasicCloseableHttpResponse . adapt ( result ) ) ; } } eventManager . fire ( EventManager . EVENT_FRAGMENT_POST , event ) ; } CloseableHttpResponse httpResponse = event . getHttpResponse ( ) ; if ( httpResponse == null ) { throw new HttpErrorPage ( HttpStatus . SC_INTERNAL_SERVER_ERROR , "Request was cancelled by server" , "Request was cancelled by server" ) ; } if ( HttpResponseUtils . isError ( httpResponse ) ) { throw new HttpErrorPage ( httpResponse ) ; } return httpResponse ; } | Execute a HTTP request . |
8,554 | public void init ( Properties properties ) { staleIfError = Parameters . STALE_IF_ERROR . getValue ( properties ) ; staleWhileRevalidate = Parameters . STALE_WHILE_REVALIDATE . getValue ( properties ) ; int maxAsynchronousWorkers = Parameters . MAX_ASYNCHRONOUS_WORKERS . getValue ( properties ) ; if ( staleWhileRevalidate > 0 && maxAsynchronousWorkers == 0 ) { throw new ConfigurationException ( "You must set a positive value for maxAsynchronousWorkers " + "in order to enable background revalidation (staleWhileRevalidate)" ) ; } ttl = Parameters . TTL . getValue ( properties ) ; xCacheHeader = Parameters . X_CACHE_HEADER . getValue ( properties ) ; viaHeader = Parameters . VIA_HEADER . getValue ( properties ) ; LOG . info ( "Initializing cache for provider " + Arrays . toString ( Parameters . REMOTE_URL_BASE . getValue ( properties ) ) + " staleIfError=" + staleIfError + " staleWhileRevalidate=" + staleWhileRevalidate + " ttl=" + ttl + " xCacheHeader=" + xCacheHeader + " viaHeader=" + viaHeader ) ; } | Inititalize the instance . |
8,555 | private static List < UriMapping > parseMappings ( Properties props ) { List < UriMapping > mappings = new ArrayList < > ( ) ; Collection < String > mappingsParam = Parameters . MAPPINGS . getValue ( props ) ; for ( String mappingParam : mappingsParam ) { mappings . add ( UriMapping . create ( mappingParam ) ) ; } return mappings ; } | Read the Mappings parameter and create the corresponding UriMapping rules . |
8,556 | public static String encodeCookie ( Cookie cookie ) { int maxAge = - 1 ; if ( cookie . getExpiryDate ( ) != null ) { maxAge = ( int ) ( ( cookie . getExpiryDate ( ) . getTime ( ) - System . currentTimeMillis ( ) ) / ONE_SECOND ) ; if ( maxAge < 0 ) { maxAge = 0 ; } } String cookieName = cookie . getName ( ) ; String cookieValue = cookie . getValue ( ) ; StringBuilder buffer = new StringBuilder ( ) ; if ( cookie . getVersion ( ) > 0 && ! isQuoteEnclosed ( cookieValue ) ) { buffer . append ( BasicHeaderValueFormatter . INSTANCE . formatHeaderElement ( null , new BasicHeaderElement ( cookieName , cookieValue ) , false ) . toString ( ) ) ; } else { buffer . append ( cookieName ) ; buffer . append ( "=" ) ; if ( cookieValue != null ) { buffer . append ( cookieValue ) ; } } appendAttribute ( buffer , "Comment" , cookie . getComment ( ) ) ; appendAttribute ( buffer , "Domain" , cookie . getDomain ( ) ) ; appendAttribute ( buffer , "Max-Age" , maxAge ) ; appendAttribute ( buffer , "Path" , cookie . getPath ( ) ) ; if ( cookie . isSecure ( ) ) { appendAttribute ( buffer , "Secure" ) ; } if ( ( ( BasicClientCookie ) cookie ) . containsAttribute ( HTTP_ONLY_ATTR ) ) { appendAttribute ( buffer , "HttpOnly" ) ; } appendAttribute ( buffer , "Version" , cookie . getVersion ( ) ) ; return ( buffer . toString ( ) ) ; } | Utility method to transform a Cookie into a Set - Cookie Header . |
8,557 | public static < T extends Extension > T getExtension ( Properties properties , Parameter < String > parameter , Driver d ) { T result ; String className = parameter . getValue ( properties ) ; if ( className == null ) { return null ; } try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Creating extension " + className ) ; } result = ( T ) Class . forName ( className ) . newInstance ( ) ; result . init ( d , properties ) ; } catch ( InstantiationException | IllegalAccessException | ClassNotFoundException e ) { throw new ConfigurationException ( e ) ; } return result ; } | Get an extension as configured in properties . |
8,558 | void characters ( CharSequence csq , int start , int end ) throws IOException { getCurrent ( ) . characters ( csq , start , end ) ; } | Writes characters into current writer . |
8,559 | private static int getProperty ( String prefix , String name , int defaultValue ) { int result = defaultValue ; try { result = Integer . parseInt ( System . getProperty ( prefix + name ) ) ; } catch ( NumberFormatException e ) { LOG . warn ( "Value for " + prefix + name + " must be an integer. Using default " + defaultValue ) ; } return result ; } | Get an integer from System properties |
8,560 | private static String getProperty ( String prefix , String name , String defaultValue ) { return System . getProperty ( prefix + name , defaultValue ) ; } | Get String from System properties |
8,561 | public static void init ( ) { String configFile = null ; Properties serverProperties = new Properties ( ) ; try { configFile = System . getProperty ( PROPERTY_PREFIX + "config" , "server.properties" ) ; LOG . info ( "Loading server configuration from " + configFile ) ; try ( InputStream is = new FileInputStream ( configFile ) ) { serverProperties . load ( is ) ; } } catch ( FileNotFoundException e ) { LOG . warn ( configFile + " not found." ) ; } catch ( IOException e ) { LOG . error ( "Unexpected error reading " + configFile ) ; } init ( serverProperties ) ; } | Read server configuration from System properties and from server . properties . |
8,562 | public static void init ( Properties configuration ) { for ( Object prop : configuration . keySet ( ) ) { String serverPropertyName = ( String ) prop ; System . setProperty ( PROPERTY_PREFIX + serverPropertyName , configuration . getProperty ( serverPropertyName ) ) ; } LOG . info ( "Using configuration provided using '-D' parameter and/or default values" ) ; EsigateServer . port = getProperty ( PROPERTY_PREFIX , "port" , PROPERTY_DEFAULT_HTTP_PORT ) ; EsigateServer . controlPort = getProperty ( PROPERTY_PREFIX , "controlPort" , PROPERTY_DEFAULT_CONTROL_PORT ) ; EsigateServer . contextPath = getProperty ( PROPERTY_PREFIX , "contextPath" , "/" ) ; EsigateServer . extraClasspath = getProperty ( PROPERTY_PREFIX , "extraClasspath" , null ) ; EsigateServer . maxThreads = getProperty ( PROPERTY_PREFIX , "maxThreads" , 500 ) ; EsigateServer . minThreads = getProperty ( PROPERTY_PREFIX , "minThreads" , 40 ) ; EsigateServer . outputBufferSize = getProperty ( PROPERTY_PREFIX , "outputBufferSize" , 8 * 1024 ) ; EsigateServer . idleTimeout = getProperty ( PROPERTY_PREFIX , "idleTimeout" , 30 * 1000 ) ; EsigateServer . sessionCookieName = getProperty ( PROPERTY_PREFIX , "sessionCookieName" , null ) ; } | Set the provided server configuration then read configuration from System properties or load defaults . |
8,563 | public static void main ( String [ ] args ) throws Exception { if ( args . length < 1 ) { EsigateServer . usage ( ) ; return ; } switch ( args [ 0 ] ) { case "start" : EsigateServer . init ( ) ; EsigateServer . start ( ) ; break ; case "stop" : EsigateServer . stop ( ) ; break ; default : EsigateServer . usage ( ) ; break ; } } | Esigate Server entry point . |
8,564 | public static void start ( ) throws Exception { MetricRegistry registry = new MetricRegistry ( ) ; QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool ( registry ) ; threadPool . setName ( "esigate" ) ; threadPool . setMaxThreads ( maxThreads ) ; threadPool . setMinThreads ( minThreads ) ; srv = new Server ( threadPool ) ; srv . setStopAtShutdown ( true ) ; srv . setStopTimeout ( 5000 ) ; HttpConfiguration httpConfig = new HttpConfiguration ( ) ; httpConfig . setOutputBufferSize ( outputBufferSize ) ; httpConfig . setSendServerVersion ( false ) ; Timer processTime = registry . timer ( "processTime" ) ; try ( ServerConnector connector = new InstrumentedServerConnector ( "main" , EsigateServer . port , srv , registry , new InstrumentedConnectionFactory ( new HttpConnectionFactory ( httpConfig ) , processTime ) ) ; ServerConnector controlConnector = new ServerConnector ( srv ) ) { connector . setIdleTimeout ( EsigateServer . idleTimeout ) ; connector . setSoLingerTime ( - 1 ) ; connector . setName ( "main" ) ; connector . setAcceptQueueSize ( 200 ) ; controlConnector . setHost ( "127.0.0.1" ) ; controlConnector . setPort ( EsigateServer . controlPort ) ; controlConnector . setName ( "control" ) ; srv . setConnectors ( new Connector [ ] { connector , controlConnector } ) ; ProtectionDomain protectionDomain = EsigateServer . class . getProtectionDomain ( ) ; String warFile = protectionDomain . getCodeSource ( ) . getLocation ( ) . toExternalForm ( ) ; String currentDir = new File ( protectionDomain . getCodeSource ( ) . getLocation ( ) . getPath ( ) ) . getParent ( ) ; File workDir = resetTempDirectory ( currentDir ) ; WebAppContext context = new WebAppContext ( warFile , EsigateServer . contextPath ) ; context . setServer ( srv ) ; context . setTempDirectory ( workDir ) ; if ( StringUtils . isNoneEmpty ( sessionCookieName ) ) { context . getSessionHandler ( ) . getSessionManager ( ) . getSessionCookieConfig ( ) . setName ( sessionCookieName ) ; } if ( EsigateServer . extraClasspath != null ) { context . setExtraClasspath ( EsigateServer . extraClasspath ) ; } HandlerCollection handlers = new HandlerList ( ) ; handlers . addHandler ( new ControlHandler ( registry ) ) ; InstrumentedHandler ih = new InstrumentedHandler ( registry ) ; ih . setName ( "main" ) ; ih . setHandler ( context ) ; handlers . addHandler ( ih ) ; srv . setHandler ( handlers ) ; srv . start ( ) ; srv . join ( ) ; } } | Create and start server . |
8,565 | private static void usage ( ) { StringBuilder usageText = new StringBuilder ( ) ; usageText . append ( "Usage: java -D" ) . append ( PROPERTY_PREFIX ) . append ( "config=esigate.properties -jar esigate-server.jar [start|stop]\n\t" ) ; usageText . append ( "start Start the server (default)\n\t" ) ; usageText . append ( "stop Stop the server gracefully\n\t" ) ; System . out . println ( usageText . toString ( ) ) ; System . exit ( - 1 ) ; } | Display usage information . |
8,566 | public static String encodeIllegalCharacters ( String uri ) { StringBuilder result = new StringBuilder ( ) ; int length = uri . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { char character = uri . charAt ( i ) ; if ( character == '%' ) { if ( i >= length - 2 || ! isHex ( uri . charAt ( i + 1 ) ) || ! isHex ( uri . charAt ( i + 2 ) ) ) { result . append ( "%25" ) ; } else { result . append ( '%' ) ; } } else { int j = ( int ) character ; if ( j >= CONVERSION_TABLE_SIZE || j < 0 ) { result . append ( encode ( character ) ) ; } else { result . append ( CONVERSION_TABLE [ j ] ) ; } } } return result . toString ( ) ; } | Fixes common mistakes in URI by replacing all illegal characters by their encoded value . |
8,567 | public static String createURI ( final String scheme , final String host , int port , final String path , final String query , final String fragment ) { StringBuilder buffer = new StringBuilder ( Parameters . SMALL_BUFFER_SIZE ) ; if ( host != null ) { if ( scheme != null ) { buffer . append ( scheme ) ; buffer . append ( "://" ) ; } buffer . append ( host ) ; if ( port > 0 ) { buffer . append ( ':' ) ; buffer . append ( port ) ; } } if ( path == null || ! path . startsWith ( "/" ) ) { buffer . append ( '/' ) ; } if ( path != null ) { buffer . append ( path ) ; } if ( query != null ) { buffer . append ( '?' ) ; buffer . append ( query ) ; } if ( fragment != null ) { buffer . append ( '#' ) ; buffer . append ( fragment ) ; } return buffer . toString ( ) ; } | Creates an URI as a String . |
8,568 | public static String rewriteURI ( String uri , HttpHost targetHost ) { try { return URIUtils . rewriteURI ( createURI ( uri ) , targetHost ) . toString ( ) ; } catch ( URISyntaxException e ) { throw new InvalidUriException ( e ) ; } } | Replaces the scheme host and port in a URI . |
8,569 | public static String removeSessionId ( String sessionId , String page ) { String regexp = ";?jsessionid=" + Pattern . quote ( sessionId ) ; return page . replaceAll ( regexp , "" ) ; } | Removes the jsessionid that may have been added to a URI on a java application server . |
8,570 | public static String removeQuerystring ( String uriString ) { URI uri = createURI ( uriString ) ; try { return new URI ( uri . getScheme ( ) , uri . getUserInfo ( ) , uri . getHost ( ) , uri . getPort ( ) , uri . getPath ( ) , null , null ) . toASCIIString ( ) ; } catch ( URISyntaxException e ) { throw new InvalidUriException ( e ) ; } } | Removes the query and fragment at the end of a URI . |
8,571 | public static String formatDate ( Date date ) { return org . apache . http . client . utils . DateUtils . formatDate ( date ) ; } | Formats the given date according to the RFC 1123 pattern . |
8,572 | static ElementAttributes createElementAttributes ( String tag ) { Pattern pattern = Pattern . compile ( "(?<=\\$)(?:[^\\$]|\\$\\()*(?=\\$)" ) ; Matcher matcher = pattern . matcher ( tag ) ; List < String > listparameters = new ArrayList < > ( ) ; while ( matcher . find ( ) ) { listparameters . add ( matcher . group ( ) ) ; } String [ ] parameters = listparameters . toArray ( new String [ listparameters . size ( ) ] ) ; Driver driver ; String page = "" ; String name = null ; if ( parameters . length > 1 ) { driver = DriverFactory . getInstance ( parameters [ 1 ] ) ; } else { driver = DriverFactory . getInstance ( ) ; } if ( parameters . length > 2 ) { page = parameters [ 2 ] ; } if ( parameters . length > 3 ) { name = parameters [ 3 ] ; } return new ElementAttributes ( driver , page , name ) ; } | Parse the tag and return the ElementAttributes |
8,573 | public boolean isTextContentType ( HttpResponse httpResponse ) { String contentType = HttpResponseUtils . getFirstHeader ( HttpHeaders . CONTENT_TYPE , httpResponse ) ; return isTextContentType ( contentType ) ; } | Check whether the given request s content - type corresponds to parseable text . |
8,574 | public boolean isTextContentType ( String contentType ) { if ( contentType != null ) { String lowerContentType = contentType . toLowerCase ( ) ; for ( String textContentType : this . parsableContentTypes ) { if ( lowerContentType . startsWith ( textContentType ) ) { return true ; } } } return false ; } | Check whether the given content - type corresponds to parseable text . |
8,575 | public static void configure ( ) { InputStream inputStream = null ; try { URL configUrl = getConfigUrl ( ) ; if ( configUrl == null ) { throw new ConfigurationException ( "esigate.properties configuration file " + "was not found in the classpath" ) ; } inputStream = configUrl . openStream ( ) ; Properties merged = new Properties ( ) ; if ( inputStream != null ) { Properties props = new Properties ( ) ; props . load ( inputStream ) ; merged . putAll ( props ) ; } configure ( merged ) ; } catch ( IOException e ) { throw new ConfigurationException ( "Error loading configuration" , e ) ; } finally { try { if ( inputStream != null ) { inputStream . close ( ) ; } } catch ( IOException e ) { throw new ConfigurationException ( "failed to close stream" , e ) ; } } } | Loads all instances according to default configuration file . |
8,576 | public static void configure ( Properties props ) { Properties defaultProperties = new Properties ( ) ; HashMap < String , Properties > driversProps = new HashMap < > ( ) ; for ( Enumeration < ? > enumeration = props . propertyNames ( ) ; enumeration . hasMoreElements ( ) ; ) { String propertyName = ( String ) enumeration . nextElement ( ) ; String value = props . getProperty ( propertyName ) ; int idx = propertyName . lastIndexOf ( '.' ) ; if ( idx < 0 ) { defaultProperties . put ( propertyName , value ) ; } else { String prefix = propertyName . substring ( 0 , idx ) ; String name = propertyName . substring ( idx + 1 ) ; Properties driverProperties = driversProps . get ( prefix ) ; if ( driverProperties == null ) { driverProperties = new Properties ( ) ; driversProps . put ( prefix , driverProperties ) ; } driverProperties . put ( name , value ) ; } } Map < String , Driver > newInstances = new HashMap < > ( ) ; for ( Entry < String , Properties > entry : driversProps . entrySet ( ) ) { String name = entry . getKey ( ) ; Properties properties = new Properties ( ) ; properties . putAll ( defaultProperties ) ; properties . putAll ( entry . getValue ( ) ) ; newInstances . put ( name , createDriver ( name , properties ) ) ; } if ( newInstances . get ( DEFAULT_INSTANCE_NAME ) == null && Parameters . REMOTE_URL_BASE . getValue ( defaultProperties ) != null ) { newInstances . put ( DEFAULT_INSTANCE_NAME , createDriver ( DEFAULT_INSTANCE_NAME , defaultProperties ) ) ; } instances = new IndexedInstances ( newInstances ) ; } | Loads all instances according to the properties parameter . |
8,577 | static MatchedRequest selectProvider ( IncomingRequest request ) throws HttpErrorPage { URI requestURI = UriUtils . createURI ( request . getRequestLine ( ) . getUri ( ) ) ; String host = UriUtils . extractHost ( requestURI ) . toHostString ( ) ; Header hostHeader = request . getFirstHeader ( HttpHeaders . HOST ) ; if ( hostHeader != null ) { host = hostHeader . getValue ( ) ; } String scheme = requestURI . getScheme ( ) ; String relativeUri = requestURI . getPath ( ) ; String contextPath = request . getContextPath ( ) ; if ( ! StringUtils . isEmpty ( contextPath ) && relativeUri . startsWith ( contextPath ) ) { relativeUri = relativeUri . substring ( contextPath . length ( ) ) ; } Driver driver = null ; UriMapping uriMapping = null ; for ( UriMapping mapping : instances . getUrimappings ( ) . keySet ( ) ) { if ( mapping . matches ( scheme , host , relativeUri ) ) { driver = getInstance ( instances . getUrimappings ( ) . get ( mapping ) ) ; uriMapping = mapping ; break ; } } if ( driver == null ) { throw new HttpErrorPage ( HttpStatus . SC_NOT_FOUND , "Not found" , "No mapping defined for this URI." ) ; } if ( driver . getConfiguration ( ) . isStripMappingPath ( ) ) { relativeUri = DriverFactory . stripMappingPath ( relativeUri , uriMapping ) ; } MatchedRequest context = new MatchedRequest ( driver , relativeUri ) ; LOG . debug ( "Selected {} for scheme:{} host:{} relUrl:{}" , driver , scheme , host , relativeUri ) ; return context ; } | Selects the Driver instance for this request based on the mappings declared in the configuration . |
8,578 | public static String replaceAllVariables ( String strVars , DriverRequest request ) { String result = strVars ; if ( VariablesResolver . containsVariable ( strVars ) ) { Matcher matcher = VAR_PATTERN . matcher ( strVars ) ; while ( matcher . find ( ) ) { String group = matcher . group ( ) ; String var = group . substring ( 2 , group . length ( ) - 1 ) ; String arg = null ; int argIndex = var . indexOf ( '{' ) ; if ( argIndex != - 1 ) { arg = VarUtils . removeSimpleQuotes ( var . substring ( argIndex + 1 , var . indexOf ( '}' ) ) ) ; } String defaultValue = StringUtils . EMPTY ; int defaultValueIndex = var . indexOf ( '|' ) ; if ( defaultValueIndex != - 1 ) { defaultValue = VarUtils . removeSimpleQuotes ( var . substring ( defaultValueIndex + 1 ) ) ; } String value = getProperty ( var , arg , request ) ; if ( value == null ) { value = defaultValue ; } result = result . replace ( group , value ) ; } } return result ; } | Replace all ESI variables found in strVars by their matching value in vars . properties . |
8,579 | public void register ( EventDefinition eventDefinition , IEventListener listener ) { if ( eventDefinition . getType ( ) == EventDefinition . TYPE_POST ) { register ( listenersPost , eventDefinition , listener , true ) ; } else { register ( listeners , eventDefinition , listener , false ) ; } } | Start listening to an event . |
8,580 | public void fire ( EventDefinition eventDefinition , Event eventDetails ) { if ( eventDefinition . getType ( ) == EventDefinition . TYPE_POST ) { fire ( listenersPost , eventDefinition , eventDetails ) ; } else { fire ( listeners , eventDefinition , eventDetails ) ; } } | Fire a new event and run all the listeners . |
8,581 | public void unregister ( EventDefinition eventDefinition , IEventListener eventListener ) { if ( eventDefinition . getType ( ) == EventDefinition . TYPE_POST ) { unregister ( listenersPost , eventDefinition , eventListener ) ; } else { unregister ( listeners , eventDefinition , eventListener ) ; } } | Stop listening to an event . |
8,582 | public static void moveHeader ( HttpResponse response , String srcName , String targetName ) { if ( response . containsHeader ( srcName ) ) { LOG . info ( "Moving header {} to {}" , srcName , targetName ) ; Header [ ] headers = response . getHeaders ( srcName ) ; response . removeHeaders ( targetName ) ; for ( Header h : headers ) { response . addHeader ( targetName , h . getValue ( ) ) ; } response . removeHeaders ( srcName ) ; } } | This method can be used directly to move an header . |
8,583 | public CloseableHttpResponse render ( String pageUrl , IncomingRequest incomingRequest , Renderer ... renderers ) throws IOException , HttpErrorPage { DriverRequest driverRequest = new DriverRequest ( incomingRequest , this , pageUrl ) ; String resultingPageUrl = VariablesResolver . replaceAllVariables ( pageUrl , driverRequest ) ; String targetUrl = ResourceUtils . getHttpUrlWithQueryString ( resultingPageUrl , driverRequest , false ) ; String currentValue ; CloseableHttpResponse response ; String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl ; Pair < String , CloseableHttpResponse > cachedValue = incomingRequest . getAttribute ( cacheKey ) ; if ( cachedValue == null ) { OutgoingRequest outgoingRequest = requestExecutor . createOutgoingRequest ( driverRequest , targetUrl , false ) ; headerManager . copyHeaders ( driverRequest , outgoingRequest ) ; response = requestExecutor . execute ( outgoingRequest ) ; int redirects = MAX_REDIRECTS ; try { while ( redirects > 0 && this . redirectStrategy . isRedirected ( outgoingRequest , response , outgoingRequest . getContext ( ) ) ) { EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; redirects -- ; outgoingRequest = this . requestExecutor . createOutgoingRequest ( driverRequest , this . redirectStrategy . getLocationURI ( outgoingRequest , response , outgoingRequest . getContext ( ) ) . toString ( ) , false ) ; this . headerManager . copyHeaders ( driverRequest , outgoingRequest ) ; response = requestExecutor . execute ( outgoingRequest ) ; } } catch ( ProtocolException e ) { throw new HttpErrorPage ( HttpStatus . SC_BAD_GATEWAY , "Invalid response from server" , e ) ; } response = this . headerManager . copyHeaders ( outgoingRequest , incomingRequest , response ) ; currentValue = HttpResponseUtils . toString ( response , this . eventManager ) ; cachedValue = new ImmutablePair < > ( currentValue , response ) ; incomingRequest . setAttribute ( cacheKey , cachedValue ) ; } currentValue = cachedValue . getKey ( ) ; response = cachedValue . getValue ( ) ; logAction ( "render" , pageUrl , renderers ) ; currentValue = performRendering ( pageUrl , driverRequest , response , currentValue , renderers ) ; response . setEntity ( new StringEntity ( currentValue , HttpResponseUtils . getContentType ( response ) ) ) ; return response ; } | Perform rendering on a single url content and append result to writer . Automatically follows redirects |
8,584 | public CloseableHttpResponse proxy ( String relUrl , IncomingRequest incomingRequest , Renderer ... renderers ) throws IOException , HttpErrorPage { DriverRequest driverRequest = new DriverRequest ( incomingRequest , this , relUrl ) ; driverRequest . setCharacterEncoding ( this . config . getUriEncoding ( ) ) ; boolean postProxyPerformed = false ; ProxyEvent e = new ProxyEvent ( incomingRequest ) ; this . eventManager . fire ( EventManager . EVENT_PROXY_PRE , e ) ; if ( e . isExit ( ) ) { return e . getResponse ( ) ; } logAction ( "proxy" , relUrl , renderers ) ; String url = ResourceUtils . getHttpUrlWithQueryString ( relUrl , driverRequest , true ) ; OutgoingRequest outgoingRequest = requestExecutor . createOutgoingRequest ( driverRequest , url , true ) ; headerManager . copyHeaders ( driverRequest , outgoingRequest ) ; try { CloseableHttpResponse response = requestExecutor . execute ( outgoingRequest ) ; response = headerManager . copyHeaders ( outgoingRequest , incomingRequest , response ) ; e . setResponse ( response ) ; e . setResponse ( performRendering ( relUrl , driverRequest , e . getResponse ( ) , renderers ) ) ; postProxyPerformed = true ; this . eventManager . fire ( EventManager . EVENT_PROXY_POST , e ) ; return e . getResponse ( ) ; } catch ( HttpErrorPage errorPage ) { e . setErrorPage ( errorPage ) ; CloseableHttpResponse response = e . getErrorPage ( ) . getHttpResponse ( ) ; response = headerManager . copyHeaders ( outgoingRequest , incomingRequest , response ) ; e . setErrorPage ( new HttpErrorPage ( performRendering ( relUrl , driverRequest , response , renderers ) ) ) ; postProxyPerformed = true ; this . eventManager . fire ( EventManager . EVENT_PROXY_POST , e ) ; throw e . getErrorPage ( ) ; } finally { if ( ! postProxyPerformed ) { this . eventManager . fire ( EventManager . EVENT_PROXY_POST , e ) ; } } } | Retrieves a resource from the provider application and transforms it using the Renderer passed as a parameter . |
8,585 | public static String getFirstHeader ( String headerName , HttpResponse httpResponse ) { Header header = httpResponse . getFirstHeader ( headerName ) ; if ( header != null ) { return header . getValue ( ) ; } return null ; } | Get the value of the first header matching headerName . |
8,586 | public CloseableHttpResponse copyHeaders ( OutgoingRequest outgoingRequest , HttpEntityEnclosingRequest incomingRequest , HttpResponse httpClientResponse ) { HttpResponse result = new BasicHttpResponse ( httpClientResponse . getStatusLine ( ) ) ; result . setEntity ( httpClientResponse . getEntity ( ) ) ; String originalUri = incomingRequest . getRequestLine ( ) . getUri ( ) ; String baseUrl = outgoingRequest . getBaseUrl ( ) . toString ( ) ; String visibleBaseUrl = outgoingRequest . getOriginalRequest ( ) . getVisibleBaseUrl ( ) ; for ( Header header : httpClientResponse . getAllHeaders ( ) ) { String name = header . getName ( ) ; String value = header . getValue ( ) ; try { if ( ! HttpHeaders . CONTENT_ENCODING . equalsIgnoreCase ( name ) ) { if ( isForwardedResponseHeader ( name ) ) { if ( HttpHeaders . LOCATION . equalsIgnoreCase ( name ) || HttpHeaders . CONTENT_LOCATION . equalsIgnoreCase ( name ) ) { value = urlRewriter . rewriteUrl ( value , originalUri , baseUrl , visibleBaseUrl , true ) ; value = HttpResponseUtils . removeSessionId ( value , httpClientResponse ) ; result . addHeader ( name , value ) ; } else if ( "Link" . equalsIgnoreCase ( name ) ) { if ( value . startsWith ( "<" ) && value . contains ( ">" ) ) { String urlValue = value . substring ( 1 , value . indexOf ( ">" ) ) ; String targetUrlValue = urlRewriter . rewriteUrl ( urlValue , originalUri , baseUrl , visibleBaseUrl , true ) ; targetUrlValue = HttpResponseUtils . removeSessionId ( targetUrlValue , httpClientResponse ) ; value = value . replace ( "<" + urlValue + ">" , "<" + targetUrlValue + ">" ) ; } result . addHeader ( name , value ) ; } else if ( "Refresh" . equalsIgnoreCase ( name ) ) { int urlPosition = value . indexOf ( "url=" ) ; if ( urlPosition >= 0 ) { value = urlRewriter . rewriteRefresh ( value , originalUri , baseUrl , visibleBaseUrl ) ; value = HttpResponseUtils . removeSessionId ( value , httpClientResponse ) ; } result . addHeader ( name , value ) ; } else if ( "P3p" . equalsIgnoreCase ( name ) ) { result . addHeader ( name , value ) ; } else { result . addHeader ( header . getName ( ) , header . getValue ( ) ) ; } } } } catch ( Exception e1 ) { LOG . error ( "Error while copying headers" , e1 ) ; result . addHeader ( "X-Esigate-Error" , "Error processing header " + name + ": " + value ) ; } } return BasicCloseableHttpResponse . adapt ( result ) ; } | Copies end - to - end headers from a response received from the server to the response to be sent to the client . |
8,587 | public void add ( String toAdd ) { if ( toAdd . contains ( "*" ) ) { set . clear ( ) ; defaultContains = true ; } else { if ( ! defaultContains ) { set . add ( toAdd ) ; } else { set . remove ( toAdd ) ; } } } | Add some tokens to the list . By default the list is empty . If the list already contains the added tokens or everything this method will have no effect . |
8,588 | public void remove ( String toRemove ) { if ( toRemove . contains ( "*" ) ) { set . clear ( ) ; defaultContains = false ; } else { if ( defaultContains ) { set . add ( toRemove ) ; } else { set . remove ( toRemove ) ; } } } | Remove some tokens from the list . If the list is already empty or does not contains the tokens this method will have no effect . |
8,589 | private void updateEndCountText ( ) { final String END_COUNT_MARKER = "%d" ; String endString = mResources . getQuantityString ( R . plurals . recurrence_end_count , mModel . endCount ) ; int markerStart = endString . indexOf ( END_COUNT_MARKER ) ; if ( markerStart != - 1 ) { if ( markerStart == 0 ) { Log . e ( TAG , "No text to put in to recurrence's end spinner." ) ; } else { int postTextStart = markerStart + END_COUNT_MARKER . length ( ) ; mPostEndCount . setText ( endString . substring ( postTextStart , endString . length ( ) ) . trim ( ) ) ; } } } | Update the Repeat for N events end option with the proper string values based on the value that has been entered for N . |
8,590 | public void onCheckedChanged ( CompoundButton buttonView , boolean isChecked ) { int itemIdx = - 1 ; for ( int i = 0 ; i < 7 ; i ++ ) { if ( itemIdx == - 1 && buttonView == mWeekByDayButtons [ i ] ) { itemIdx = i ; mModel . weeklyByDayOfWeek [ i ] = isChecked ; } } updateDialog ( ) ; } | Week repeat by day of week |
8,591 | public void onCheckedChanged ( RadioGroup group , int checkedId ) { if ( checkedId == R . id . repeatMonthlyByNthDayOfMonth ) { mModel . monthlyRepeat = RecurrenceModel . MONTHLY_BY_DATE ; } else if ( checkedId == R . id . repeatMonthlyByNthDayOfTheWeek ) { mModel . monthlyRepeat = RecurrenceModel . MONTHLY_BY_NTH_DAY_OF_WEEK ; } updateDialog ( ) ; } | Month repeat by radio buttons |
8,592 | public static int calendarDay2Day ( int day ) { switch ( day ) { case Calendar . SUNDAY : return SU ; case Calendar . MONDAY : return MO ; case Calendar . TUESDAY : return TU ; case Calendar . WEDNESDAY : return WE ; case Calendar . THURSDAY : return TH ; case Calendar . FRIDAY : return FR ; case Calendar . SATURDAY : return SA ; default : throw new RuntimeException ( "bad day of week: " + day ) ; } } | Converts one of the Calendar . SUNDAY constants to the SU MO etc . constants . btw I think we should switch to those here too to get rid of this function if possible . |
8,593 | public void parse ( String recur ) { resetFields ( ) ; int parseFlags = 0 ; String [ ] parts ; if ( ALLOW_LOWER_CASE ) { parts = recur . toUpperCase ( ) . split ( ";" ) ; } else { parts = recur . split ( ";" ) ; } for ( String part : parts ) { if ( TextUtils . isEmpty ( part ) ) { continue ; } int equalIndex = part . indexOf ( '=' ) ; if ( equalIndex <= 0 ) { throw new InvalidFormatException ( "Missing LHS in " + part ) ; } String lhs = part . substring ( 0 , equalIndex ) ; String rhs = part . substring ( equalIndex + 1 ) ; if ( rhs . length ( ) == 0 ) { throw new InvalidFormatException ( "Missing RHS in " + part ) ; } PartParser parser = sParsePartMap . get ( lhs ) ; if ( parser == null ) { if ( lhs . startsWith ( "X-" ) ) { continue ; } throw new InvalidFormatException ( "Couldn't find parser for " + lhs ) ; } else { int flag = parser . parsePart ( rhs , this ) ; if ( ( parseFlags & flag ) != 0 ) { throw new InvalidFormatException ( "Part " + lhs + " was specified twice" ) ; } parseFlags |= flag ; } } if ( ( parseFlags & PARSED_WKST ) == 0 ) { wkst = MO ; } if ( ( parseFlags & PARSED_FREQ ) == 0 ) { throw new InvalidFormatException ( "Must specify a FREQ value" ) ; } if ( ( parseFlags & ( PARSED_UNTIL | PARSED_COUNT ) ) == ( PARSED_UNTIL | PARSED_COUNT ) ) { if ( ONLY_ONE_UNTIL_COUNT ) { throw new InvalidFormatException ( "Must not specify both UNTIL and COUNT: " + recur ) ; } else { Log . w ( TAG , "Warning: rrule has both UNTIL and COUNT: " + recur ) ; } } } | Parses an rfc2445 recurrence rule string into its component pieces . Attempting to parse malformed input will result in an EventRecurrence . InvalidFormatException . |
8,594 | public static boolean compareCursors ( Cursor c1 , Cursor c2 ) { if ( c1 == null || c2 == null ) { return false ; } int numColumns = c1 . getColumnCount ( ) ; if ( numColumns != c2 . getColumnCount ( ) ) { return false ; } if ( c1 . getCount ( ) != c2 . getCount ( ) ) { return false ; } c1 . moveToPosition ( - 1 ) ; c2 . moveToPosition ( - 1 ) ; while ( c1 . moveToNext ( ) && c2 . moveToNext ( ) ) { for ( int i = 0 ; i < numColumns ; i ++ ) { if ( ! TextUtils . equals ( c1 . getString ( i ) , c2 . getString ( i ) ) ) { return false ; } } } return true ; } | Compares two cursors to see if they contain the same data . |
8,595 | public static int getFirstDayOfWeek ( Context context ) { int startDay = Calendar . getInstance ( ) . getFirstDayOfWeek ( ) ; if ( startDay == Calendar . SATURDAY ) { return Time . SATURDAY ; } else if ( startDay == Calendar . MONDAY ) { return Time . MONDAY ; } else { return Time . SUNDAY ; } } | Get first day of week as android . text . format . Time constant . |
8,596 | public static int convertDayOfWeekFromTimeToCalendar ( int timeDayOfWeek ) { switch ( timeDayOfWeek ) { case Time . MONDAY : return Calendar . MONDAY ; case Time . TUESDAY : return Calendar . TUESDAY ; case Time . WEDNESDAY : return Calendar . WEDNESDAY ; case Time . THURSDAY : return Calendar . THURSDAY ; case Time . FRIDAY : return Calendar . FRIDAY ; case Time . SATURDAY : return Calendar . SATURDAY ; case Time . SUNDAY : return Calendar . SUNDAY ; default : throw new IllegalArgumentException ( "Argument must be between Time.SUNDAY and " + "Time.SATURDAY" ) ; } } | Converts the day of the week from android . text . format . Time to java . util . Calendar |
8,597 | public static boolean isSaturday ( int column , int firstDayOfWeek ) { return ( firstDayOfWeek == Time . SUNDAY && column == 6 ) || ( firstDayOfWeek == Time . MONDAY && column == 5 ) || ( firstDayOfWeek == Time . SATURDAY && column == 0 ) ; } | Determine whether the column position is Saturday or not . |
8,598 | public static boolean isSunday ( int column , int firstDayOfWeek ) { return ( firstDayOfWeek == Time . SUNDAY && column == 0 ) || ( firstDayOfWeek == Time . MONDAY && column == 6 ) || ( firstDayOfWeek == Time . SATURDAY && column == 1 ) ; } | Determine whether the column position is Sunday or not . |
8,599 | public static long convertAlldayUtcToLocal ( Time recycle , long utcTime , String tz ) { if ( recycle == null ) { recycle = new Time ( ) ; } recycle . timezone = Time . TIMEZONE_UTC ; recycle . set ( utcTime ) ; recycle . timezone = tz ; return recycle . normalize ( true ) ; } | Convert given UTC time into current local time . This assumes it is for an allday event and will adjust the time to be on a midnight boundary . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.