idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
29,600
public static long bytes_to_long ( byte [ ] bytes , int offset ) { if ( bytes . length - offset < 8 ) throw new PickleException ( "too few bytes to convert to long" ) ; long i = bytes [ 7 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 6 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 5 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 4 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 3 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 2 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ 1 + offset ] & 0xff ; i <<= 8 ; i |= bytes [ offset ] & 0xff ; return i ; }
Convert 8 little endian bytes into a long
29,601
public static double bytes_to_double ( byte [ ] bytes , int offset ) { try { long result = bytes [ 0 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 1 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 2 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 3 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 4 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 5 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 6 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 7 + offset ] & 0xff ; return Double . longBitsToDouble ( result ) ; } catch ( IndexOutOfBoundsException x ) { throw new PickleException ( "decoding double: too few bytes" ) ; } }
Convert a big endian 8 - byte to a double .
29,602
public static float bytes_to_float ( byte [ ] bytes , int offset ) { try { int result = bytes [ 0 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 1 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 2 + offset ] & 0xff ; result <<= 8 ; result |= bytes [ 3 + offset ] & 0xff ; return Float . intBitsToFloat ( result ) ; } catch ( IndexOutOfBoundsException x ) { throw new PickleException ( "decoding float: too few bytes" ) ; } }
Convert a big endian 4 - byte to a float .
29,603
public static Number optimizeBigint ( BigInteger bigint ) { final BigInteger MAXLONG = BigInteger . valueOf ( Long . MAX_VALUE ) ; final BigInteger MINLONG = BigInteger . valueOf ( Long . MIN_VALUE ) ; switch ( bigint . signum ( ) ) { case 0 : return 0L ; case 1 : if ( bigint . compareTo ( MAXLONG ) <= 0 ) return bigint . longValue ( ) ; break ; case - 1 : if ( bigint . compareTo ( MINLONG ) >= 0 ) return bigint . longValue ( ) ; break ; } return bigint ; }
Optimize a biginteger if possible return a long primitive datatype .
29,604
public static String rawStringFromBytes ( byte [ ] data ) { StringBuilder str = new StringBuilder ( data . length ) ; for ( byte b : data ) { str . append ( ( char ) ( b & 0xff ) ) ; } return str . toString ( ) ; }
Construct a String from the given bytes where these are directly converted to the corresponding chars without using a given character encoding
29,605
public static byte [ ] str2bytes ( String str ) throws IOException { byte [ ] b = new byte [ str . length ( ) ] ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c > 255 ) throw new UnsupportedEncodingException ( "string contained a char > 255, cannot convert to bytes" ) ; b [ i ] = ( byte ) c ; } return b ; }
Convert a string to a byte array no encoding is used . String must only contain characters <256 .
29,606
public static byte [ ] recv ( InputStream in , int size ) throws IOException { byte [ ] bytes = new byte [ size ] ; int numRead = in . read ( bytes ) ; if ( numRead == - 1 ) { throw new IOException ( "premature end of data" ) ; } while ( numRead < size ) { int len = in . read ( bytes , numRead , size - numRead ) ; if ( len == - 1 ) { throw new IOException ( "premature end of data" ) ; } numRead += len ; } return bytes ; }
Receive a message of the given size from the inputstream . Makes sure the complete message is received raises IOException otherwise .
29,607
private static void closeAndIgnoreError ( Socket socket ) { if ( socket == null ) return ; try { socket . close ( ) ; } catch ( IOException e ) { log . warn ( String . format ( "Failed to close the client socket on port %d: %s. Exception ignored." , socket . getPort ( ) , e . getMessage ( ) ) , e ) ; } }
make Suro compilable and runnable under Java 6 .
29,608
private void respond ( BufferedWriter out , String response ) throws IOException { out . append ( response ) ; out . append ( "\n" ) ; out . flush ( ) ; }
Writes line - based response .
29,609
public SequenceFile . Writer createSequenceFile ( String newPath ) throws IOException { if ( codec != null ) { return SequenceFile . createWriter ( fs , conf , new Path ( newPath ) , Text . class , MessageWritable . class , SequenceFile . CompressionType . BLOCK , codec ) ; } else { return SequenceFile . createWriter ( fs , conf , new Path ( newPath ) , Text . class , MessageWritable . class , SequenceFile . CompressionType . NONE , codec ) ; } }
Create a new sequence file
29,610
public FSDataOutputStream createFSDataOutputStream ( String path ) throws IOException { return fs . create ( new Path ( path ) , false ) ; }
Create a new FSDataOutputStream from path
29,611
public DataOutputStream createDataOutputStream ( FSDataOutputStream outputStream ) throws IOException { if ( codec != null ) { return new FSDataOutputStream ( codec . createOutputStream ( outputStream ) , null ) ; } else { return outputStream ; } }
Create a DataOutputStream from FSDataOutputStream . If the codec is available it will create compressed DataOutputStream otherwise it will return itself .
29,612
public void start ( ) throws Exception { executor = Executors . newCachedThreadPool ( new ThreadFactoryBuilder ( ) . setNameFormat ( "KafkaConsumer-%d" ) . build ( ) ) ; connector = Consumer . createJavaConsumerConnector ( new ConsumerConfig ( consumerProps ) ) ; final Map < String , List < KafkaStream < byte [ ] , byte [ ] > > > streams = connector . createMessageStreams ( ImmutableMap . of ( topic , readers ) ) ; final List < KafkaStream < byte [ ] , byte [ ] > > streamList = streams . get ( topic ) ; if ( streamList == null ) { throw new RuntimeException ( topic + " is not valid" ) ; } running = true ; for ( KafkaStream < byte [ ] , byte [ ] > stream : streamList ) { final ConsumerIterator < byte [ ] , byte [ ] > iterator = stream . iterator ( ) ; runners . add ( executor . submit ( new Runnable ( ) { public void run ( ) { while ( running ) { try { long pause = Math . min ( pausedTime . get ( ) , MAX_PAUSE ) ; if ( pause > 0 ) { Thread . sleep ( pause ) ; pausedTime . set ( 0 ) ; } byte [ ] message = iterator . next ( ) . message ( ) ; router . process ( KafkaConsumer . this , new DefaultMessageContainer ( new Message ( topic , message ) , jsonMapper ) ) ; } catch ( ConsumerTimeoutException timeoutException ) { } catch ( Exception e ) { log . error ( "Exception on consuming kafka with topic: " + topic , e ) ; } } } } ) ) ; } }
not final for the test
29,613
public long checkPause ( ) { if ( pauseOnLongQueue && ( getNumOfPendingMessages ( ) > queue4Sink . remainingCapacity ( ) || getNumOfPendingMessages ( ) > MAX_PENDING_MESSAGES_TO_PAUSE ) ) { double throughputRate = Math . max ( throughput . meanRate ( ) , 1.0 ) ; return ( long ) ( getNumOfPendingMessages ( ) / throughputRate ) ; } else { return 0 ; } }
so setting up minimum threshold as 1 message per millisecond
29,614
protected void beforePolling ( ) throws IOException { if ( isRunning && ( writer . getLength ( ) > maxFileSize || System . currentTimeMillis ( ) > nextRotation ) ) { rotate ( ) ; } }
Before polling messages from the queue it should check whether to rotate the file and start to write to new file .
29,615
protected void write ( List < Message > msgList ) throws IOException { for ( Message msg : msgList ) { writer . writeTo ( msg ) ; String routingKey = normalizeRoutingKey ( msg ) ; DynamicCounter . increment ( MonitorConfig . builder ( "writtenMessages" ) . withTag ( TagKey . DATA_SOURCE , routingKey ) . build ( ) ) ; ++ writtenMessages ; DynamicCounter . increment ( MonitorConfig . builder ( "writtenBytes" ) . withTag ( TagKey . DATA_SOURCE , routingKey ) . build ( ) , msg . getPayload ( ) . length ) ; writtenBytes += msg . getPayload ( ) . length ; messageWrittenInRotation = true ; } writer . sync ( ) ; throughput . increment ( msgList . size ( ) ) ; }
Write all messages in msgList to file writer sync the file commit the queue and clear messages
29,616
public int cleanUp ( String dir , boolean fetchAll ) { if ( ! dir . endsWith ( "/" ) ) { dir += "/" ; } int count = 0 ; try { FileSystem fs = writer . getFS ( ) ; FileStatus [ ] files = fs . listStatus ( new Path ( dir ) ) ; for ( FileStatus file : files ) { if ( file . getLen ( ) > 0 ) { String fileName = file . getPath ( ) . getName ( ) ; String fileExt = getFileExt ( fileName ) ; if ( fileExt != null && fileExt . equals ( done ) ) { notice . send ( dir + fileName ) ; ++ count ; } else if ( fileExt != null ) { long lastPeriod = new DateTime ( ) . minus ( rotationPeriod ) . minus ( rotationPeriod ) . getMillis ( ) ; if ( file . getModificationTime ( ) < lastPeriod ) { ++ errorClosedFiles ; DynamicCounter . increment ( "closedFileError" ) ; log . error ( dir + fileName + " is not closed properly!!!" ) ; String doneFile = fileName . replace ( fileExt , done ) ; writer . setDone ( dir + fileName , dir + doneFile ) ; notice . send ( dir + doneFile ) ; ++ count ; } else if ( fetchAll ) { ++ count ; } } } } } catch ( Exception e ) { log . error ( "Exception while on cleanUp: " + e . getMessage ( ) , e ) ; return Integer . MAX_VALUE ; } return count ; }
List all files under the directory . If the file is marked as done the notice for that file would be sent . Otherwise it checks the file is not closed properly the file is marked as done and the notice would be sent . That file would cause EOFException when reading .
29,617
public static String getFileExt ( String fileName ) { int dotPos = fileName . lastIndexOf ( '.' ) ; if ( dotPos != - 1 && dotPos != fileName . length ( ) - 1 ) { return fileName . substring ( dotPos ) ; } else { return null ; } }
Simply returns file extension from the file path
29,618
public void deleteFile ( String filePath ) { int retryCount = 1 ; while ( retryCount <= deleteFileRetryCount ) { try { if ( writer . getFS ( ) . exists ( new Path ( filePath ) ) ) { Thread . sleep ( 1000 * retryCount ) ; writer . getFS ( ) . delete ( new Path ( filePath ) , false ) ; ++ retryCount ; } else { break ; } } catch ( Exception e ) { log . warn ( "Exception while deleting the file: " + e . getMessage ( ) , e ) ; } } }
With AWS EBS sometimes deletion failure without any IOException was observed To prevent the surplus files let s iterate file deletion . By default it will try for five times .
29,619
public SuroConnection chooseConnection ( ) { SuroConnection connection = connectionQueue . poll ( ) ; if ( connection == null ) { connection = chooseFromPool ( ) ; } if ( config . getEnableOutPool ( ) ) { synchronized ( this ) { for ( int i = 0 ; i < config . getRetryCount ( ) && connection == null ; ++ i ) { Server server = lb . chooseServer ( null ) ; if ( server != null ) { connection = new SuroConnection ( server , config , false ) ; try { connection . connect ( ) ; ++ outPoolSize ; logger . info ( connection + " is created out of the pool" ) ; break ; } catch ( Exception e ) { logger . error ( "Error in connecting to " + connection + " message: " + e . getMessage ( ) , e ) ; lb . markServerDown ( server ) ; } } } } } if ( connection == null ) { logger . error ( "No valid connection exists after " + config . getRetryCount ( ) + " retries" ) ; } return connection ; }
When the client calls this method it will return the connection .
29,620
public void endConnection ( SuroConnection connection ) { if ( connection != null && shouldChangeConnection ( connection ) ) { connection . initStat ( ) ; connectionPool . put ( connection . getServer ( ) , connection ) ; connection = chooseFromPool ( ) ; } if ( connection != null ) { connectionQueue . offer ( connection ) ; } }
When the client finishes communication with the client this method should be called to release the connection and return it to the pool .
29,621
public void markServerDown ( SuroConnection connection ) { if ( connection != null ) { lb . markServerDown ( connection . getServer ( ) ) ; removeConnection ( new ImmutableSet . Builder < Server > ( ) . add ( connection . getServer ( ) ) . build ( ) ) ; } }
Mark up the server related with the connection as down When the client fails to communicate with the connection this method should be called to remove the server from the pool
29,622
public Server chooseServer ( Object key ) { Server server = super . chooseServer ( key ) ; if ( server == null ) { return null ; } server . setPort ( port ) ; return server ; }
This function is called from ConnectionPool to retrieve which server to communicate
29,623
public < T extends Sink > void addSinkType ( String typeName , Class < T > sinkClass ) { LOG . info ( "Adding sinkType: " + typeName + " -> " + sinkClass . getCanonicalName ( ) ) ; Multibinder < TypeHolder > bindings = Multibinder . newSetBinder ( binder ( ) , TypeHolder . class ) ; bindings . addBinding ( ) . toInstance ( new TypeHolder ( typeName , sinkClass ) ) ; }
Add a sink implementation to Suro . typeName is the expected value of the type field of a JSON configuration .
29,624
private static Iterable < String > head ( final Response origin , final int status , final CharSequence reason ) throws IOException { if ( status < 100 || status > 999 ) { throw new IllegalArgumentException ( String . format ( "according to RFC 7230 HTTP status code must have three digits: %d" , status ) ) ; } return new Concat < > ( Collections . singletonList ( String . format ( "HTTP/1.1 %d %s" , status , reason ) ) , new Filtered < > ( item -> ! item . startsWith ( "HTTP/" ) , origin . head ( ) ) ) ; }
Make head .
29,625
private static Map < Integer , String > make ( ) { final Map < Integer , String > map = new HashMap < > ( 0 ) ; map . put ( HttpURLConnection . HTTP_OK , "OK" ) ; map . put ( HttpURLConnection . HTTP_NO_CONTENT , "No Content" ) ; map . put ( HttpURLConnection . HTTP_CREATED , "Created" ) ; map . put ( HttpURLConnection . HTTP_ACCEPTED , "Accepted" ) ; map . put ( HttpURLConnection . HTTP_MOVED_PERM , "Moved Permanently" ) ; map . put ( HttpURLConnection . HTTP_MOVED_TEMP , "Moved Temporarily" ) ; map . put ( HttpURLConnection . HTTP_SEE_OTHER , "See Other" ) ; map . put ( HttpURLConnection . HTTP_NOT_MODIFIED , "Not Modified" ) ; map . put ( HttpURLConnection . HTTP_USE_PROXY , "Use Proxy" ) ; map . put ( HttpURLConnection . HTTP_BAD_REQUEST , "Bad Request" ) ; map . put ( HttpURLConnection . HTTP_UNAUTHORIZED , "Unauthorized" ) ; map . put ( HttpURLConnection . HTTP_PAYMENT_REQUIRED , "Payment Required" ) ; map . put ( HttpURLConnection . HTTP_FORBIDDEN , "Forbidden" ) ; map . put ( HttpURLConnection . HTTP_NOT_FOUND , "Not Found" ) ; map . put ( HttpURLConnection . HTTP_BAD_METHOD , "Bad Method" ) ; map . put ( HttpURLConnection . HTTP_NOT_ACCEPTABLE , "Not Acceptable" ) ; map . put ( HttpURLConnection . HTTP_CLIENT_TIMEOUT , "Client Timeout" ) ; map . put ( HttpURLConnection . HTTP_GONE , "Gone" ) ; map . put ( HttpURLConnection . HTTP_LENGTH_REQUIRED , "Length Required" ) ; map . put ( HttpURLConnection . HTTP_PRECON_FAILED , "Precon Failed" ) ; map . put ( HttpURLConnection . HTTP_ENTITY_TOO_LARGE , "Entity Too Large" ) ; map . put ( HttpURLConnection . HTTP_REQ_TOO_LONG , "Request Too Long" ) ; map . put ( HttpURLConnection . HTTP_UNSUPPORTED_TYPE , "Unsupported Type" ) ; map . put ( HttpURLConnection . HTTP_INTERNAL_ERROR , "Internal Error" ) ; map . put ( HttpURLConnection . HTTP_BAD_GATEWAY , "Bad Gateway" ) ; map . put ( HttpURLConnection . HTTP_NOT_IMPLEMENTED , "Not Implemented" ) ; return map ; }
Make all reasons .
29,626
public String bare ( ) { final StringBuilder text = new StringBuilder ( this . uri . toString ( ) ) ; if ( this . uri . getPath ( ) . isEmpty ( ) ) { text . append ( '/' ) ; } return text . toString ( ) ; }
Get URI without params .
29,627
public Iterable < String > param ( final Object key ) { final List < String > values = this . params . getOrDefault ( key . toString ( ) , Collections . emptyList ( ) ) ; final Iterable < String > iter ; if ( values . isEmpty ( ) ) { iter = new VerboseIterable < > ( Collections . emptyList ( ) , String . format ( "there are no URI params by name \"%s\" among %d others" , key , this . params . size ( ) ) ) ; } else { iter = new VerboseIterable < > ( values , String . format ( "there are only %d URI params by name \"%s\"" , values . size ( ) , key ) ) ; } return iter ; }
Get query param .
29,628
public Href path ( final Object suffix ) { return new Href ( URI . create ( new StringBuilder ( Href . TRAILING_SLASH . matcher ( this . uri . toString ( ) ) . replaceAll ( "" ) ) . append ( '/' ) . append ( Href . encode ( suffix . toString ( ) ) ) . toString ( ) ) , this . params , this . fragment ) ; }
Add this path to the URI .
29,629
public Href with ( final Object key , final Object value ) { final SortedMap < String , List < String > > map = new TreeMap < > ( this . params ) ; if ( ! map . containsKey ( key . toString ( ) ) ) { map . put ( key . toString ( ) , new LinkedList < > ( ) ) ; } map . get ( key . toString ( ) ) . add ( value . toString ( ) ) ; return new Href ( this . uri , map , this . fragment ) ; }
Add this extra param .
29,630
public Href without ( final Object key ) { final SortedMap < String , List < String > > map = new TreeMap < > ( this . params ) ; map . remove ( key . toString ( ) ) ; return new Href ( this . uri , map , this . fragment ) ; }
Without this query param .
29,631
private static String encode ( final String txt ) { try { return URLEncoder . encode ( txt , Charset . defaultCharset ( ) . name ( ) ) ; } catch ( final UnsupportedEncodingException ex ) { throw new IllegalStateException ( ex ) ; } }
Encode into URL .
29,632
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static SortedMap < String , List < String > > asMap ( final String query ) { final SortedMap < String , List < String > > params = new TreeMap < > ( ) ; if ( query != null ) { for ( final String pair : query . split ( "&" ) ) { final String [ ] parts = pair . split ( "=" , 2 ) ; final String key = Href . decode ( parts [ 0 ] ) ; final String value ; if ( parts . length > 1 ) { value = Href . decode ( parts [ 1 ] ) ; } else { value = "" ; } if ( ! params . containsKey ( key ) ) { params . put ( key , new LinkedList < > ( ) ) ; } params . get ( key ) . add ( value ) ; } } return params ; }
Convert the provided query into a Map .
29,633
private static URI createBare ( final URI link ) { final URI uri ; if ( link . getRawQuery ( ) == null && link . getRawFragment ( ) == null ) { uri = link ; } else { final String href = link . toString ( ) ; final int idx ; if ( link . getRawQuery ( ) == null ) { idx = href . indexOf ( '#' ) ; } else { idx = href . indexOf ( '?' ) ; } uri = URI . create ( href . substring ( 0 , idx ) ) ; } return uri ; }
Remove query and fragment parts from the provided URI and return the resulting URI .
29,634
private static Opt < String > readFragment ( final URI link ) { final Opt < String > fragment ; if ( link . getRawFragment ( ) == null ) { fragment = new Opt . Empty < > ( ) ; } else { fragment = new Opt . Single < > ( link . getRawFragment ( ) ) ; } return fragment ; }
Read fragment part from the given URI .
29,635
private static Request consume ( final Request req ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; new RqPrint ( req ) . printBody ( baos ) ; return new Request ( ) { public Iterable < String > head ( ) throws IOException { return req . head ( ) ; } public InputStream body ( ) { return new ByteArrayInputStream ( baos . toByteArray ( ) ) ; } } ; }
Consume the request .
29,636
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private com . jcabi . http . Request request ( final Request req , final URI dest ) throws IOException { final String method = new RqMethod . Base ( req ) . method ( ) ; com . jcabi . http . Request proxied = new JdkRequest ( dest ) . method ( method ) ; final RqHeaders headers = new RqHeaders . Base ( req ) ; for ( final String name : headers . names ( ) ) { if ( "content-length" . equals ( new EnglishLowerCase ( name ) . string ( ) ) ) { continue ; } if ( TkProxy . isHost ( name ) ) { proxied = proxied . header ( name , this . target ) ; continue ; } for ( final String value : headers . header ( name ) ) { proxied = proxied . header ( name , value ) ; } } if ( headers . header ( "Content-Length" ) . iterator ( ) . hasNext ( ) || headers . header ( "Transfer-Encoding" ) . iterator ( ) . hasNext ( ) ) { final ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; new RqPrint ( new RqLengthAware ( req ) ) . printBody ( output ) ; proxied = proxied . body ( ) . set ( output . toByteArray ( ) ) . back ( ) ; } return proxied ; }
Creates the request to be forwarded to the target host .
29,637
private Response response ( final String home , final URI dest , final com . jcabi . http . Response rsp ) { final Collection < String > hdrs = new LinkedList < > ( ) ; hdrs . add ( String . format ( "X-Takes-TkProxy: from %s to %s by %s" , home , dest , this . label ) ) ; for ( final Map . Entry < String , List < String > > entry : rsp . headers ( ) . entrySet ( ) ) { for ( final String value : entry . getValue ( ) ) { final String val ; if ( TkProxy . isHost ( entry . getKey ( ) ) ) { val = this . target . toString ( ) ; } else { val = value ; } hdrs . add ( String . format ( "%s: %s" , entry . getKey ( ) , val ) ) ; } } return new RsWithStatus ( new RsWithBody ( new RsWithHeaders ( hdrs ) , rsp . binary ( ) ) , rsp . status ( ) , rsp . reason ( ) ) ; }
Creates the response received from the target host .
29,638
private static List < String > tokens ( final Request req ) throws IOException { final List < String > tokens = new LinkedList < > ( ) ; final Iterable < String > headers = new RqHeaders . Base ( req ) . header ( "User-Agent" ) ; for ( final String header : headers ) { final Matcher matcher = PATTERN . matcher ( header ) ; if ( matcher . matches ( ) ) { tokens . add ( matcher . group ( ) ) ; } } return tokens ; }
Extract tokens from request .
29,639
public boolean contains ( final MediaTypes types ) { boolean contains = false ; for ( final MediaType type : types . list ) { if ( this . contains ( type ) ) { contains = true ; break ; } } return contains ; }
Contains any of these types?
29,640
public boolean contains ( final MediaType type ) { boolean contains = false ; for ( final MediaType mine : this . list ) { if ( mine . matches ( type ) ) { contains = true ; break ; } } return contains ; }
Contains this type?
29,641
public MediaTypes merge ( final MediaTypes types ) { final SortedSet < MediaType > set = new TreeSet < > ( ) ; set . addAll ( this . list ) ; set . addAll ( types . list ) ; return new MediaTypes ( set ) ; }
Merge with this one .
29,642
private byte [ ] encrypt ( final byte [ ] bytes ) throws IOException { try { final byte [ ] vector = new byte [ CcAes . BLOCK ] ; this . random . nextBytes ( vector ) ; final byte [ ] message = this . cipher ( Cipher . ENCRYPT_MODE , new IvParameterSpec ( vector ) ) . doFinal ( bytes ) ; final byte [ ] res = new byte [ vector . length + message . length ] ; System . arraycopy ( vector , 0 , res , 0 , vector . length ) ; System . arraycopy ( message , 0 , res , vector . length , message . length ) ; return res ; } catch ( final BadPaddingException | IllegalBlockSizeException ex ) { throw new IOException ( ex ) ; } }
Encrypt the given bytes using AES .
29,643
private static byte [ ] withCorrectBlockSize ( final byte [ ] key ) { if ( key . length != CcAes . BLOCK ) { throw new IllegalArgumentException ( String . format ( "the length of the AES key must be exactly %d bytes" , CcAes . BLOCK ) ) ; } return key ; }
Check the block size of the key .
29,644
private byte [ ] decrypt ( final byte [ ] bytes ) throws IOException { if ( bytes . length < CcAes . BLOCK << 1 ) { throw new DecodingException ( "Invalid encrypted message format" ) ; } try { final byte [ ] vector = new byte [ CcAes . BLOCK ] ; final byte [ ] message = new byte [ bytes . length - vector . length ] ; System . arraycopy ( bytes , 0 , vector , 0 , vector . length ) ; System . arraycopy ( bytes , vector . length , message , 0 , message . length ) ; return this . cipher ( Cipher . DECRYPT_MODE , new IvParameterSpec ( vector ) ) . doFinal ( message ) ; } catch ( final BadPaddingException | IllegalBlockSizeException ex ) { throw new DecodingException ( ex ) ; } }
Decrypt the given bytes using AES .
29,645
private Identity fetch ( final String token ) throws IOException { final String uri = this . apihref . with ( "oauth2_access_token" , token ) . with ( "format" , "json" ) . toString ( ) ; return PsLinkedin . parse ( new JdkRequest ( uri ) . header ( "accept" , "application/json" ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) ) ; }
Get user name from Linkedin with the token provided .
29,646
private String token ( final String home , final String code ) throws IOException { final String uri = this . tkhref . toString ( ) ; return new JdkRequest ( uri ) . method ( "POST" ) . header ( "Accept" , "application/xml" ) . body ( ) . formParam ( "grant_type" , "authorization_code" ) . formParam ( "client_id" , this . app ) . formParam ( "redirect_uri" , home ) . formParam ( "client_secret" , this . key ) . formParam ( PsLinkedin . CODE , code ) . back ( ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) . getString ( "access_token" ) ; }
Retrieve PsLinkedin access token .
29,647
private static String validLocation ( final String loc ) throws IOException { if ( ! RsReturn . LOC_PTRN . matcher ( loc ) . matches ( ) ) { throw new IOException ( String . format ( "Location \"%s\" should complain RFC 3987" , loc ) ) ; } return loc ; }
Checks location according to RFC 3987 .
29,648
public ServerSocket socket ( ) throws IOException { final String port = this . map . get ( "port" ) ; if ( port == null ) { throw new IllegalArgumentException ( "--port must be specified" ) ; } final ServerSocket socket ; if ( port . matches ( "\\d+" ) ) { socket = new ServerSocket ( Integer . parseInt ( port ) ) ; } else { final File file = new File ( port ) ; if ( file . exists ( ) ) { try ( Reader reader = new Utf8InputStreamContent ( Files . newInputStream ( file . toPath ( ) ) ) ) { final char [ ] chars = new char [ 8 ] ; final int length = reader . read ( chars ) ; socket = new ServerSocket ( Integer . parseInt ( new String ( chars , 0 , length ) ) ) ; } } else { socket = new ServerSocket ( 0 ) ; try ( Writer writer = new Utf8OutputStreamContent ( Files . newOutputStream ( file . toPath ( ) ) ) ) { writer . append ( Integer . toString ( socket . getLocalPort ( ) ) ) ; } } } return socket ; }
Get the socket to listen to .
29,649
public int threads ( ) { return Integer . parseInt ( this . map . getOrDefault ( "threads" , String . valueOf ( Runtime . getRuntime ( ) . availableProcessors ( ) << 2 ) ) ) ; }
Get the threads .
29,650
private static Map < String , String > asMap ( final Iterable < String > args ) { final Map < String , String > map = new HashMap < > ( 0 ) ; final Pattern ptn = Pattern . compile ( "--([a-z\\-]+)(=.+)?" ) ; for ( final String arg : args ) { final Matcher matcher = ptn . matcher ( arg ) ; if ( ! matcher . matches ( ) ) { throw new IllegalStateException ( String . format ( "can't parse this argument: '%s'" , arg ) ) ; } final String value = matcher . group ( 2 ) ; if ( value == null ) { map . put ( matcher . group ( 1 ) , "" ) ; } else { map . put ( matcher . group ( 1 ) , value . substring ( 1 ) ) ; } } return map ; }
Convert the provided arguments into a Map .
29,651
public String print ( ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; this . print ( baos ) ; return new Utf8String ( baos . toByteArray ( ) ) . asString ( ) ; }
Print it into string .
29,652
public String printBody ( ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; this . printBody ( baos ) ; return new Utf8String ( baos . toByteArray ( ) ) . asString ( ) ; }
Print body into string .
29,653
public String printHead ( ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; this . printHead ( baos ) ; return new Utf8String ( baos . toByteArray ( ) ) . asString ( ) ; }
Print head into string .
29,654
public void printHead ( final Writer writer ) throws IOException { final String eol = "\r\n" ; int pos = 0 ; try { for ( final String line : this . head ( ) ) { if ( pos == 0 && ! RsPrint . FIRST . matcher ( line ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "first line of HTTP response \"%s\" doesn't match \"%s\" regular expression, but it should, according to RFC 7230" , line , RsPrint . FIRST ) ) ; } if ( pos > 0 && ! RsPrint . OTHERS . matcher ( line ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "header line #%d of HTTP response \"%s\" doesn't match \"%s\" regular expression, but it should, according to RFC 7230" , pos + 1 , line , RsPrint . OTHERS ) ) ; } writer . append ( line ) ; writer . append ( eol ) ; ++ pos ; } writer . append ( eol ) ; } finally { writer . flush ( ) ; } }
Print it into a writer .
29,655
public void printBody ( final OutputStream output ) throws IOException { final byte [ ] buf = new byte [ 4096 ] ; try ( InputStream body = this . body ( ) ) { while ( true ) { final int bytes = body . read ( buf ) ; if ( bytes < 0 ) { break ; } output . write ( buf , 0 , bytes ) ; } } finally { output . flush ( ) ; } }
Print it into output stream .
29,656
private static Response pick ( final Request req , final Iterable < Fork > forks ) throws IOException { for ( final Fork fork : forks ) { final Opt < Response > rsps = fork . route ( req ) ; if ( rsps . has ( ) ) { return rsps . get ( ) ; } } throw new HttpException ( HttpURLConnection . HTTP_NOT_FOUND ) ; }
Pick the right one .
29,657
private void loop ( final ServerSocket server ) throws IOException { try { this . back . accept ( server . accept ( ) ) ; } catch ( final SocketTimeoutException ignored ) { } }
Make a loop cycle .
29,658
private static InputStream render ( final Node dom , final XeSource src ) throws IOException { final Node copy = cloneNode ( dom ) ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final Node node = new Xembler ( src . toXembly ( ) ) . applyQuietly ( copy ) ; try { TransformerFactory . newInstance ( ) . newTransformer ( ) . transform ( new DOMSource ( node ) , new StreamResult ( new Utf8OutputStreamContent ( baos ) ) ) ; } catch ( final TransformerException ex ) { throw new IllegalStateException ( ex ) ; } return new ByteArrayInputStream ( baos . toByteArray ( ) ) ; }
Render source as XML .
29,659
private static Document emptyDocument ( ) { try { return DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . newDocument ( ) ; } catch ( final ParserConfigurationException ex ) { throw new IllegalStateException ( "Could not instantiate DocumentBuilderFactory and build empty Document" , ex ) ; } }
Create empty DOM Document .
29,660
private static Node cloneNode ( final Node dom ) { final Transformer transformer ; try { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; } catch ( final TransformerConfigurationException ex ) { throw new IllegalStateException ( "Could not create new Transformer to clone Node" , ex ) ; } final DOMSource source = new DOMSource ( dom ) ; try { final DOMResult result = new DOMResult ( ) ; transformer . transform ( source , result ) ; return result . getNode ( ) ; } catch ( final TransformerException ex ) { throw new IllegalArgumentException ( String . format ( "Could not clone Node %s with Transformer %s" , source , transformer ) , ex ) ; } }
Create Node clone .
29,661
public Request single ( final CharSequence name ) throws HttpException { final Iterator < Request > parts = this . part ( name ) . iterator ( ) ; if ( ! parts . hasNext ( ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "form param \"%s\" is mandatory" , name ) ) ; } return parts . next ( ) ; }
Get single part .
29,662
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static Iterable < String > extend ( final Response res , final Iterable < ? extends CharSequence > headers ) throws IOException { Response resp = res ; for ( final CharSequence hdr : headers ) { resp = new RsWithHeader ( resp , hdr ) ; } return resp . head ( ) ; }
Add to head additional headers .
29,663
private static InputStream transform ( final InputStream origin , final URIResolver resolver ) throws IOException { try { final TransformerFactory factory = TransformerFactory . newInstance ( ) ; factory . setURIResolver ( resolver ) ; return RsXslt . transform ( factory , origin ) ; } catch ( final TransformerException ex ) { throw new IOException ( ex ) ; } }
Build body .
29,664
private static InputStream transform ( final TransformerFactory factory , final InputStream xml ) throws TransformerException { final byte [ ] input ; try { input = RsXslt . consume ( xml ) ; } catch ( final IOException ex ) { throw new IllegalStateException ( ex ) ; } final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final Source xsl = RsXslt . stylesheet ( factory , new StreamSource ( new Utf8InputStreamContent ( new ByteArrayInputStream ( new Utf8String ( input ) . asBytes ( ) ) ) ) ) ; RsXslt . transformer ( factory , xsl ) . transform ( new StreamSource ( new Utf8InputStreamContent ( new ByteArrayInputStream ( new Utf8String ( input ) . asBytes ( ) ) ) ) , new StreamResult ( new Utf8OutputStreamContent ( baos ) ) ) ; return new ByteArrayInputStream ( new Utf8String ( baos . toByteArray ( ) ) . asBytes ( ) ) ; }
Transform XML into HTML .
29,665
private static Transformer transformer ( final TransformerFactory factory , final Source stylesheet ) throws TransformerConfigurationException { final Transformer tnfr = factory . newTransformer ( stylesheet ) ; if ( tnfr == null ) { throw new TransformerConfigurationException ( String . format ( "%s failed to create new XSL transformer for '%s'" , factory . getClass ( ) , stylesheet . getSystemId ( ) ) ) ; } return tnfr ; }
Make a transformer from this stylesheet .
29,666
public RsFluent withHeader ( final CharSequence key , final CharSequence value ) { return new RsFluent ( new RsWithHeader ( this , key , value ) ) ; }
With this header .
29,667
private static String make ( final CharSequence name , final CharSequence value , final CharSequence ... attrs ) { final StringBuilder text = new StringBuilder ( String . format ( "%s=%s;" , name , value ) ) ; for ( final CharSequence attr : attrs ) { text . append ( attr ) . append ( ';' ) ; } return text . toString ( ) ; }
Build cookie string .
29,668
private static CharSequence validValue ( final CharSequence value ) { if ( ! RsWithCookie . CVALUE_PTRN . matcher ( value ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "Cookie value \"%s\" contains invalid characters" , value ) ) ; } return value ; }
Checks value according RFC 6265 section 4 . 1 . 1 .
29,669
private static CharSequence validName ( final CharSequence name ) { if ( ! RsWithCookie . CNAME_PTRN . matcher ( name ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "Cookie name \"%s\" contains invalid characters" , name ) ) ; } return name ; }
Checks name according RFC 2616 section 2 . 2 .
29,670
private Map < String , List < Request > > requests ( final Request req ) throws IOException { final String header = new RqHeaders . Smart ( req ) . single ( "Content-Type" ) ; if ( ! new EnglishLowerCase ( header ) . string ( ) . startsWith ( "multipart/form-data" ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "RqMtBase can only parse multipart/form-data, while Content-Type specifies a different type: \"%s\"" , header ) ) ; } final Matcher matcher = RqMtBase . BOUNDARY . matcher ( header ) ; if ( ! matcher . matches ( ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "boundary is not specified in Content-Type header: \"%s\"" , header ) ) ; } final ReadableByteChannel body = Channels . newChannel ( this . stream ) ; if ( body . read ( this . buffer ) < 0 ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , "failed to read the request body" ) ; } final byte [ ] boundary = String . format ( "%s--%s" , RqMtBase . CRLF , matcher . group ( 1 ) ) . getBytes ( RqMtBase . ENCODING ) ; this . buffer . flip ( ) ; this . buffer . position ( boundary . length - 2 ) ; final Collection < Request > requests = new LinkedList < > ( ) ; while ( this . buffer . hasRemaining ( ) ) { final byte data = this . buffer . get ( ) ; if ( data == '-' ) { break ; } this . buffer . position ( this . buffer . position ( ) + 1 ) ; requests . add ( this . make ( boundary , body ) ) ; } return RqMtBase . asMap ( requests ) ; }
Build a request for each part of the origin request .
29,671
private Request make ( final byte [ ] boundary , final ReadableByteChannel body ) throws IOException { final File file = File . createTempFile ( RqMultipart . class . getName ( ) , ".tmp" ) ; try ( WritableByteChannel channel = Files . newByteChannel ( file . toPath ( ) , StandardOpenOption . READ , StandardOpenOption . WRITE ) ) { channel . write ( ByteBuffer . wrap ( this . head ( ) . iterator ( ) . next ( ) . getBytes ( RqMtBase . ENCODING ) ) ) ; channel . write ( ByteBuffer . wrap ( RqMtBase . CRLF . getBytes ( RqMtBase . ENCODING ) ) ) ; this . copy ( channel , boundary , body ) ; } return new RqTemp ( file ) ; }
Make a request . Scans the origin request until the boundary reached . Caches the content into a temporary file and returns it as a new request .
29,672
private void copy ( final WritableByteChannel target , final byte [ ] boundary , final ReadableByteChannel body ) throws IOException { int match = 0 ; boolean cont = true ; while ( cont ) { if ( ! this . buffer . hasRemaining ( ) ) { this . buffer . clear ( ) ; for ( int idx = 0 ; idx < match ; ++ idx ) { this . buffer . put ( boundary [ idx ] ) ; } match = 0 ; if ( body . read ( this . buffer ) == - 1 ) { break ; } this . buffer . flip ( ) ; } final ByteBuffer btarget = this . buffer . slice ( ) ; final int offset = this . buffer . position ( ) ; btarget . limit ( 0 ) ; while ( this . buffer . hasRemaining ( ) ) { final byte data = this . buffer . get ( ) ; if ( data == boundary [ match ] ) { ++ match ; } else if ( data == boundary [ 0 ] ) { match = 1 ; } else { match = 0 ; btarget . limit ( this . buffer . position ( ) - offset ) ; } if ( match == boundary . length ) { cont = false ; break ; } } target . write ( btarget ) ; } }
Copy until boundary reached .
29,673
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static Map < String , List < Request > > asMap ( final Collection < Request > reqs ) throws IOException { final Map < String , List < Request > > map = new HashMap < > ( reqs . size ( ) ) ; for ( final Request req : reqs ) { final String header = new RqHeaders . Smart ( req ) . single ( "Content-Disposition" ) ; final Matcher matcher = RqMtBase . NAME . matcher ( header ) ; if ( ! matcher . matches ( ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "\"name\" not found in Content-Disposition header: %s" , header ) ) ; } final String name = matcher . group ( 1 ) ; if ( ! map . containsKey ( name ) ) { map . put ( name , new LinkedList < > ( ) ) ; } map . get ( name ) . add ( req ) ; } return map ; }
Convert a list of requests to a map .
29,674
private int validated ( final int idx ) { if ( idx < 0 ) { throw new IllegalArgumentException ( String . format ( "Index %d must be >= 0." , idx ) ) ; } if ( idx >= this . all . size ( ) ) { throw new IllegalArgumentException ( String . format ( "Trying to return index %d from a list of %d passes" , idx , this . all . size ( ) ) ) ; } return idx ; }
Validate index .
29,675
private boolean allMatch ( final Request request ) throws IOException { boolean success = true ; for ( final Pass pass : this . all ) { if ( ! pass . enter ( request ) . has ( ) ) { success = false ; break ; } } return success ; }
Checks if you can enter every Pass with a request .
29,676
@ SuppressWarnings ( "PMD.AvoidCatchingThrowable" ) private void print ( final Request req , final OutputStream output ) throws IOException { try { new RsPrint ( this . take . act ( req ) ) . print ( output ) ; } catch ( final HttpException ex ) { new RsPrint ( BkBasic . failure ( ex , ex . code ( ) ) ) . print ( output ) ; } catch ( final Throwable ex ) { new RsPrint ( BkBasic . failure ( ex , HttpURLConnection . HTTP_INTERNAL_ERROR ) ) . print ( output ) ; } }
Print response to output stream safely .
29,677
private static Response failure ( final Throwable err , final int code ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try ( PrintStream stream = new Utf8PrintStream ( baos , false ) ) { err . printStackTrace ( stream ) ; } return new RsWithStatus ( new RsText ( new ByteArrayInputStream ( baos . toByteArray ( ) ) ) , code ) ; }
Make a failure response .
29,678
@ SuppressWarnings ( "PMD.AvoidDuplicateLiterals" ) private static Request addSocketHeaders ( final Request req , final Socket socket ) { return new RqWithHeaders ( req , String . format ( "%s: %s" , BkBasic . LOCALADDR , socket . getLocalAddress ( ) . getHostAddress ( ) ) , String . format ( "%s: %d" , BkBasic . LOCALPORT , socket . getLocalPort ( ) ) , String . format ( "%s: %s" , BkBasic . REMOTEADDR , socket . getInetAddress ( ) . getHostAddress ( ) ) , String . format ( "%s: %d" , BkBasic . REMOTEADDR , socket . getPort ( ) ) ) ; }
Adds custom headers with information about socket .
29,679
private static ByteArrayOutputStream sizeLine ( final InputStream stream ) throws IOException { State state = State . NORMAL ; final ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; while ( state != State . END ) { state = next ( stream , state , result ) ; } return result ; }
Extract line with chunk size from stream .
29,680
private static State next ( final InputStream stream , final State state , final ByteArrayOutputStream line ) throws IOException { final int next = stream . read ( ) ; if ( next == - 1 ) { throw new IOException ( "chunked stream ended unexpectedly" ) ; } final State result ; switch ( state ) { case NORMAL : result = nextNormal ( state , line , next ) ; break ; case R : if ( next == '\n' ) { result = State . END ; } else { throw new IOException ( String . format ( "%s%s" , "Protocol violation: Unexpected" , " single newline character in chunk size" ) ) ; } break ; case QUOTED_STRING : result = nextQuoted ( stream , state , line , next ) ; break ; default : throw new IllegalStateException ( "Bad state" ) ; } return result ; }
Get next state for FSM .
29,681
private static State nextNormal ( final State state , final ByteArrayOutputStream line , final int next ) { final State result ; switch ( next ) { case '\r' : result = State . R ; break ; case '\"' : result = State . QUOTED_STRING ; break ; default : result = state ; line . write ( next ) ; break ; } return result ; }
Maintain next symbol for current state = State . NORMAL .
29,682
private static State nextQuoted ( final InputStream stream , final State state , final ByteArrayOutputStream line , final int next ) throws IOException { final State result ; switch ( next ) { case '\\' : result = state ; line . write ( stream . read ( ) ) ; break ; case '\"' : result = State . NORMAL ; break ; default : result = state ; line . write ( next ) ; break ; } return result ; }
Maintain next symbol for current state = State . QUOTED_STRING .
29,683
@ SuppressWarnings ( "PMD.AssignmentInOperand" ) private static byte [ ] asBytes ( final InputStream input ) throws IOException { input . reset ( ) ; try ( ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ) { final byte [ ] buffer = new byte [ 1024 ] ; int read ; while ( ( read = input . read ( buffer , 0 , buffer . length ) ) != - 1 ) { output . write ( buffer , 0 , read ) ; } output . flush ( ) ; return output . toByteArray ( ) ; } }
InputStream as bytes .
29,684
public String single ( final CharSequence name ) throws IOException { final Iterator < String > params = this . param ( name ) . iterator ( ) ; if ( ! params . hasNext ( ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "form param \"%s\" is mandatory" , name ) ) ; } return params . next ( ) ; }
Get single param or throw HTTP exception .
29,685
public String single ( final CharSequence name , final String def ) throws IOException { final String value ; final Iterator < String > params = this . param ( name ) . iterator ( ) ; if ( params . hasNext ( ) ) { value = params . next ( ) ; } else { value = def ; } return value ; }
Get single param or default .
29,686
private static Response route ( final Take take , final Fallback fbk , final Request req ) throws IOException { final long start = System . currentTimeMillis ( ) ; Response res ; try { res = TkFallback . wrap ( take . act ( req ) , fbk , req ) ; } catch ( final HttpException ex ) { final Opt < Response > fbres = fbk . route ( TkFallback . fallback ( req , start , ex , ex . code ( ) ) ) ; if ( ! fbres . has ( ) ) { throw new IOException ( String . format ( "There is no fallback available in %s" , fbk . getClass ( ) . getCanonicalName ( ) ) , TkFallback . error ( ex , req , start ) ) ; } res = TkFallback . wrap ( fbres . get ( ) , fbk , req ) ; } catch ( final Throwable ex ) { final Opt < Response > fbres = fbk . route ( TkFallback . fallback ( req , start , ex , HttpURLConnection . HTTP_INTERNAL_ERROR ) ) ; if ( ! fbres . has ( ) ) { throw new IOException ( String . format ( "There is no fallback available for %s in %s" , ex . getClass ( ) . getCanonicalName ( ) , fbk . getClass ( ) . getCanonicalName ( ) ) , TkFallback . error ( ex , req , start ) ) ; } res = TkFallback . wrap ( fbres . get ( ) , fbk , req ) ; } return res ; }
Route this request .
29,687
private static RqFallback . Fake fallback ( final Request req , final long start , final Throwable throwable , final int code ) throws IOException { return new RqFallback . Fake ( req , code , TkFallback . error ( throwable , req , start ) ) ; }
Fallback request .
29,688
private static Response wrap ( final Response res , final Fallback fbk , final Request req ) { return new Response ( ) { public Iterable < String > head ( ) throws IOException { final long start = System . currentTimeMillis ( ) ; Iterable < String > head ; try { head = res . head ( ) ; } catch ( final HttpException ex ) { head = fbk . route ( TkFallback . fallback ( req , start , ex , ex . code ( ) ) ) . get ( ) . head ( ) ; } catch ( final Throwable ex ) { head = fbk . route ( TkFallback . fallback ( req , start , ex , HttpURLConnection . HTTP_INTERNAL_ERROR ) ) . get ( ) . head ( ) ; } return head ; } public InputStream body ( ) throws IOException { final long start = System . currentTimeMillis ( ) ; InputStream body ; try { body = res . body ( ) ; } catch ( final HttpException ex ) { body = fbk . route ( TkFallback . fallback ( req , start , ex , ex . code ( ) ) ) . get ( ) . body ( ) ; } catch ( final Throwable ex ) { body = fbk . route ( TkFallback . fallback ( req , start , ex , HttpURLConnection . HTTP_INTERNAL_ERROR ) ) . get ( ) . body ( ) ; } return body ; } } ; }
Wrap response .
29,689
private static Throwable error ( final Throwable exp , final Request req , final long start ) throws IOException { final String time ; final long msec = System . currentTimeMillis ( ) - start ; if ( msec < TimeUnit . SECONDS . toMillis ( 1L ) ) { time = String . format ( "%dms" , msec ) ; } else { time = String . format ( "%ds" , msec / TimeUnit . SECONDS . toMillis ( 1L ) ) ; } return new IllegalStateException ( String . format ( "[%s %s] failed in %s: %s" , new RqMethod . Base ( req ) . method ( ) , new RqHref . Base ( req ) . href ( ) , time , exp . getLocalizedMessage ( ) ) , exp ) ; }
Create an error .
29,690
private static Response join ( final Response response ) throws IOException { final StringBuilder cookies = new StringBuilder ( ) ; for ( final String header : response . head ( ) ) { final Matcher matcher = TkJoinedCookies . PTN . matcher ( header ) ; if ( ! matcher . matches ( ) ) { continue ; } cookies . append ( matcher . group ( 1 ) ) . append ( ", " ) ; } final Response out ; if ( cookies . length ( ) > 0 ) { out = new RsWithHeader ( new RsWithoutHeader ( response , "Set-cookie" ) , "Set-Cookie" , cookies . toString ( ) ) ; } else { out = response ; } return out ; }
Join them .
29,691
public void printHead ( final OutputStream output ) throws IOException { final String eol = "\r\n" ; final Writer writer = new Utf8OutputStreamContent ( output ) ; for ( final String line : this . head ( ) ) { writer . append ( line ) ; writer . append ( eol ) ; } writer . append ( eol ) ; writer . flush ( ) ; }
Print it all .
29,692
public void printBody ( final OutputStream output ) throws IOException { final InputStream input = new RqChunk ( new RqLengthAware ( this ) ) . body ( ) ; final byte [ ] buf = new byte [ 4096 ] ; while ( true ) { final int bytes = input . read ( buf ) ; if ( bytes < 0 ) { break ; } output . write ( buf , 0 , bytes ) ; } }
Print body .
29,693
private static ServerSocket random ( ) throws IOException { final ServerSocket skt = new ServerSocket ( 0 ) ; skt . setReuseAddress ( true ) ; return skt ; }
Make a random socket .
29,694
public void applyTo ( final HttpServletResponse sresp ) throws IOException { final Iterator < String > head = this . rsp . head ( ) . iterator ( ) ; final Matcher matcher = ResponseOf . HTTP_MATCHER . matcher ( head . next ( ) ) ; if ( matcher . matches ( ) ) { sresp . setStatus ( Integer . parseInt ( matcher . group ( 1 ) ) ) ; while ( head . hasNext ( ) ) { ResponseOf . applyHeader ( sresp , head . next ( ) ) ; } try ( InputStream body = this . rsp . body ( ) ; OutputStream out = sresp . getOutputStream ( ) ) { final byte [ ] buff = new byte [ ResponseOf . BUFSIZE ] ; for ( int read = body . read ( buff ) ; read >= 0 ; read = body . read ( buff ) ) { out . write ( buff ) ; } } } else { throw new IOException ( "Invalid response: response code not found" ) ; } }
Apply to servlet response .
29,695
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static void applyHeader ( final HttpServletResponse sresp , final String header ) { final String [ ] parts = header . split ( ":" ) ; final String name = parts [ 0 ] . trim ( ) ; final String val = parts [ 1 ] . trim ( ) ; if ( "set-cookie" . equals ( name . toLowerCase ( Locale . getDefault ( ) ) ) ) { for ( final HttpCookie cck : HttpCookie . parse ( header ) ) { sresp . addCookie ( new Cookie ( cck . getName ( ) , cck . getValue ( ) ) ) ; } } else { sresp . setHeader ( name , val ) ; } }
Apply header to servlet response .
29,696
private void check ( ) { for ( final Map . Entry < Thread , Long > entry : this . threads . entrySet ( ) ) { final long time = System . currentTimeMillis ( ) ; if ( time - entry . getValue ( ) > this . latency ) { final Thread thread = entry . getKey ( ) ; if ( thread . isAlive ( ) ) { thread . interrupt ( ) ; } this . threads . remove ( thread ) ; } } }
Checking threads storage and interrupt long running threads .
29,697
private Exit exit ( final Exit exit ) { final long start = System . currentTimeMillis ( ) ; final long max = this . options . lifetime ( ) ; return new Exit . Or ( exit , new Lifetime ( start , max ) ) ; }
Create exit .
29,698
@ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static Request parse ( final InputStream input ) throws IOException { boolean eof = true ; final Collection < String > head = new LinkedList < > ( ) ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; Opt < Integer > data = new Opt . Empty < > ( ) ; data = RqLive . data ( input , data , false ) ; while ( data . get ( ) > 0 ) { eof = false ; if ( data . get ( ) == '\r' ) { RqLive . checkLineFeed ( input , baos , head . size ( ) + 1 ) ; if ( baos . size ( ) == 0 ) { break ; } data = new Opt . Single < > ( input . read ( ) ) ; final Opt < String > header = RqLive . newHeader ( data , baos ) ; if ( header . has ( ) ) { head . add ( header . get ( ) ) ; } data = RqLive . data ( input , data , false ) ; continue ; } baos . write ( RqLive . legalCharacter ( data , baos , head . size ( ) + 1 ) ) ; data = RqLive . data ( input , new Opt . Empty < > ( ) , true ) ; } if ( eof ) { throw new IOException ( "empty request" ) ; } return new Request ( ) { public Iterable < String > head ( ) { return head ; } public InputStream body ( ) { return input ; } } ; }
Parse input stream .
29,699
private static Opt < String > newHeader ( final Opt < Integer > data , final ByteArrayOutputStream baos ) { Opt < String > header = new Opt . Empty < > ( ) ; if ( data . get ( ) != ' ' && data . get ( ) != '\t' ) { header = new Opt . Single < > ( new Utf8String ( baos . toByteArray ( ) ) . asString ( ) ) ; baos . reset ( ) ; } return header ; }
Builds current read header .