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 [...
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...
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 ( resul...
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 bigin...
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 ] =...
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 (...
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 (...
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 [ ] , byt...
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 ( ) / throughpu...
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 ( ) ) ; +...
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 . getPa...
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 ; } ...
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 se...
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 ( connecti...
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 ( ) . toInstan...
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 n...
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...
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 ( "ther...
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 ...
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...
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 . ind...
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 ( ) ...
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 ) ; fin...
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 < Stri...
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...
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 [...
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 ] ; S...
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 . clas...
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" , thi...
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 ) ) ; } e...
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 ( ) )...
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 \"%...
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 ( ...
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 ...
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...
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 ...
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 TransformerExceptio...
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 ByteArrayOu...
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 n...
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 . HTT...
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 ...
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...
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...
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 . ...
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 ( outpu...
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 ByteArrayIn...
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 . LOCAL...
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 = ne...
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...
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 ,...
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...
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 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 ...
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 . forma...
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 ( ma...
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 (...
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 ...
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 ....
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 ....
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...
Builds current read header .