idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
29,700 | private static Integer legalCharacter ( final Opt < Integer > data , final ByteArrayOutputStream baos , final Integer position ) throws HttpException { if ( ( data . get ( ) > 0x7f || data . get ( ) < 0x20 ) && data . get ( ) != '\t' ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "illegal character 0x%02X in HTTP header line #%d: \"%s\"" , data . get ( ) , position , new Utf8String ( baos . toByteArray ( ) ) . asString ( ) ) ) ; } return data . get ( ) ; } | Returns a legal character based n the read character . |
29,701 | private static Opt < Integer > data ( final InputStream input , final Opt < Integer > data , final boolean available ) throws IOException { final Opt < Integer > ret ; if ( data . has ( ) ) { ret = data ; } else if ( available && input . available ( ) <= 0 ) { ret = new Opt . Single < > ( - 1 ) ; } else { ret = new Opt . Single < > ( input . read ( ) ) ; } return ret ; } | Obtains new byte if hasn t . |
29,702 | @ SuppressWarnings ( { "PMD.InsufficientStringBufferDeclaration" , "PMD.AvoidInstantiatingObjectsInLoops" } ) private static StringBuilder fakeBody ( final Request ... parts ) throws IOException { final StringBuilder builder = new StringBuilder ( ) ; for ( final Request part : parts ) { builder . append ( String . format ( "--%s" , RqMtFake . BOUNDARY ) ) . append ( RqMtFake . CRLF ) . append ( "Content-Disposition: " ) . append ( new RqHeaders . Smart ( new RqHeaders . Base ( part ) ) . single ( "Content-Disposition" ) ) . append ( RqMtFake . CRLF ) ; final String body = new RqPrint ( part ) . printBody ( ) ; if ( ! ( RqMtFake . CRLF . equals ( body ) || body . isEmpty ( ) ) ) { builder . append ( RqMtFake . CRLF ) . append ( body ) . append ( RqMtFake . CRLF ) ; } } builder . append ( "Content-Transfer-Encoding: utf-8" ) . append ( RqMtFake . CRLF ) . append ( String . format ( "--%s--" , RqMtFake . BOUNDARY ) ) ; return builder ; } | Fake body creator . |
29,703 | private static byte [ ] gzip ( final InputStream input ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final byte [ ] buf = new byte [ 4096 ] ; final OutputStream gzip = new GZIPOutputStream ( baos ) ; try { while ( true ) { final int len = input . read ( buf ) ; if ( len < 0 ) { break ; } gzip . write ( buf , 0 , len ) ; } } finally { gzip . close ( ) ; input . close ( ) ; } return baos . toByteArray ( ) ; } | Gzip input stream . |
29,704 | private Identity fetch ( final String token ) throws IOException { final String uri = new Href ( this . gapi ) . path ( "plus" ) . path ( "v1" ) . path ( "people" ) . path ( "me" ) . with ( PsGoogle . ACCESS_TOKEN , token ) . toString ( ) ; final JsonObject json = new JdkRequest ( uri ) . fetch ( ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) ; if ( json . containsKey ( PsGoogle . ERROR ) ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "could not retrieve id from Google, possible cause: %s." , json . getJsonObject ( PsGoogle . ERROR ) . get ( "message" ) ) ) ; } return PsGoogle . parse ( json ) ; } | Get user name from Google with the token provided . |
29,705 | private String token ( final String code ) throws IOException { return new JdkRequest ( new Href ( this . gauth ) . path ( "o" ) . path ( "oauth2" ) . path ( "token" ) . toString ( ) ) . body ( ) . formParam ( "client_id" , this . app ) . formParam ( "redirect_uri" , this . redir ) . formParam ( "client_secret" , this . key ) . formParam ( "grant_type" , "authorization_code" ) . formParam ( PsGoogle . CODE , code ) . back ( ) . header ( "Content-Type" , "application/x-www-form-urlencoded" ) . method ( com . jcabi . http . Request . POST ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) . getString ( PsGoogle . ACCESS_TOKEN ) ; } | Retrieve Google access token . |
29,706 | private static Identity applyRules ( final Identity identity ) { if ( ! identity . equals ( Identity . ANONYMOUS ) ) { final String urn = identity . urn ( ) ; if ( urn . isEmpty ( ) ) { throw new DecodingException ( "urn is empty" ) ; } if ( ! CcStrict . PTN . matcher ( urn ) . matches ( ) ) { throw new DecodingException ( String . format ( "urn isn't valid: \"%s\"" , urn ) ) ; } } return identity ; } | Apply validation rules to identity . |
29,707 | private static Double priority ( final String text ) { final String [ ] parts = MediaType . split ( text ) ; final Double priority ; if ( parts . length > 1 ) { final String num = MediaType . NON_DIGITS . matcher ( parts [ 1 ] ) . replaceAll ( "" ) ; if ( num . isEmpty ( ) ) { priority = 0.0d ; } else { priority = Double . parseDouble ( num ) ; } } else { priority = 1.0d ; } return priority ; } | Returns the media type priority . |
29,708 | private static String lowPart ( final String text ) { final String sector ; final String [ ] sectors = MediaType . sectors ( text ) ; if ( sectors . length > 1 ) { sector = sectors [ 1 ] . trim ( ) ; } else { sector = "" ; } return sector ; } | Returns the low part of the media type . |
29,709 | private static String [ ] sectors ( final String text ) { return new EnglishLowerCase ( MediaType . split ( text ) [ 0 ] ) . string ( ) . split ( "/" , 2 ) ; } | Returns the media type sectors . |
29,710 | private static String construct ( final String ... params ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int idx = 0 ; idx < params . length ; idx += 2 ) { builder . append ( encode ( params [ idx ] ) ) . append ( '=' ) . append ( encode ( params [ idx + 1 ] ) ) . append ( '&' ) ; } return builder . toString ( ) ; } | Construct request body from parameters . |
29,711 | private static Iterable < String > append ( final Response res , final int length ) throws IOException { final String header = "Content-Length" ; return new RsWithHeader ( new RsWithoutHeader ( res , header ) , header , Integer . toString ( length ) ) . head ( ) ; } | Appends content length to header from response . |
29,712 | private static byte [ ] checkIllegalCharacters ( final byte [ ] bytes ) { final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; for ( final byte byt : bytes ) { if ( BASE64CHARS . indexOf ( byt ) < 0 ) { out . write ( byt ) ; } } return out . toByteArray ( ) ; } | Check the byte array for non - Base64 characters . |
29,713 | private Mac mac ( ) throws IOException { try { final Mac mac = Mac . getInstance ( this . alg ) ; mac . init ( this . key ) ; return mac ; } catch ( final NoSuchAlgorithmException | InvalidKeyException err ) { throw new IOException ( err ) ; } } | Obtain MAC instance . |
29,714 | @ SuppressWarnings ( "PMD.AssignmentInOperand" ) private String text ( final T item ) throws IOException { final String text ; try ( InputStream input = this . itemBody ( item ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ) { final byte [ ] buffer = new byte [ 1024 ] ; int len ; while ( ( len = input . read ( buffer , 0 , buffer . length ) ) != - 1 ) { output . write ( buffer , 0 , len ) ; } output . flush ( ) ; text = new String ( output . toByteArray ( ) , this . charset ) ; } return text ; } | Text from item . |
29,715 | private Response act ( final Request req , final Identity identity ) throws IOException { Request wrap = new RqWithoutHeader ( req , this . header ) ; if ( ! identity . equals ( Identity . ANONYMOUS ) ) { wrap = new RqWithAuth ( identity , this . header , wrap ) ; } return this . pass . exit ( this . origin . act ( wrap ) , identity ) ; } | Make take . |
29,716 | private static Request build ( final Request req , final String hdr , final String val ) throws IOException { final Request request ; if ( new RqHeaders . Base ( req ) . header ( hdr ) . iterator ( ) . hasNext ( ) ) { request = req ; } else { request = new RqWithHeader ( req , hdr , val ) ; } return request ; } | Builds the request with the default header if it is not already present . |
29,717 | private static int decode ( final int hex ) { if ( hex >= CcHex . BACK . length ) { throw new DecodingException ( String . format ( "invalid hex char: 0x%2x" , hex ) ) ; } final int dec = CcHex . BACK [ hex ] ; if ( dec < 0 ) { throw new DecodingException ( String . format ( "invalid hex character: 0x%2x" , hex ) ) ; } return dec ; } | Convert hex to number . |
29,718 | private static byte [ ] transform ( final InputStream body ) throws IOException { final SAXSource source = new SAXSource ( new InputSource ( body ) ) ; final ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; try { final XMLReader xmlreader = SAXParserFactory . newInstance ( ) . newSAXParser ( ) . getXMLReader ( ) ; source . setXMLReader ( xmlreader ) ; xmlreader . setFeature ( RsPrettyXml . LOAD_EXTERNAL_DTD , false ) ; final String yes = "yes" ; final Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , yes ) ; RsPrettyXml . prepareDocType ( body , transformer ) ; transformer . setOutputProperty ( OutputKeys . INDENT , yes ) ; transformer . transform ( source , new StreamResult ( result ) ) ; } catch ( final TransformerException | ParserConfigurationException | SAXException ex ) { throw new IOException ( ex ) ; } return result . toByteArray ( ) ; } | Format body with proper indents using SAX . |
29,719 | private static void prepareDocType ( final InputStream body , final Transformer transformer ) throws IOException { try { final String html = "html" ; final DocumentType doctype = RsPrettyXml . getDocType ( body ) ; if ( null != doctype ) { if ( null == doctype . getSystemId ( ) && null == doctype . getPublicId ( ) && html . equalsIgnoreCase ( doctype . getName ( ) ) ) { transformer . setOutputProperty ( OutputKeys . METHOD , html ) ; transformer . setOutputProperty ( OutputKeys . VERSION , "5.0" ) ; return ; } if ( null != doctype . getSystemId ( ) ) { transformer . setOutputProperty ( OutputKeys . DOCTYPE_SYSTEM , doctype . getSystemId ( ) ) ; } if ( null != doctype . getPublicId ( ) ) { transformer . setOutputProperty ( OutputKeys . DOCTYPE_PUBLIC , doctype . getPublicId ( ) ) ; } } } finally { body . reset ( ) ; } } | Parses body to get DOCTYPE and configure Transformer with proper method public id and system id . |
29,720 | private static DocumentType getDocType ( final InputStream body ) throws IOException { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; try { factory . setFeature ( RsPrettyXml . LOAD_EXTERNAL_DTD , false ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( body ) . getDoctype ( ) ; } catch ( final ParserConfigurationException | SAXException ex ) { throw new IOException ( ex ) ; } } | Parses the input stream and returns DocumentType built without loading any external DTD schemas . |
29,721 | private byte [ ] xor ( final byte [ ] input ) { final byte [ ] output = new byte [ input . length ] ; if ( this . secret . length == 0 ) { System . arraycopy ( input , 0 , output , 0 , input . length ) ; } else { int spos = 0 ; for ( int pos = 0 ; pos < input . length ; ++ pos ) { output [ pos ] = ( byte ) ( input [ pos ] ^ this . secret [ spos ] ) ; ++ spos ; if ( spos >= this . secret . length ) { spos = 0 ; } } } return output ; } | XOR array of bytes . |
29,722 | private Identity identity ( final String tkn ) throws IOException { return parse ( this . user . uri ( ) . set ( URI . create ( new Href ( PsTwitter . VERIFY_URL ) . with ( PsTwitter . ACCESS_TOKEN , tkn ) . toString ( ) ) ) . back ( ) . header ( "accept" , "application/json" ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) ) ; } | Get user name from Twitter with the token provided . |
29,723 | private String fetch ( ) throws IOException { return this . token . method ( "POST" ) . header ( "Content-Type" , "application/x-www-form-urlencoded;charset=UTF-8" ) . header ( "Authorization" , String . format ( "Basic %s" , DatatypeConverter . printBase64Binary ( new Utf8String ( String . format ( "%s:%s" , this . app , this . key ) ) . asBytes ( ) ) ) ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( JsonResponse . class ) . json ( ) . readObject ( ) . getString ( PsTwitter . ACCESS_TOKEN ) ; } | Retrieve Twitter access token . |
29,724 | private static int bitLength ( final int bits ) { int correct = bits ; if ( bits != SiHmac . HMAC256 && bits != SiHmac . HMAC384 && bits != SiHmac . HMAC512 ) { correct = SiHmac . HMAC256 ; } return correct ; } | Check for correct bit length . |
29,725 | private byte [ ] encrypt ( final byte [ ] bytes ) throws IOException { try ( Formatter formatter = new Formatter ( ) ) { for ( final byte byt : this . create ( ) . doFinal ( bytes ) ) { formatter . format ( "%02x" , byt ) ; } return formatter . toString ( ) . getBytes ( Charset . defaultCharset ( ) ) ; } } | Encrypt the given bytes using HMAC . |
29,726 | private User fetch ( final String token ) { try { return new DefaultFacebookClient ( token , this . requestor , new DefaultJsonMapper ( ) , Version . LATEST ) . fetchObject ( "me" , User . class ) ; } catch ( final FacebookException ex ) { throw new IllegalArgumentException ( ex ) ; } } | Get user name from Facebook but the code provided . |
29,727 | private String token ( final String home , final String code ) throws IOException { final String response = this . request . uri ( ) . set ( URI . create ( new Href ( PsFacebook . ACCESS_TOKEN_URL ) . with ( PsFacebook . CLIENT_ID , this . app ) . with ( "redirect_uri" , home ) . with ( PsFacebook . CLIENT_SECRET , this . key ) . with ( PsFacebook . CODE , code ) . toString ( ) ) ) . back ( ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . body ( ) ; final String [ ] sectors = response . split ( "&" ) ; for ( final String sector : sectors ) { final String [ ] pair = sector . split ( "=" ) ; if ( pair . length != 2 ) { throw new IllegalArgumentException ( String . format ( "Invalid response: '%s'" , response ) ) ; } if ( "access_token" . equals ( pair [ 0 ] ) ) { return pair [ 1 ] ; } } throw new IllegalArgumentException ( String . format ( "Access token not found in response: '%s'" , response ) ) ; } | Retrieve Facebook access token . |
29,728 | public Identity identity ( ) throws IOException { final Iterator < String > headers = new RqHeaders . Base ( this ) . header ( this . header ) . iterator ( ) ; final Identity user ; if ( headers . hasNext ( ) ) { user = new CcPlain ( ) . decode ( new Utf8String ( headers . next ( ) ) . asBytes ( ) ) ; } else { user = Identity . ANONYMOUS ; } return user ; } | Authenticated user . |
29,729 | private static byte [ ] transform ( final InputStream body ) throws IOException { final ByteArrayOutputStream res = new ByteArrayOutputStream ( ) ; try ( JsonReader rdr = Json . createReader ( body ) ) { final JsonObject obj = rdr . readObject ( ) ; try ( JsonWriter wrt = Json . createWriterFactory ( Collections . singletonMap ( JsonGenerator . PRETTY_PRINTING , true ) ) . createWriter ( res ) ) { wrt . writeObject ( obj ) ; } } catch ( final JsonException ex ) { throw new IOException ( ex ) ; } return res . toByteArray ( ) ; } | Format body with proper indents . |
29,730 | private static String make ( ) { final ResourceBundle res = ResourceBundle . getBundle ( "org.takes.version" ) ; return String . format ( "%s %s %s" , res . getString ( "version" ) , res . getString ( "revision" ) , res . getString ( "date" ) ) ; } | Make a version . |
29,731 | @ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static Iterable < Directive > transform ( final Iterable < String > texts ) { final Collection < Directive > list = new LinkedList < > ( ) ; for ( final String text : texts ) { try { for ( final Directive dir : new Directives ( text ) ) { list . add ( dir ) ; } } catch ( final SyntaxException ex ) { throw new IllegalStateException ( ex ) ; } } return list ; } | Transform strings to directives . |
29,732 | private static int port ( final File file ) throws Exception { while ( ! file . exists ( ) ) { TimeUnit . MILLISECONDS . sleep ( 1L ) ; } final int port ; try ( InputStream input = Files . newInputStream ( file . toPath ( ) ) ) { final byte [ ] buf = new byte [ 10 ] ; while ( true ) { if ( input . read ( buf ) > 0 ) { break ; } } port = Integer . parseInt ( new TrimmedText ( new Utf8String ( buf ) ) . asString ( ) ) ; } return port ; } | Read port number from file . |
29,733 | @ SuppressWarnings ( "PMD.AvoidInstantiatingObjectsInLoops" ) private static MediaTypes getType ( final Request req ) throws IOException { MediaTypes list = new MediaTypes ( ) ; final Iterable < String > headers = new RqHeaders . Base ( req ) . header ( "Content-Type" ) ; for ( final String hdr : headers ) { list = list . merge ( new MediaTypes ( hdr ) ) ; } if ( list . isEmpty ( ) ) { list = new MediaTypes ( "*/*" ) ; } return list ; } | Get Content - Type type provided by the client . |
29,734 | private static InputStream render ( final String folder , final InputStream template , final Map < String , Object > params ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final Writer writer = new Utf8OutputStreamContent ( baos ) ; final VelocityEngine engine = new VelocityEngine ( ) ; engine . setProperty ( "file.resource.loader.path" , folder ) ; engine . evaluate ( new VelocityContext ( params ) , writer , "" , new Utf8InputStreamContent ( template ) ) ; writer . close ( ) ; return new ByteArrayInputStream ( baos . toByteArray ( ) ) ; } | Render it . |
29,735 | private static Map < String , Object > convert ( final Map < CharSequence , Object > params ) { final Map < String , Object > map = new HashMap < > ( params . size ( ) ) ; for ( final Map . Entry < CharSequence , Object > ent : params . entrySet ( ) ) { map . put ( ent . getKey ( ) . toString ( ) , ent . getValue ( ) ) ; } return map ; } | Converts Map of CharSequence Object to Map of String Object . |
29,736 | private static byte [ ] print ( final RsJson . Source src ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try ( JsonWriter writer = Json . createWriter ( baos ) ) { writer . write ( src . toJson ( ) ) ; } return baos . toByteArray ( ) ; } | Print JSON . |
29,737 | private Identity fetch ( final String token ) throws IOException { final String uri = new Href ( this . api ) . path ( "user" ) . with ( PsGithub . ACCESS_TOKEN , token ) . toString ( ) ; return PsGithub . 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 Github with the token provided . |
29,738 | private String token ( final String home , final String code ) throws IOException { final String uri = new Href ( this . github ) . path ( PsGithub . LOGIN ) . path ( "oauth" ) . path ( PsGithub . ACCESS_TOKEN ) . toString ( ) ; return new JdkRequest ( uri ) . method ( "POST" ) . header ( "Accept" , "application/xml" ) . body ( ) . formParam ( "client_id" , this . app ) . formParam ( "redirect_uri" , home ) . formParam ( "client_secret" , this . key ) . formParam ( PsGithub . CODE , code ) . back ( ) . fetch ( ) . as ( RestResponse . class ) . assertStatus ( HttpURLConnection . HTTP_OK ) . as ( XmlResponse . class ) . assertXPath ( "/OAuth/access_token" ) . xml ( ) . xpath ( "/OAuth/access_token/text()" ) . get ( 0 ) ; } | Retrieve Github access token . |
29,739 | private static Iterable < String > extend ( final Iterable < String > head , final String header ) { if ( ! RsWithHeader . HEADER . matcher ( header ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "header line of HTTP response \"%s\" doesn't match \"%s\" regular expression, but it should, according to RFC 7230" , header , RsWithHeader . HEADER ) ) ; } return new Concat < > ( head , Collections . singleton ( header ) ) ; } | Add to head additional header . |
29,740 | private static Request wrap ( final Request req ) { final AtomicBoolean seen = new AtomicBoolean ( false ) ; return new Request ( ) { public Iterable < String > head ( ) throws IOException { return req . head ( ) ; } public InputStream body ( ) throws IOException { if ( ! seen . getAndSet ( true ) ) { throw new IllegalStateException ( "It's not allowed to call body() more than once" ) ; } return req . body ( ) ; } } ; } | Wrap the request . |
29,741 | private static Fork fork ( final String host , final Take take ) { return new Fork ( ) { public Opt < Response > route ( final Request req ) throws IOException { final String hst = new RqHeaders . Smart ( new RqHeaders . Base ( req ) ) . single ( "host" ) ; final Opt < Response > rsp ; if ( new EnglishLowerCase ( host ) . string ( ) . equals ( new EnglishLowerCase ( hst ) . string ( ) ) ) { rsp = new Opt . Single < > ( take . act ( req ) ) ; } else { rsp = new Opt . Empty < > ( ) ; } return rsp ; } } ; } | Make fork . |
29,742 | private static List < String > strings ( final List < IOException > failures ) { final List < String > result = new ArrayList < > ( failures . size ( ) ) ; final Iterable < String > transform = new Transform < > ( failures , new TransformAction < IOException , String > ( ) { public String transform ( final IOException element ) { final Opt < String > message = new Opt . Single < > ( element . getMessage ( ) ) ; String result = "" ; if ( message . has ( ) ) { result = message . get ( ) ; } return result ; } } ) ; final Iterator < String > messages = transform . iterator ( ) ; while ( messages . hasNext ( ) ) { result . add ( messages . next ( ) ) ; } return result ; } | Transforms a list of exceptions and returns a list of messages . |
29,743 | @ SuppressWarnings ( "PMD.AvoidArrayLoops" ) private static byte [ ] salt ( final byte [ ] text ) { final byte size = ( byte ) CcSalted . RND . nextInt ( Tv . TEN ) ; final byte [ ] output = new byte [ text . length + ( int ) size + 2 ] ; output [ 0 ] = size ; byte sum = ( byte ) 0 ; for ( int idx = 0 ; idx < ( int ) size ; ++ idx ) { output [ idx + 1 ] = ( byte ) CcSalted . RND . nextInt ( ) ; sum += output [ idx + 1 ] ; } System . arraycopy ( text , 0 , output , ( int ) size + 1 , text . length ) ; output [ output . length - 1 ] = sum ; return output ; } | Salt the string . |
29,744 | @ SuppressWarnings ( "PMD.CyclomaticComplexity" ) private static byte [ ] unsalt ( final byte [ ] text ) { if ( text . length == 0 ) { throw new DecodingException ( "empty input" ) ; } final int size = text [ 0 ] ; if ( size < 0 ) { throw new DecodingException ( String . format ( "Length of salt %+d is negative, something is wrong" , size ) ) ; } if ( text . length < size + 2 ) { throw new DecodingException ( String . format ( "Not enough bytes for salt, length is %d while %d required" , text . length , size + 2 ) ) ; } byte sum = ( byte ) 0 ; for ( int idx = 0 ; idx < size ; ++ idx ) { sum += text [ idx + 1 ] ; } if ( text [ text . length - 1 ] != sum ) { throw new DecodingException ( String . format ( "Checksum %d failure, while %d expected" , text [ text . length - 1 ] , sum ) ) ; } final byte [ ] output = new byte [ text . length - size - 2 ] ; System . arraycopy ( text , size + 1 , output , 0 , output . length ) ; return output ; } | Un - salt the string . |
29,745 | private Map < String , List < String > > map ( ) throws IOException { if ( this . saved . isEmpty ( ) ) { this . saved . add ( this . freshMap ( ) ) ; } return this . saved . get ( 0 ) ; } | Create map of request parameters . |
29,746 | private Map < String , List < String > > freshMap ( ) throws IOException { final String body = new RqPrint ( this . req ) . printBody ( ) ; final Map < String , List < String > > map = new HashMap < > ( 1 ) ; for ( final String pair : body . split ( "&" ) ) { if ( pair . isEmpty ( ) ) { continue ; } final String [ ] parts = pair . split ( "=" , 2 ) ; if ( parts . length < 2 ) { throw new HttpException ( HttpURLConnection . HTTP_BAD_REQUEST , String . format ( "invalid form body pair: %s" , pair ) ) ; } final String key = RqFormBase . decode ( new EnglishLowerCase ( parts [ 0 ] . trim ( ) ) . string ( ) ) ; if ( ! map . containsKey ( key ) ) { map . put ( key , new LinkedList < > ( ) ) ; } map . get ( key ) . add ( RqFormBase . decode ( parts [ 1 ] . trim ( ) ) ) ; } return map ; } | Create map of request parameter . |
29,747 | public InetAddress getLocalAddress ( ) throws IOException { return InetAddress . getByName ( new RqHeaders . Smart ( new RqHeaders . Base ( this ) ) . single ( "X-Takes-LocalAddress" ) ) ; } | Returns IP address from the X - Takes - LocalAddress header . |
29,748 | public InetAddress getRemoteAddress ( ) throws IOException { return InetAddress . getByName ( new RqHeaders . Smart ( new RqHeaders . Base ( this ) ) . single ( "X-Takes-RemoteAddress" ) ) ; } | Returns IP address from the X - Takes - RemoteAddress header . |
29,749 | public static boolean containsEntry ( File zip , String name ) { ZipFile zf = null ; try { zf = new ZipFile ( zip ) ; return zf . getEntry ( name ) != null ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { closeQuietly ( zf ) ; } } | Checks if the ZIP file contains the given entry . |
29,750 | public static int getCompressionMethodOfEntry ( File zip , String name ) { ZipFile zf = null ; try { zf = new ZipFile ( zip ) ; ZipEntry zipEntry = zf . getEntry ( name ) ; if ( zipEntry == null ) { return - 1 ; } return zipEntry . getMethod ( ) ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { closeQuietly ( zf ) ; } } | Returns the compression method of a given entry of the ZIP file . |
29,751 | public static boolean containsAnyEntry ( File zip , String [ ] names ) { ZipFile zf = null ; try { zf = new ZipFile ( zip ) ; for ( int i = 0 ; i < names . length ; i ++ ) { if ( zf . getEntry ( names [ i ] ) != null ) { return true ; } } return false ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { closeQuietly ( zf ) ; } } | Checks if the ZIP file contains any of the given entries . |
29,752 | private static byte [ ] doUnpackEntry ( ZipFile zf , String name ) throws IOException { ZipEntry ze = zf . getEntry ( name ) ; if ( ze == null ) { return null ; } InputStream is = zf . getInputStream ( ze ) ; try { return IOUtils . toByteArray ( is ) ; } finally { IOUtils . closeQuietly ( is ) ; } } | Unpacks a single entry from a ZIP file . |
29,753 | public static byte [ ] unpackEntry ( InputStream is , String name ) { ByteArrayUnpacker action = new ByteArrayUnpacker ( ) ; if ( ! handle ( is , name , action ) ) return null ; return action . getBytes ( ) ; } | Unpacks a single entry from a ZIP stream . |
29,754 | public static boolean unpackEntry ( InputStream is , String name , File file ) throws IOException { return handle ( is , name , new FileUnpacker ( file ) ) ; } | Unpacks a single file from a ZIP stream to a file . |
29,755 | public static boolean handle ( File zip , String name , ZipEntryCallback action ) { ZipFile zf = null ; try { zf = new ZipFile ( zip ) ; ZipEntry ze = zf . getEntry ( name ) ; if ( ze == null ) { return false ; } InputStream in = new BufferedInputStream ( zf . getInputStream ( ze ) ) ; try { action . process ( in , ze ) ; } finally { IOUtils . closeQuietly ( in ) ; } return true ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { closeQuietly ( zf ) ; } } | Reads the given ZIP file and executes the given action for a single entry . |
29,756 | public static boolean handle ( InputStream is , String name , ZipEntryCallback action ) { SingleZipEntryCallback helper = new SingleZipEntryCallback ( name , action ) ; iterate ( is , helper ) ; return helper . found ( ) ; } | Reads the given ZIP stream and executes the given action for a single entry . |
29,757 | public static void unpack ( File zip , final File outputDir , Charset charset ) { unpack ( zip , outputDir , IdentityNameMapper . INSTANCE , charset ) ; } | Unpacks a ZIP file to the given directory using a specific Charset for the input file . |
29,758 | public static byte [ ] packEntry ( File file ) { log . trace ( "Compressing '{}' into a ZIP file with single entry." , file ) ; ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; try { ZipOutputStream out = new ZipOutputStream ( result ) ; ZipEntry entry = ZipEntryUtil . fromFile ( file . getName ( ) , file ) ; InputStream in = new BufferedInputStream ( new FileInputStream ( file ) ) ; try { ZipEntryUtil . addEntry ( entry , in , out ) ; } finally { IOUtils . closeQuietly ( in ) ; } out . close ( ) ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } return result . toByteArray ( ) ; } | Compresses the given file into a ZIP file with single entry . |
29,759 | private static void pack ( File dir , ZipOutputStream out , NameMapper mapper , String pathPrefix , boolean mustHaveChildren ) throws IOException { String [ ] filenames = dir . list ( ) ; if ( filenames == null ) { if ( ! dir . exists ( ) ) { throw new ZipException ( "Given file '" + dir + "' doesn't exist!" ) ; } throw new IOException ( "Given file is not a directory '" + dir + "'" ) ; } if ( mustHaveChildren && filenames . length == 0 ) { throw new ZipException ( "Given directory '" + dir + "' doesn't contain any files!" ) ; } for ( int i = 0 ; i < filenames . length ; i ++ ) { String filename = filenames [ i ] ; File file = new File ( dir , filename ) ; boolean isDir = file . isDirectory ( ) ; String path = pathPrefix + file . getName ( ) ; if ( isDir ) { path += PATH_SEPARATOR ; } String name = mapper . map ( path ) ; if ( name != null ) { ZipEntry zipEntry = ZipEntryUtil . fromFile ( name , file ) ; out . putNextEntry ( zipEntry ) ; if ( ! isDir ) { FileUtils . copy ( file , out ) ; } out . closeEntry ( ) ; } if ( isDir ) { pack ( file , out , mapper , path , false ) ; } } } | Compresses the given directory and all its sub - directories into a ZIP file . |
29,760 | public static void createEmpty ( File file ) { FileOutputStream fos = null ; try { fos = new FileOutputStream ( file ) ; fos . write ( new byte [ ] { 0x50 , 0x4B , 0x05 , 0x06 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 } ) ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { IOUtils . closeQuietly ( fos ) ; } } | Creates an empty ZIP archive at the location of the provided file . |
29,761 | public static void pack ( ZipEntrySource [ ] entries , OutputStream os ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Creating stream from {}." , Arrays . asList ( entries ) ) ; } pack ( entries , os , false ) ; } | Compresses the given entries into an output stream . |
29,762 | public static void pack ( ZipEntrySource [ ] entries , File zip ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Creating '{}' from {}." , zip , Arrays . asList ( entries ) ) ; } OutputStream out = null ; try { out = new BufferedOutputStream ( new FileOutputStream ( zip ) ) ; pack ( entries , out , true ) ; } catch ( IOException e ) { throw ZipExceptionUtil . rethrow ( e ) ; } finally { IOUtils . closeQuietly ( out ) ; } } | Compresses the given entries into a new ZIP file . |
29,763 | public static void removeEntry ( File zip , String path , File destZip ) { removeEntries ( zip , new String [ ] { path } , destZip ) ; } | Copies an existing ZIP file and removes entry with a given path . |
29,764 | private static void copyEntries ( File zip , final ZipOutputStream out ) { final Set < String > names = new HashSet < String > ( ) ; iterate ( zip , new ZipEntryCallback ( ) { public void process ( InputStream in , ZipEntry zipEntry ) throws IOException { String entryName = zipEntry . getName ( ) ; if ( names . add ( entryName ) ) { ZipEntryUtil . copyEntry ( zipEntry , in , out ) ; } else if ( log . isDebugEnabled ( ) ) { log . debug ( "Duplicate entry: {}" , entryName ) ; } } } ) ; } | Copies all entries from one ZIP file to another . |
29,765 | private static void copyEntries ( File zip , final ZipOutputStream out , final Set < String > ignoredEntries ) { final Set < String > names = new HashSet < String > ( ) ; final Set < String > dirNames = filterDirEntries ( zip , ignoredEntries ) ; iterate ( zip , new ZipEntryCallback ( ) { public void process ( InputStream in , ZipEntry zipEntry ) throws IOException { String entryName = zipEntry . getName ( ) ; if ( ignoredEntries . contains ( entryName ) ) { return ; } for ( String dirName : dirNames ) { if ( entryName . startsWith ( dirName ) ) { return ; } } if ( names . add ( entryName ) ) { ZipEntryUtil . copyEntry ( zipEntry , in , out ) ; } else if ( log . isDebugEnabled ( ) ) { log . debug ( "Duplicate entry: {}" , entryName ) ; } } } ) ; } | Copies all entries from one ZIP file to another ignoring entries with path in ignoredEntries |
29,766 | public static boolean replaceEntries ( File zip , ZipEntrySource [ ] entries , File destZip ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays . asList ( entries ) + "." ) ; } final Map < String , ZipEntrySource > entryByPath = entriesByPath ( entries ) ; final int entryCount = entryByPath . size ( ) ; try { final ZipOutputStream out = new ZipOutputStream ( new BufferedOutputStream ( new FileOutputStream ( destZip ) ) ) ; try { final Set < String > names = new HashSet < String > ( ) ; iterate ( zip , new ZipEntryCallback ( ) { public void process ( InputStream in , ZipEntry zipEntry ) throws IOException { if ( names . add ( zipEntry . getName ( ) ) ) { ZipEntrySource entry = ( ZipEntrySource ) entryByPath . remove ( zipEntry . getName ( ) ) ; if ( entry != null ) { addEntry ( entry , out ) ; } else { ZipEntryUtil . copyEntry ( zipEntry , in , out ) ; } } else if ( log . isDebugEnabled ( ) ) { log . debug ( "Duplicate entry: {}" , zipEntry . getName ( ) ) ; } } } ) ; } finally { IOUtils . closeQuietly ( out ) ; } } catch ( IOException e ) { ZipExceptionUtil . rethrow ( e ) ; } return entryByPath . size ( ) < entryCount ; } | Copies an existing ZIP file and replaces the given entries in it . |
29,767 | public static FileSource [ ] pair ( File [ ] files , String [ ] names ) { if ( files . length > names . length ) { throw new IllegalArgumentException ( "names array must contain " + "at least the same amount of items as files array or more" ) ; } FileSource [ ] result = new FileSource [ files . length ] ; for ( int i = 0 ; i < files . length ; i ++ ) { result [ i ] = new FileSource ( names [ i ] , files [ i ] ) ; } return result ; } | Creates a sequence of FileSource objects via mapping a sequence of files to the sequence of corresponding names for the entries |
29,768 | public void transform ( InputStream in , ZipEntry zipEntry , ZipOutputStream out ) throws IOException { File inFile = null ; File outFile = null ; try { inFile = File . createTempFile ( "zip" , null ) ; outFile = File . createTempFile ( "zip" , null ) ; copy ( in , inFile ) ; transform ( zipEntry , inFile , outFile ) ; FileSource source = new FileSource ( zipEntry . getName ( ) , outFile ) ; ZipEntrySourceZipEntryTransformer . addEntry ( source , out ) ; } finally { FileUtils . deleteQuietly ( inFile ) ; FileUtils . deleteQuietly ( outFile ) ; } } | Copies the input stream to the file then transforms the file . FileSource is added then to the output stream . |
29,769 | public byte [ ] getLocalFileDataData ( ) { byte [ ] data = new byte [ getLocalFileDataLength ( ) . getValue ( ) - WORD ] ; System . arraycopy ( ZipShort . getBytes ( getMode ( ) ) , 0 , data , 0 , 2 ) ; byte [ ] linkArray = getLinkedFile ( ) . getBytes ( ) ; System . arraycopy ( ZipLong . getBytes ( linkArray . length ) , 0 , data , 2 , WORD ) ; System . arraycopy ( ZipShort . getBytes ( getUserId ( ) ) , 0 , data , 6 , 2 ) ; System . arraycopy ( ZipShort . getBytes ( getGroupId ( ) ) , 0 , data , 8 , 2 ) ; System . arraycopy ( linkArray , 0 , data , 10 , linkArray . length ) ; crc . reset ( ) ; crc . update ( data ) ; long checksum = crc . getValue ( ) ; byte [ ] result = new byte [ data . length + WORD ] ; System . arraycopy ( ZipLong . getBytes ( checksum ) , 0 , result , 0 , WORD ) ; System . arraycopy ( data , 0 , result , WORD , data . length ) ; return result ; } | The actual data to put into local file data - without Header - ID or length specifier . |
29,770 | public void parseFromLocalFileData ( byte [ ] data , int offset , int length ) throws ZipException { long givenChecksum = ZipLong . getValue ( data , offset ) ; byte [ ] tmp = new byte [ length - WORD ] ; System . arraycopy ( data , offset + WORD , tmp , 0 , length - WORD ) ; crc . reset ( ) ; crc . update ( tmp ) ; long realChecksum = crc . getValue ( ) ; if ( givenChecksum != realChecksum ) { throw new ZipException ( "bad CRC checksum " + Long . toHexString ( givenChecksum ) + " instead of " + Long . toHexString ( realChecksum ) ) ; } int newMode = ZipShort . getValue ( tmp , 0 ) ; byte [ ] linkArray = new byte [ ( int ) ZipLong . getValue ( tmp , 2 ) ] ; uid = ZipShort . getValue ( tmp , 6 ) ; gid = ZipShort . getValue ( tmp , 8 ) ; if ( linkArray . length == 0 ) { link = "" ; } else { System . arraycopy ( tmp , 10 , linkArray , 0 , linkArray . length ) ; link = new String ( linkArray ) ; } setDirectory ( ( newMode & DIR_FLAG ) != 0 ) ; setMode ( newMode ) ; } | Populate data from this array as if it was in local file data . |
29,771 | protected int getMode ( int mode ) { int type = FILE_FLAG ; if ( isLink ( ) ) { type = LINK_FLAG ; } else if ( isDirectory ( ) ) { type = DIR_FLAG ; } return type | ( mode & PERM_MASK ) ; } | Get the file mode for given permissions with the correct file type . |
29,772 | static ZipEntry copy ( ZipEntry original , String newName ) { ZipEntry copy = new ZipEntry ( newName == null ? original . getName ( ) : newName ) ; if ( original . getCrc ( ) != - 1 ) { copy . setCrc ( original . getCrc ( ) ) ; } if ( original . getMethod ( ) != - 1 ) { copy . setMethod ( original . getMethod ( ) ) ; } if ( original . getSize ( ) >= 0 ) { copy . setSize ( original . getSize ( ) ) ; } if ( original . getExtra ( ) != null ) { copy . setExtra ( original . getExtra ( ) ) ; } copy . setComment ( original . getComment ( ) ) ; copy . setTime ( original . getTime ( ) ) ; return copy ; } | Copy entry with another name . |
29,773 | static void copyEntry ( ZipEntry zipEntry , InputStream in , ZipOutputStream out ) throws IOException { copyEntry ( zipEntry , in , out , true ) ; } | Copies a given ZIP entry to a ZIP file . |
29,774 | static void copyEntry ( ZipEntry originalEntry , InputStream in , ZipOutputStream out , boolean preserveTimestamps ) throws IOException { ZipEntry copy = copy ( originalEntry ) ; if ( preserveTimestamps ) { TimestampStrategyFactory . getInstance ( ) . setTime ( copy , originalEntry ) ; } else { copy . setTime ( System . currentTimeMillis ( ) ) ; } addEntry ( copy , new BufferedInputStream ( in ) , out ) ; } | Copies a given ZIP entry to a ZIP file . If this . preserveTimestamps is true original timestamp is carried over otherwise uses current time . |
29,775 | static ZipEntry fromFile ( String name , File file ) { ZipEntry zipEntry = new ZipEntry ( name ) ; if ( ! file . isDirectory ( ) ) { zipEntry . setSize ( file . length ( ) ) ; } zipEntry . setTime ( file . lastModified ( ) ) ; ZTFilePermissions permissions = ZTFilePermissionsUtil . getDefaultStategy ( ) . getPermissions ( file ) ; if ( permissions != null ) { ZipEntryUtil . setZTFilePermissions ( zipEntry , permissions ) ; } return zipEntry ; } | Create new Zip entry and fill it with associated with file meta - info |
29,776 | public static void register ( Class < ? > c ) { try { ZipExtraField ze = ( ZipExtraField ) c . newInstance ( ) ; implementations . put ( ze . getHeaderId ( ) , c ) ; } catch ( ClassCastException cc ) { throw new RuntimeException ( c + " doesn\'t implement ZipExtraField" ) ; } catch ( InstantiationException ie ) { throw new RuntimeException ( c + " is not a concrete class" ) ; } catch ( IllegalAccessException ie ) { throw new RuntimeException ( c + "\'s no-arg constructor is not public" ) ; } } | Register a ZipExtraField implementation . |
29,777 | public static List < ZipExtraField > parse ( byte [ ] data ) throws ZipException { List < ZipExtraField > v = new ArrayList < ZipExtraField > ( ) ; if ( data == null ) { return v ; } int start = 0 ; while ( start <= data . length - WORD ) { ZipShort headerId = new ZipShort ( data , start ) ; int length = ( new ZipShort ( data , start + 2 ) ) . getValue ( ) ; if ( start + WORD + length > data . length ) { throw new ZipException ( "bad extra field starting at " + start + ". Block length of " + length + " bytes exceeds remaining" + " data of " + ( data . length - start - WORD ) + " bytes." ) ; } try { ZipExtraField ze = createExtraField ( headerId ) ; ze . parseFromLocalFileData ( data , start + WORD , length ) ; v . add ( ze ) ; } catch ( InstantiationException ie ) { throw new ZipException ( ie . getMessage ( ) ) ; } catch ( IllegalAccessException iae ) { throw new ZipException ( iae . getMessage ( ) ) ; } start += ( length + WORD ) ; } return v ; } | Split the array into ExtraFields and populate them with the given data as local file data throwing an exception if the data cannot be parsed . |
29,778 | public static byte [ ] mergeLocalFileDataData ( List < ZipExtraField > data ) { int regularExtraFieldCount = data . size ( ) ; int sum = WORD * regularExtraFieldCount ; for ( ZipExtraField element : data ) { sum += element . getLocalFileDataLength ( ) . getValue ( ) ; } byte [ ] result = new byte [ sum ] ; int start = 0 ; for ( ZipExtraField element : data ) { System . arraycopy ( element . getHeaderId ( ) . getBytes ( ) , 0 , result , start , 2 ) ; System . arraycopy ( element . getLocalFileDataLength ( ) . getBytes ( ) , 0 , result , start + 2 , 2 ) ; byte [ ] local = element . getLocalFileDataData ( ) ; System . arraycopy ( local , 0 , result , start + WORD , local . length ) ; start += ( local . length + WORD ) ; } return result ; } | Merges the local file data fields of the given ZipExtraFields . |
29,779 | public static byte [ ] getBytes ( long value ) { byte [ ] result = new byte [ WORD ] ; result [ 0 ] = ( byte ) ( ( value & BYTE_MASK ) ) ; result [ BYTE_1 ] = ( byte ) ( ( value & BYTE_1_MASK ) >> BYTE_1_SHIFT ) ; result [ BYTE_2 ] = ( byte ) ( ( value & BYTE_2_MASK ) >> BYTE_2_SHIFT ) ; result [ BYTE_3 ] = ( byte ) ( ( value & BYTE_3_MASK ) >> BYTE_3_SHIFT ) ; return result ; } | Get value as four bytes in big endian byte order . |
29,780 | public static long getValue ( byte [ ] bytes , int offset ) { long value = ( bytes [ offset + BYTE_3 ] << BYTE_3_SHIFT ) & BYTE_3_MASK ; value += ( bytes [ offset + BYTE_2 ] << BYTE_2_SHIFT ) & BYTE_2_MASK ; value += ( bytes [ offset + BYTE_1 ] << BYTE_1_SHIFT ) & BYTE_1_MASK ; value += ( bytes [ offset ] & BYTE_MASK ) ; return value ; } | Helper method to get the value as a Java long from four bytes starting at given array offset |
29,781 | public static void forceDeleteOnExit ( File file ) throws IOException { if ( file . isDirectory ( ) ) { deleteDirectoryOnExit ( file ) ; } else { file . deleteOnExit ( ) ; } } | Schedules a file to be deleted when JVM exits . If file is directory delete it and all sub - directories . |
29,782 | private static void deleteDirectoryOnExit ( File directory ) throws IOException { if ( ! directory . exists ( ) ) { return ; } directory . deleteOnExit ( ) ; if ( ! isSymlink ( directory ) ) { cleanDirectoryOnExit ( directory ) ; } } | Schedules a directory recursively for deletion on JVM exit . |
29,783 | public static void copy ( File file , OutputStream out ) throws IOException { FileInputStream in = new FileInputStream ( file ) ; try { IOUtils . copy ( new BufferedInputStream ( in ) , out ) ; } finally { IOUtils . closeQuietly ( in ) ; } } | Copies the given file into an output stream . |
29,784 | public static File getTempFileFor ( File file ) { File parent = file . getParentFile ( ) ; String name = file . getName ( ) ; File result ; int index = 0 ; do { result = new File ( parent , name + "_" + index ++ ) ; } while ( result . exists ( ) ) ; return result ; } | Find a non - existing file in the same directory using the same name as prefix . |
29,785 | public Zips addTransformer ( String path , ZipEntryTransformer transformer ) { this . transformers . add ( new ZipEntryTransformerEntry ( path , transformer ) ) ; return this ; } | Registers a transformer for a given entry . |
29,786 | public void process ( ) { if ( src == null && dest == null ) { throw new IllegalArgumentException ( "Source and destination shouldn't be null together" ) ; } File destinationFile = null ; try { destinationFile = getDestinationFile ( ) ; ZipOutputStream out = null ; ZipEntryOrInfoAdapter zipEntryAdapter = null ; if ( destinationFile . isFile ( ) ) { out = ZipFileUtil . createZipOutputStream ( new BufferedOutputStream ( new FileOutputStream ( destinationFile ) ) , charset ) ; zipEntryAdapter = new ZipEntryOrInfoAdapter ( new CopyingCallback ( transformers , out , preserveTimestamps ) , null ) ; } else { zipEntryAdapter = new ZipEntryOrInfoAdapter ( new UnpackingCallback ( transformers , destinationFile ) , null ) ; } try { processAllEntries ( zipEntryAdapter ) ; } finally { IOUtils . closeQuietly ( out ) ; } handleInPlaceActions ( destinationFile ) ; } catch ( IOException e ) { ZipExceptionUtil . rethrow ( e ) ; } finally { if ( isInPlace ( ) ) { FileUtils . deleteQuietly ( destinationFile ) ; } } } | Iterates through source Zip entries removing or changing them according to set parameters . |
29,787 | private void iterateExistingExceptRemoved ( ZipEntryOrInfoAdapter zipEntryCallback ) { if ( src == null ) { return ; } final Set < String > removedDirs = ZipUtil . filterDirEntries ( src , removedEntries ) ; ZipFile zf = null ; try { zf = getZipFile ( ) ; Enumeration < ? extends ZipEntry > en = zf . entries ( ) ; while ( en . hasMoreElements ( ) ) { ZipEntry entry = en . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( removedEntries . contains ( entryName ) || isEntryInDir ( removedDirs , entryName ) ) { continue ; } if ( nameMapper != null ) { String mappedName = nameMapper . map ( entry . getName ( ) ) ; if ( mappedName == null ) { continue ; } else if ( ! mappedName . equals ( entry . getName ( ) ) ) { entry = ZipEntryUtil . copy ( entry , mappedName ) ; } } InputStream is = zf . getInputStream ( entry ) ; try { zipEntryCallback . process ( is , entry ) ; } catch ( ZipBreakException ex ) { break ; } finally { IOUtils . closeQuietly ( is ) ; } } } catch ( IOException e ) { ZipExceptionUtil . rethrow ( e ) ; } finally { ZipUtil . closeQuietly ( zf ) ; } } | Iterate through source for not removed entries with a given callback |
29,788 | private void iterateChangedAndAdded ( ZipEntryOrInfoAdapter zipEntryCallback ) { for ( ZipEntrySource entrySource : changedEntries ) { InputStream entrySourceStream = null ; try { ZipEntry entry = entrySource . getEntry ( ) ; if ( nameMapper != null ) { String mappedName = nameMapper . map ( entry . getName ( ) ) ; if ( mappedName == null ) { continue ; } else if ( ! mappedName . equals ( entry . getName ( ) ) ) { entry = ZipEntryUtil . copy ( entry , mappedName ) ; } } entrySourceStream = entrySource . getInputStream ( ) ; zipEntryCallback . process ( entrySourceStream , entry ) ; } catch ( ZipBreakException ex ) { break ; } catch ( IOException e ) { ZipExceptionUtil . rethrow ( e ) ; } finally { IOUtils . closeQuietly ( entrySourceStream ) ; } } } | Iterate through ZipEntrySources for added or changed entries with a given callback |
29,789 | private void handleInPlaceActions ( File result ) throws IOException { if ( isInPlace ( ) ) { FileUtils . forceDelete ( src ) ; if ( result . isFile ( ) ) { FileUtils . moveFile ( result , src ) ; } else { FileUtils . moveDirectory ( result , src ) ; } } } | if we are doing something in place move result file into src . |
29,790 | private boolean isEntryInDir ( Set < String > dirNames , String entryName ) { for ( String dirName : dirNames ) { if ( entryName . startsWith ( dirName ) ) { return true ; } } return false ; } | Checks if entry given by name resides inside of one of the dirs . |
29,791 | static ZipInputStream createZipInputStream ( InputStream inStream , Charset charset ) { if ( charset == null ) return new ZipInputStream ( inStream ) ; try { Constructor < ZipInputStream > constructor = ZipInputStream . class . getConstructor ( new Class [ ] { InputStream . class , Charset . class } ) ; return ( ZipInputStream ) constructor . newInstance ( new Object [ ] { inStream , charset } ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( MISSING_METHOD_PLEASE_UPGRADE , e ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_INPUT + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_INPUT + e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_INPUT + e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_INPUT + e . getMessage ( ) , e ) ; } } | Returns a ZipInputStream opened with a given charset . |
29,792 | static ZipOutputStream createZipOutputStream ( BufferedOutputStream outStream , Charset charset ) { if ( charset == null ) return new ZipOutputStream ( outStream ) ; try { Constructor < ZipOutputStream > constructor = ZipOutputStream . class . getConstructor ( new Class [ ] { OutputStream . class , Charset . class } ) ; return ( ZipOutputStream ) constructor . newInstance ( new Object [ ] { outStream , charset } ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( MISSING_METHOD_PLEASE_UPGRADE , e ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_OUTPUT + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_OUTPUT + e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_OUTPUT + e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_OUTPUT + e . getMessage ( ) , e ) ; } } | Returns a ZipOutputStream opened with a given charset . |
29,793 | static ZipFile getZipFile ( File src , Charset charset ) throws IOException { if ( charset == null ) { return new ZipFile ( src ) ; } try { Constructor < ZipFile > constructor = ZipFile . class . getConstructor ( new Class [ ] { File . class , Charset . class } ) ; return ( ZipFile ) constructor . newInstance ( new Object [ ] { src , charset } ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( MISSING_METHOD_PLEASE_UPGRADE , e ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_ZIPFILE + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_ZIPFILE + e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_ZIPFILE + e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( CONSTRUCTOR_MESSAGE_FOR_ZIPFILE + e . getMessage ( ) , e ) ; } } | Returns a zipFile opened with a given charset |
29,794 | public byte [ ] getBytes ( ) { byte [ ] result = new byte [ 2 ] ; result [ 0 ] = ( byte ) ( value & BYTE_MASK ) ; result [ 1 ] = ( byte ) ( ( value & BYTE_1_MASK ) >> BYTE_1_SHIFT ) ; return result ; } | Get value as two bytes in big endian byte order . |
29,795 | public static int getValue ( byte [ ] bytes , int offset ) { int value = ( bytes [ offset + 1 ] << BYTE_1_SHIFT ) & BYTE_1_MASK ; value += ( bytes [ offset ] & BYTE_MASK ) ; return value ; } | Helper method to get the value as a java int from two bytes starting at given array offset |
29,796 | private static byte [ ] copy ( byte [ ] from ) { if ( from != null ) { byte [ ] to = new byte [ from . length ] ; System . arraycopy ( from , 0 , to , 0 , to . length ) ; return to ; } return null ; } | Create a copy of the given array - or return null if the argument is null . |
29,797 | public void transform ( InputStream in , ZipEntry zipEntry , ZipOutputStream out ) throws IOException { ZipEntry entry = new ZipEntry ( zipEntry . getName ( ) ) ; entry . setTime ( System . currentTimeMillis ( ) ) ; out . putNextEntry ( entry ) ; transform ( zipEntry , in , out ) ; out . closeEntry ( ) ; } | Transforms the input stream entry writes that to output stream closes entry in the output stream . |
29,798 | public JsonAssert node ( String node ) { return new JsonAssert ( path . to ( node ) , configuration , getNode ( actual , node ) ) ; } | Moves comparison to given node . Second call navigates from the last position in the JSON . |
29,799 | public JsonAssert and ( JsonAssertion ... assertions ) { Arrays . stream ( assertions ) . forEach ( a -> a . doAssert ( this ) ) ; return this ; } | Allows to do multiple comparisons on a document like |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.