idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
40,800
|
private void tryToEliminateTheScope ( ) { for ( int i = 0 ; i < _statements . length ; i ++ ) { Statement statement = _statements [ i ] ; if ( statement instanceof VarStatement || ( ! ( statement instanceof StatementList ) && statement . getContainedParsedElementsByType ( EvalExpression . class , null ) ) ) { return ; } } setNoScope ( ) ; }
|
A statement - list needs to push a new scope on the symbol table to provide a for local variable scoping . Since this is a relatively expensive operation we avoid pushing the scope if we know none of the statements declare variables .
|
40,801
|
public static String escapeAttribute ( String string ) { if ( string == null || string . length ( ) == 0 ) { return string ; } StringBuilder resultBuffer = null ; for ( int i = 0 , length = string . length ( ) ; i < length ; i ++ ) { String entity = null ; char ch = string . charAt ( i ) ; switch ( ch ) { case '"' : entity = """ ; break ; case '&' : entity = "&" ; break ; default : break ; } if ( entity != null ) { if ( resultBuffer == null ) { resultBuffer = new StringBuilder ( string ) ; resultBuffer . setLength ( i ) ; } resultBuffer . append ( entity ) ; } else if ( resultBuffer != null ) { resultBuffer . append ( ch ) ; } } return ( resultBuffer != null ) ? resultBuffer . toString ( ) : string ; }
|
Escape a string for use as an HTML attribute by replacing all double quotes and & .
|
40,802
|
public static Map < String , ISettings > makeDefaultSettings ( Experiment experiment ) { Map < String , ISettings > settings = new TreeMap < > ( ) ; CompilerSettings compilerSettings = new CompilerSettings ( ) ; compilerSettings . resetToDefaultSettings ( experiment ) ; settings . put ( compilerSettings . getPath ( ) , compilerSettings ) ; return settings ; }
|
Reset Experiment - specific settings to defaults .
|
40,803
|
public static Map < String , ISettings > makeDefaultSettings ( ) { Map < String , ISettings > settings = new TreeMap < > ( ) ; AppearanceSettings appearanceSettings = new AppearanceSettings ( ) ; appearanceSettings . resetToDefaultSettings ( null ) ; settings . put ( appearanceSettings . getPath ( ) , appearanceSettings ) ; return settings ; }
|
Reset Gosu Lab application - level settings to defaults .
|
40,804
|
public static Map < String , ISettings > mergeSettings ( Map < String , ISettings > old , Experiment experiment ) { Map < String , ISettings > defaultSettings = makeDefaultSettings ( experiment ) ; old . keySet ( ) . forEach ( key -> defaultSettings . put ( key , old . get ( key ) ) ) ; return defaultSettings ; }
|
Assumes settings map is ordered top - down in tree order
|
40,805
|
public void setSrcdir ( Path srcDir ) { if ( _src == null ) { _src = srcDir ; } else { _src . append ( srcDir ) ; } }
|
Set the source directories to find the source Gosu files .
|
40,806
|
public Curve25519KeyPair generateKeyPair ( ) { byte [ ] privateKey = provider . generatePrivateKey ( ) ; byte [ ] publicKey = provider . generatePublicKey ( privateKey ) ; return new Curve25519KeyPair ( publicKey , privateKey ) ; }
|
Generates a Curve25519 keypair .
|
40,807
|
public byte [ ] calculateAgreement ( byte [ ] publicKey , byte [ ] privateKey ) { if ( publicKey == null || privateKey == null ) { throw new IllegalArgumentException ( "Keys must not be null!" ) ; } if ( publicKey . length != 32 || privateKey . length != 32 ) { throw new IllegalArgumentException ( "Keys must be 32 bytes!" ) ; } return provider . calculateAgreement ( privateKey , publicKey ) ; }
|
Calculates an ECDH agreement .
|
40,808
|
public boolean verifySignature ( byte [ ] publicKey , byte [ ] message , byte [ ] signature ) { if ( publicKey == null || publicKey . length != 32 ) { throw new IllegalArgumentException ( "Invalid public key!" ) ; } if ( message == null || signature == null || signature . length != 64 ) { return false ; } return provider . verifySignature ( publicKey , message , signature ) ; }
|
Verify a Curve25519 signature .
|
40,809
|
public byte [ ] calculateVrfSignature ( byte [ ] privateKey , byte [ ] message ) { if ( privateKey == null || privateKey . length != 32 ) { throw new IllegalArgumentException ( "Invalid private key!" ) ; } byte [ ] random = provider . getRandom ( 64 ) ; return provider . calculateVrfSignature ( random , privateKey , message ) ; }
|
Calculates a Unique Curve25519 signature .
|
40,810
|
public byte [ ] verifyVrfSignature ( byte [ ] publicKey , byte [ ] message , byte [ ] signature ) throws VrfSignatureVerificationFailedException { if ( publicKey == null || publicKey . length != 32 ) { throw new IllegalArgumentException ( "Invalid public key!" ) ; } if ( message == null || signature == null || signature . length != 96 ) { throw new VrfSignatureVerificationFailedException ( "Invalid message or signature format" ) ; } return provider . verifyVrfSignature ( publicKey , message , signature ) ; }
|
Verify a Unique Curve25519 signature .
|
40,811
|
private Record setDefault ( Record record ) { int size = record . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) if ( record . get ( i ) == null ) { @ SuppressWarnings ( "unchecked" ) Field < Object > field = ( Field < Object > ) record . field ( i ) ; if ( ! field . getDataType ( ) . nullable ( ) && ! field . getDataType ( ) . identity ( ) ) record . set ( field , DSL . defaultValue ( ) ) ; } return record ; }
|
Defaults fields that have a default value and are nullable .
|
40,812
|
protected Object convertToAsyncDriverTypes ( Object object ) { if ( object instanceof Enum ) { return ( ( Enum ) object ) . name ( ) ; } else if ( object instanceof LocalDateTime ) { LocalDateTime convert = ( LocalDateTime ) object ; return new org . joda . time . LocalDateTime ( convert . getYear ( ) , convert . getMonthValue ( ) , convert . getDayOfMonth ( ) , convert . getHour ( ) , convert . getMinute ( ) , convert . getSecond ( ) , convert . get ( ChronoField . MILLI_OF_SECOND ) ) ; } else if ( object instanceof LocalDate ) { LocalDate convert = ( LocalDate ) object ; return new org . joda . time . LocalDate ( convert . getYear ( ) , convert . getMonthValue ( ) , convert . getDayOfMonth ( ) ) ; } else if ( object instanceof ZonedDateTime ) { ZonedDateTime convert = ( ZonedDateTime ) object ; return new org . joda . time . DateTime ( convert . getYear ( ) , convert . getMonthValue ( ) , convert . getDayOfMonth ( ) , convert . getHour ( ) , convert . getMinute ( ) , convert . getSecond ( ) , convert . get ( ChronoField . MILLI_OF_SECOND ) , DateTimeZone . forID ( convert . getZone ( ) . getId ( ) ) ) ; } else if ( object instanceof OffsetDateTime ) { OffsetDateTime obj = ( OffsetDateTime ) object ; ZonedDateTime convert = obj . toZonedDateTime ( ) ; org . joda . time . DateTime dt = new org . joda . time . DateTime ( convert . getYear ( ) , convert . getMonthValue ( ) , convert . getDayOfMonth ( ) , convert . getHour ( ) , convert . getMinute ( ) , convert . getSecond ( ) , convert . get ( ChronoField . MILLI_OF_SECOND ) , DateTimeZone . forID ( convert . getZone ( ) . getId ( ) ) ) ; return dt ; } else if ( object instanceof Instant ) { Instant convert = ( Instant ) object ; org . joda . time . Instant i = org . joda . time . Instant . parse ( convert . toString ( ) ) ; return i . toDateTime ( ) ; } return object ; }
|
Async - driver uses joda - time instead of java - time so we need to convert it .
|
40,813
|
public void sql ( BindingSQLContext < JsonArray > ctx ) { RenderContext context = ctx . render ( ) . visit ( DSL . val ( ctx . convert ( converter ( ) ) . value ( ) ) ) ; if ( SQLDialect . POSTGRES . equals ( ctx . configuration ( ) . dialect ( ) . family ( ) ) ) { context . sql ( "::json" ) ; } }
|
Rending a bind variable for the binding context s value and casting it to the json type
|
40,814
|
public void register ( BindingRegisterContext < JsonArray > ctx ) throws SQLException { ctx . statement ( ) . registerOutParameter ( ctx . index ( ) , Types . VARCHAR ) ; }
|
Registering VARCHAR types for JDBC CallableStatement OUT parameters
|
40,815
|
public void set ( BindingSetStatementContext < JsonArray > ctx ) throws SQLException { ctx . statement ( ) . setString ( ctx . index ( ) , Objects . toString ( ctx . convert ( converter ( ) ) . value ( ) , null ) ) ; }
|
Converting the JsonArray to a String value and setting that on a JDBC PreparedStatement
|
40,816
|
public void get ( BindingGetResultSetContext < JsonArray > ctx ) throws SQLException { ctx . convert ( converter ( ) ) . value ( ctx . resultSet ( ) . getString ( ctx . index ( ) ) ) ; }
|
Getting a String value from a JDBC ResultSet and converting that to a JsonArray
|
40,817
|
protected Collection < JavaWriter > writeExtraData ( SchemaDefinition definition , Function < File , JavaWriter > writerGenerator ) { return Collections . emptyList ( ) ; }
|
Write some extra data during code generation
|
40,818
|
protected void generateDao ( TableDefinition table , JavaWriter out1 ) { UniqueKeyDefinition key = table . getPrimaryKey ( ) ; if ( key == null ) { logger . info ( "Skipping DAO generation" , out1 . file ( ) . getName ( ) ) ; return ; } VertxJavaWriter out = ( VertxJavaWriter ) out1 ; generateDAO ( key , table , out ) ; }
|
copied from jOOQ s JavaGenerator
|
40,819
|
public void get ( BindingGetStatementContext < JsonObject > ctx ) throws SQLException { ctx . convert ( converter ( ) ) . value ( ctx . statement ( ) . getString ( ctx . index ( ) ) ) ; }
|
Getting a String value from a JDBC CallableStatement and converting that to a JsonObject
|
40,820
|
boolean startsWith ( final Literal literal ) { final int index = literal . getIndex ( ) ; final Boolean cached = myPrefixCache . get ( index ) ; if ( cached != null ) { return cached . booleanValue ( ) ; } final boolean result = literal . matches ( myChars , 0 ) ; myPrefixCache . set ( index , result ) ; return result ; }
|
Indicates whether this instance starts with the specified prefix .
|
40,821
|
boolean endsWith ( final Literal literal ) { final int index = literal . getIndex ( ) ; final Boolean cached = myPostfixCache . get ( index ) ; if ( cached != null ) { return cached . booleanValue ( ) ; } final boolean result = literal . matches ( myChars , myChars . length - literal . getLength ( ) ) ; myPostfixCache . set ( index , result ) ; return result ; }
|
Indicates whether this instance ends with the specified postfix .
|
40,822
|
int [ ] getIndices ( final Literal literal ) { final int index = literal . getIndex ( ) ; final int [ ] cached = myIndices [ index ] ; if ( cached != null ) { return cached ; } final int [ ] values = findIndices ( literal ) ; myIndices [ index ] = values ; return values ; }
|
Returns all indices where the literal argument can be found in this String . Results are cached for better performance .
|
40,823
|
private int [ ] findIndices ( final Literal literal ) { int count = 0 ; final char s = literal . getFirstChar ( ) ; for ( int i = 0 ; i < myChars . length ; i ++ ) { if ( ( myChars [ i ] == s || s == '?' ) && literal . matches ( myChars , i ) ) { myBuffer [ count ] = i ; count ++ ; } } if ( count == 0 ) { return EMPTY ; } if ( count == 1 && myBuffer [ 0 ] < SINGLE_VALUES . length ) { final int index = myBuffer [ 0 ] ; return SINGLE_VALUES [ index ] ; } final int [ ] values = new int [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { values [ i ] = myBuffer [ i ] ; } return values ; }
|
Returns all indices where the literal argument can be found in this String .
|
40,824
|
boolean matches ( final char [ ] value , final int from ) { final int len = myCharacters . length ; if ( len + from > value . length || from < 0 ) { return false ; } for ( int i = 0 ; i < len ; i ++ ) { if ( myCharacters [ i ] != value [ i + from ] && myCharacters [ i ] != '?' ) { return false ; } } return true ; }
|
Checks whether the value represents a complete substring from the from index .
|
40,825
|
boolean requires ( final String value ) { if ( requires ( myPrefix , value ) || requires ( myPostfix , value ) ) { return true ; } if ( mySuffixes == null ) { return false ; } for ( final Literal suffix : mySuffixes ) { if ( requires ( suffix , value ) ) { return true ; } } return false ; }
|
Tests whether this rule needs a specific string in the useragent to match .
|
40,826
|
private static int checkWildCard ( final SearchableString value , final Literal suffix , final int start ) { for ( final int index : value . getIndices ( suffix ) ) { if ( index >= start ) { return index ; } } return - 1 ; }
|
Return found index or - 1
|
40,827
|
String getPattern ( ) { final StringBuilder result = new StringBuilder ( ) ; if ( myPrefix != null ) { result . append ( myPrefix ) ; } if ( mySuffixes != null ) { result . append ( "*" ) ; for ( final Literal sub : mySuffixes ) { result . append ( sub ) ; result . append ( "*" ) ; } } if ( myPostfix != null ) { result . append ( myPostfix ) ; } return result . toString ( ) ; }
|
Returns the reconstructed original pattern .
|
40,828
|
static Rule [ ] getOrderedRules ( final Rule [ ] rules ) { final Comparator < Rule > c = Comparator . comparing ( Rule :: getSize ) . reversed ( ) . thenComparing ( Rule :: getPattern ) ; final Rule [ ] result = Arrays . copyOf ( rules , rules . length ) ; parallelSort ( result , c ) ; return result ; }
|
Sort by size and alphabet so the first match can be returned immediately
|
40,829
|
public static UserAgentParser parse ( final Reader input , final Collection < BrowsCapField > fields ) throws IOException , ParseException { return new UserAgentFileParser ( fields ) . parse ( input ) ; }
|
Parses a csv stream of rules .
|
40,830
|
public UserAgentParser loadParser ( ) throws IOException , ParseException { final Set < BrowsCapField > defaultFields = Stream . of ( BrowsCapField . values ( ) ) . filter ( BrowsCapField :: isDefault ) . collect ( toSet ( ) ) ; return createParserWithFields ( defaultFields ) ; }
|
Returns a parser based on the bundled BrowsCap version
|
40,831
|
private InputStream getCsvFileStream ( ) throws FileNotFoundException { if ( myZipFileStream == null ) { if ( myZipFilePath == null ) { final String csvFileName = getBundledCsvFileName ( ) ; return getClass ( ) . getClassLoader ( ) . getResourceAsStream ( csvFileName ) ; } else { return new FileInputStream ( myZipFilePath ) ; } } else { return myZipFileStream ; } }
|
Returns the InputStream to the CSV file . This is either the bundled ZIP file or the one passed in the constructor .
|
40,832
|
public static long sizeOfInstance ( Class < ? > type ) { long size = SPEC . getObjectHeaderSize ( ) + sizeOfDeclaredFields ( type ) ; while ( ( type = type . getSuperclass ( ) ) != Object . class && type != null ) size += roundTo ( sizeOfDeclaredFields ( type ) , SPEC . getSuperclassFieldPadding ( ) ) ; return roundTo ( size , SPEC . getObjectPadding ( ) ) ; }
|
sizeOfInstanceWithUnsafe is safe against this miscounting
|
40,833
|
public static long sizeOfInstanceWithUnsafe ( Class < ? > type ) { while ( type != null ) { long size = 0 ; for ( Field f : declaredFieldsOf ( type ) ) size = Math . max ( size , unsafe . objectFieldOffset ( f ) + sizeOf ( f ) ) ; if ( size > 0 ) return roundTo ( size , SPEC . getObjectPadding ( ) ) ; type = type . getSuperclass ( ) ; } return roundTo ( SPEC . getObjectHeaderSize ( ) , SPEC . getObjectPadding ( ) ) ; }
|
attemps to use sun . misc . Unsafe to find the maximum object offset this work around helps deal with long alignment
|
40,834
|
public static long sizeOfArray ( int length , long elementSize ) { return roundTo ( SPEC . getArrayHeaderSize ( ) + length * elementSize , SPEC . getObjectPadding ( ) ) ; }
|
Memory an array will consume
|
40,835
|
private static int getAlignment ( ) { RuntimeMXBean runtimeMxBean = ManagementFactory . getRuntimeMXBean ( ) ; for ( String arg : runtimeMxBean . getInputArguments ( ) ) { if ( arg . startsWith ( "-XX:ObjectAlignmentInBytes=" ) ) { try { return Integer . parseInt ( arg . substring ( "-XX:ObjectAlignmentInBytes=" . length ( ) ) ) ; } catch ( Exception e ) { } } } return 8 ; }
|
check if we have a non - standard object alignment we need to round to
|
40,836
|
public void configure ( Object obj , Element cfg , int startIdx ) throws Exception { String id = getAttribute ( cfg , "id" ) ; if ( id != null ) { _idMap . put ( id , obj ) ; } Element [ ] children = getChildren ( cfg ) ; for ( int i = startIdx ; i < children . length ; i ++ ) { Element node = children [ i ] ; try { String tag = node . getTagName ( ) ; if ( "Set" . equals ( tag ) ) { set ( obj , node ) ; } else if ( "Put" . equals ( tag ) ) { put ( obj , node ) ; } else if ( "Call" . equals ( tag ) ) { call ( obj , node ) ; } else if ( "Get" . equals ( tag ) ) { get ( obj , node ) ; } else if ( "New" . equals ( tag ) ) { newObj ( obj , node ) ; } else if ( "Array" . equals ( tag ) ) { newArray ( obj , node ) ; } else if ( "Ref" . equals ( tag ) ) { refObj ( obj , node ) ; } else if ( "Property" . equals ( tag ) ) { propertyObj ( obj , node ) ; } else { throw new IllegalStateException ( "Unknown tag: " + tag ) ; } } catch ( Exception e ) { LOG . warn ( "Config error at " + node , e . toString ( ) ) ; throw e ; } } }
|
Recursive configuration step . This method applies the remaining Set Put and Call elements to the current object .
|
40,837
|
protected void scanJspConfig ( ) throws IOException , SAXException { JspConfigDescriptor jspConfigDescriptor = context . getJspConfigDescriptor ( ) ; if ( jspConfigDescriptor == null ) { return ; } Collection < TaglibDescriptor > descriptors = jspConfigDescriptor . getTaglibs ( ) ; for ( TaglibDescriptor descriptor : descriptors ) { if ( descriptor == null ) { continue ; } String taglibURI = descriptor . getTaglibURI ( ) ; String resourcePath = descriptor . getTaglibLocation ( ) ; if ( ! resourcePath . startsWith ( "/" ) ) { resourcePath = WEB_INF + resourcePath ; } if ( uriTldResourcePathMap . containsKey ( taglibURI ) ) { LOG . warn ( Localizer . getMessage ( MSG + ".webxmlSkip" , resourcePath , taglibURI ) ) ; continue ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( Localizer . getMessage ( MSG + ".webxmlAdd" , resourcePath , taglibURI ) ) ; } URL url = context . getResource ( resourcePath ) ; if ( url != null ) { TldResourcePath tldResourcePath ; if ( resourcePath . endsWith ( ".jar" ) ) { tldResourcePath = new TldResourcePath ( url , resourcePath , "META-INF/taglib.tld" ) ; } else { tldResourcePath = new TldResourcePath ( url , resourcePath ) ; } TaglibXml tld = tldParser . parse ( tldResourcePath ) ; uriTldResourcePathMap . put ( taglibURI , tldResourcePath ) ; tldResourcePathTaglibXmlMap . put ( tldResourcePath , tld ) ; if ( tld . getListeners ( ) != null ) { listeners . addAll ( tld . getListeners ( ) ) ; } } else { LOG . warn ( Localizer . getMessage ( MSG + ".webxmlFailPathDoesNotExist" , resourcePath , taglibURI ) ) ; continue ; } } }
|
Scan for TLDs defined in < ; jsp - config> ; .
|
40,838
|
protected void scanResourcePaths ( String startPath ) throws IOException , SAXException { Set < String > dirList = context . getResourcePaths ( startPath ) ; if ( dirList != null ) { for ( String path : dirList ) { if ( path . startsWith ( "/WEB-INF/classes/" ) ) { } else if ( path . startsWith ( "/WEB-INF/lib/" ) ) { } else if ( path . endsWith ( "/" ) ) { scanResourcePaths ( path ) ; } else if ( path . startsWith ( "/WEB-INF/tags/" ) ) { if ( path . endsWith ( "/implicit.tld" ) ) { parseTld ( path ) ; } } else if ( path . endsWith ( TLD_EXT ) ) { parseTld ( path ) ; } } } }
|
Scan web application resources for TLDs recursively .
|
40,839
|
private void trackHttpContexts ( final BundleContext bundleContext , ExtendedHttpServiceRuntime httpServiceRuntime ) { final ServiceTracker < HttpContext , HttpContextElement > httpContextTracker = HttpContextTracker . createTracker ( extenderContext , bundleContext , httpServiceRuntime ) ; httpContextTracker . open ( ) ; trackers . add ( 0 , httpContextTracker ) ; final ServiceTracker < HttpContextMapping , HttpContextElement > httpContextMappingTracker = HttpContextMappingTracker . createTracker ( extenderContext , bundleContext , httpServiceRuntime ) ; httpContextMappingTracker . open ( ) ; trackers . add ( 0 , httpContextMappingTracker ) ; }
|
Track http contexts .
|
40,840
|
private void trackResources ( final BundleContext bundleContext ) { ServiceTracker < Object , ResourceWebElement > resourceTracker = ResourceTracker . createTracker ( extenderContext , bundleContext ) ; resourceTracker . open ( ) ; trackers . add ( 0 , resourceTracker ) ; final ServiceTracker < ResourceMapping , ResourceMappingWebElement > resourceMappingTracker = ResourceMappingTracker . createTracker ( extenderContext , bundleContext ) ; resourceMappingTracker . open ( ) ; trackers . add ( 0 , resourceMappingTracker ) ; }
|
Track resources .
|
40,841
|
private void trackFilters ( final BundleContext bundleContext ) { final ServiceTracker < Filter , FilterWebElement > filterTracker = FilterTracker . createTracker ( extenderContext , bundleContext ) ; filterTracker . open ( ) ; trackers . add ( 0 , filterTracker ) ; final ServiceTracker < FilterMapping , FilterMappingWebElement > filterMappingTracker = FilterMappingTracker . createTracker ( extenderContext , bundleContext ) ; filterMappingTracker . open ( ) ; trackers . add ( 0 , filterMappingTracker ) ; }
|
Track filters .
|
40,842
|
private void trackListeners ( final BundleContext bundleContext ) { final ServiceTracker < EventListener , ListenerWebElement > listenerTracker = ListenerTracker . createTracker ( extenderContext , bundleContext ) ; listenerTracker . open ( ) ; trackers . add ( 0 , listenerTracker ) ; final ServiceTracker < ListenerMapping , ListenerMappingWebElement > listenerMappingTracker = ListenerMappingTracker . createTracker ( extenderContext , bundleContext ) ; listenerMappingTracker . open ( ) ; trackers . add ( 0 , listenerMappingTracker ) ; }
|
Track listeners .
|
40,843
|
private void trackJspMappings ( final BundleContext bundleContext ) { final ServiceTracker < JspMapping , JspWebElement > jspMappingTracker = JspMappingTracker . createTracker ( extenderContext , bundleContext ) ; jspMappingTracker . open ( ) ; trackers . add ( 0 , jspMappingTracker ) ; }
|
Track JSPs .
|
40,844
|
private void trackWelcomeFiles ( final BundleContext bundleContext ) { final ServiceTracker < WelcomeFileMapping , WelcomeFileWebElement > welcomeFileTracker = WelcomeFileMappingTracker . createTracker ( extenderContext , bundleContext ) ; welcomeFileTracker . open ( ) ; trackers . add ( 0 , welcomeFileTracker ) ; }
|
Track welcome files
|
40,845
|
private void trackErrorPages ( final BundleContext bundleContext ) { final ServiceTracker < ErrorPageMapping , ErrorPageWebElement > errorPagesTracker = ErrorPageMappingTracker . createTracker ( extenderContext , bundleContext ) ; errorPagesTracker . open ( ) ; trackers . add ( 0 , errorPagesTracker ) ; }
|
Track error pages
|
40,846
|
public void sessionCreated ( final HttpSessionEvent event ) { counter ++ ; final HttpSession session = event . getSession ( ) ; final String id = session . getId ( ) ; SESSIONS . put ( id , session ) ; }
|
Fires whenever a new session is created .
|
40,847
|
public void sessionDestroyed ( final HttpSessionEvent event ) { final HttpSession session = event . getSession ( ) ; final String id = session . getId ( ) ; SESSIONS . remove ( id ) ; counter -- ; }
|
Fires whenever a session is destroyed .
|
40,848
|
public static synchronized List < Object > getAttributes ( final String name ) { final List < Object > data = new ArrayList < > ( ) ; for ( final String id : SESSIONS . keySet ( ) ) { final HttpSession session = SESSIONS . get ( id ) ; try { final Object o = session . getAttribute ( name ) ; data . add ( o ) ; } catch ( final Exception e ) { } } return data ; }
|
Return a list with all session values for a given attribute name .
|
40,849
|
public void start ( BundleContext bc ) throws Exception { httpServiceRef = bc . getServiceReference ( HttpService . class ) ; if ( httpServiceRef != null ) { httpService = ( HttpService ) bc . getService ( httpServiceRef ) ; httpService . registerServlet ( "/status" , new StatusServlet ( ) , null , null ) ; httpService . registerServlet ( "/status-with-auth" , new StatusServlet ( ) , null , new AuthHttpContext ( ) ) ; } }
|
Called whenever the OSGi framework starts our bundle
|
40,850
|
public void stop ( BundleContext bc ) throws Exception { if ( httpService != null ) { bc . ungetService ( httpServiceRef ) ; httpServiceRef = null ; httpService = null ; } }
|
Called whenever the OSGi framework stops our bundle
|
40,851
|
public void setAttribute ( final String name , Object value ) { if ( HttpContext . AUTHENTICATION_TYPE . equals ( name ) ) { handleAuthenticationType ( value ) ; } else if ( HttpContext . REMOTE_USER . equals ( name ) ) { handleRemoteUser ( value ) ; } super . setAttribute ( name , value ) ; }
|
Filter the setting of authentication related attributes . If one of HttpContext . AUTHENTICATION_TYPE or HTTPContext . REMOTE_USER set the corresponding values in original request .
|
40,852
|
private void handleAuthenticationType ( final Object authenticationType ) { if ( request != null ) { if ( authenticationType != null ) { if ( ! ( authenticationType instanceof String ) ) { final String message = "Attribute " + HttpContext . AUTHENTICATION_TYPE + " expected to be a String but was an [" + authenticationType . getClass ( ) + "]" ; LOG . error ( message ) ; throw new IllegalArgumentException ( message ) ; } } getOsgiAuth ( ) . setAuthMethod ( ( String ) authenticationType ) ; } else { LOG . warn ( "Authentication type cannot be set to " + authenticationType + ". HttpService specific authentication is disabled because the ServletRequest object cannot be used: " + "Expected to be an instance of " + Request . class . getName ( ) + " but got " + originalRequest . getClass ( ) . getName ( ) + "." ) ; } }
|
Handles setting of authentication type attribute .
|
40,853
|
private void handleRemoteUser ( final Object remoteUser ) { if ( request != null ) { Principal userPrincipal = null ; if ( remoteUser != null ) { if ( ! ( remoteUser instanceof String ) ) { final String message = "Attribute " + HttpContext . REMOTE_USER + " expected to be a String but was an [" + remoteUser . getClass ( ) + "]" ; LOG . error ( message ) ; throw new IllegalArgumentException ( message ) ; } userPrincipal = new User ( ( String ) remoteUser ) ; } getOsgiAuth ( ) . setUserPrincipal ( userPrincipal ) ; } else { LOG . warn ( "Remote user cannot be set to " + remoteUser + ". HttpService specific authentication is disabled because the ServletRequest object cannot be used: " + "Expected to be an instance of " + Request . class . getName ( ) + " but got " + originalRequest . getClass ( ) . getName ( ) + "." ) ; } }
|
Handles setting of remote user attribute .
|
40,854
|
public Compiler createCompiler ( ) { if ( jspCompiler != null ) { return jspCompiler ; } jspCompiler = null ; if ( options . getCompilerClassName ( ) != null ) { jspCompiler = createCompiler ( options . getCompilerClassName ( ) ) ; } else { if ( options . getCompiler ( ) == null ) { jspCompiler = createCompiler ( "org.apache.jasper.compiler.JDTCompiler" ) ; if ( jspCompiler == null ) { jspCompiler = createCompiler ( "org.apache.jasper.compiler.AntCompiler" ) ; } } else { jspCompiler = createCompiler ( "org.apache.jasper.compiler.AntCompiler" ) ; if ( jspCompiler == null ) { jspCompiler = createCompiler ( "org.apache.jasper.compiler.JDTCompiler" ) ; } } } if ( jspCompiler == null ) { throw new IllegalStateException ( Localizer . getMessage ( "jsp.error.compiler.config" , options . getCompilerClassName ( ) , options . getCompiler ( ) ) ) ; } jspCompiler . init ( this , jsw ) ; return jspCompiler ; }
|
Create a Compiler object based on some init param data . This is not done yet . Right now we re just hardcoding the actual compilers that are created .
|
40,855
|
public String resolveRelativeUri ( String uri ) { if ( uri . startsWith ( "/" ) || uri . startsWith ( File . separator ) ) { return uri ; } else { return baseURI + uri ; } }
|
Get the full value of a URI relative to this compilations context uses current file as the base .
|
40,856
|
public String getRealPath ( String path ) { if ( context != null ) { return context . getRealPath ( path ) ; } return path ; }
|
Gets the actual path of a URI relative to the context of the compilation .
|
40,857
|
public String getServletPackageName ( ) { if ( isTagFile ( ) ) { String className = tagInfo . getTagClassName ( ) ; int lastIndex = className . lastIndexOf ( '.' ) ; String pkgName = "" ; if ( lastIndex != - 1 ) { pkgName = className . substring ( 0 , lastIndex ) ; } return pkgName ; } else { String dPackageName = getDerivedPackageName ( ) ; if ( dPackageName . length ( ) == 0 ) { return basePackageName ; } return basePackageName + '.' + getDerivedPackageName ( ) ; } }
|
Package name for the generated class is make up of the base package name which is user settable and the derived package name . The derived package name directly mirrors the file hierarchy of the JSP page .
|
40,858
|
public void visit ( final WebAppServlet webAppServlet ) { NullArgumentException . validateNotNull ( webAppServlet , "Web app servlet" ) ; final String [ ] urlPatterns = webAppServlet . getAliases ( ) ; if ( urlPatterns == null || urlPatterns . length == 0 ) { LOG . warn ( "Servlet [" + webAppServlet + "] does not have any mapping. Skipped." ) ; } try { if ( webAppServlet instanceof WebAppJspServlet ) { webContainer . registerJspServlet ( urlPatterns , httpContext , ( ( WebAppJspServlet ) webAppServlet ) . getJspPath ( ) ) ; } else { Class < ? extends Servlet > servletClass = RegisterWebAppVisitorHS . loadClass ( Servlet . class , bundleClassLoader , webAppServlet . getServletClassName ( ) ) ; webContainer . registerServlet ( servletClass , urlPatterns , RegisterWebAppVisitorHS . convertInitParams ( webAppServlet . getInitParams ( ) ) , webAppServlet . getLoadOnStartup ( ) , webAppServlet . getAsyncSupported ( ) , webAppServlet . getMultipartConfig ( ) , httpContext ) ; } } catch ( Exception ignore ) { LOG . error ( REGISTRATION_EXCEPTION_SKIPPING , ignore ) ; } }
|
Registers servlets with web container .
|
40,859
|
public void visit ( final WebAppFilter webAppFilter ) { NullArgumentException . validateNotNull ( webAppFilter , "Web app filter" ) ; LOG . debug ( "registering filter: {}" , webAppFilter ) ; final String [ ] urlPatterns = webAppFilter . getUrlPatterns ( ) ; final String [ ] servletNames = webAppFilter . getServletNames ( ) ; if ( ( urlPatterns == null || urlPatterns . length == 0 ) && ( servletNames == null || servletNames . length == 0 ) ) { LOG . warn ( "Filter [" + webAppFilter + "] does not have any mapping. Skipped." ) ; } boolean asyncSupported = false ; if ( webAppFilter . getAsyncSupported ( ) != null ) { asyncSupported = webAppFilter . getAsyncSupported ( ) ; } try { String filterName = webAppFilter . getFilterName ( ) ; Class < ? extends Filter > filterClass = RegisterWebAppVisitorHS . loadClass ( Filter . class , bundleClassLoader , webAppFilter . getFilterClass ( ) ) ; webAppFilter . setFilterClass ( filterClass ) ; Dictionary < String , String > initParams = RegisterWebAppVisitorHS . convertInitParams ( webAppFilter . getInitParams ( ) ) ; DispatcherType [ ] dispatcherTypes = webAppFilter . getDispatcherTypes ( ) . toArray ( new DispatcherType [ webAppFilter . getDispatcherTypes ( ) . size ( ) ] ) ; StringBuilder dispatcherTypeString = new StringBuilder ( ) ; for ( int i = 0 ; i < dispatcherTypes . length ; i ++ ) { dispatcherTypeString . append ( dispatcherTypes [ i ] . name ( ) ) ; if ( i < dispatcherTypes . length ) { dispatcherTypeString . append ( "," ) ; } } initParams . put ( WebContainerConstants . FILTER_MAPPING_DISPATCHER , dispatcherTypeString . toString ( ) ) ; initParams . put ( WebContainerConstants . FILTER_NAME , filterName ) ; webContainer . registerFilter ( filterClass , urlPatterns , servletNames , initParams , asyncSupported , httpContext ) ; } catch ( Exception ignore ) { LOG . error ( REGISTRATION_EXCEPTION_SKIPPING , ignore ) ; } }
|
Registers filters with web container .
|
40,860
|
public void visit ( final WebAppListener webAppListener ) { NullArgumentException . validateNotNull ( webAppListener , "Web app listener" ) ; try { final EventListener listener = RegisterWebAppVisitorHS . newInstance ( EventListener . class , bundleClassLoader , webAppListener . getListenerClass ( ) ) ; webAppListener . setListener ( listener ) ; webContainer . registerEventListener ( listener , httpContext ) ; } catch ( Exception ignore ) { LOG . error ( REGISTRATION_EXCEPTION_SKIPPING , ignore ) ; } }
|
Registers listeners with web container .
|
40,861
|
public void visit ( final WebAppErrorPage webAppErrorPage ) { NullArgumentException . validateNotNull ( webAppErrorPage , "Web app error page" ) ; try { webContainer . registerErrorPage ( webAppErrorPage . getError ( ) , webAppErrorPage . getLocation ( ) , httpContext ) ; } catch ( Exception ignore ) { LOG . error ( REGISTRATION_EXCEPTION_SKIPPING , ignore ) ; } }
|
Registers error pages with web container .
|
40,862
|
private static void parseContextParams ( final ParamValueType contextParam , final WebApp webApp ) { final WebAppInitParam initParam = new WebAppInitParam ( ) ; initParam . setParamName ( contextParam . getParamName ( ) . getValue ( ) ) ; initParam . setParamValue ( contextParam . getParamValue ( ) . getValue ( ) ) ; webApp . addContextParam ( initParam ) ; }
|
Parses context params out of web . xml .
|
40,863
|
private static void parseSessionConfig ( final SessionConfigType sessionConfigType , final WebApp webApp ) { if ( sessionConfigType . getSessionTimeout ( ) != null ) { webApp . setSessionTimeout ( sessionConfigType . getSessionTimeout ( ) . getValue ( ) . toString ( ) ) ; } if ( sessionConfigType . getCookieConfig ( ) != null ) { CookieConfigType cookieConfig = sessionConfigType . getCookieConfig ( ) ; WebAppCookieConfig sessionCookieConfig = new WebAppCookieConfig ( ) ; if ( cookieConfig . getDomain ( ) != null ) { sessionCookieConfig . setDomain ( cookieConfig . getDomain ( ) . getValue ( ) ) ; } if ( cookieConfig . getHttpOnly ( ) != null ) { sessionCookieConfig . setHttpOnly ( cookieConfig . getHttpOnly ( ) . isValue ( ) ) ; } if ( cookieConfig . getMaxAge ( ) != null ) { sessionCookieConfig . setMaxAge ( cookieConfig . getMaxAge ( ) . getValue ( ) . intValue ( ) ) ; } if ( cookieConfig . getName ( ) != null ) { sessionCookieConfig . setName ( cookieConfig . getName ( ) . getValue ( ) ) ; } if ( cookieConfig . getPath ( ) != null ) { sessionCookieConfig . setPath ( cookieConfig . getPath ( ) . getValue ( ) ) ; } if ( cookieConfig . getSecure ( ) != null ) { sessionCookieConfig . setSecure ( cookieConfig . getSecure ( ) . isValue ( ) ) ; } webApp . setSessionCookieConfig ( sessionCookieConfig ) ; } if ( sessionConfigType . getTrackingMode ( ) != null ) { List < TrackingModeType > trackingMode = sessionConfigType . getTrackingMode ( ) ; for ( TrackingModeType trackingModeType : trackingMode ) { String value = trackingModeType . getValue ( ) ; webApp . addSessionTrackingMode ( value ) ; } } }
|
Parses session config out of web . xml .
|
40,864
|
private static void parseServlets ( final ServletType servletType , final WebApp webApp ) { final WebAppServlet servlet = new WebAppServlet ( ) ; servlet . setServletName ( servletType . getServletName ( ) . getValue ( ) ) ; if ( servletType . getServletClass ( ) != null ) { servlet . setServletClassName ( servletType . getServletClass ( ) . getValue ( ) ) ; webApp . addServlet ( servlet ) ; } else { String jspFile = servletType . getJspFile ( ) . getValue ( ) ; if ( jspFile != null ) { WebAppJspServlet jspServlet = new WebAppJspServlet ( ) ; jspServlet . setServletName ( servletType . getServletName ( ) . getValue ( ) ) ; jspServlet . setJspPath ( jspFile ) ; webApp . addServlet ( jspServlet ) ; } } servlet . setLoadOnStartup ( servletType . getLoadOnStartup ( ) ) ; if ( servletType . getAsyncSupported ( ) != null ) { servlet . setAsyncSupported ( servletType . getAsyncSupported ( ) . isValue ( ) ) ; } MultipartConfigType multipartConfig = servletType . getMultipartConfig ( ) ; if ( multipartConfig != null ) { String location ; if ( multipartConfig . getLocation ( ) == null ) { location = null ; } else { location = multipartConfig . getLocation ( ) . getValue ( ) ; } long maxFileSize ; if ( multipartConfig . getMaxFileSize ( ) == null ) { maxFileSize = - 1L ; } else { maxFileSize = multipartConfig . getMaxFileSize ( ) ; } long maxRequestSize ; if ( multipartConfig . getMaxRequestSize ( ) == null ) { maxRequestSize = - 1L ; } else { maxRequestSize = multipartConfig . getMaxRequestSize ( ) ; } int fileSizeThreshold ; if ( multipartConfig . getFileSizeThreshold ( ) == null ) { fileSizeThreshold = 0 ; } else { fileSizeThreshold = multipartConfig . getFileSizeThreshold ( ) . intValue ( ) ; } MultipartConfigElement multipartConfigElement = new MultipartConfigElement ( location , maxFileSize , maxRequestSize , fileSizeThreshold ) ; servlet . setMultipartConfig ( multipartConfigElement ) ; } List < ParamValueType > servletInitParams = servletType . getInitParam ( ) ; for ( ParamValueType initParamElement : servletInitParams ) { final WebAppInitParam initParam = new WebAppInitParam ( ) ; initParam . setParamName ( initParamElement . getParamName ( ) . getValue ( ) ) ; initParam . setParamValue ( initParamElement . getParamValue ( ) . getValue ( ) ) ; servlet . addInitParam ( initParam ) ; } }
|
Parses servlets and servlet mappings out of web . xml .
|
40,865
|
private static void parseFilters ( final FilterType filterType , final WebApp webApp ) { final WebAppFilter filter = new WebAppFilter ( ) ; if ( filterType . getFilterName ( ) != null ) { filter . setFilterName ( filterType . getFilterName ( ) . getValue ( ) ) ; } if ( filterType . getFilterClass ( ) != null ) { filter . setFilterClass ( filterType . getFilterClass ( ) . getValue ( ) ) ; } if ( filterType . getAsyncSupported ( ) != null ) { filter . setAsyncSupported ( filterType . getAsyncSupported ( ) . isValue ( ) ) ; } webApp . addFilter ( filter ) ; List < ParamValueType > initParams = filterType . getInitParam ( ) ; if ( initParams != null && initParams . size ( ) > 0 ) { for ( ParamValueType initParamElement : initParams ) { final WebAppInitParam initParam = new WebAppInitParam ( ) ; initParam . setParamName ( initParamElement . getParamName ( ) . getValue ( ) ) ; initParam . setParamValue ( initParamElement . getParamValue ( ) . getValue ( ) ) ; filter . addInitParam ( initParam ) ; } } List < DescriptionType > description = filterType . getDescription ( ) ; for ( DescriptionType descriptionType : description ) { filter . addDispatcherType ( DispatcherType . valueOf ( descriptionType . getValue ( ) ) ) ; } }
|
Parses filters and filter mappings out of web . xml .
|
40,866
|
private static void parseErrorPages ( final ErrorPageType errorPageType , final WebApp webApp ) { final WebAppErrorPage errorPage = new WebAppErrorPage ( ) ; if ( errorPageType . getErrorCode ( ) != null ) { errorPage . setErrorCode ( errorPageType . getErrorCode ( ) . getValue ( ) . toString ( ) ) ; } if ( errorPageType . getExceptionType ( ) != null ) { errorPage . setExceptionType ( errorPageType . getExceptionType ( ) . getValue ( ) ) ; } if ( errorPageType . getLocation ( ) != null ) { errorPage . setLocation ( errorPageType . getLocation ( ) . getValue ( ) ) ; } if ( errorPage . getErrorCode ( ) == null && errorPage . getExceptionType ( ) == null ) { errorPage . setExceptionType ( ErrorPageModel . ERROR_PAGE ) ; } webApp . addErrorPage ( errorPage ) ; }
|
Parses error pages out of web . xml .
|
40,867
|
private static void parseWelcomeFiles ( final WelcomeFileListType welcomeFileList , final WebApp webApp ) { if ( welcomeFileList != null && welcomeFileList . getWelcomeFile ( ) != null && ! welcomeFileList . getWelcomeFile ( ) . isEmpty ( ) ) { welcomeFileList . getWelcomeFile ( ) . forEach ( webApp :: addWelcomeFile ) ; } }
|
Parses welcome files out of web . xml .
|
40,868
|
private static void parseMimeMappings ( final MimeMappingType mimeMappingType , final WebApp webApp ) { final WebAppMimeMapping mimeMapping = new WebAppMimeMapping ( ) ; mimeMapping . setExtension ( mimeMappingType . getExtension ( ) . getValue ( ) ) ; mimeMapping . setMimeType ( mimeMappingType . getMimeType ( ) . getValue ( ) ) ; webApp . addMimeMapping ( mimeMapping ) ; }
|
Parses mime mappings out of web . xml .
|
40,869
|
private static String getTextContent ( final Element element ) { if ( element != null ) { String content = element . getTextContent ( ) ; if ( content != null ) { content = content . trim ( ) ; } return content ; } return null ; }
|
Returns the text content of an element or null if the element is null .
|
40,870
|
public static int parseInt ( byte [ ] b , int offset , int length , int base ) { int value = 0 ; if ( length < 0 ) { length = b . length - offset ; } for ( int i = 0 ; i < length ; i ++ ) { char c = ( char ) ( _0XFF & b [ offset + i ] ) ; int digit = c - '0' ; if ( digit < 0 || digit >= base || digit >= TEN ) { digit = TEN + c - 'A' ; if ( digit < TEN || digit >= base ) { digit = TEN + c - 'a' ; } } if ( digit < 0 || digit >= base ) { throw new NumberFormatException ( new String ( b , offset , length ) ) ; } value = value * base + digit ; } return value ; }
|
Parse an int from a byte array of ascii characters . Negative numbers are not handled .
|
40,871
|
public HttpService addingService ( final ServiceReference < HttpService > serviceReference ) { LOG . debug ( "HttpService available {}" , serviceReference ) ; lock . lock ( ) ; HttpService addedHttpService = null ; try { if ( httpService != null ) { return super . addingService ( serviceReference ) ; } httpService = super . addingService ( serviceReference ) ; addedHttpService = httpService ; } finally { lock . unlock ( ) ; } try { listener . available ( addedHttpService ) ; } catch ( Exception ignore ) { LOG . error ( "Cannot register" , ignore ) ; } return addedHttpService ; }
|
Gets the service if one is not already available and notify listeners .
|
40,872
|
public void removedService ( final ServiceReference < HttpService > serviceReference , final HttpService service ) { LOG . debug ( "HttpService removed {}" , serviceReference ) ; lock . lock ( ) ; HttpService removedHttpService = null ; try { if ( context != null ) { super . removedService ( serviceReference , service ) ; } if ( httpService != service ) { return ; } removedHttpService = httpService ; httpService = null ; } finally { lock . unlock ( ) ; } listener . unavailable ( removedHttpService ) ; }
|
Notify listeners that the http service became unavailable . Then looks for another one and if available notifies listeners .
|
40,873
|
public void start ( BundleContext bc ) throws Exception { int counter = 0 ; boolean started = false ; while ( ! started ) { webContainerRef = bc . getServiceReference ( WebContainer . class ) ; started = webContainerRef != null ; if ( started ) { final WebContainer webContainer = ( WebContainer ) bc . getService ( webContainerRef ) ; if ( webContainer != null ) { httpContext = webContainer . createDefaultHttpContext ( ) ; webContainer . setSessionTimeout ( 10 , httpContext ) ; final Dictionary < String , Object > initParamsServlet = new Hashtable < > ( ) ; initParamsServlet . put ( "from" , "WebContainer" ) ; helloWorldServlet = new HelloWorldServlet ( ) ; webContainer . registerServlet ( helloWorldServlet , new String [ ] { "/helloworld/wc" } , initParamsServlet , httpContext ) ; final Dictionary < String , Object > initParamsFilter = new Hashtable < > ( ) ; initParamsFilter . put ( "title" , "Hello World (url pattern)" ) ; helloWorldFilter = new HelloWorldFilter ( ) ; webContainer . registerFilter ( helloWorldFilter , new String [ ] { "/helloworld/wc" } , null , initParamsFilter , httpContext ) ; worldServlet = new HelloWorldServlet ( ) ; webContainer . registerServlet ( worldServlet , "HelloWorld" , new String [ ] { "/helloworld/wc/sn" } , initParamsServlet , httpContext ) ; initParamsFilter . put ( "title" , "Hello World (servlet name)" ) ; webContainer . registerFilter ( new HelloWorldFilter ( ) , null , new String [ ] { "HelloWorld" } , initParamsFilter , httpContext ) ; helloWorldListener = new HelloWorldListener ( ) ; webContainer . registerEventListener ( helloWorldListener , httpContext ) ; sessionListener = new HelloWorldSessionListener ( ) ; webContainer . registerEventListener ( sessionListener , httpContext ) ; webContainer . registerResources ( "/images" , "/images" , httpContext ) ; webContainer . registerWelcomeFiles ( new String [ ] { "index.html" } , true , httpContext ) ; webContainer . registerResources ( "/html" , "/html" , httpContext ) ; errorServlet = new HelloWorldErrorServlet ( ) ; webContainer . registerServlet ( errorServlet , new String [ ] { "/helloworld/wc/error" } , null , httpContext ) ; errorMakerServlet = new HelloWorldErrorMakerServlet ( ) ; webContainer . registerServlet ( errorMakerServlet , new String [ ] { "/helloworld/wc/error/create" } , null , httpContext ) ; webContainer . registerErrorPage ( "java.lang.Exception" , "/helloworld/wc/error" , httpContext ) ; webContainer . registerErrorPage ( "404" , "/helloworld/wc/error" , httpContext ) ; webContainer . end ( httpContext ) ; } } else { if ( counter > 10 ) { throw new Exception ( "Could not start the helloworld-wc service, WebContainer service not started or not available." ) ; } else { counter ++ ; Thread . sleep ( counter * 1000 ) ; } } } }
|
Called when the OSGi framework starts our bundle .
|
40,874
|
private static void printAttribute ( final PrintWriter writer , final HttpServletRequest request , final String attribute ) { writer . println ( "<tr><td>" + attribute + "</td><td>" + ( request . getAttribute ( attribute ) != null ? request . getAttribute ( attribute ) : "" ) + "</td></tr>" ) ; }
|
Prints an error request attribute .
|
40,875
|
public Enumeration < URL > getResources ( String name ) throws IOException { return bundleClassLoader . getResources ( name ) ; }
|
Delegate to bundle class loader .
|
40,876
|
public List < URL > scanBundlesInClassSpace ( String directory , String filePattern , boolean recursive ) { Set < Bundle > bundlesInClassSpace = ClassPathUtil . getBundlesInClassSpace ( bundleClassLoader . getBundle ( ) , new HashSet < > ( ) ) ; List < URL > matching = new ArrayList < > ( ) ; for ( Bundle bundle : bundlesInClassSpace ) { @ SuppressWarnings ( "rawtypes" ) Enumeration e = bundle . findEntries ( directory , filePattern , recursive ) ; if ( e == null ) { continue ; } while ( e . hasMoreElements ( ) ) { URL u = ( URL ) e . nextElement ( ) ; matching . add ( u ) ; } } return matching ; }
|
Scans the imported and required bundles for matching resources . Can be used to obtain references to TLD files XML definition files etc .
|
40,877
|
public BindingInfo bindingInfo ( String socketBindingName ) { SocketBinding sb = socketBinding ( socketBindingName ) ; if ( sb == null ) { throw new IllegalArgumentException ( "Can't find socket binding with name \"" + socketBindingName + "\"" ) ; } Interface iface = interfaceRef ( sb . getInterfaceRef ( ) ) ; if ( iface == null ) { throw new IllegalArgumentException ( "Can't find interface with name \"" + sb . getInterfaceRef ( ) + "\"" ) ; } BindingInfo result = new BindingInfo ( sb . getPort ( ) ) ; for ( Interface . InetAddress address : iface . getAddresses ( ) ) { result . getAddresses ( ) . add ( address . getIp ( ) ) ; } return result ; }
|
Returns valid information about interfaces + port to listen on
|
40,878
|
public void configureWelcomeFiles ( List < String > welcomePages ) { this . welcomePages = welcomePages ; ( ( ResourceHandler ) handler ) . setWelcomeFiles ( ) ; ( ( ResourceHandler ) handler ) . addWelcomeFiles ( welcomePages . toArray ( new String [ welcomePages . size ( ) ] ) ) ; }
|
Reconfigures default welcome pages with ones provided externally
|
40,879
|
public static String getStringProperty ( final ServiceReference < ? > serviceReference , final String key ) { NullArgumentException . validateNotNull ( serviceReference , "Service reference" ) ; NullArgumentException . validateNotEmpty ( key , true , "Property key" ) ; Object value = serviceReference . getProperty ( key ) ; if ( value != null && ! ( value instanceof String ) ) { LOG . error ( "Property [" + key + "] value must be a String" ) ; return null ; } return ( String ) value ; }
|
Returns a property as String .
|
40,880
|
public static Integer getIntegerProperty ( final ServiceReference < ? > serviceReference , final String key ) { NullArgumentException . validateNotNull ( serviceReference , "Service reference" ) ; NullArgumentException . validateNotEmpty ( key , true , "Property key" ) ; final Object value = serviceReference . getProperty ( key ) ; if ( value instanceof Integer ) { return ( Integer ) value ; } else if ( value != null ) { try { return Integer . parseInt ( String . valueOf ( value ) ) ; } catch ( NumberFormatException e ) { final String message = String . format ( "Property [%s] value must be an Integer: %s" , key , e . getMessage ( ) ) ; LOG . error ( message , e ) ; return null ; } } else { return null ; } }
|
Returns a property as Integer .
|
40,881
|
public static Map < String , Object > getSubsetStartingWith ( final ServiceReference < ? > serviceReference , final String prefix ) { final Map < String , Object > subset = new HashMap < > ( ) ; for ( String key : serviceReference . getPropertyKeys ( ) ) { if ( key != null && key . startsWith ( prefix ) && key . trim ( ) . length ( ) > prefix . length ( ) ) { subset . put ( key . substring ( prefix . length ( ) ) , serviceReference . getProperty ( key ) ) ; } } if ( subset . isEmpty ( ) ) { return null ; } return subset ; }
|
Returns the subset of properties that start with the prefix . The returned dictionary will have as keys the original key without the prefix .
|
40,882
|
public static String extractHttpContextId ( final ServiceReference < ? > serviceReference ) { String httpContextId = getStringProperty ( serviceReference , ExtenderConstants . PROPERTY_HTTP_CONTEXT_ID ) ; if ( httpContextId == null ) { String httpContextSelector = getStringProperty ( serviceReference , HttpWhiteboardConstants . HTTP_WHITEBOARD_CONTEXT_SELECT ) ; if ( httpContextSelector != null ) { httpContextSelector = httpContextSelector . substring ( 1 , httpContextSelector . length ( ) ) ; httpContextId = httpContextSelector . substring ( HttpWhiteboardConstants . HTTP_WHITEBOARD_CONTEXT_NAME . length ( ) + 1 ) ; httpContextId = httpContextId . substring ( 0 , httpContextId . length ( ) - 1 ) ; } } return httpContextId ; }
|
Utility method to extract the httpContextID from the service reference . This can either be included with the old Pax - Web style or the new OSGi R6 Whiteboard style .
|
40,883
|
public static Boolean extractSharedHttpContext ( final ServiceReference < ? > serviceReference ) { Boolean sharedHttpContext = Boolean . parseBoolean ( ( String ) serviceReference . getProperty ( ExtenderConstants . PROPERTY_HTTP_CONTEXT_SHARED ) ) ; if ( serviceReference . getProperty ( HttpWhiteboardConstants . HTTP_WHITEBOARD_CONTEXT_SELECT ) != null ) { sharedHttpContext = true ; } return sharedHttpContext ; }
|
Utility method to extract the shared state of the HttpContext
|
40,884
|
public void addInitParam ( final WebAppInitParam param ) { NullArgumentException . validateNotNull ( param , "Init param" ) ; NullArgumentException . validateNotNull ( param . getParamName ( ) , "Init param name" ) ; NullArgumentException . validateNotNull ( param . getParamValue ( ) , "Init param value" ) ; initParams . add ( param ) ; }
|
Add a init param for filter .
|
40,885
|
public Extension createExtension ( final Bundle bundle ) { NullArgumentException . validateNotNull ( bundle , "Bundle" ) ; if ( bundle . getState ( ) != Bundle . ACTIVE ) { LOG . debug ( "Bundle is not in ACTIVE state, ignore it!" ) ; return null ; } Boolean canSeeServletClass = canSeeClass ( bundle , Servlet . class ) ; if ( Boolean . FALSE . equals ( canSeeServletClass ) ) { LOG . debug ( "Ignore bundle {} which is not compatible with this extender" , bundle ) ; return null ; } String contextName = getHeader ( bundle , "Web-ContextPath" ) ; if ( contextName == null ) { return null ; } contextName = contextName . trim ( ) ; if ( contextName . startsWith ( "/" ) ) { contextName = contextName . substring ( 1 ) ; } final WebApp webApp = new WebApp ( ) ; webApp . setDeploymentState ( WebEvent . UNDEPLOYED ) ; webApp . setBundle ( bundle ) ; webApp . setContextName ( contextName ) ; try { eventDispatcher . webEvent ( webApp , WebEvent . DEPLOYING ) ; parser . parse ( bundle , webApp ) ; String requireCapabilityHeader = ManifestUtil . getHeader ( bundle , "Require-Capability" ) ; if ( requireCapabilityHeader == null || ! requireCapabilityHeader . contains ( "osgi.extender=pax.cdi" ) ) { webApp . setHasDependencies ( true ) ; dependencyManager . addWebApp ( webApp ) ; } synchronized ( webApps ) { webApps . put ( bundle . getBundleId ( ) , webApp ) ; } return new SimpleExtension ( bundle ) { public void doStart ( ) { synchronized ( webApps ) { if ( ! webApps . containsKey ( bundle . getBundleId ( ) ) ) { return ; } } if ( Optional . ofNullable ( ManifestUtil . getHeader ( bundle , "Webapp-Deploy" ) ) . orElse ( "true" ) . equals ( "true" ) ) { deploy ( webApp ) ; } else { eventDispatcher . webEvent ( new WebEvent ( WebEvent . UNDEPLOYED , "/" + webApp . getContextName ( ) , webApp . getBundle ( ) , bundleContext . getBundle ( ) ) ) ; } } public void doDestroy ( ) { synchronized ( webApps ) { webApps . remove ( bundle . getBundleId ( ) ) ; } dependencyManager . removeWebApp ( webApp ) ; undeploy ( webApp ) ; eventDispatcher . removeWebApp ( webApp ) ; } } ; } catch ( Exception e ) { LOG . error ( "Error scanning web bundle " + bundle + ": " + e . getMessage ( ) , e ) ; eventDispatcher . webEvent ( webApp , WebEvent . FAILED , e ) ; return null ; } }
|
Parse the web app and create the extension that will be managed by the extender .
|
40,886
|
public static String normalizeResourcePath ( final String path ) { if ( path == null ) { return null ; } String normalizedPath = replaceSlashes ( path . trim ( ) ) ; if ( normalizedPath . startsWith ( "/" ) && normalizedPath . length ( ) > 1 ) { normalizedPath = normalizedPath . substring ( 1 ) ; } return normalizedPath ; }
|
Normalize the path for accesing a resource meaning that will replace consecutive slashes and will remove a leading slash if present .
|
40,887
|
public static String [ ] normalizePatterns ( final String [ ] urlPatterns ) { String [ ] normalized = null ; if ( urlPatterns != null ) { normalized = new String [ urlPatterns . length ] ; for ( int i = 0 ; i < urlPatterns . length ; i ++ ) { normalized [ i ] = normalizePattern ( urlPatterns [ i ] ) ; } } return normalized ; }
|
Normalize an array of patterns .
|
40,888
|
public static URL [ ] getClassPathJars ( final Bundle bundle ) { final List < URL > urls = new ArrayList < > ( ) ; final String bundleClasspath = ( String ) bundle . getHeaders ( ) . get ( "Bundle-ClassPath" ) ; if ( bundleClasspath != null ) { String [ ] segments = bundleClasspath . split ( "," ) ; for ( String segment : segments ) { final URL url = bundle . getEntry ( segment ) ; if ( url != null ) { if ( url . toExternalForm ( ) . endsWith ( "jar" ) ) { LOG . debug ( "Using url: " + url ) ; try { URL jarUrl = new URL ( "jar:" + url . toExternalForm ( ) + "!/" ) ; urls . add ( jarUrl ) ; } catch ( MalformedURLException ignore ) { LOG . debug ( ignore . getMessage ( ) ) ; } } } } } LOG . debug ( "Bundle-ClassPath URLs: " + urls ) ; urls . addAll ( getLocationsOfBundlesInClassSpace ( bundle ) ) ; return urls . toArray ( new URL [ urls . size ( ) ] ) ; }
|
Returns a list of urls to jars that composes the Bundle - ClassPath .
|
40,889
|
public static Set < Bundle > getBundlesInClassSpace ( Bundle bundle , Set < Bundle > bundleSet ) { return getBundlesInClassSpace ( bundle . getBundleContext ( ) , bundle , bundleSet ) ; }
|
Gets a list of bundles that are imported or required by this bundle .
|
40,890
|
public void addServletModel ( final ServletModel model ) throws NamespaceException , ServletException { servletLock . writeLock ( ) . lock ( ) ; try { associateBundle ( model . getContextModel ( ) . getVirtualHosts ( ) , model . getContextModel ( ) . getBundle ( ) ) ; for ( String virtualHost : resolveVirtualHosts ( model ) ) { if ( servlets . get ( virtualHost ) == null ) { servlets . put ( virtualHost , new HashSet < > ( ) ) ; } if ( model . getServlet ( ) != null && servlets . get ( virtualHost ) . contains ( model . getServlet ( ) ) ) { throw new ServletException ( "servlet already registered with a different alias" ) ; } if ( model . getAlias ( ) != null ) { final String alias = getFullPath ( model . getContextModel ( ) , model . getAlias ( ) ) ; if ( aliasMapping . get ( virtualHost ) == null ) { aliasMapping . put ( virtualHost , new HashMap < > ( ) ) ; } if ( aliasMapping . get ( virtualHost ) . containsKey ( alias ) ) { throw new NamespaceException ( "alias: '" + alias + "' is already in use in this or another context" ) ; } aliasMapping . get ( virtualHost ) . put ( alias , model ) ; } if ( model . getServlet ( ) != null ) { servlets . get ( virtualHost ) . add ( model . getServlet ( ) ) ; } for ( String urlPattern : model . getUrlPatterns ( ) ) { if ( servletUrlPatterns . get ( virtualHost ) == null ) { servletUrlPatterns . put ( virtualHost , new HashMap < > ( ) ) ; } servletUrlPatterns . get ( virtualHost ) . put ( getFullPath ( model . getContextModel ( ) , urlPattern ) , new UrlPattern ( getFullPath ( model . getContextModel ( ) , urlPattern ) , model ) ) ; } } } finally { servletLock . writeLock ( ) . unlock ( ) ; } }
|
Registers a servlet model .
|
40,891
|
public void removeServletModel ( final ServletModel model ) { servletLock . writeLock ( ) . lock ( ) ; try { deassociateBundle ( model . getContextModel ( ) . getVirtualHosts ( ) , model . getContextModel ( ) . getBundle ( ) ) ; for ( String virtualHost : resolveVirtualHosts ( model ) ) { if ( model . getAlias ( ) != null ) { aliasMapping . get ( virtualHost ) . remove ( getFullPath ( model . getContextModel ( ) , model . getAlias ( ) ) ) ; } if ( model . getServlet ( ) != null ) { servlets . get ( virtualHost ) . remove ( model . getServlet ( ) ) ; } if ( model . getUrlPatterns ( ) != null ) { for ( String urlPattern : model . getUrlPatterns ( ) ) { servletUrlPatterns . get ( virtualHost ) . remove ( getFullPath ( model . getContextModel ( ) , urlPattern ) ) ; } } } } finally { servletLock . writeLock ( ) . unlock ( ) ; } }
|
Unregisters a servlet model .
|
40,892
|
public void addFilterModel ( final FilterModel model ) { if ( model . getUrlPatterns ( ) != null ) { try { filterLock . writeLock ( ) . lock ( ) ; associateBundle ( model . getContextModel ( ) . getVirtualHosts ( ) , model . getContextModel ( ) . getBundle ( ) ) ; for ( String virtualHost : resolveVirtualHosts ( model ) ) { for ( String urlPattern : model . getUrlPatterns ( ) ) { final UrlPattern newUrlPattern = new UrlPattern ( getFullPath ( model . getContextModel ( ) , urlPattern ) , model ) ; String fullPath = getFullPath ( model . getContextModel ( ) , urlPattern ) ; if ( filterUrlPatterns . get ( virtualHost ) == null ) { filterUrlPatterns . put ( virtualHost , new ConcurrentHashMap < > ( ) ) ; } Set < UrlPattern > urlSet = filterUrlPatterns . get ( virtualHost ) . get ( fullPath ) ; if ( urlSet == null ) { urlSet = new HashSet < > ( ) ; } urlSet . add ( newUrlPattern ) ; filterUrlPatterns . get ( virtualHost ) . put ( fullPath , urlSet ) ; } } } finally { filterLock . writeLock ( ) . unlock ( ) ; } } }
|
Registers a filter model .
|
40,893
|
public void removeFilterModel ( final FilterModel model ) { if ( model . getUrlPatterns ( ) != null ) { try { deassociateBundle ( model . getContextModel ( ) . getVirtualHosts ( ) , model . getContextModel ( ) . getBundle ( ) ) ; filterLock . writeLock ( ) . lock ( ) ; for ( String virtualHost : resolveVirtualHosts ( model ) ) { for ( String urlPattern : model . getUrlPatterns ( ) ) { String fullPath = getFullPath ( model . getContextModel ( ) , urlPattern ) ; Set < UrlPattern > urlSet = filterUrlPatterns . get ( virtualHost ) . get ( fullPath ) ; UrlPattern toDelete = null ; for ( UrlPattern pattern : urlSet ) { FilterModel filterModel = ( FilterModel ) pattern . getModel ( ) ; Class < ? > filter = filterModel . getFilterClass ( ) ; Class < ? > matchFilter = model . getFilterClass ( ) ; if ( filter != null && filter . equals ( matchFilter ) ) { toDelete = pattern ; break ; } } urlSet . remove ( toDelete ) ; } } } finally { filterLock . writeLock ( ) . unlock ( ) ; } } }
|
Unregister a filter model .
|
40,894
|
public void associateHttpContext ( final WebContainerContext httpContext , final Bundle bundle , final boolean allowReAsssociation ) { List < String > virtualHosts = resolveVirtualHosts ( bundle ) ; for ( String virtualHost : virtualHosts ) { ConcurrentMap < WebContainerContext , Bundle > virtualHostHttpContexts = httpContexts . get ( virtualHost ) ; if ( virtualHostHttpContexts == null ) { virtualHostHttpContexts = new ConcurrentHashMap < > ( ) ; httpContexts . put ( virtualHost , virtualHostHttpContexts ) ; } final Bundle currentBundle = virtualHostHttpContexts . putIfAbsent ( httpContext , bundle ) ; if ( ( ! allowReAsssociation ) && currentBundle != null && currentBundle != bundle ) { throw new IllegalStateException ( "Http context " + httpContext + " is already associated to bundle " + currentBundle ) ; } } }
|
Associates a http context with a bundle if the http service is not already associated to another bundle . This is done in order to prevent sharing http context between bundles . The implementation is not 100% correct as it can be that at a certain moment in time when this method is called another thread is processing a release of the http service process that will deassociate the bundle that released the http service and that bundle could actually be related to the http context that this method is trying to associate . But this is less likely to happen as it should have as precondition that this is happening concurrent and that the two bundles are sharing the http context . But this solution has the benefits of not needing synchronization .
|
40,895
|
protected final ServiceTracker < T , W > create ( String filter ) { try { return new ServiceTracker < > ( bundleContext , bundleContext . createFilter ( filter ) , this ) ; } catch ( InvalidSyntaxException e ) { throw new IllegalArgumentException ( "Unexpected InvalidSyntaxException: " + e . getMessage ( ) ) ; } }
|
Creates a new tracker that tracks services by generic filter
|
40,896
|
public void visit ( final WebApp webApp ) { NullArgumentException . validateNotNull ( webApp , "Web app" ) ; bundleClassLoader = new BundleClassLoader ( webApp . getBundle ( ) ) ; httpContext = new WebAppHttpContext ( httpService . createDefaultHttpContext ( ) , webApp . getRootPath ( ) , webApp . getBundle ( ) , webApp . getMimeMappings ( ) ) ; try { LOG . info ( "Pax Web not available. Skipping context params registration" ) ; httpService . registerResources ( "/" , "default" , httpContext ) ; } catch ( Throwable ignore ) { LOG . error ( "Registration exception. Skipping." , ignore ) ; } }
|
Creates a default context that will be used for all following registrations and registers a resource for root of war .
|
40,897
|
public void visit ( final WebAppServlet webAppServlet ) { NullArgumentException . validateNotNull ( webAppServlet , "Web app servlet" ) ; final String [ ] aliases = webAppServlet . getAliases ( ) ; if ( aliases != null && aliases . length > 0 ) { for ( final String alias : aliases ) { try { final Servlet servlet = newInstance ( Servlet . class , bundleClassLoader , webAppServlet . getServletClassName ( ) ) ; httpService . registerServlet ( alias , servlet , convertInitParams ( webAppServlet . getInitParams ( ) ) , httpContext ) ; } catch ( Throwable ignore ) { LOG . error ( "Registration exception. Skipping." , ignore ) ; } } } else { LOG . warn ( "Servlet [" + webAppServlet + "] does not have any alias. Skipped." ) ; } }
|
Registers servlets with http context .
|
40,898
|
public static < T > T newInstance ( final Class < T > clazz , final ClassLoader classLoader , final String className ) throws ClassNotFoundException , IllegalAccessException , InstantiationException { return loadClass ( clazz , classLoader , className ) . newInstance ( ) ; }
|
Creates an instance of a class from class name .
|
40,899
|
@ SuppressWarnings ( "unchecked" ) public static < T > Class < ? extends T > loadClass ( final Class < T > clazz , final ClassLoader classLoader , final String className ) throws ClassNotFoundException , IllegalAccessException { NullArgumentException . validateNotNull ( clazz , "Class" ) ; NullArgumentException . validateNotNull ( classLoader , "ClassLoader" ) ; NullArgumentException . validateNotNull ( className , "Servlet Class" ) ; return ( Class < ? extends T > ) classLoader . loadClass ( className ) ; }
|
Load a class from class name .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.