Input: Decodes the Multipart Body data and put it into Key / Value pairs . [CODESPLIT] private void decodeMultipartFormData ( ContentType contentType , ByteBuffer fbuf , Map < String , List < String > > parms , Map < String , String > files ) throws ResponseException { int pcount = 0 ; try { int [ ] boundaryIdxs = getBoundaryPositions ( fbuf , contentType . getBoundary ( ) . getBytes ( ) ) ; if ( boundaryIdxs . length < 2 ) { throw new ResponseException ( Status . BAD_REQUEST , "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings." ) ; } byte [ ] partHeaderBuff = new byte [ MAX_HEADER_SIZE ] ; for ( int boundaryIdx = 0 ; boundaryIdx < boundaryIdxs . length - 1 ; boundaryIdx ++ ) { fbuf . position ( boundaryIdxs [ boundaryIdx ] ) ; int len = ( fbuf . remaining ( ) < MAX_HEADER_SIZE ) ? fbuf . remaining ( ) : MAX_HEADER_SIZE ; fbuf . get ( partHeaderBuff , 0 , len ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( new ByteArrayInputStream ( partHeaderBuff , 0 , len ) , Charset . forName ( contentType . getEncoding ( ) ) ) , len ) ; int headerLines = 0 ; // First line is boundary string String mpline = in . readLine ( ) ; headerLines ++ ; if ( mpline == null || ! mpline . contains ( contentType . getBoundary ( ) ) ) { throw new ResponseException ( Status . BAD_REQUEST , "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary." ) ; } String partName = null , fileName = null , partContentType = null ; // Parse the reset of the header lines mpline = in . readLine ( ) ; headerLines ++ ; while ( mpline != null && mpline . trim ( ) . length ( ) > 0 ) { Matcher matcher = NanoHTTPD . CONTENT_DISPOSITION_PATTERN . matcher ( mpline ) ; if ( matcher . matches ( ) ) { String attributeString = matcher . group ( 2 ) ; matcher = NanoHTTPD . CONTENT_DISPOSITION_ATTRIBUTE_PATTERN . matcher ( attributeString ) ; while ( matcher . find ( ) ) { String key = matcher . group ( 1 ) ; if ( "name" . equalsIgnoreCase ( key ) ) { partName = matcher . group ( 2 ) ; } else if ( "filename" . equalsIgnoreCase ( key ) ) { fileName = matcher . group ( 2 ) ; // add these two line to support multiple // files uploaded using the same field Id if ( ! fileName . isEmpty ( ) ) { if ( pcount > 0 ) partName = partName + String . valueOf ( pcount ++ ) ; else pcount ++ ; } } } } matcher = NanoHTTPD . CONTENT_TYPE_PATTERN . matcher ( mpline ) ; if ( matcher . matches ( ) ) { partContentType = matcher . group ( 2 ) . trim ( ) ; } mpline = in . readLine ( ) ; headerLines ++ ; } int partHeaderLength = 0 ; while ( headerLines -- > 0 ) { partHeaderLength = scipOverNewLine ( partHeaderBuff , partHeaderLength ) ; } // Read the part data if ( partHeaderLength >= len - 4 ) { throw new ResponseException ( Status . INTERNAL_ERROR , "Multipart header size exceeds MAX_HEADER_SIZE." ) ; } int partDataStart = boundaryIdxs [ boundaryIdx ] + partHeaderLength ; int partDataEnd = boundaryIdxs [ boundaryIdx + 1 ] - 4 ; fbuf . position ( partDataStart ) ; List < String > values = parms . get ( partName ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; parms . put ( partName , values ) ; } if ( partContentType == null ) { // Read the part into a string byte [ ] data_bytes = new byte [ partDataEnd - partDataStart ] ; fbuf . get ( data_bytes ) ; values . add ( new String ( data_bytes , contentType . getEncoding ( ) ) ) ; } else { // Read it into a file String path = saveTmpFile ( fbuf , partDataStart , partDataEnd - partDataStart , fileName ) ; if ( ! files . containsKey ( partName ) ) { files . put ( partName , path ) ; } else { int count = 2 ; while ( files . containsKey ( partName + count ) ) { count ++ ; } files . put ( partName + count , path ) ; } values . add ( fileName ) ; } } } catch ( ResponseException re ) { throw re ; } catch ( Exception e ) { throw new ResponseException ( Status . INTERNAL_ERROR , e . toString ( ) ) ; } }


Input: Decodes parameters in percent - encoded URI - format ( e . g . name = Jack%20Daniels&pass = Single%20Malt ) and adds them to given Map . [CODESPLIT] private void decodeParms ( String parms , Map < String , List < String > > p ) { if ( parms == null ) { this . queryParameterString = "" ; return ; } this . queryParameterString = parms ; StringTokenizer st = new StringTokenizer ( parms , "&" ) ; while ( st . hasMoreTokens ( ) ) { String e = st . nextToken ( ) ; int sep = e . indexOf ( ' ' ) ; String key = null ; String value = null ; if ( sep >= 0 ) { key = NanoHTTPD . decodePercent ( e . substring ( 0 , sep ) ) . trim ( ) ; value = NanoHTTPD . decodePercent ( e . substring ( sep + 1 ) ) ; } else { key = NanoHTTPD . decodePercent ( e ) . trim ( ) ; value = "" ; } List < String > values = p . get ( key ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; p . put ( key , values ) ; } values . add ( value ) ; } }


Input: Find byte index separating header from body . It must be the last byte of the first two sequential new lines . [CODESPLIT] private int findHeaderEnd ( final byte [ ] buf , int rlen ) { int splitbyte = 0 ; while ( splitbyte + 1 < rlen ) { // RFC2616 if ( buf [ splitbyte ] == ' ' && buf [ splitbyte + 1 ] == ' ' && splitbyte + 3 < rlen && buf [ splitbyte + 2 ] == ' ' && buf [ splitbyte + 3 ] == ' ' ) { return splitbyte + 4 ; } // tolerance if ( buf [ splitbyte ] == ' ' && buf [ splitbyte + 1 ] == ' ' ) { return splitbyte + 2 ; } splitbyte ++ ; } return 0 ; }


Input: Find the byte positions where multipart boundaries start . This reads a large block at a time and uses a temporary buffer to optimize ( memory mapped ) file access . [CODESPLIT] private int [ ] getBoundaryPositions ( ByteBuffer b , byte [ ] boundary ) { int [ ] res = new int [ 0 ] ; if ( b . remaining ( ) < boundary . length ) { return res ; } int search_window_pos = 0 ; byte [ ] search_window = new byte [ 4 * 1024 + boundary . length ] ; int first_fill = ( b . remaining ( ) < search_window . length ) ? b . remaining ( ) : search_window . length ; b . get ( search_window , 0 , first_fill ) ; int new_bytes = first_fill - boundary . length ; do { // Search the search_window for ( int j = 0 ; j < new_bytes ; j ++ ) { for ( int i = 0 ; i < boundary . length ; i ++ ) { if ( search_window [ j + i ] != boundary [ i ] ) break ; if ( i == boundary . length - 1 ) { // Match found, add it to results int [ ] new_res = new int [ res . length + 1 ] ; System . arraycopy ( res , 0 , new_res , 0 , res . length ) ; new_res [ res . length ] = search_window_pos + j ; res = new_res ; } } } search_window_pos += new_bytes ; // Copy the end of the buffer to the start System . arraycopy ( search_window , search_window . length - boundary . length , search_window , 0 , boundary . length ) ; // Refill search_window new_bytes = search_window . length - boundary . length ; new_bytes = ( b . remaining ( ) < new_bytes ) ? b . remaining ( ) : new_bytes ; b . get ( search_window , boundary . length , new_bytes ) ; } while ( new_bytes > 0 ) ; return res ; }


Input: Deduce body length in bytes . Either from content - length header or read bytes . [CODESPLIT] public long getBodySize ( ) { if ( this . headers . containsKey ( "content-length" ) ) { return Long . parseLong ( this . headers . get ( "content-length" ) ) ; } else if ( this . splitbyte < this . rlen ) { return this . rlen - this . splitbyte ; } return 0 ; }


Input: Retrieves the content of a sent file and saves it to a temporary file . The full path to the saved file is returned . [CODESPLIT] private String saveTmpFile ( ByteBuffer b , int offset , int len , String filename_hint ) { String path = "" ; if ( len > 0 ) { FileOutputStream fileOutputStream = null ; try { ITempFile tempFile = this . tempFileManager . createTempFile ( filename_hint ) ; ByteBuffer src = b . duplicate ( ) ; fileOutputStream = new FileOutputStream ( tempFile . getName ( ) ) ; FileChannel dest = fileOutputStream . getChannel ( ) ; src . position ( offset ) . limit ( offset + len ) ; dest . write ( src . slice ( ) ) ; path = tempFile . getName ( ) ; } catch ( Exception e ) { // Catch exception if any throw new Error ( e ) ; // we won't recover, so throw an error } finally { NanoHTTPD . safeClose ( fileOutputStream ) ; } } return path ; }


Input: Creates an SSLSocketFactory for HTTPS . Pass a loaded KeyStore and an array of loaded KeyManagers . These objects must properly loaded / initialized by the caller . [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( KeyStore loadedKeyStore , KeyManager [ ] keyManagers ) throws IOException { SSLServerSocketFactory res = null ; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( loadedKeyStore ) ; SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; ctx . init ( keyManagers , trustManagerFactory . getTrustManagers ( ) , null ) ; res = ctx . getServerSocketFactory ( ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } return res ; }


Input: Creates an SSLSocketFactory for HTTPS . Pass a loaded KeyStore and a loaded KeyManagerFactory . These objects must properly loaded / initialized by the caller . [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( KeyStore loadedKeyStore , KeyManagerFactory loadedKeyFactory ) throws IOException { try { return makeSSLSocketFactory ( loadedKeyStore , loadedKeyFactory . getKeyManagers ( ) ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } }


Input: Creates an SSLSocketFactory for HTTPS . Pass a KeyStore resource with your certificate and passphrase [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( String keyAndTrustStoreClasspathPath , char [ ] passphrase ) throws IOException { try { KeyStore keystore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; InputStream keystoreStream = NanoHTTPD . class . getResourceAsStream ( keyAndTrustStoreClasspathPath ) ; if ( keystoreStream == null ) { throw new IOException ( "Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath ) ; } keystore . load ( keystoreStream , passphrase ) ; KeyManagerFactory keyManagerFactory = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; keyManagerFactory . init ( keystore , passphrase ) ; return makeSSLSocketFactory ( keystore , keyManagerFactory ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } }


Input: Get MIME type from file name extension if possible [CODESPLIT] public static String getMimeTypeForFile ( String uri ) { int dot = uri . lastIndexOf ( ' ' ) ; String mime = null ; if ( dot >= 0 ) { mime = mimeTypes ( ) . get ( uri . substring ( dot + 1 ) . toLowerCase ( ) ) ; } return mime == null ? "application/octet-stream" : mime ; }


Input: This is the master method that delegates requests to handlers and makes sure there is a response to every request . You are not supposed to call or override this method in any circumstances . But no one will stop you if you do . I m a Javadoc not Code Police . [CODESPLIT] public Response handle ( IHTTPSession session ) { for ( IHandler < IHTTPSession , Response > interceptor : interceptors ) { Response response = interceptor . handle ( session ) ; if ( response != null ) return response ; } return httpHandler . handle ( session ) ; }


Input: Override this to customize the server . <p / > <p / > ( By default this returns a 404 Not Found plain text error response . ) [CODESPLIT] @ Deprecated protected Response serve ( IHTTPSession session ) { return Response . newFixedLengthResponse ( Status . NOT_FOUND , NanoHTTPD . MIME_PLAINTEXT , "Not Found" ) ; }


Input: Stop the server . [CODESPLIT] public void stop ( ) { try { safeClose ( this . myServerSocket ) ; this . asyncRunner . closeAll ( ) ; if ( this . myThread != null ) { this . myThread . join ( ) ; } } catch ( Exception e ) { NanoHTTPD . LOG . log ( Level . SEVERE , "Could not stop all connections" , e ) ; } }


Input: default routings they are over writable . [CODESPLIT] public void addMappings ( ) { router . setNotImplemented ( NotImplementedHandler . class ) ; router . setNotFoundHandler ( Error404UriHandler . class ) ; router . addRoute ( "/" , Integer . MAX_VALUE / 2 , IndexHandler . class ) ; router . addRoute ( "/index.html" , Integer . MAX_VALUE / 2 , IndexHandler . class ) ; }


Input: Sends given response to the socket . [CODESPLIT] public void send ( OutputStream outputStream ) { SimpleDateFormat gmtFrmt = new SimpleDateFormat ( "E, d MMM yyyy HH:mm:ss 'GMT'" , Locale . US ) ; gmtFrmt . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; try { if ( this . status == null ) { throw new Error ( "sendResponse(): Status can't be null." ) ; } PrintWriter pw = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( outputStream , new ContentType ( this . mimeType ) . getEncoding ( ) ) ) , false ) ; pw . append ( "HTTP/1.1 " ) . append ( this . status . getDescription ( ) ) . append ( " \r\n" ) ; if ( this . mimeType != null ) { printHeader ( pw , "Content-Type" , this . mimeType ) ; } if ( getHeader ( "date" ) == null ) { printHeader ( pw , "Date" , gmtFrmt . format ( new Date ( ) ) ) ; } for ( Entry < String , String > entry : this . header . entrySet ( ) ) { printHeader ( pw , entry . getKey ( ) , entry . getValue ( ) ) ; } for ( String cookieHeader : this . cookieHeaders ) { printHeader ( pw , "Set-Cookie" , cookieHeader ) ; } if ( getHeader ( "connection" ) == null ) { printHeader ( pw , "Connection" , ( this . keepAlive ? "keep-alive" : "close" ) ) ; } if ( getHeader ( "content-length" ) != null ) { setUseGzip ( false ) ; } if ( useGzipWhenAccepted ( ) ) { printHeader ( pw , "Content-Encoding" , "gzip" ) ; setChunkedTransfer ( true ) ; } long pending = this . data != null ? this . contentLength : 0 ; if ( this . requestMethod != Method . HEAD && this . chunkedTransfer ) { printHeader ( pw , "Transfer-Encoding" , "chunked" ) ; } else if ( ! useGzipWhenAccepted ( ) ) { pending = sendContentLengthHeaderIfNotAlreadyPresent ( pw , pending ) ; } pw . append ( "\r\n" ) ; pw . flush ( ) ; sendBodyWithCorrectTransferAndEncoding ( outputStream , pending ) ; outputStream . flush ( ) ; NanoHTTPD . safeClose ( this . data ) ; } catch ( IOException ioe ) { NanoHTTPD . LOG . log ( Level . SEVERE , "Could not send response to the client" , ioe ) ; } }


Input: Sends the body to the specified OutputStream . The pending parameter limits the maximum amounts of bytes sent unless it is - 1 in which case everything is sent . [CODESPLIT] private void sendBody ( OutputStream outputStream , long pending ) throws IOException { long BUFFER_SIZE = 16 * 1024 ; byte [ ] buff = new byte [ ( int ) BUFFER_SIZE ] ; boolean sendEverything = pending == - 1 ; while ( pending > 0 || sendEverything ) { long bytesToRead = sendEverything ? BUFFER_SIZE : Math . min ( pending , BUFFER_SIZE ) ; int read = this . data . read ( buff , 0 , ( int ) bytesToRead ) ; if ( read <= 0 ) { break ; } try { outputStream . write ( buff , 0 , read ) ; } catch ( Exception e ) { if ( this . data != null ) { this . data . close ( ) ; } } if ( ! sendEverything ) { pending -= read ; } } }


Input: Create a response with unknown length ( using HTTP 1 . 1 chunking ) . [CODESPLIT] public static Response newChunkedResponse ( IStatus status , String mimeType , InputStream data ) { return new Response ( status , mimeType , data , - 1 ) ; }


Input: Create a response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( IStatus status , String mimeType , InputStream data , long totalBytes ) { return new Response ( status , mimeType , data , totalBytes ) ; }


Input: Create a text response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( IStatus status , String mimeType , String txt ) { ContentType contentType = new ContentType ( mimeType ) ; if ( txt == null ) { return newFixedLengthResponse ( status , mimeType , new ByteArrayInputStream ( new byte [ 0 ] ) , 0 ) ; } else { byte [ ] bytes ; try { CharsetEncoder newEncoder = Charset . forName ( contentType . getEncoding ( ) ) . newEncoder ( ) ; if ( ! newEncoder . canEncode ( txt ) ) { contentType = contentType . tryUTF8 ( ) ; } bytes = txt . getBytes ( contentType . getEncoding ( ) ) ; } catch ( UnsupportedEncodingException e ) { NanoHTTPD . LOG . log ( Level . SEVERE , "encoding problem, responding nothing" , e ) ; bytes = new byte [ 0 ] ; } return newFixedLengthResponse ( status , contentType . getContentTypeHeader ( ) , new ByteArrayInputStream ( bytes ) , bytes . length ) ; } }


Input: Create a text response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( String msg ) { return newFixedLengthResponse ( Status . OK , NanoHTTPD . MIME_HTML , msg ) ; }


Input: Else decide whether or not to use Gzip . [CODESPLIT] public boolean useGzipWhenAccepted ( ) { if ( gzipUsage == GzipUsage . DEFAULT ) return getMimeType ( ) != null && ( getMimeType ( ) . toLowerCase ( ) . contains ( "text/" ) || getMimeType ( ) . toLowerCase ( ) . contains ( "/json" ) ) ; else return gzipUsage == GzipUsage . ALWAYS ; }


Input: Facade --------------------------- [CODESPLIT] private void readWebsocket ( ) { try { while ( this . state == State . OPEN ) { handleWebsocketFrame ( WebSocketFrame . read ( this . in ) ) ; } } catch ( CharacterCodingException e ) { onException ( e ) ; doClose ( CloseCode . InvalidFramePayloadData , e . toString ( ) , false ) ; } catch ( IOException e ) { onException ( e ) ; if ( e instanceof WebSocketException ) { doClose ( ( ( WebSocketException ) e ) . getCode ( ) , ( ( WebSocketException ) e ) . getReason ( ) , false ) ; } } finally { doClose ( CloseCode . InternalServerError , "Handler terminated without closing the connection." , false ) ; } }


Input: Translates the specified byte array into Base64 string . <p > Android has android . util . Base64 sun has sun . misc . Base64Encoder Java 8 hast java . util . Base64 I have this from stackoverflow : http : // stackoverflow . com / a / 4265472 < / p > [CODESPLIT] private static String encodeBase64 ( byte [ ] buf ) { int size = buf . length ; char [ ] ar = new char [ ( size + 2 ) / 3 * 4 ] ; int a = 0 ; int i = 0 ; while ( i < size ) { byte b0 = buf [ i ++ ] ; byte b1 = i < size ? buf [ i ++ ] : 0 ; byte b2 = i < size ? buf [ i ++ ] : 0 ; int mask = 0x3F ; ar [ a ++ ] = NanoWSD . ALPHABET [ b0 >> 2 & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ ( b0 << 4 | ( b1 & 0xFF ) >> 4 ) & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ ( b1 << 2 | ( b2 & 0xFF ) >> 6 ) & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ b2 & mask ] ; } switch ( size % 3 ) { case 1 : ar [ -- a ] = ' ' ; case 2 : ar [ -- a ] = ' ' ; } return new String ( ar ) ; }


Input: -------------------------------- SERIALIZATION --------------------------- [CODESPLIT] public String getTextPayload ( ) { if ( this . _payloadString == null ) { try { this . _payloadString = binary2Text ( getBinaryPayload ( ) ) ; } catch ( CharacterCodingException e ) { throw new RuntimeException ( "Undetected CharacterCodingException" , e ) ; } } return this . _payloadString ; }


Input: -------------------------------- ENCODING -------------------------------- [CODESPLIT] private void readPayloadInfo ( InputStream in ) throws IOException { byte b = ( byte ) checkedRead ( in . read ( ) ) ; boolean masked = ( b & 0x80 ) != 0 ; this . _payloadLength = ( byte ) ( 0x7F & b ) ; if ( this . _payloadLength == 126 ) { // checkedRead must return int for this to work this . _payloadLength = ( checkedRead ( in . read ( ) ) << 8 | checkedRead ( in . read ( ) ) ) & 0xFFFF ; if ( this . _payloadLength < 126 ) { throw new WebSocketException ( CloseCode . ProtocolError , "Invalid data frame 2byte length. (not using minimal length encoding)" ) ; } } else if ( this . _payloadLength == 127 ) { long _payloadLength = ( long ) checkedRead ( in . read ( ) ) << 56 | ( long ) checkedRead ( in . read ( ) ) << 48 | ( long ) checkedRead ( in . read ( ) ) << 40 | ( long ) checkedRead ( in . read ( ) ) << 32 | checkedRead ( in . read ( ) ) << 24 | checkedRead ( in . read ( ) ) << 16 | checkedRead ( in . read ( ) ) << 8 | checkedRead ( in . read ( ) ) ; if ( _payloadLength < 65536 ) { throw new WebSocketException ( CloseCode . ProtocolError , "Invalid data frame 4byte length. (not using minimal length encoding)" ) ; } if ( _payloadLength < 0 || _payloadLength > Integer . MAX_VALUE ) { throw new WebSocketException ( CloseCode . MessageTooBig , "Max frame length has been exceeded." ) ; } this . _payloadLength = ( int ) _payloadLength ; } if ( this . opCode . isControlFrame ( ) ) { if ( this . _payloadLength > 125 ) { throw new WebSocketException ( CloseCode . ProtocolError , "Control frame with payload length > 125 bytes." ) ; } if ( this . opCode == OpCode . Close && this . _payloadLength == 1 ) { throw new WebSocketException ( CloseCode . ProtocolError , "Received close frame with payload len 1." ) ; } } if ( masked ) { this . maskingKey = new byte [ 4 ] ; int read = 0 ; while ( read < this . maskingKey . length ) { read += checkedRead ( in . read ( this . maskingKey , read , this . maskingKey . length - read ) ) ; } } }


Input: ------------------------------------------------------------------------ [CODESPLIT] public void write ( OutputStream out ) throws IOException { byte header = 0 ; if ( this . fin ) { header |= 0x80 ; } header |= this . opCode . getValue ( ) & 0x0F ; out . write ( header ) ; this . _payloadLength = getBinaryPayload ( ) . length ; if ( this . _payloadLength <= 125 ) { out . write ( isMasked ( ) ? 0x80 | ( byte ) this . _payloadLength : ( byte ) this . _payloadLength ) ; } else if ( this . _payloadLength <= 0xFFFF ) { out . write ( isMasked ( ) ? 0xFE : 126 ) ; out . write ( this . _payloadLength >>> 8 ) ; out . write ( this . _payloadLength ) ; } else { out . write ( isMasked ( ) ? 0xFF : 127 ) ; out . write ( this . _payloadLength >>> 56 & 0 ) ; // integer only // contains // 31 bit out . write ( this . _payloadLength >>> 48 & 0 ) ; out . write ( this . _payloadLength >>> 40 & 0 ) ; out . write ( this . _payloadLength >>> 32 & 0 ) ; out . write ( this . _payloadLength >>> 24 ) ; out . write ( this . _payloadLength >>> 16 ) ; out . write ( this . _payloadLength >>> 8 ) ; out . write ( this . _payloadLength ) ; } if ( isMasked ( ) ) { out . write ( this . maskingKey ) ; for ( int i = 0 ; i < this . _payloadLength ; i ++ ) { out . write ( getBinaryPayload ( ) [ i ] ^ this . maskingKey [ i % 4 ] ) ; } } else { out . write ( getBinaryPayload ( ) ) ; } out . flush ( ) ; }


Input: Sets a cookie . [CODESPLIT] public void set ( String name , String value , int expires ) { this . queue . add ( new Cookie ( name , value , Cookie . getHTTPTime ( expires ) ) ) ; }


Input: Internally used by the webserver to add all queued cookies into the Response s HTTP Headers . [CODESPLIT] public void unloadQueue ( Response response ) { for ( Cookie cookie : this . queue ) { response . addCookieHeader ( cookie . getHTTPHeader ( ) ) ; } }


Input: end :: findbyusername [] [CODESPLIT] @ RequestMapping ( value = "/sessions/{sessionIdToDelete}" , method = RequestMethod . DELETE ) public String removeSession ( Principal principal , @ PathVariable String sessionIdToDelete ) { Set < String > usersSessionIds = this . sessions . findByPrincipalName ( principal . getName ( ) ) . keySet ( ) ; if ( usersSessionIds . contains ( sessionIdToDelete ) ) { this . sessions . deleteById ( sessionIdToDelete ) ; } return "redirect:/" ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public List < String > readCookieValues ( HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; List < String > matchingCookieValues = new ArrayList <> ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { if ( this . cookieName . equals ( cookie . getName ( ) ) ) { String sessionId = ( this . useBase64Encoding ? base64Decode ( cookie . getValue ( ) ) : cookie . getValue ( ) ) ; if ( sessionId == null ) { continue ; } if ( this . jvmRoute != null && sessionId . endsWith ( this . jvmRoute ) ) { sessionId = sessionId . substring ( 0 , sessionId . length ( ) - this . jvmRoute . length ( ) ) ; } matchingCookieValues . add ( sessionId ) ; } } } return matchingCookieValues ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void writeCookieValue ( CookieValue cookieValue ) { HttpServletRequest request = cookieValue . getRequest ( ) ; HttpServletResponse response = cookieValue . getResponse ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( this . cookieName ) . append ( ' ' ) ; String value = getValue ( cookieValue ) ; if ( value != null && value . length ( ) > 0 ) { validateValue ( value ) ; sb . append ( value ) ; } int maxAge = getMaxAge ( cookieValue ) ; if ( maxAge > - 1 ) { sb . append ( "; Max-Age=" ) . append ( cookieValue . getCookieMaxAge ( ) ) ; OffsetDateTime expires = ( maxAge != 0 ) ? OffsetDateTime . now ( ) . plusSeconds ( maxAge ) : Instant . EPOCH . atOffset ( ZoneOffset . UTC ) ; sb . append ( "; Expires=" ) . append ( expires . format ( DateTimeFormatter . RFC_1123_DATE_TIME ) ) ; } String domain = getDomainName ( request ) ; if ( domain != null && domain . length ( ) > 0 ) { validateDomain ( domain ) ; sb . append ( "; Domain=" ) . append ( domain ) ; } String path = getCookiePath ( request ) ; if ( path != null && path . length ( ) > 0 ) { validatePath ( path ) ; sb . append ( "; Path=" ) . append ( path ) ; } if ( isSecureCookie ( request ) ) { sb . append ( "; Secure" ) ; } if ( this . useHttpOnlyCookie ) { sb . append ( "; HttpOnly" ) ; } if ( this . sameSite != null ) { sb . append ( "; SameSite=" ) . append ( this . sameSite ) ; } response . addHeader ( "Set-Cookie" , sb . toString ( ) ) ; }


Input: Decode the value using Base64 . [CODESPLIT] private String base64Decode ( String base64Value ) { try { byte [ ] decodedCookieBytes = Base64 . getDecoder ( ) . decode ( base64Value ) ; return new String ( decodedCookieBytes ) ; } catch ( Exception ex ) { logger . debug ( "Unable to Base64 decode value: " + base64Value ) ; return null ; } }


Input: Encode the value using Base64 . [CODESPLIT] private String base64Encode ( String value ) { byte [ ] encodedCookieBytes = Base64 . getEncoder ( ) . encode ( value . getBytes ( ) ) ; return new String ( encodedCookieBytes ) ; }


Input: <p > Sets a case insensitive pattern used to extract the domain name from the { @link HttpServletRequest#getServerName () } . The pattern should provide a single grouping that defines what the value is that should be matched . User s should be careful not to output malicious characters like new lines to prevent from things like <a href = https : // www . owasp . org / index . php / HTTP_Response_Splitting > HTTP Response Splitting< / a > . < / p > [CODESPLIT] public void setDomainNamePattern ( String domainNamePattern ) { if ( this . domainName != null ) { throw new IllegalStateException ( "Cannot set both domainName and domainNamePattern" ) ; } this . domainNamePattern = Pattern . compile ( domainNamePattern , Pattern . CASE_INSENSITIVE ) ; }


Input: Set the name of database table used to store sessions . [CODESPLIT] public void setTableName ( String tableName ) { Assert . hasText ( tableName , "Table name must not be empty" ) ; this . tableName = tableName . trim ( ) ; prepareQueries ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void onApplicationEvent ( AbstractSessionEvent event ) { if ( this . listeners . isEmpty ( ) ) { return ; } HttpSessionEvent httpSessionEvent = createHttpSessionEvent ( event ) ; for ( HttpSessionListener listener : this . listeners ) { if ( event instanceof SessionDestroyedEvent ) { listener . sessionDestroyed ( httpSessionEvent ) ; } else if ( event instanceof SessionCreatedEvent ) { listener . sessionCreated ( httpSessionEvent ) ; } } }


Input: tag :: cookie - serializer [] [CODESPLIT] @ Bean public CookieSerializer cookieSerializer ( ) { DefaultCookieSerializer serializer = new DefaultCookieSerializer ( ) ; serializer . setCookieName ( "JSESSIONID" ) ; // <1> serializer . setCookiePath ( "/" ) ; // <2> serializer . setDomainNamePattern ( "^.+?\\.(\\w+\\.[a-z]+)$" ) ; // <3> return serializer ; }


Input: Customized { @link ObjectMapper } to add mix - in for class that doesn t have default constructors [CODESPLIT] private ObjectMapper objectMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; mapper . registerModules ( SecurityJackson2Modules . getModules ( this . loader ) ) ; return mapper ; }


Input: tag :: dofilterinternal [] [CODESPLIT] @ Override public void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { chain . doFilter ( request , response ) ; HttpSession session = request . getSession ( false ) ; if ( session != null ) { String remoteAddr = getRemoteAddress ( request ) ; String geoLocation = getGeoLocation ( remoteAddr ) ; SessionDetails details = new SessionDetails ( ) ; details . setAccessType ( request . getHeader ( "User-Agent" ) ) ; details . setLocation ( remoteAddr + " " + geoLocation ) ; session . setAttribute ( "SESSION_DETAILS" , details ) ; } }


Input: end :: dofilterinternal [] [CODESPLIT] String getGeoLocation ( String remoteAddr ) { try { CityResponse city = this . reader . city ( InetAddress . getByName ( remoteAddr ) ) ; String cityName = city . getCity ( ) . getName ( ) ; String countryName = city . getCountry ( ) . getName ( ) ; if ( cityName == null && countryName == null ) { return null ; } else if ( cityName == null ) { return countryName ; } else if ( countryName == null ) { return cityName ; } return cityName + ", " + countryName ; } catch ( Exception ex ) { return UNKNOWN ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void configure ( RedisConnection connection ) { String notifyOptions = getNotifyOptions ( connection ) ; String customizedNotifyOptions = notifyOptions ; if ( ! customizedNotifyOptions . contains ( "E" ) ) { customizedNotifyOptions += "E" ; } boolean A = customizedNotifyOptions . contains ( "A" ) ; if ( ! ( A || customizedNotifyOptions . contains ( "g" ) ) ) { customizedNotifyOptions += "g" ; } if ( ! ( A || customizedNotifyOptions . contains ( "x" ) ) ) { customizedNotifyOptions += "x" ; } if ( ! notifyOptions . equals ( customizedNotifyOptions ) ) { connection . setConfig ( CONFIG_NOTIFY_KEYSPACE_EVENTS , customizedNotifyOptions ) ; } }


Input: Configure a { @link WebSessionManager } using a provided { @link ReactiveSessionRepository } . [CODESPLIT] @ Bean ( WebHttpHandlerBuilder . WEB_SESSION_MANAGER_BEAN_NAME ) public WebSessionManager webSessionManager ( ReactiveSessionRepository < ? extends Session > repository ) { SpringSessionWebSessionStore < ? extends Session > sessionStore = new SpringSessionWebSessionStore <> ( repository ) ; DefaultWebSessionManager manager = new DefaultWebSessionManager ( ) ; manager . setSessionStore ( sessionStore ) ; if ( this . webSessionIdResolver != null ) { manager . setSessionIdResolver ( this . webSessionIdResolver ) ; } return manager ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { User user = this . userRepository . findByEmail ( username ) ; if ( user == null ) { throw new UsernameNotFoundException ( "Could not find user " + username ) ; } return new CustomUserDetails ( user ) ; }


Input: Allows customization of whether a remember - me login has been requested . The default is to return { [CODESPLIT] protected boolean rememberMeRequested ( HttpServletRequest request , String parameter ) { String rememberMe = request . getParameter ( parameter ) ; if ( rememberMe != null ) { if ( rememberMe . equalsIgnoreCase ( "true" ) || rememberMe . equalsIgnoreCase ( "on" ) || rememberMe . equalsIgnoreCase ( "yes" ) || rememberMe . equals ( "1" ) ) { return true ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')" ) ; } return false ; }


Input: Derives a String name for the given principal . [CODESPLIT] protected String name ( Object principal ) { if ( principal instanceof UserDetails ) { return ( ( UserDetails ) principal ) . getUsername ( ) ; } if ( principal instanceof Principal ) { return ( ( Principal ) principal ) . getName ( ) ; } return principal . toString ( ) ; }


Input: Registers the springSessionRepositoryFilter . [CODESPLIT] private void insertSessionRepositoryFilter ( ServletContext servletContext ) { String filterName = DEFAULT_FILTER_NAME ; DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy ( filterName ) ; String contextAttribute = getWebApplicationContextAttribute ( ) ; if ( contextAttribute != null ) { springSessionRepositoryFilter . setContextAttribute ( contextAttribute ) ; } registerFilter ( servletContext , true , filterName , springSessionRepositoryFilter ) ; }


Input: Get the { [CODESPLIT] protected EnumSet < DispatcherType > getSessionDispatcherTypes ( ) { return EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ERROR , DispatcherType . ASYNC ) ; }


Input: Tries to determine the principal s name from the given Session . [CODESPLIT] private static String resolvePrincipal ( Session session ) { String principalName = session . getAttribute ( FindByIndexNameSessionRepository . PRINCIPAL_NAME_INDEX_NAME ) ; if ( principalName != null ) { return principalName ; } SecurityContext securityContext = session . getAttribute ( SPRING_SECURITY_CONTEXT ) ; if ( securityContext != null && securityContext . getAuthentication ( ) != null ) { return securityContext . getAuthentication ( ) . getName ( ) ; } return "" ; }


Input: This { [CODESPLIT] @ Override public final void doFilter ( ServletRequest request , ServletResponse response , FilterChain filterChain ) throws ServletException , IOException { if ( ! ( request instanceof HttpServletRequest ) || ! ( response instanceof HttpServletResponse ) ) { throw new ServletException ( "OncePerRequestFilter just supports HTTP requests" ) ; } HttpServletRequest httpRequest = ( HttpServletRequest ) request ; HttpServletResponse httpResponse = ( HttpServletResponse ) response ; boolean hasAlreadyFilteredAttribute = request . getAttribute ( this . alreadyFilteredAttributeName ) != null ; if ( hasAlreadyFilteredAttribute ) { // Proceed without invoking this filter... filterChain . doFilter ( request , response ) ; } else { // Do invoke this filter... request . setAttribute ( this . alreadyFilteredAttributeName , Boolean . TRUE ) ; try { doFilterInternal ( httpRequest , httpResponse , filterChain ) ; } finally { // Remove the "already filtered" request attribute for this request. request . removeAttribute ( this . alreadyFilteredAttributeName ) ; } } }


Input: Gets the session . [CODESPLIT] private RedisSession getSession ( String id , boolean allowExpired ) { Map < Object , Object > entries = getSessionBoundHashOperations ( id ) . entries ( ) ; if ( entries . isEmpty ( ) ) { return null ; } MapSession loaded = loadSession ( id , entries ) ; if ( ! allowExpired && loaded . isExpired ( ) ) { return null ; } RedisSession result = new RedisSession ( loaded ) ; result . originalLastAccessTime = loaded . getLastAccessedTime ( ) ; return result ; }


Input: Gets the { [CODESPLIT] private BoundHashOperations < Object , Object , Object > getSessionBoundHashOperations ( String sessionId ) { String key = getSessionKey ( sessionId ) ; return this . sessionRedisOperations . boundHashOps ( key ) ; }


Input: Make any runtime changes necessary to effect the changes indicated by the given { @code operation } . E <p > It constructs a MailSessionService that provides mail session and registers it to Naming service . < / p > [CODESPLIT] @ Override protected void performRuntime ( OperationContext context , ModelNode operation , ModelNode model ) throws OperationFailedException { final PathAddress address = context . getCurrentAddress ( ) ; ModelNode fullTree = Resource . Tools . readModel ( context . readResource ( PathAddress . EMPTY_ADDRESS ) ) ; installRuntimeServices ( context , address , fullTree ) ; }


Input: Extracts the raw JNDI_NAME value from the given model node and depending on the value and the value of any USE_JAVA_CONTEXT child node converts the raw name into a compliant jndi name . [CODESPLIT] static String getJndiName ( final ModelNode modelNode , OperationContext context ) throws OperationFailedException { final String rawJndiName = MailSessionDefinition . JNDI_NAME . resolveModelAttribute ( context , modelNode ) . asString ( ) ; return getJndiName ( rawJndiName ) ; }


Input: This method returns the class names of the parameters of the given method in canonical form . In case of a method without parameters it will return an empty array . [CODESPLIT] public static String [ ] getCanonicalParameterTypes ( Method viewMethod ) { Class < ? > [ ] parameterTypes = viewMethod . getParameterTypes ( ) ; if ( parameterTypes == null ) { return NO_STRINGS ; } String [ ] canonicalNames = new String [ parameterTypes . length ] ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { canonicalNames [ i ] = parameterTypes [ i ] . getCanonicalName ( ) ; } return canonicalNames ; }


Input: This is only allowed at various points of the transaction lifecycle . [CODESPLIT] public void registerInterposedSynchronization ( Synchronization synchronization ) throws IllegalStateException , SystemException { int status = ContextTransactionSynchronizationRegistry . getInstance ( ) . getTransactionStatus ( ) ; switch ( status ) { case javax . transaction . Status . STATUS_ACTIVE : case javax . transaction . Status . STATUS_PREPARING : break ; case Status . STATUS_MARKED_ROLLBACK : // do nothing; we can pretend like it was registered, but it'll never be run anyway. return ; default : throw TransactionLogger . ROOT_LOGGER . syncsnotallowed ( status ) ; } if ( synchronization . getClass ( ) . getName ( ) . startsWith ( "org.jboss.jca" ) ) { if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( "JCAOrderedLastSynchronizationList.jcaSyncs.add - Class: " + synchronization . getClass ( ) + " HashCode: " + synchronization . hashCode ( ) + " toString: " + synchronization ) ; } jcaSyncs . add ( synchronization ) ; } else { if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( "JCAOrderedLastSynchronizationList.preJcaSyncs.add - Class: " + synchronization . getClass ( ) + " HashCode: " + synchronization . hashCode ( ) + " toString: " + synchronization ) ; } preJcaSyncs . add ( synchronization ) ; } }


Input: Exceptions from Synchronizations that are registered with this TSR are not trapped for before completion . This is because an error in a Sync here should result in the transaction rolling back . [CODESPLIT] @ Override public void beforeCompletion ( ) { // This is needed to guard against syncs being registered during the run, otherwise we could have used an iterator int lastIndexProcessed = 0 ; while ( ( lastIndexProcessed < preJcaSyncs . size ( ) ) ) { Synchronization preJcaSync = preJcaSyncs . get ( lastIndexProcessed ) ; if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( "JCAOrderedLastSynchronizationList.preJcaSyncs.before_completion - Class: " + preJcaSync . getClass ( ) + " HashCode: " + preJcaSync . hashCode ( ) + " toString: " + preJcaSync ) ; } preJcaSync . beforeCompletion ( ) ; lastIndexProcessed = lastIndexProcessed + 1 ; } // Do the same for the jca syncs lastIndexProcessed = 0 ; while ( ( lastIndexProcessed < jcaSyncs . size ( ) ) ) { Synchronization jcaSync = jcaSyncs . get ( lastIndexProcessed ) ; if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( "JCAOrderedLastSynchronizationList.jcaSyncs.before_completion - Class: " + jcaSync . getClass ( ) + " HashCode: " + jcaSync . hashCode ( ) + " toString: " + jcaSync ) ; } jcaSync . beforeCompletion ( ) ; lastIndexProcessed = lastIndexProcessed + 1 ; } }


Input: Called by <code > TxServerInterceptorInitializer< / code > at ORB initialization time . [CODESPLIT] static void init ( int slotId , Codec codec , org . omg . PortableInterceptor . Current piCurrent ) { TxServerInterceptor . slotId = slotId ; TxServerInterceptor . codec = codec ; TxServerInterceptor . piCurrent = piCurrent ; }


Input: Returns the transaction associated with the transaction propagation context that arrived in the current IIOP request . [CODESPLIT] public static Transaction getCurrentTransaction ( ) { Transaction tx = null ; if ( piCurrent != null ) { // A non-null piCurrent means that a TxServerInterceptor was // installed: check if there is a transaction propagation context try { Any any = piCurrent . get_slot ( slotId ) ; if ( any . type ( ) . kind ( ) . value ( ) != TCKind . _tk_null ) { // Yes, there is a TPC: add the foreign transaction marker tx = ForeignTransaction . INSTANCE ; } } catch ( InvalidSlot e ) { throw IIOPLogger . ROOT_LOGGER . errorGettingSlotInTxInterceptor ( e ) ; } } return tx ; }


Input: Reads and trims the text for the given attribute and returns it or { @code defaultValue } if there is no value for the attribute [CODESPLIT] private String rawAttributeText ( XMLStreamReader reader , String attributeName , String defaultValue ) { return reader . getAttributeValue ( "" , attributeName ) == null ? defaultValue : reader . getAttributeValue ( "" , attributeName ) . trim ( ) ; }


Input: { [CODESPLIT] @ Override public synchronized void start ( StartContext context ) throws StartException { SecurityLogger . ROOT_LOGGER . debugf ( "Starting SubjectFactoryService" ) ; final ISecurityManagement injectedSecurityManagement = securityManagementValue . getValue ( ) ; int i = subjectFactoryClassName . lastIndexOf ( ":" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( "subject-factory-class-name attribute" ) ; String moduleSpec = subjectFactoryClassName . substring ( 0 , i ) ; String className = subjectFactoryClassName . substring ( i + 1 ) ; JBossSecuritySubjectFactory subjectFactory = null ; try { Class < ? > subjectFactoryClazz = SecurityActions . getModuleClassLoader ( moduleSpec ) . loadClass ( className ) ; subjectFactory = ( JBossSecuritySubjectFactory ) subjectFactoryClazz . newInstance ( ) ; } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( "SubjectFactoryService" , e ) ; } subjectFactory . setSecurityManagement ( injectedSecurityManagement ) ; this . subjectFactory = subjectFactory ; }


Input: Add POJO module if we have any bean factories . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext . getDeploymentUnit ( ) ; final List < KernelDeploymentXmlDescriptor > kdXmlDescriptors = unit . getAttachment ( KernelDeploymentXmlDescriptor . ATTACHMENT_KEY ) ; if ( kdXmlDescriptors == null || kdXmlDescriptors . isEmpty ( ) ) return ; for ( KernelDeploymentXmlDescriptor kdxd : kdXmlDescriptors ) { if ( kdxd . getBeanFactoriesCount ( ) > 0 ) { final ModuleSpecification moduleSpecification = unit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; ModuleDependency dependency = new ModuleDependency ( moduleLoader , POJO_MODULE , false , false , false , false ) ; PathFilter filter = PathFilters . isChildOf ( BaseBeanFactory . class . getPackage ( ) . getName ( ) ) ; dependency . addImportFilter ( filter , true ) ; dependency . addImportFilter ( PathFilters . rejectAll ( ) , false ) ; moduleSpecification . addSystemDependency ( dependency ) ; return ; } } }


Input: Return a list of all the entries contained here . [CODESPLIT] protected ArrayList getContainedEntries ( ) { final ArrayList ret = new ArrayList ( constants . length + attributes . length + members . length ) ; for ( int i = 0 ; i < constants . length ; ++ i ) ret . ( constants [ i ] ) ; for ( int i = 0 ; i < attributes . length ; ++ i ) ret . ( attributes [ i ] ) ; for ( int i = 0 ; i < members . length ; ++ i ) ret . ( members [ i ] ) ; return ret ; }


Input: determine if management console can display the second level cache entries [CODESPLIT] @ Override public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName ( PersistenceUnitMetadata pu ) { String cacheRegionPrefix = pu . getProperties ( ) . getProperty ( AvailableSettings . CACHE_REGION_PREFIX ) ; return cacheRegionPrefix == null || cacheRegionPrefix . equals ( pu . getScopedPersistenceUnitName ( ) ) ; }


Input: Process the model to figure out the name of the services the server config service has to depend on [CODESPLIT] private static List < ServiceName > getServerConfigDependencies ( OperationContext context , boolean appclient ) { final List < ServiceName > serviceNames = new ArrayList < ServiceName > ( ) ; final Resource subsystemResource = context . readResourceFromRoot ( PathAddress . pathAddress ( WSExtension . SUBSYSTEM_PATH ) , false ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . CLIENT_CONFIG ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . ENDPOINT_CONFIG ) ; if ( ! appclient ) { serviceNames . add ( CommonWebServer . SERVICE_NAME ) ; } return serviceNames ; }


Input: Validates the credential . Unfortunately there is not much we can do here by default . <p / > This method can be overridden to provide some real validation logic [CODESPLIT] protected void validateCredential ( final String username , final SASCurrent credential ) throws LoginException { if ( credential . get_incoming_principal_name ( ) == null || credential . get_incoming_principal_name ( ) . length == 0 ) { throw new LoginException ( ) ; } }


Input: Returns true if the passed <code > mdbClass< / code > meets the requirements set by the EJB3 spec about bean implementation classes . The passed <code > mdbClass< / code > must not be an interface and must be public and not final and not abstract . If it passes these requirements then this method returns true . Else it returns false . [CODESPLIT] public static Collection < MdbValidityStatus > assertEjbClassValidity ( final ClassInfo mdbClass ) throws DeploymentUnitProcessingException { Collection < MdbValidityStatus > mdbComplianceIssueList = new ArrayList <> ( MdbValidityStatus . values ( ) . length ) ; final String className = mdbClass . name ( ) . toString ( ) ; verifyModifiers ( className , mdbClass . flags ( ) , mdbComplianceIssueList ) ; for ( MethodInfo method : mdbClass . methods ( ) ) { if ( "onMessage" . equals ( method . name ( ) ) ) { verifyOnMessageMethod ( className , method . flags ( ) , mdbComplianceIssueList ) ; } if ( "finalize" . equals ( method . name ( ) ) ) { EjbLogger . DEPLOYMENT_LOGGER . mdbCantHaveFinalizeMethod ( className ) ; mdbComplianceIssueList . add ( MdbValidityStatus . MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD ) ; } } return mdbComplianceIssueList ; }


Input: <p > This method needs to be called once to initialize the static fields orb and rootPoa . < / p > [CODESPLIT] public static void init ( org . omg . CORBA . ORB orb , org . omg . PortableServer . POA rootPoa ) { CorbaNamingContext . orb = orb ; CorbaNamingContext . rootPoa = rootPoa ; }


Input: <p > This method needs to be called for each newly created or re - read naming context to set its POA . < / p > [CODESPLIT] public void init ( POA poa , boolean doPurge , boolean noPing ) { this . poa = poa ; this . doPurge = doPurge ; this . noPing = noPing ; }


Input: ======================================= NamingContextOperation Methods ================================== // [CODESPLIT] public void bind ( NameComponent [ ] nc , org . omg . CORBA . Object obj ) throws NotFound , CannotProceed , InvalidName , AlreadyBound { if ( this . destroyed ) throw new CannotProceed ( ) ; if ( nc == null || nc . length == 0 ) throw new InvalidName ( ) ; if ( obj == null ) throw new org . omg . CORBA . BAD_PARAM ( ) ; Name n = new Name ( nc ) ; Name ctx = n . ctxName ( ) ; NameComponent nb = n . baseNameComponent ( ) ; if ( ctx == null ) { if ( this . names . containsKey ( n ) ) { // if the name is still in use, try to ping the object org . omg . CORBA . Object ref = ( org . omg . CORBA . Object ) this . names . get ( n ) ; if ( isDead ( ref ) ) { rebind ( n . components ( ) , obj ) ; return ; } throw new AlreadyBound ( ) ; } else if ( this . contexts . containsKey ( n ) ) { // if the name is still in use, try to ping the object org . omg . CORBA . Object ref = ( org . omg . CORBA . Object ) this . contexts . get ( n ) ; if ( isDead ( ref ) ) unbind ( n . components ( ) ) ; throw new AlreadyBound ( ) ; } if ( ( this . names . put ( n , obj ) ) != null ) throw new CannotProceed ( _this ( ) , n . components ( ) ) ; IIOPLogger . ROOT_LOGGER . debugf ( "Bound name: %s" , n ) ; } else { NameComponent [ ] ncx = new NameComponent [ ] { nb } ; org . omg . CORBA . Object context = this . resolve ( ctx . components ( ) ) ; // try first to call the context implementation object directly. String contextOID = this . getObjectOID ( context ) ; CorbaNamingContext jbossContext = ( contextOID == null ? null : contextImpls . get ( contextOID ) ) ; if ( jbossContext != null ) jbossContext . bind ( ncx , obj ) ; else NamingContextExtHelper . narrow ( context ) . bind ( ncx , obj ) ; } }


Input: ======================================= NamingContextExtOperations Methods ================================== // [CODESPLIT] public org . omg . CORBA . Object resolve_str ( String n ) throws NotFound , CannotProceed , InvalidName { return resolve ( to_name ( n ) ) ; }


Input: <p > Cleanup bindings i . e . ping every object and remove bindings to non - existent objects . < / p > [CODESPLIT] private void cleanup ( ) { // Check if object purging enabled if ( ! this . doPurge ) return ; for ( Name key : this . names . keySet ( ) ) { if ( isDead ( ( ( org . omg . CORBA . Object ) this . names . get ( key ) ) ) ) { this . names . remove ( key ) ; } } for ( Name key : this . contexts . keySet ( ) ) { org . omg . CORBA . Object object = ( org . omg . CORBA . Object ) this . contexts . get ( key ) ; if ( isDead ( object ) ) { this . contexts . remove ( key ) ; String oid = this . getObjectOID ( object ) ; if ( oid != null ) contextImpls . remove ( oid ) ; } } }


Input: <p > Obtains the OID of the specified CORBA object . < / p > [CODESPLIT] private String getObjectOID ( org . omg . CORBA . Object object ) { String oid = null ; try { byte [ ] oidBytes = this . poa . reference_to_id ( object ) ; if ( oidBytes != null ) oid = new String ( oidBytes , StandardCharsets . UTF_8 ) ; } catch ( Exception e ) { IIOPLogger . ROOT_LOGGER . debug ( "Unable to obtain id from object" , e ) ; } return oid ; }


Input: <p > Determines if the supplied object is non_existent < / p > [CODESPLIT] private boolean isDead ( org . omg . CORBA . Object o ) { boolean non_exist ; try { non_exist = o . _non_existent ( ) ; } catch ( org . omg . CORBA . SystemException e ) { non_exist = true ; } return non_exist ; }


Input:
<p > Overrides readObject in Serializable . < / p > [CODESPLIT] private void readObject ( ObjectInputStream in ) throws Exception { in . defaultReadObject ( ) ; /**
         * Recreate tables. For serialization, object references have been transformed into strings
         */ for ( Name key : this . contexts . keySet ( ) ) { String ref = ( String ) this . contexts . remove ( key ) ; this . contexts . put ( key , orb . string_to_object ( ref ) ) ; } for ( Name key : this . names . keySet ( ) ) { String ref = ( String ) this . names . remove ( key ) ; this . names . put ( key , orb . string_to_object ( ref ) ) ; } }


Input:
<p > Overrides writeObject in Serializable . < / p > [CODESPLIT] private void writeObject ( java . io . ObjectOutputStream out ) throws IOException { /*
        * For serialization, object references are transformed into strings
        */ for ( Name key : this . contexts . keySet ( ) ) { org . omg . CORBA . Object o = ( org . omg . CORBA . Object ) this . contexts . remove ( key ) ; this . contexts . put ( key , orb . object_to_string ( o ) ) ; } for ( Name key : this . names . keySet ( ) ) { org . omg . CORBA . Object o = ( org . omg . CORBA . Object ) this . names . remove ( key ) ; this . names . put ( key , orb . object_to_string ( o ) ) ; } out . defaultWriteObject ( ) ; }


Input: Ensures that the current thread doesn t hold any read locks . If the thread holds any read locks this method throws a { [CODESPLIT] private void checkLoopback ( ) { Integer current = readLockCount . get ( ) ; if ( current != null ) { assert current . intValue ( ) > 0 : "readLockCount is set, but to 0" ; throw EjbLogger . ROOT_LOGGER . failToUpgradeToWriteLock ( ) ; } }


Input: Decrements the read lock count held by the thread [CODESPLIT] private void decReadLockCount ( ) { Integer current = readLockCount . get ( ) ; int next ; assert current != null : "can't decrease, readLockCount is not set" ; next = current . intValue ( ) - 1 ; if ( next == 0 ) readLockCount . remove ( ) ; else readLockCount . set ( new Integer ( next ) ) ; }


Input: Increments the read lock count held by the thread [CODESPLIT] private void incReadLockCount ( ) { Integer current = readLockCount . get ( ) ; int next ; if ( current == null ) next = 1 ; else next = current . intValue ( ) + 1 ; readLockCount . set ( new Integer ( next ) ) ; }


Input: Makes all { @link BeanDeploymentArchiveImpl } s in the given module accessible to all bdas in this module [CODESPLIT] public synchronized void addBeanDeploymentModule ( BeanDeploymentModule module ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { bda . addBeanDeploymentArchives ( module . beanDeploymentArchives ) ; } }


Input: Makes all { @link BeanDeploymentArchiveImpl } s in the given modules accessible to all bdas in this module [CODESPLIT] public synchronized void addBeanDeploymentModules ( Collection < BeanDeploymentModule > modules ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { for ( BeanDeploymentModule bdm : modules ) { bda . addBeanDeploymentArchives ( bdm . beanDeploymentArchives ) ; } } }


Input: Adds a service to all bean deployment archives in the module [CODESPLIT] public synchronized < S extends Service > void addService ( Class < S > clazz , S service ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { bda . getServices ( ) . add ( clazz , service ) ; } }


Input: <p > Sets the JACC contextID using a privileged action and returns the previousID from the { @code PolicyContext } . < / p > [CODESPLIT] protected String setContextID ( final String contextID ) { if ( ! WildFlySecurityManager . isChecking ( ) ) { final String previousID = PolicyContext . getContextID ( ) ; PolicyContext . setContextID ( contextID ) ; return previousID ; } else { final PrivilegedAction < String > action = new SetContextIDAction ( contextID ) ; return AccessController . doPrivileged ( action ) ; } }


Input: FunctionalService#destroyer implementation [CODESPLIT] @ Override public void accept ( ModClusterConfiguration modClusterConfiguration ) { if ( advertiseSocketDependency != null ) { SocketBinding binding = advertiseSocketDependency . get ( ) ; ManagedBinding simpleManagedBinding = ManagedBinding . Factory . createSimpleManagedBinding ( binding ) ; binding . getSocketBindings ( ) . getNamedRegistry ( ) . unregisterBinding ( simpleManagedBinding ) ; } }


Input: { [CODESPLIT] @ Override public void registerOperations ( ManagementResourceRegistration container ) { super . registerOperations ( container ) ; container . registerOperationHandler ( ADD_PARAM , WebValveParamAdd . INSTANCE ) ; container . registerOperationHandler ( REMOVE_PARAM , ReloadRequiredRemoveStepHandler . INSTANCE ) ; }


Input: Makes sure that the timer is only run once after being restored . [CODESPLIT] public void handleRestorationCalculation ( ) { if ( nextExpiration == null ) { return ; } //next expiration in the future, we don't care if ( nextExpiration . getTime ( ) >= System . currentTimeMillis ( ) ) { return ; } //just set the next expiration to 1ms in the past //this means it will run to catch up the missed expiration //and then the next calculated expiration will be in the future nextExpiration = new Date ( System . currentTimeMillis ( ) - 1 ) ; }


Input: Returns the { @link java . lang . reflect . Method } represented by the { @link org . jboss . as . ejb3 . timerservice . persistence . TimeoutMethod } <p > Note : This method uses the { @link Thread#getContextClassLoader () } to load the relevant classes while getting the { @link java . lang . reflect . Method } < / p > [CODESPLIT] public static Method getTimeoutMethod ( TimeoutMethod timeoutMethodInfo , ClassLoader classLoader ) { if ( timeoutMethodInfo == null ) { return null ; } String declaringClass = timeoutMethodInfo . getDeclaringClass ( ) ; Class < ? > timeoutMethodDeclaringClass = null ; try { timeoutMethodDeclaringClass = Class . forName ( declaringClass , false , classLoader ) ; } catch ( ClassNotFoundException cnfe ) { throw EjbLogger . EJB3_TIMER_LOGGER . failToLoadDeclaringClassOfTimeOut ( declaringClass ) ; } String timeoutMethodName = timeoutMethodInfo . getMethodName ( ) ; String [ ] timeoutMethodParams = timeoutMethodInfo . getMethodParams ( ) ; // load the method param classes Class < ? > [ ] timeoutMethodParamTypes = new Class < ? > [ ] { } ; if ( timeoutMethodParams != null ) { timeoutMethodParamTypes = new Class < ? > [ timeoutMethodParams . length ] ; int i = 0 ; for ( String paramClassName : timeoutMethodParams ) { Class < ? > methodParamClass = null ; try { methodParamClass = Class . forName ( paramClassName , false , classLoader ) ; } catch ( ClassNotFoundException cnfe ) { throw EjbLogger . EJB3_TIMER_LOGGER . failedToLoadTimeoutMethodParamClass ( cnfe , paramClassName ) ; } timeoutMethodParamTypes [ i ++ ] = methodParamClass ; } } // now start looking for the method Class < ? > klass = timeoutMethodDeclaringClass ; while ( klass != null ) { Method [ ] methods = klass . getDeclaredMethods ( ) ; for ( Method method : methods ) { if ( method . getName ( ) . equals ( timeoutMethodName ) ) { Class < ? > [ ] methodParamTypes = method . getParameterTypes ( ) ; // param length doesn't match if ( timeoutMethodParamTypes . length != methodParamTypes . length ) { continue ; } boolean match = true ; for ( int i = 0 ; i < methodParamTypes . length ; i ++ ) { // param type doesn't match if ( ! timeoutMethodParamTypes [ i ] . equals ( methodParamTypes [ i ] ) ) { match = false ; break ; } } if ( match ) { // match found return method ; } } } klass = klass . getSuperclass ( ) ; } // no match found return null ; }


Input: { [CODESPLIT] public void handle ( javax . security . auth . callback . Callback [ ] callbacks ) throws UnsupportedCallbackException , IOException { if ( SUBSYSTEM_RA_LOGGER . isTraceEnabled ( ) ) SUBSYSTEM_RA_LOGGER . elytronHandlerHandle ( Arrays . toString ( callbacks ) ) ; // work wrapper calls the callback handler a second time with default callback values after the handler was invoked // by the RA. We must check if the execution subject already contains an identity and allow for replacement of the // identity with values found in the default callbacks only if the subject has no identity yet or if the identity // is the anonymous one. if ( this . executionSubject != null ) { final SecurityIdentity subjectIdentity = this . getPrivateCredential ( this . executionSubject , SecurityIdentity . class ) ; if ( subjectIdentity != null && ! subjectIdentity . isAnonymous ( ) ) { return ; } } if ( callbacks != null && callbacks . length > 0 ) { if ( this . mappings != null && this . mappings . isMappingRequired ( ) ) { callbacks = this . mappings . mapCallbacks ( callbacks ) ; } GroupPrincipalCallback groupPrincipalCallback = null ; CallerPrincipalCallback callerPrincipalCallback = null ; PasswordValidationCallback passwordValidationCallback = null ; for ( javax . security . auth . callback . Callback callback : callbacks ) { if ( callback instanceof GroupPrincipalCallback ) { groupPrincipalCallback = ( GroupPrincipalCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = groupPrincipalCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( groupPrincipalCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else if ( callback instanceof CallerPrincipalCallback ) { callerPrincipalCallback = ( CallerPrincipalCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = callerPrincipalCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( callerPrincipalCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else if ( callback instanceof PasswordValidationCallback ) { passwordValidationCallback = ( PasswordValidationCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = passwordValidationCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( passwordValidationCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else { throw new UnsupportedCallbackException ( callback ) ; } } this . handleInternal ( callerPrincipalCallback , groupPrincipalCallback , passwordValidationCallback ) ; } }


Input: Authenticate the user with the given credential against the configured Elytron security domain . [CODESPLIT] private SecurityIdentity authenticate ( final String username , final char [ ] credential ) throws IOException { final ServerAuthenticationContext context = this . securityDomain . createNewAuthenticationContext ( ) ; final PasswordGuessEvidence evidence = new PasswordGuessEvidence ( credential != null ? credential : null ) ; try { context . setAuthenticationName ( username ) ; if ( context . verifyEvidence ( evidence ) ) { if ( context . authorize ( ) ) { context . succeed ( ) ; return context . getAuthorizedIdentity ( ) ; } else { context . fail ( ) ; throw new SecurityException ( "Authorization failed" ) ; } } else { context . fail ( ) ; throw new SecurityException ( "Authentication failed" ) ; } } catch ( IllegalArgumentException | IllegalStateException | RealmUnavailableException e ) { context . fail ( ) ; throw e ; } finally { if ( ! context . isDone ( ) ) { context . fail ( ) ; } evidence . destroy ( ) ; } }


Input: Loads the persistence provider adapter [CODESPLIT] public static PersistenceProviderAdaptor loadPersistenceAdapterModule ( final String adapterModule , final Platform platform , JtaManagerImpl manager ) throws ModuleLoadException { final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; if ( adapterModule == null ) { return noopAdaptor ; } PersistenceProviderAdaptor persistenceProviderAdaptor = null ; Module module = moduleLoader . loadModule ( ModuleIdentifier . fromString ( adapterModule ) ) ; final ServiceLoader < PersistenceProviderAdaptor > serviceLoader = module . loadService ( PersistenceProviderAdaptor . class ) ; if ( serviceLoader != null ) { for ( PersistenceProviderAdaptor adaptor : serviceLoader ) { if ( persistenceProviderAdaptor != null ) { throw JpaLogger . ROOT_LOGGER . multipleAdapters ( adapterModule ) ; } persistenceProviderAdaptor = adaptor ; ROOT_LOGGER . debugf ( "loaded persistence provider adapter %s" , adapterModule ) ; } if ( persistenceProviderAdaptor != null ) { persistenceProviderAdaptor . injectJtaManager ( manager ) ; persistenceProviderAdaptor . injectPlatform ( platform ) ; } } return persistenceProviderAdaptor ; }


Input: Loads the persistence provider adapter [CODESPLIT] public static PersistenceProviderAdaptor loadPersistenceAdapter ( final PersistenceProvider persistenceProvider , final Platform platform , final JtaManagerImpl jtaManager ) { PersistenceProviderAdaptor persistenceProviderAdaptor = null ; final ServiceLoader < PersistenceProviderAdaptor > serviceLoader = ServiceLoader . load ( PersistenceProviderAdaptor . class , persistenceProvider . getClass ( ) . getClassLoader ( ) ) ; if ( serviceLoader != null ) { for ( PersistenceProviderAdaptor adaptor : serviceLoader ) { if ( persistenceProviderAdaptor != null ) { throw JpaLogger . ROOT_LOGGER . classloaderHasMultipleAdapters ( persistenceProvider . getClass ( ) . getClassLoader ( ) . toString ( ) ) ; } persistenceProviderAdaptor = adaptor ; ROOT_LOGGER . debugf ( "loaded persistence provider adapter %s from classloader %s" , persistenceProviderAdaptor . getClass ( ) . getName ( ) , persistenceProvider . getClass ( ) . getClassLoader ( ) . toString ( ) ) ; } if ( persistenceProviderAdaptor != null ) { persistenceProviderAdaptor . injectJtaManager ( jtaManager ) ; persistenceProviderAdaptor . injectPlatform ( platform ) ; } } return persistenceProviderAdaptor == null ? noopAdaptor : persistenceProviderAdaptor ; }


Input: if set to auto will behave like not having set the property [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; if ( JPADeploymentMarker . isJPADeployment ( deploymentUnit ) ) { addSearchDependency ( moduleSpecification , moduleLoader , deploymentUnit ) ; } }


Input: Returns the { [CODESPLIT] public Timer getTimer ( ) throws IllegalStateException , EJBException { if ( service == null ) { // get hold of the timer service through the use of timed object id service = ( TimerServiceImpl ) currentServiceContainer ( ) . getRequiredService ( ServiceName . parse ( serviceName ) ) . getValue ( ) ; if ( service == null ) { throw EjbLogger . EJB3_TIMER_LOGGER . timerServiceWithIdNotRegistered ( timedObjectId ) ; } } final TimerImpl timer = this . service . getTimer ( this ) ; if ( timer == null || ! timer . isActive ( ) ) { throw EjbLogger . EJB3_TIMER_LOGGER . timerHandleIsNotActive ( this ) ; } return timer ; }


Input: { @link org . jboss . as . weld . deployment . processors . WeldDeploymentProcessor } assembles a basic accessibility graph based on the deployment structure . Here we complete the graph by examining classloader visibility . This allows additional accessibility edges caused e . g . by the Class - Path declaration in the manifest file to be recognized . [CODESPLIT] private void calculateAccessibilityGraph ( Iterable < BeanDeploymentArchiveImpl > beanDeploymentArchives ) { for ( BeanDeploymentArchiveImpl from : beanDeploymentArchives ) { for ( BeanDeploymentArchiveImpl target : beanDeploymentArchives ) { if ( from . isAccessible ( target ) ) { from . addBeanDeploymentArchive ( target ) ; } } } }


Input: Adds additional edges to the accessibility graph that allow static CDI - enabled modules to inject beans from top - level deployment units [CODESPLIT] private void makeTopLevelBdasVisibleFromStaticModules ( ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { if ( bda . getBeanArchiveType ( ) . equals ( BeanDeploymentArchiveImpl . BeanArchiveType . EXTERNAL ) || bda . getBeanArchiveType ( ) . equals ( BeanDeploymentArchiveImpl . BeanArchiveType . SYNTHETIC ) ) { for ( BeanDeploymentArchiveImpl topLevelBda : rootBeanDeploymentModule . getBeanDeploymentArchives ( ) ) { bda . addBeanDeploymentArchive ( topLevelBda ) ; } } } }


Input:
{ [CODESPLIT] public synchronized BeanDeploymentArchive loadBeanDeploymentArchive ( final Class < ? > beanClass ) { final BeanDeploymentArchive bda = this . getBeanDeploymentArchive ( beanClass ) ; if ( bda != null ) { return bda ; } Module module = Module . forClass ( beanClass ) ; if ( module == null ) { // Bean class loaded by the bootstrap class loader if ( bootstrapClassLoaderBeanDeploymentArchive == null ) { bootstrapClassLoaderBeanDeploymentArchive = createAndRegisterAdditionalBeanDeploymentArchive ( module , beanClass ) ; } else { bootstrapClassLoaderBeanDeploymentArchive . addBeanClass ( beanClass ) ; } return bootstrapClassLoaderBeanDeploymentArchive ; } /*
         * No, there is no BDA for the class yet. Let's create one.
         */ return createAndRegisterAdditionalBeanDeploymentArchive ( module , beanClass ) ; }


Input: Builds universal JSE meta data model that is AS agnostic . [CODESPLIT] JSEArchiveMetaData create ( final Deployment dep ) { if ( WSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { WSLogger . ROOT_LOGGER . tracef ( "Creating JBoss agnostic meta data for POJO webservice deployment: %s" , dep . getSimpleName ( ) ) ; } final JBossWebMetaData jbossWebMD = WSHelper . getRequiredAttachment ( dep , JBossWebMetaData . class ) ; final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; final List < POJOEndpoint > pojoEndpoints = getPojoEndpoints ( unit ) ; final JSEArchiveMetaData . Builder builder = new JSEArchiveMetaData . Builder ( ) ; // set context root final String contextRoot = getContextRoot ( dep , jbossWebMD ) ; builder . setContextRoot ( contextRoot ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting context root: %s" , contextRoot ) ; // set servlet url patterns mappings final Map < String , String > servletMappings = getServletUrlPatternsMappings ( jbossWebMD , pojoEndpoints ) ; builder . setServletMappings ( servletMappings ) ; // set servlet class names mappings final Map < String , String > servletClassNamesMappings = getServletClassMappings ( jbossWebMD , pojoEndpoints ) ; builder . setServletClassNames ( servletClassNamesMappings ) ; // set security domain final String securityDomain = jbossWebMD . getSecurityDomain ( ) ; builder . setSecurityDomain ( securityDomain ) ; // set wsdl location resolver final JBossWebservicesMetaData jbossWebservicesMD = WSHelper . getOptionalAttachment ( dep , JBossWebservicesMetaData . class ) ; if ( jbossWebservicesMD != null ) { final PublishLocationAdapter resolver = new PublishLocationAdapterImpl ( jbossWebservicesMD . getWebserviceDescriptions ( ) ) ; builder . setPublishLocationAdapter ( resolver ) ; } // set security meta data final List < JSESecurityMetaData > jseSecurityMDs = getSecurityMetaData ( jbossWebMD . getSecurityConstraints ( ) ) ; builder . setSecurityMetaData ( jseSecurityMDs ) ; // set config name and file setConfigNameAndFile ( builder , jbossWebMD , jbossWebservicesMD ) ; return builder . build ( ) ; }


Input: Sets config name and config file . [CODESPLIT] private void setConfigNameAndFile ( final JSEArchiveMetaData . Builder builder , final JBossWebMetaData jbossWebMD , final JBossWebservicesMetaData jbossWebservicesMD ) { if ( jbossWebservicesMD != null ) { if ( jbossWebservicesMD . getConfigName ( ) != null ) { final String configName = jbossWebservicesMD . getConfigName ( ) ; builder . setConfigName ( configName ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting config name: %s" , configName ) ; final String configFile = jbossWebservicesMD . getConfigFile ( ) ; builder . setConfigFile ( configFile ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting config file: %s" , configFile ) ; // ensure higher priority against web.xml context parameters return ; } } final List < ParamValueMetaData > contextParams = jbossWebMD . getContextParams ( ) ; if ( contextParams != null ) { for ( final ParamValueMetaData contextParam : contextParams ) { if ( WSConstants . JBOSSWS_CONFIG_NAME . equals ( contextParam . getParamName ( ) ) ) { final String configName = contextParam . getParamValue ( ) ; builder . setConfigName ( configName ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting config name: %s" , configName ) ; } if ( WSConstants . JBOSSWS_CONFIG_FILE . equals ( contextParam . getParamName ( ) ) ) { final String configFile = contextParam . getParamValue ( ) ; builder . setConfigFile ( configFile ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting config file: %s" , configFile ) ; } } } }


Input: Builds security meta data . [CODESPLIT] private List < JSESecurityMetaData > getSecurityMetaData ( final List < SecurityConstraintMetaData > securityConstraintsMD ) { final List < JSESecurityMetaData > jseSecurityMDs = new LinkedList < JSESecurityMetaData > ( ) ; if ( securityConstraintsMD != null ) { for ( final SecurityConstraintMetaData securityConstraintMD : securityConstraintsMD ) { final JSESecurityMetaData . Builder jseSecurityMDBuilder = new JSESecurityMetaData . Builder ( ) ; // transport guarantee jseSecurityMDBuilder . setTransportGuarantee ( securityConstraintMD . getTransportGuarantee ( ) . name ( ) ) ; // web resources for ( final WebResourceCollectionMetaData webResourceMD : securityConstraintMD . getResourceCollections ( ) ) { jseSecurityMDBuilder . addWebResource ( webResourceMD . getName ( ) , webResourceMD . getUrlPatterns ( ) ) ; } jseSecurityMDs . add ( jseSecurityMDBuilder . build ( ) ) ; } } return jseSecurityMDs ; }


Input: Returns servlet name to url pattern mappings . [CODESPLIT] private Map < String , String > getServletUrlPatternsMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final List < ServletMappingMetaData > servletMappings = WebMetaDataHelper . getServletMappings ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { mappings . put ( pojoEndpoint . getName ( ) , pojoEndpoint . getUrlPattern ( ) ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final List < String > urlPatterns = WebMetaDataHelper . getUrlPatterns ( pojoEndpoint . getUrlPattern ( ) ) ; WebMetaDataHelper . newServletMapping ( endpointName , urlPatterns , servletMappings ) ; } } return mappings ; }


Input: Returns servlet name to servlet class mappings . [CODESPLIT] private Map < String , String > getServletClassMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final JBossServletsMetaData servlets = WebMetaDataHelper . getServlets ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { final String pojoName = pojoEndpoint . getName ( ) ; final String pojoClassName = pojoEndpoint . getClassName ( ) ; mappings . put ( pojoName , pojoClassName ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final String endpointClassName = pojoEndpoint . getClassName ( ) ; WebMetaDataHelper . newServlet ( endpointName , endpointClassName , servlets ) ; } } return mappings ; }


Input: Checks if this ejb injection has been resolved yet and if not resolves it . [CODESPLIT] private void resolve ( ) { if ( ! resolved ) { synchronized ( this ) { if ( ! resolved ) { final Set < ViewDescription > views = getViews ( ) ; final Set < EJBViewDescription > ejbsForViewName = new HashSet < EJBViewDescription > ( ) ; for ( final ViewDescription view : views ) { if ( view instanceof EJBViewDescription ) { final MethodIntf viewType = ( ( EJBViewDescription ) view ) . getMethodIntf ( ) ; // @EJB injection *shouldn't* consider the @WebService endpoint view or MDBs if ( viewType == MethodIntf . SERVICE_ENDPOINT || viewType == MethodIntf . MESSAGE_ENDPOINT ) { continue ; } ejbsForViewName . add ( ( EJBViewDescription ) view ) ; } } if ( ejbsForViewName . isEmpty ( ) ) { if ( beanName == null ) { error = EjbLogger . ROOT_LOGGER . ejbNotFound ( typeName , bindingName ) ; } else { error = EjbLogger . ROOT_LOGGER . ejbNotFound ( typeName , beanName , bindingName ) ; } } else if ( ejbsForViewName . size ( ) > 1 ) { if ( beanName == null ) { error = EjbLogger . ROOT_LOGGER . moreThanOneEjbFound ( typeName , bindingName , ejbsForViewName ) ; } else { error = EjbLogger . ROOT_LOGGER . moreThanOneEjbFound ( typeName , beanName , bindingName , ejbsForViewName ) ; } } else { final EJBViewDescription description = ejbsForViewName . iterator ( ) . next ( ) ; final EJBViewDescription ejbViewDescription = ( EJBViewDescription ) description ; //for remote interfaces we do not want to use a normal binding //we need to bind the remote proxy factory into JNDI instead to get the correct behaviour if ( ejbViewDescription . getMethodIntf ( ) == MethodIntf . REMOTE || ejbViewDescription . getMethodIntf ( ) == MethodIntf . HOME ) { final EJBComponentDescription componentDescription = ( EJBComponentDescription ) description . getComponentDescription ( ) ; final EEModuleDescription moduleDescription = componentDescription . getModuleDescription ( ) ; final String earApplicationName = moduleDescription . getEarApplicationName ( ) ; final Value < ClassLoader > viewClassLoader = new Value < ClassLoader > ( ) { @ Override public ClassLoader getValue ( ) throws IllegalStateException , IllegalArgumentException { final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; return module != null ? module . getClassLoader ( ) : null ; } } ; remoteFactory = new RemoteViewManagedReferenceFactory ( earApplicationName , moduleDescription . getModuleName ( ) , moduleDescription . getDistinctName ( ) , componentDescription . getComponentName ( ) , description . getViewClassName ( ) , componentDescription . isStateful ( ) , viewClassLoader , appclient ) ; } final ServiceName serviceName = description . getServiceName ( ) ; resolvedViewName = serviceName ; } resolved = true ; } } } }


Input: { [CODESPLIT] @ Override public Node elect ( List < Node > nodes ) { int size = nodes . size ( ) ; return ( size > 0 ) ? nodes . get ( this . random . nextInt ( size ) ) : null ; }


Input: FIXME use capabilities & requirements [CODESPLIT] private static Set < String > getAvailableConnectors ( final OperationContext context , final ModelNode operation ) throws OperationFailedException { PathAddress address = PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) ; PathAddress active = MessagingServices . getActiveMQServerPathAddress ( address ) ; Set < String > availableConnectors = new HashSet < String > ( ) ; Resource subsystemResource = context . readResourceFromRoot ( active . getParent ( ) , false ) ; availableConnectors . addAll ( subsystemResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; Resource activeMQServerResource = context . readResourceFromRoot ( active , false ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . HTTP_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . IN_VM_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . CONNECTOR ) ) ; return availableConnectors ; }


Input: { [CODESPLIT] public void getResourceValue ( final ResolutionContext resolutionContext , final ServiceBuilder < ? > serviceBuilder , final DeploymentPhaseContext phaseContext , final Injector < ManagedReferenceFactory > injector ) { if ( serviceName != null ) { serviceBuilder . requires ( serviceName ) ; } final RemoteViewManagedReferenceFactory factory = new RemoteViewManagedReferenceFactory ( appName , moduleName , distinctName , beanName , viewClass , stateful , viewClassLoader , appclient ) ; injector . inject ( factory ) ; }


Input: Handle the core - environment element and children [CODESPLIT] static void parseCoreEnvironmentElement ( final XMLExtendedStreamReader reader , final ModelNode operation ) throws XMLStreamException { final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; switch ( attribute ) { case NODE_IDENTIFIER : TransactionSubsystemRootResourceDefinition . NODE_IDENTIFIER . parseAndSetParameter ( value , operation , reader ) ; break ; case PATH : case RELATIVE_TO : throw TransactionLogger . ROOT_LOGGER . unsupportedAttribute ( attribute . getLocalName ( ) , reader . getLocation ( ) ) ; default : throw unexpectedAttribute ( reader , i ) ; } } // elements final EnumSet < Element > required = EnumSet . of ( Element . PROCESS_ID ) ; final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; required . remove ( element ) ; switch ( element ) { case PROCESS_ID : { if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , reader . getLocalName ( ) ) ; } parseProcessIdEnvironmentElement ( reader , operation ) ; break ; } default : throw unexpectedElement ( reader ) ; } } if ( ! required . isEmpty ( ) ) { throw missingRequiredElement ( reader , required ) ; } }


Input: Handle the process - id child elements [CODESPLIT] static void parseProcessIdEnvironmentElement ( XMLExtendedStreamReader reader , ModelNode coreEnvironmentAdd ) throws XMLStreamException { // no attributes if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } // elements boolean encountered = false ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case UUID : if ( encountered ) { throw unexpectedElement ( reader ) ; } encountered = true ; if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } coreEnvironmentAdd . get ( TransactionSubsystemRootResourceDefinition . PROCESS_ID_UUID . getName ( ) ) . set ( true ) ; requireNoContent ( reader ) ; break ; case SOCKET : { if ( encountered ) { throw unexpectedElement ( reader ) ; } encountered = true ; parseSocketProcessIdElement ( reader , coreEnvironmentAdd ) ; break ; } default : throw unexpectedElement ( reader ) ; } } if ( ! encountered ) { throw missingOneOf ( reader , EnumSet . of ( Element . UUID , Element . SOCKET ) ) ; } }


Input: Create EE container entity manager factory [CODESPLIT] private EntityManagerFactoryBuilder createContainerEntityManagerFactoryBuilder ( ) { persistenceProviderAdaptor . beforeCreateContainerEntityManagerFactory ( pu ) ; try { TwoPhaseBootstrapCapable twoPhaseBootstrapCapable = ( TwoPhaseBootstrapCapable ) persistenceProviderAdaptor ; return twoPhaseBootstrapCapable . getBootstrap ( pu , properties . getValue ( ) ) ; } finally { try { persistenceProviderAdaptor . afterCreateContainerEntityManagerFactory ( pu ) ; } finally { pu . setAnnotationIndex ( null ) ; // close reference to Annotation Index (only needed during call to createContainerEntityManagerFactory) } } }


Input: org . hibernate . jpa . event . spi . jpa . ExtendedBeanManager is added to Hibernate 5 . 1 as an extension for delaying registration of entity listeners until the CDI AfterDeploymentValidation event is triggered . This allows entity listener classes to reference the ( origin ) persistence unit ( WFLY - 2387 ) . [CODESPLIT] private boolean isHibernateExtendedBeanManagerSupported ( ) { try { Class . forName ( HIBERNATE_EXTENDED_BEANMANAGER ) ; return true ; } catch ( ClassNotFoundException ignore ) { return false ; } catch ( NoClassDefFoundError ignore ) { return false ; } }


Input: Returns the address of the specified operation [CODESPLIT] public static PathAddress getPathAddress ( ModelNode operation ) { return PathAddress . pathAddress ( operation . require ( ModelDescriptionConstants . OP_ADDR ) ) ; }


Input: Sets the address of the specified operation . [CODESPLIT] public static void setPathAddress ( ModelNode operation , PathAddress address ) { operation . get ( ModelDescriptionConstants . OP_ADDR ) . set ( address . toModelNode ( ) ) ; }


Input: Returns the attribute value of the specified operation [CODESPLIT] public static ModelNode getAttributeValue ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . VALUE ) ? operation . get ( ModelDescriptionConstants . VALUE ) : new ModelNode ( ) ; }


Input: Indicates whether or not this operation expects to include default values . [CODESPLIT] public static boolean isIncludeDefaults ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) ? operation . get ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) . asBoolean ( ) : true ; }


Input: Creates a composite operation using the specified operation steps . [CODESPLIT] public static ModelNode createCompositeOperation ( List < ModelNode > operations ) { ModelNode operation = Util . createOperation ( ModelDescriptionConstants . COMPOSITE , PathAddress . EMPTY_ADDRESS ) ; ModelNode steps = operation . get ( ModelDescriptionConstants . STEPS ) ; for ( ModelNode step : operations ) { steps . add ( step ) ; } return operation ; }


Input: Creates an add operation using the specified address and parameters [CODESPLIT] public static ModelNode createAddOperation ( PathAddress address , Map < Attribute , ModelNode > parameters ) { ModelNode operation = Util . createAddOperation ( address ) ; for ( Map . Entry < Attribute , ModelNode > entry : parameters . entrySet ( ) ) { operation . get ( entry . getKey ( ) . getName ( ) ) . set ( entry . getValue ( ) ) ; } return operation ; }


Input: Creates an indexed add operation using the specified address and index [CODESPLIT] public static ModelNode createAddOperation ( PathAddress address , int index ) { return createAddOperation ( address , index , Collections . emptyMap ( ) ) ; }


Input: Creates a read - attribute operation using the specified address and name . [CODESPLIT] public static ModelNode createReadAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . READ_ATTRIBUTE_OPERATION , address , attribute ) ; }


Input: Creates a write - attribute operation using the specified address name and value . [CODESPLIT] public static ModelNode createWriteAttributeOperation ( PathAddress address , Attribute attribute , ModelNode value ) { ModelNode operation = createAttributeOperation ( ModelDescriptionConstants . WRITE_ATTRIBUTE_OPERATION , address , attribute ) ; operation . get ( ModelDescriptionConstants . VALUE ) . set ( value ) ; return operation ; }


Input: Creates an undefine - attribute operation using the specified address and name . [CODESPLIT] public static ModelNode createUndefineAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . UNDEFINE_ATTRIBUTE_OPERATION , address , attribute ) ; }


Input: Lookup the value from the naming context . [CODESPLIT] public T getValue ( ) throws IllegalStateException { final Context context = contextValue . getValue ( ) ; try { return ( T ) context . lookup ( contextName ) ; } catch ( NamingException e ) { throw NamingLogger . ROOT_LOGGER . entryNotRegistered ( e , contextName , context ) ; } }


Input: Add an ObjectFactory to handle requests for a specific URL scheme . [CODESPLIT] public static synchronized void addUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; factories . put ( scheme , factory ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; }


Input: Remove an ObjectFactory from the map of registered ones . To make sure that not anybody can remove an ObjectFactory both the scheme as well as the actual object factory itself need to be supplied . So you can only remove the factory if you have the factory object . [CODESPLIT] public static synchronized void removeUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; ObjectFactory f = factories . get ( scheme ) ; if ( f == factory ) { factories . remove ( scheme ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; return ; } else { throw new IllegalArgumentException ( ) ; } }


Input: Returns a list with all { @link ValidationProvider } validation providers . [CODESPLIT] @ Override public List < ValidationProvider < ? > > getValidationProviders ( ) { // first try the TCCL List < ValidationProvider < ? > > providers = loadProviders ( WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ) ; if ( providers != null && ! providers . isEmpty ( ) ) { return providers ; } // otherwise use the loader of this class else { return loadProviders ( WildFlySecurityManager . getClassLoaderPrivileged ( WildFlyProviderResolver . class ) ) ; } }


Input: Retrieves the providers from the given loader using the service loader mechanism . [CODESPLIT] private List < ValidationProvider < ? > > loadProviders ( ClassLoader classLoader ) { @ SuppressWarnings ( "rawtypes" ) Iterator < ValidationProvider > providerIterator = ServiceLoader . load ( ValidationProvider . class , classLoader ) . iterator ( ) ; LinkedList < ValidationProvider < ? > > providers = new LinkedList < ValidationProvider < ? > > ( ) ; while ( providerIterator . hasNext ( ) ) { try { ValidationProvider < ? > provider = providerIterator . next ( ) ; // put Hibernate Validator to the beginning of the list if ( provider . getClass ( ) . getName ( ) . equals ( "org.hibernate.validator.HibernateValidator" ) ) { providers . addFirst ( provider ) ; } else { providers . add ( provider ) ; } } catch ( ServiceConfigurationError e ) { // ignore, because it can happen when multiple // providers are present and some of them are not class loader // compatible with our API. } } return providers ; }


Input: { [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { try { PolicyConfigurationFactory pcf = getPolicyConfigurationFactory ( ) ; synchronized ( pcf ) { // synchronize on the factory policyConfiguration = pcf . getPolicyConfiguration ( contextId , false ) ; if ( metaData != null ) { createPermissions ( metaData , policyConfiguration ) ; } else { SecurityLogger . ROOT_LOGGER . debugf ( "Cannot create permissions with 'null' metaData for id=%s" , contextId ) ; } if ( ! standalone ) { PolicyConfiguration parent = parentPolicy . getValue ( ) ; if ( parent != null ) { parent = pcf . getPolicyConfiguration ( parent . getContextID ( ) , false ) ; parent . linkConfiguration ( policyConfiguration ) ; policyConfiguration . commit ( ) ; parent . commit ( ) ; } else { SecurityLogger . ROOT_LOGGER . debugf ( "Could not retrieve parent policy for policy %s" , contextId ) ; } } else { policyConfiguration . commit ( ) ; } // Allow the policy to incorporate the policy configs Policy . getPolicy ( ) . refresh ( ) ; } } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( "JaccService" , e ) ; } }


Input: { [CODESPLIT] @ Override public void stop ( StopContext context ) { try { PolicyConfigurationFactory pcf = PolicyConfigurationFactory . getPolicyConfigurationFactory ( ) ; synchronized ( pcf ) { // synchronize on the factory policyConfiguration = pcf . getPolicyConfiguration ( contextId , false ) ; policyConfiguration . delete ( ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . errorDeletingJACCPolicy ( e ) ; } policyConfiguration = null ; }


Input: <p > Gets the canonical request URI - that is the request URI minus the context path . < / p > [CODESPLIT] private String getCanonicalURI ( HttpServletRequest request ) { String canonicalURI = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) ) ; if ( canonicalURI == null || canonicalURI . equals ( "/" ) ) canonicalURI = "" ; return canonicalURI ; }


Input: TODO : should this be part of the messaging subsystem [CODESPLIT] private List < BindingConfiguration > getMessageDestinationRefs ( final DeploymentDescriptorEnvironment environment , final ClassLoader classLoader , final DeploymentReflectionIndex deploymentReflectionIndex , final ResourceInjectionTarget resourceInjectionTarget , final DeploymentUnit deploymentUnit ) throws DeploymentUnitProcessingException { final List < BindingConfiguration > bindings = new ArrayList < BindingConfiguration > ( ) ; final MessageDestinationReferencesMetaData messageDestinationReferences = environment . getEnvironment ( ) . getMessageDestinationReferences ( ) ; if ( messageDestinationReferences == null ) { return bindings ; } for ( final MessageDestinationReferenceMetaData messageRef : messageDestinationReferences ) { if ( messageRef . isDependencyIgnored ( ) ) { continue ; } final String name ; if ( messageRef . getName ( ) . startsWith ( "java:" ) ) { name = messageRef . getName ( ) ; } else { name = environment . getDefaultContext ( ) + messageRef . getName ( ) ; } Class < ? > classType = null ; if ( messageRef . getType ( ) != null ) { try { classType = classLoader . loadClass ( messageRef . getType ( ) ) ; } catch ( ClassNotFoundException e ) { throw EeLogger . ROOT_LOGGER . cannotLoad ( e , messageRef . getType ( ) ) ; } } // our injection (source) comes from the local (ENC) lookup, no matter what. final LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; classType = processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , messageRef , classType ) ; final BindingConfiguration bindingConfiguration ; if ( ! isEmpty ( messageRef . getLookupName ( ) ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( messageRef . getLookupName ( ) ) ) ; bindings . add ( bindingConfiguration ) ; } else if ( ! isEmpty ( messageRef . getMappedName ( ) ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( messageRef . getMappedName ( ) ) ) ; bindings . add ( bindingConfiguration ) ; } else if ( ! isEmpty ( messageRef . getLink ( ) ) ) { final MessageDestinationInjectionSource messageDestinationInjectionSource = new MessageDestinationInjectionSource ( messageRef . getLink ( ) , name ) ; bindingConfiguration = new BindingConfiguration ( name , messageDestinationInjectionSource ) ; deploymentUnit . addToAttachmentList ( Attachments . MESSAGE_DESTINATIONS , messageDestinationInjectionSource ) ; bindings . add ( bindingConfiguration ) ; } else { ROOT_LOGGER . cannotResolve ( "message-destination-ref" , name ) ; } } return bindings ; }


Input: Modifies web meta data to configure webservice stack transport and properties . [CODESPLIT] void modify ( final Deployment dep ) { final JBossWebMetaData jbossWebMD = WSHelper . getOptionalAttachment ( dep , JBossWebMetaData . class ) ; if ( jbossWebMD != null ) { this . configureEndpoints ( dep , jbossWebMD ) ; this . modifyContextRoot ( dep , jbossWebMD ) ; } }


Input: Configures transport servlet class for every found webservice endpoint . [CODESPLIT] private void configureEndpoints ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String transportClassName = this . getTransportClassName ( dep ) ; WSLogger . ROOT_LOGGER . trace ( "Modifying servlets" ) ; // get a list of the endpoint bean class names final Set < String > epNames = new HashSet < String > ( ) ; for ( Endpoint ep : dep . getService ( ) . getEndpoints ( ) ) { epNames . add ( ep . getTargetBeanName ( ) ) ; } // fix servlet class names for endpoints for ( final ServletMetaData servletMD : jbossWebMD . getServlets ( ) ) { final String endpointClassName = ASHelper . getEndpointClassName ( servletMD ) ; if ( endpointClassName != null && endpointClassName . length ( ) > 0 ) { // exclude JSP if ( epNames . contains ( endpointClassName ) ) { // set transport servlet servletMD . setServletClass ( WSFServlet . class . getName ( ) ) ; WSLogger . ROOT_LOGGER . tracef ( "Setting transport class: %s for endpoint: %s" , transportClassName , endpointClassName ) ; final List < ParamValueMetaData > initParams = WebMetaDataHelper . getServletInitParams ( servletMD ) ; // configure transport class name WebMetaDataHelper . newParamValue ( WSFServlet . STACK_SERVLET_DELEGATE_CLASS , transportClassName , initParams ) ; // configure webservice endpoint WebMetaDataHelper . newParamValue ( Endpoint . SEPID_DOMAIN_ENDPOINT , endpointClassName , initParams ) ; } else if ( endpointClassName . startsWith ( "org.apache.cxf" ) ) { throw WSLogger . ROOT_LOGGER . invalidWSServlet ( endpointClassName ) ; } } } }


Input: Modifies context root . [CODESPLIT] private void modifyContextRoot ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String contextRoot = dep . getService ( ) . getContextRoot ( ) ; if ( WSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { WSLogger . ROOT_LOGGER . tracef ( "Setting context root: %s for deployment: %s" , contextRoot , dep . getSimpleName ( ) ) ; } jbossWebMD . setContextRoot ( contextRoot ) ; }


Input: Returns stack specific transport class name . [CODESPLIT] private String getTransportClassName ( final Deployment dep ) { String transportClassName = ( String ) dep . getProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; if ( transportClassName == null ) throw WSLogger . ROOT_LOGGER . missingDeploymentProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; return transportClassName ; }


Input: { [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public synchronized T get ( MarshallingContext context ) throws IOException , ClassNotFoundException { if ( this . object == null ) { this . context = context ; if ( this . bytes != null ) { ByteArrayInputStream input = new ByteArrayInputStream ( this . bytes ) ; ClassLoader loader = setThreadContextClassLoader ( this . context . getClassLoader ( ) ) ; try ( SimpleDataInput data = new SimpleDataInput ( Marshalling . createByteInput ( input ) ) ) { int version = IndexSerializer . VARIABLE . readInt ( data ) ; try ( Unmarshaller unmarshaller = context . createUnmarshaller ( version ) ) { unmarshaller . start ( data ) ; this . object = ( T ) unmarshaller . readObject ( ) ; unmarshaller . finish ( ) ; this . bytes = null ; // Free up memory } } finally { setThreadContextClassLoader ( loader ) ; } } } return this . object ; }


Input: Returns the last date of the month represented by the passed <code > cal< / code > [CODESPLIT] public static int getLastDateOfMonth ( Calendar calendar ) { Calendar tmpCal = new GregorianCalendar ( calendar . getTimeZone ( ) ) ; tmpCal . set ( Calendar . YEAR , calendar . get ( Calendar . YEAR ) ) ; tmpCal . set ( Calendar . MONTH , calendar . get ( Calendar . MONTH ) ) ; tmpCal . set ( Calendar . DAY_OF_MONTH , 1 ) ; return tmpCal . getActualMaximum ( Calendar . DAY_OF_MONTH ) ; }