idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
3,400
|
public static byte [ ] decode ( String in ) { in = in . replaceAll ( "\\r|\\n" , "" ) ; if ( in . length ( ) % 4 != 0 ) { throw new IllegalArgumentException ( "The length of the input string must be a multiple of four." ) ; } if ( ! in . matches ( "^[A-Za-z0-9+/]*[=]{0,3}$" ) ) { throw new IllegalArgumentException ( "The argument contains illegal characters." ) ; } byte [ ] out = new byte [ ( in . length ( ) * 3 ) / 4 ] ; char [ ] input = in . toCharArray ( ) ; int outi = 0 ; int b1 , b2 , b3 , b4 ; for ( int i = 0 ; i < input . length ; i += 4 ) { b1 = map . get ( input [ i ] ) - 1 ; b2 = map . get ( input [ i + 1 ] ) - 1 ; b3 = map . get ( input [ i + 2 ] ) - 1 ; b4 = map . get ( input [ i + 3 ] ) - 1 ; out [ outi ++ ] = ( byte ) ( b1 << 2 | b2 >>> 4 ) ; out [ outi ++ ] = ( byte ) ( ( b2 & 0x0F ) << 4 | b3 >>> 2 ) ; out [ outi ++ ] = ( byte ) ( ( b3 & 0x03 ) << 6 | ( b4 & 0x3F ) ) ; } if ( in . endsWith ( "=" ) ) { byte [ ] trimmed = new byte [ out . length - ( in . length ( ) - in . indexOf ( "=" ) ) ] ; System . arraycopy ( out , 0 , trimmed , 0 , trimmed . length ) ; return trimmed ; } return out ; }
|
Decode a base64 encoded string to a byte array .
|
3,401
|
public static String encode ( Byte [ ] in ) { byte [ ] tmp = new byte [ in . length ] ; for ( int i = 0 ; i < tmp . length ; i ++ ) { tmp [ i ] = in [ i ] ; } return encode ( tmp ) ; }
|
Encode a Byte array and return the encoded string .
|
3,402
|
public static String encode ( byte [ ] in ) { StringBuilder builder = new StringBuilder ( 4 * ( ( in . length + 2 ) / 3 ) ) ; byte [ ] encoded = encodeAsBytes ( in ) ; for ( int i = 0 ; i < encoded . length ; i ++ ) { builder . append ( code [ encoded [ i ] + 1 ] ) ; if ( i % 72 == 71 ) builder . append ( "\n" ) ; } return builder . toString ( ) ; }
|
Encode a byte array and return the encoded string .
|
3,403
|
public static byte [ ] encodeAsBytes ( byte [ ] inArray ) { byte [ ] out = new byte [ 4 * ( ( inArray . length + 2 ) / 3 ) ] ; byte [ ] in = new byte [ ( inArray . length + 2 ) / 3 * 3 ] ; System . arraycopy ( inArray , 0 , in , 0 , inArray . length ) ; int outi = 0 ; for ( int i = 0 ; i < in . length ; i += 3 ) { out [ outi ++ ] = ( byte ) ( ( in [ i ] & 0xFF ) >>> 2 ) ; out [ outi ++ ] = ( byte ) ( ( ( in [ i ] & 0x03 ) << 4 ) | ( ( in [ i + 1 ] & 0xFF ) >>> 4 ) ) ; out [ outi ++ ] = ( byte ) ( ( ( in [ i + 1 ] & 0x0F ) << 2 ) | ( ( in [ i + 2 ] & 0xFF ) >>> 6 ) ) ; out [ outi ++ ] = ( byte ) ( in [ i + 2 ] & 0x3F ) ; } for ( int i = in . length - inArray . length ; i > 0 ; i -- ) { out [ out . length - i ] = - 1 ; } return out ; }
|
Encode a byte array and return the encoded byte array . Bytes that has been appended to pad the string to a multiple of four are set to - 1 in the array .
|
3,404
|
public void setAuthentication ( HttpURLConnection http ) { if ( user == null || pass == null || user . length ( ) <= 0 || pass . length ( ) <= 0 ) { return ; } String base64login = Base64 . encode ( user + ":" + pass ) ; http . addRequestProperty ( "Authorization" , "Basic " + base64login ) ; }
|
Set the authentication at the HttpURLConnection .
|
3,405
|
private XmlElement getXMLParam ( Object o ) throws XMLRPCException { XmlElement param = new XmlElement ( XMLRPCClient . PARAM ) ; XmlElement value = new XmlElement ( XMLRPCClient . VALUE ) ; param . addChildren ( value ) ; value . addChildren ( serializerHandler . serialize ( o ) ) ; return param ; }
|
Generates the param xml tag for a specific parameter object .
|
3,406
|
public void setCustomHttpHeader ( String headerName , String headerValue ) { if ( CONTENT_TYPE . equals ( headerName ) || HOST . equals ( headerName ) || CONTENT_LENGTH . equals ( headerName ) ) { throw new XMLRPCRuntimeException ( "You cannot modify the Host, Content-Type or Content-Length header." ) ; } httpParameters . put ( headerName , headerValue ) ; }
|
Set a HTTP header field to a custom value . You cannot modify the Host or Content - Type field that way . If the field already exists the old value is overwritten .
|
3,407
|
public long callAsync ( XMLRPCCallback listener , String methodName , Object ... params ) { long id = System . currentTimeMillis ( ) ; new Caller ( listener , id , methodName , params ) . start ( ) ; return id ; }
|
Asynchronously call a remote procedure on the server . The method must be described by a method name . If the method requires parameters this must be set . When the server returns a response the onResponse method is called on the listener . If the server returns an error the onServerError method is called on the listener . The onError method is called whenever something fails . This method returns immediately and returns an identifier for the request . All listener methods get this id as a parameter to distinguish between multiple requests .
|
3,408
|
public void cancel ( long id ) { Caller cancel = backgroundCalls . get ( id ) ; if ( cancel == null ) { return ; } cancel . cancel ( ) ; try { cancel . join ( ) ; } catch ( InterruptedException ex ) { } }
|
Cancel a specific asynchronous call .
|
3,409
|
private Call createCall ( String method , Object [ ] params ) { if ( isFlagSet ( FLAGS_STRICT ) && ! method . matches ( "^[A-Za-z0-9\\._:/]*$" ) ) { throw new XMLRPCRuntimeException ( "Method name must only contain A-Z a-z . : _ / " ) ; } return new Call ( serializerHandler , method , params ) ; }
|
Create a call object from a given method string and parameters .
|
3,410
|
public static String getOnlyTextContent ( NodeList list ) throws XMLRPCException { StringBuilder builder = new StringBuilder ( ) ; Node n ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { n = list . item ( i ) ; if ( n . getNodeType ( ) == Node . COMMENT_NODE ) { continue ; } if ( n . getNodeType ( ) != Node . TEXT_NODE ) { throw new XMLRPCException ( "Element must contain only text elements." ) ; } builder . append ( n . getNodeValue ( ) ) ; } return builder . toString ( ) ; }
|
Returns the text node from a given NodeList . If the list contains more then just text nodes an exception will be thrown .
|
3,411
|
public static XmlElement makeXmlTag ( String type , String content ) { XmlElement xml = new XmlElement ( type ) ; xml . setContent ( content ) ; return xml ; }
|
Creates an xml tag with a given type and content .
|
3,412
|
public void readCookies ( HttpURLConnection http ) { if ( ( flags & XMLRPCClient . FLAGS_ENABLE_COOKIES ) == 0 ) return ; String cookie , key ; String [ ] split ; for ( int i = 0 ; i < http . getHeaderFields ( ) . size ( ) ; i ++ ) { key = http . getHeaderFieldKey ( i ) ; if ( key != null && SET_COOKIE . equalsIgnoreCase ( key . toLowerCase ( ) ) ) { cookie = http . getHeaderField ( i ) . split ( ";" ) [ 0 ] ; split = cookie . split ( "=" ) ; if ( split . length >= 2 ) cookies . put ( split [ 0 ] , split [ 1 ] ) ; } } }
|
Read the cookies from an http response . It will look at every Set - Cookie header and put the cookie to the map of cookies .
|
3,413
|
public void setCookies ( HttpURLConnection http ) { if ( ( flags & XMLRPCClient . FLAGS_ENABLE_COOKIES ) == 0 ) return ; String concat = "" ; for ( Map . Entry < String , String > cookie : cookies . entrySet ( ) ) { concat += cookie . getKey ( ) + "=" + cookie . getValue ( ) + "; " ; } http . setRequestProperty ( COOKIE , concat ) ; }
|
Write the cookies to a http connection . It will set the Cookie field to all currently set cookies in the map .
|
3,414
|
protected final void usePreparedStatement ( PreparedStatement pPreparedStatement ) throws SQLException { ResultSet lResultSet = null ; pPreparedStatement . setFetchSize ( 1000 ) ; setParameter ( pPreparedStatement ) ; try { lResultSet = pPreparedStatement . executeQuery ( ) ; useResultSet ( lResultSet ) ; } finally { if ( lResultSet != null ) { lResultSet . close ( ) ; } } }
|
Calls setParameter first than executeQuery on the CallableStatement is called and the resultest is passed to useResultSet .
|
3,415
|
protected void setParameter ( PreparedStatement pPreparedStatement ) throws SQLException { if ( _parameters != null ) { for ( int i = 0 ; i < _parameters . size ( ) ; i ++ ) { pPreparedStatement . setObject ( i + 1 , _parameters . get ( i ) ) ; } } }
|
Is called before the CallabelStatement is executed . It is usually used to set parameters . The CallableStatement may not be executed . The default implementaion does nothing .
|
3,416
|
public void export ( Graph pGraph , Schema pSchema , DotWriter pDotWriter , boolean pOutRefsOnly ) { pDotWriter . printHeaderStart ( pGraph . getStyleForGraph ( ) ) ; if ( pGraph . isCollapseSubgraphs ( ) ) { _writeSubgraphRecursiveCollapsed ( pGraph , pSchema , pDotWriter , pOutRefsOnly ) ; List < Graph > lEndGraphs = _getEndGraphListRecursive ( pGraph ) ; List < GraphAssociation > lGraphAssociations = new ArrayList < GraphAssociation > ( ) ; for ( Graph lGraphFrom : lEndGraphs ) { for ( Graph lGraphTo : lEndGraphs ) { GraphAssociation lGraphAssociation = new GraphAssociation ( ) ; lGraphAssociation . _graphFrom = lGraphFrom ; lGraphAssociation . _graphTo = lGraphTo ; for ( Table lTableFrom : pSchema . getTables ( ) ) { if ( lGraphFrom . containsTableRecursive ( lTableFrom ) ) { for ( Table lTableTo : pSchema . getTables ( ) ) { if ( lGraphTo . containsTableRecursive ( lTableTo ) ) { for ( Association lAssociation : pSchema . getAssociations ( ) ) { if ( lAssociation . getTableFrom ( ) == lTableFrom && lAssociation . getTableTo ( ) == lTableTo ) { lGraphAssociation . _countTableFks += 1 ; } } } } } } if ( lGraphAssociation . _countTableFks > 0 ) { lGraphAssociations . add ( lGraphAssociation ) ; } } } for ( GraphAssociation lGraphAssociation : _filterGraphAssociations ( lGraphAssociations ) ) { _printGraphAssociation ( lGraphAssociation , pDotWriter ) ; } } else { List < Association > lExtraAssociations = new ArrayList < Association > ( ) ; boolean lOtherTablesFound = false ; for ( Table lTable : pSchema . getTables ( ) ) { if ( ! pGraph . containsTableRecursive ( lTable ) ) { List < Association > lVisibleAssociation = pGraph . getVisibleAssociation ( lTable , pSchema , pOutRefsOnly ) ; if ( ! lVisibleAssociation . isEmpty ( ) ) { lExtraAssociations . addAll ( lVisibleAssociation ) ; lOtherTablesFound = true ; _printTable ( lTable , pDotWriter , lVisibleAssociation , pOutRefsOnly , pGraph . getStyleForTable ( lTable ) ) ; } } } _writeSubgraphRecursive ( pGraph , pSchema , pDotWriter , pOutRefsOnly , new ArrayList < Table > ( ) , lOtherTablesFound , pGraph . isRenderClusterForSubgraphs ( ) ) ; for ( Association lAssociation : pSchema . getAssociations ( ) ) { if ( lExtraAssociations . contains ( lAssociation ) || ( pGraph . allAssociations ( ) && ( pGraph . containsTableRecursive ( lAssociation . getTableFrom ( ) ) || ( ! pOutRefsOnly && pGraph . containsTableRecursive ( lAssociation . getTableTo ( ) ) ) ) ) ) { _printAssociation ( lAssociation , pDotWriter , pGraph ) ; } } } pDotWriter . printHeaderEnd ( ) ; }
|
Creates a dot File for the Schema .
|
3,417
|
protected final void useResultSet ( ResultSet pResultSet ) throws SQLException { boolean lFirst = true ; if ( ! pResultSet . next ( ) ) { handleEmptyResultSet ( ) ; } else { while ( lFirst || pResultSet . next ( ) ) { lFirst = false ; useResultSetRow ( pResultSet ) ; } } }
|
iterates through the resultset and calls the callback methods .
|
3,418
|
protected final Object getValueFromResultSet ( ResultSet pResultSet ) throws SQLException { if ( ! pResultSet . next ( ) ) { if ( _returnNullInsteadOfNoDataFoundException ) { return null ; } throw new NoDataFoundException ( ) ; } return pResultSet . getObject ( getObjectIndex ( ) ) ; }
|
Extracts the first value .
|
3,419
|
public String getExecutable ( VirtualChannel channel ) throws IOException , InterruptedException { return channel . call ( new MasterToSlaveCallable < String , IOException > ( ) { public String call ( ) throws IOException { File exe = getExeFile ( "groovy" ) ; if ( exe . exists ( ) ) { return exe . getPath ( ) ; } return null ; } private static final long serialVersionUID = 1L ; } ) ; }
|
Gets the executable path of this groovy installation on the given target system .
|
3,420
|
private String [ ] parseParams ( String line ) { CommandLine cmdLine = CommandLine . parse ( "executable_placeholder " + line ) ; String [ ] parsedArgs = cmdLine . getArguments ( ) ; String [ ] args = new String [ parsedArgs . length ] ; if ( parsedArgs . length > 0 ) { System . arraycopy ( parsedArgs , 0 , args , 0 , parsedArgs . length ) ; } return args ; }
|
Parse parameters to be passed as arguments to the groovy binary
|
3,421
|
public long getTotalSavings ( ) { long totalSavings = 0 ; for ( OptimizerResult result : results ) { totalSavings += ( result . getOriginalFileSize ( ) - result . getOptimizedFileSize ( ) ) ; } return totalSavings ; }
|
Get the number of bytes saved in all images processed so far
|
3,422
|
public void generateDataUriCss ( String dir ) throws IOException { final String path = ( dir == null ) ? "" : dir + "/" ; final PrintWriter out = new PrintWriter ( path + "DataUriCss.html" ) ; try { out . append ( "<html>\n<head>\n\t<style>" ) ; for ( OptimizerResult result : results ) { final String name = result . fileName . replaceAll ( "[^A-Za-z0-9]" , "_" ) ; out . append ( '#' ) . append ( name ) . append ( " {\n" ) . append ( "\tbackground: url(\"data:image/png;base64," ) . append ( result . dataUri ) . append ( "\") no-repeat left top;\n" ) . append ( "\twidth: " ) . append ( String . valueOf ( result . width ) ) . append ( "px;\n" ) . append ( "\theight: " ) . append ( String . valueOf ( result . height ) ) . append ( "px;\n" ) . append ( "}\n" ) ; } out . append ( "\t</style>\n</head>\n<body>\n" ) ; for ( OptimizerResult result : results ) { final String name = result . fileName . replaceAll ( "[^A-Za-z0-9]" , "_" ) ; out . append ( "\t<div id=\"" ) . append ( name ) . append ( "\"></div>\n" ) ; } out . append ( "</body>\n</html>" ) ; } finally { if ( out != null ) { out . close ( ) ; } } }
|
Get the css containing data uris of the images processed by the optimizer
|
3,423
|
public static void decodeToFile ( String dataToDecode , String filename ) throws IOException { Base64 . OutputStream bos = null ; try { bos = new Base64 . OutputStream ( new FileOutputStream ( filename ) , Base64 . DECODE ) ; bos . write ( dataToDecode . getBytes ( PREFERRED_ENCODING ) ) ; } catch ( IOException e ) { throw e ; } finally { try { if ( bos != null ) { bos . close ( ) ; } } catch ( Exception e ) { } } }
|
Convenience method for decoding data to a file .
|
3,424
|
void getFreqs ( LzStore store ) { int [ ] sLitLens = this . litLens ; int [ ] sDists = this . dists ; System . arraycopy ( Cookie . intZeroes , 0 , sLitLens , 0 , 288 ) ; System . arraycopy ( Cookie . intZeroes , 0 , sDists , 0 , 32 ) ; int size = store . size ; char [ ] litLens = store . litLens ; char [ ] dists = store . dists ; int [ ] lengthSymbol = Util . LENGTH_SYMBOL ; int [ ] cachedDistSymbol = Util . CACHED_DIST_SYMBOL ; for ( int i = 0 ; i < size ; i ++ ) { int d = dists [ i ] ; int l = litLens [ i ] ; if ( d == 0 ) { sLitLens [ l ] ++ ; } else { sLitLens [ lengthSymbol [ l ] ] ++ ; sDists [ cachedDistSymbol [ d ] ] ++ ; } } sLitLens [ 256 ] = 1 ; calculate ( ) ; }
|
Why 32? Expect 30 .
|
3,425
|
private static long adler32 ( byte [ ] data ) { final Adler32 checksum = new Adler32 ( ) ; checksum . update ( data ) ; return checksum . getValue ( ) ; }
|
Calculates the adler32 checksum of the data
|
3,426
|
public void info ( String message , Object ... args ) { if ( DEBUG . equals ( this . logLevel ) || INFO . equals ( this . logLevel ) ) { System . out . println ( String . format ( message , args ) ) ; } }
|
Write info messages . Takes a varags list of args so that string concatenation only happens if the logging level applies .
|
3,427
|
public void error ( String message , Object ... args ) { if ( ! NONE . equals ( this . logLevel ) ) { System . out . println ( String . format ( message , args ) ) ; } }
|
Write error messages . Takes a varags list of args so that string concatenation only happens if the logging level applies .
|
3,428
|
public ProcBuilder withWorkingDirectory ( File directory ) { if ( ! directory . isDirectory ( ) ) { throw new IllegalArgumentException ( "File '" + directory . getPath ( ) + "' is not a directory." ) ; } this . directory = directory ; return this ; }
|
Override the wokring directory
|
3,429
|
public ProcResult run ( ) throws StartupException , TimeoutException , ExternalProcessFailureException { if ( stdout != defaultStdout && outputConsumer != null ) { throw new IllegalArgumentException ( "You can either ..." ) ; } try { Proc proc = new Proc ( command , args , env , stdin , outputConsumer != null ? outputConsumer : stdout , directory , timoutMillis , expectedExitStatuses , stderr ) ; return new ProcResult ( proc . toString ( ) , defaultStdout == stdout && outputConsumer == null ? defaultStdout : null , proc . getExitValue ( ) , proc . getExecutionTime ( ) , proc . getErrorBytes ( ) ) ; } finally { stdout = defaultStdout = new ByteArrayOutputStream ( ) ; stdin = null ; } }
|
Spawn the actual execution . This will block until the process terminates .
|
3,430
|
public static String run ( String cmd , String ... args ) { ProcBuilder builder = new ProcBuilder ( cmd ) . withArgs ( args ) ; return builder . run ( ) . getOutputString ( ) ; }
|
Static helper to run a process
|
3,431
|
public static String filter ( String input , String cmd , String ... args ) { ProcBuilder builder = new ProcBuilder ( cmd ) . withArgs ( args ) . withInput ( input ) ; return builder . run ( ) . getOutputString ( ) ; }
|
Static helper to filter a string through a process
|
3,432
|
public void writeSasFileProperties ( SasFileProperties sasFileProperties ) throws IOException { constructPropertiesString ( "Bitness: " , sasFileProperties . isU64 ( ) ? "x64" : "x86" ) ; constructPropertiesString ( "Compressed: " , sasFileProperties . getCompressionMethod ( ) ) ; constructPropertiesString ( "Endianness: " , sasFileProperties . getEndianness ( ) == 1 ? "LITTLE_ENDIANNESS" : "BIG_ENDIANNESS" ) ; constructPropertiesString ( "Encoding: " , sasFileProperties . getEncoding ( ) ) ; constructPropertiesString ( "Name: " , sasFileProperties . getName ( ) ) ; constructPropertiesString ( "File type: " , sasFileProperties . getFileType ( ) ) ; constructPropertiesString ( "File label: " , sasFileProperties . getFileLabel ( ) ) ; constructPropertiesString ( "Date created: " , sasFileProperties . getDateCreated ( ) ) ; constructPropertiesString ( "Date modified: " , sasFileProperties . getDateModified ( ) ) ; constructPropertiesString ( "SAS release: " , sasFileProperties . getSasRelease ( ) ) ; constructPropertiesString ( "SAS server type: " , sasFileProperties . getServerType ( ) ) ; constructPropertiesString ( "OS name: " , sasFileProperties . getOsName ( ) ) ; constructPropertiesString ( "OS type: " , sasFileProperties . getOsType ( ) ) ; constructPropertiesString ( "Header Length: " , sasFileProperties . getHeaderLength ( ) ) ; constructPropertiesString ( "Page Length: " , sasFileProperties . getPageLength ( ) ) ; constructPropertiesString ( "Page Count: " , sasFileProperties . getPageCount ( ) ) ; constructPropertiesString ( "Row Length: " , sasFileProperties . getRowLength ( ) ) ; constructPropertiesString ( "Row Count: " , sasFileProperties . getRowCount ( ) ) ; constructPropertiesString ( "Mix Page Row Count: " , sasFileProperties . getMixPageRowCount ( ) ) ; constructPropertiesString ( "Columns Count: " , sasFileProperties . getColumnsCount ( ) ) ; getWriter ( ) . flush ( ) ; }
|
The method to output the sas7bdat file properties .
|
3,433
|
private void constructPropertiesString ( String propertyName , Object property ) throws IOException { getWriter ( ) . write ( propertyName + String . valueOf ( property ) + "\n" ) ; }
|
The method to output string containing information about passed property using writer .
|
3,434
|
private static String processEntry ( Column column , Object entry , Locale locale , Map < Integer , Format > columnFormatters ) throws IOException { if ( ! String . valueOf ( entry ) . contains ( DOUBLE_INFINITY_STRING ) ) { String valueToPrint ; if ( entry . getClass ( ) == Date . class ) { valueToPrint = convertDateElementToString ( ( Date ) entry , ( SimpleDateFormat ) columnFormatters . computeIfAbsent ( column . getId ( ) , e -> getDateFormatProcessor ( column . getFormat ( ) , locale ) ) ) ; } else { if ( TIME_FORMAT_STRINGS . contains ( column . getFormat ( ) . getName ( ) ) ) { valueToPrint = convertTimeElementToString ( ( Long ) entry ) ; } else if ( PERCENT_FORMAT . equals ( column . getFormat ( ) . getName ( ) ) ) { valueToPrint = convertPercentElementToString ( entry , ( DecimalFormat ) columnFormatters . computeIfAbsent ( column . getId ( ) , e -> getPercentFormatProcessor ( column . getFormat ( ) , locale ) ) ) ; } else { valueToPrint = String . valueOf ( entry ) ; if ( entry . getClass ( ) == Double . class ) { valueToPrint = convertDoubleElementToString ( ( Double ) entry ) ; } } } return valueToPrint ; } return "" ; }
|
Checks current entry type and returns its string representation .
|
3,435
|
private static String convertDateElementToString ( Date currentDate , SimpleDateFormat dateFormat ) { return currentDate . getTime ( ) != 0 ? dateFormat . format ( currentDate . getTime ( ) ) : "" ; }
|
The function to convert a date into a string according to the format used .
|
3,436
|
private static String convertPercentElementToString ( Object value , DecimalFormat decimalFormat ) { Double doubleValue = value instanceof Long ? ( ( Long ) value ) . doubleValue ( ) : ( Double ) value ; return decimalFormat . format ( doubleValue ) ; }
|
The function to convert a percent element into a string .
|
3,437
|
private static String trimZerosFromEnd ( String string ) { return string . contains ( "." ) ? string . replaceAll ( "0*$" , "" ) . replaceAll ( "\\.$" , "" ) : string ; }
|
The function to remove trailing zeros from the decimal part of the numerals represented by a string . If there are no digits after the point the point is deleted as well .
|
3,438
|
public static String getValue ( Column column , Object entry , Locale locale , Map < Integer , Format > columnFormatters ) throws IOException { String value = "" ; if ( entry != null ) { if ( entry . getClass ( ) . getName ( ) . compareTo ( BYTE_ARRAY_CLASS_NAME ) == 0 ) { value = new String ( ( byte [ ] ) entry , ENCODING ) ; } else { value = processEntry ( column , entry , locale , columnFormatters ) ; } } return value ; }
|
The method to convert the Object that stores data from the sas7bdat file cell to string .
|
3,439
|
private static Format getPercentFormatProcessor ( ColumnFormat columnFormat , Locale locale ) { DecimalFormatSymbols dfs = new DecimalFormatSymbols ( locale ) ; if ( columnFormat . getPrecision ( ) == 0 ) { return new DecimalFormat ( "0%" , dfs ) ; } String pattern = "0%." + new String ( new char [ columnFormat . getPrecision ( ) ] ) . replace ( "\0" , "0" ) ; return new DecimalFormat ( pattern , dfs ) ; }
|
The function to get a formatter to convert percentage elements into a string .
|
3,440
|
private static Format getDateFormatProcessor ( ColumnFormat columnFormat , Locale locale ) { if ( ! DATE_OUTPUT_FORMAT_STRINGS . containsKey ( columnFormat . getName ( ) ) ) { throw new NoSuchElementException ( UNKNOWN_DATE_FORMAT_EXCEPTION ) ; } SimpleDateFormat dateFormat = new SimpleDateFormat ( DATE_OUTPUT_FORMAT_STRINGS . get ( columnFormat . getName ( ) ) , locale ) ; dateFormat . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; return dateFormat ; }
|
The function to get a formatter to convert date elements into a string .
|
3,441
|
static void checkSurroundByQuotesAndWrite ( Writer writer , String delimiter , String trimmedText ) throws IOException { writer . write ( checkSurroundByQuotes ( delimiter , trimmedText ) ) ; }
|
The method to write a text represented by an array of bytes using writer . If the text contains the delimiter line breaks tabulation characters and double quotes the text is stropped .
|
3,442
|
static String checkSurroundByQuotes ( String delimiter , String trimmedText ) throws IOException { boolean containsDelimiter = stringContainsItemFromList ( trimmedText , delimiter , "\n" , "\t" , "\r" , "\"" ) ; String trimmedTextWithoutQuotesDuplicates = trimmedText . replace ( "\"" , "\"\"" ) ; if ( containsDelimiter && trimmedTextWithoutQuotesDuplicates . length ( ) != 0 ) { return "\"" + trimmedTextWithoutQuotesDuplicates + "\"" ; } return trimmedTextWithoutQuotesDuplicates ; }
|
The method to output a text represented by an array of bytes . If the text contains the delimiter line breaks tabulation characters and double quotes the text is stropped .
|
3,443
|
Object [ ] readNext ( List < String > columnNames ) throws IOException { if ( currentRowInFileIndex ++ >= sasFileProperties . getRowCount ( ) || eof ) { return null ; } int bitOffset = sasFileProperties . isU64 ( ) ? PAGE_BIT_OFFSET_X64 : PAGE_BIT_OFFSET_X86 ; switch ( currentPageType ) { case PAGE_META_TYPE_1 : case PAGE_META_TYPE_2 : SubheaderPointer currentSubheaderPointer = currentPageDataSubheaderPointers . get ( currentRowOnPageIndex ++ ) ; ( ( ProcessingDataSubheader ) subheaderIndexToClass . get ( SubheaderIndexes . DATA_SUBHEADER_INDEX ) ) . processSubheader ( currentSubheaderPointer . offset , currentSubheaderPointer . length , columnNames ) ; if ( currentRowOnPageIndex == currentPageDataSubheaderPointers . size ( ) ) { readNextPage ( ) ; currentRowOnPageIndex = 0 ; } break ; case PAGE_MIX_TYPE : int subheaderPointerLength = sasFileProperties . isU64 ( ) ? SUBHEADER_POINTER_LENGTH_X64 : SUBHEADER_POINTER_LENGTH_X86 ; int alignCorrection = ( bitOffset + SUBHEADER_POINTERS_OFFSET + currentPageSubheadersCount * subheaderPointerLength ) % BITS_IN_BYTE ; currentRow = processByteArrayWithData ( bitOffset + SUBHEADER_POINTERS_OFFSET + alignCorrection + currentPageSubheadersCount * subheaderPointerLength + currentRowOnPageIndex ++ * sasFileProperties . getRowLength ( ) , sasFileProperties . getRowLength ( ) , columnNames ) ; if ( currentRowOnPageIndex == Math . min ( sasFileProperties . getRowCount ( ) , sasFileProperties . getMixPageRowCount ( ) ) ) { readNextPage ( ) ; currentRowOnPageIndex = 0 ; } break ; case PAGE_DATA_TYPE : currentRow = processByteArrayWithData ( bitOffset + SUBHEADER_POINTERS_OFFSET + currentRowOnPageIndex ++ * sasFileProperties . getRowLength ( ) , sasFileProperties . getRowLength ( ) , columnNames ) ; if ( currentRowOnPageIndex == currentPageBlockCount ) { readNextPage ( ) ; currentRowOnPageIndex = 0 ; } break ; default : break ; } return Arrays . copyOf ( currentRow , currentRow . length ) ; }
|
The function to read next row from current sas7bdat file .
|
3,444
|
private void processNextPage ( ) throws IOException { int bitOffset = sasFileProperties . isU64 ( ) ? PAGE_BIT_OFFSET_X64 : PAGE_BIT_OFFSET_X86 ; currentPageDataSubheaderPointers . clear ( ) ; try { sasFileStream . readFully ( cachedPage , 0 , sasFileProperties . getPageLength ( ) ) ; } catch ( EOFException ex ) { eof = true ; return ; } readPageHeader ( ) ; if ( currentPageType == PAGE_META_TYPE_1 || currentPageType == PAGE_META_TYPE_2 || currentPageType == PAGE_AMD_TYPE ) { List < SubheaderPointer > subheaderPointers = new ArrayList < SubheaderPointer > ( ) ; processPageMetadata ( bitOffset , subheaderPointers ) ; if ( currentPageType == PAGE_AMD_TYPE ) { processMissingColumnInfo ( ) ; } } }
|
Put next page to cache and read it s header .
|
3,445
|
private void processMissingColumnInfo ( ) throws UnsupportedEncodingException { for ( ColumnMissingInfo columnMissingInfo : columnMissingInfoList ) { String missedInfo = bytesToString ( columnsNamesBytes . get ( columnMissingInfo . getTextSubheaderIndex ( ) ) , columnMissingInfo . getOffset ( ) , columnMissingInfo . getLength ( ) ) . intern ( ) ; Column column = columns . get ( columnMissingInfo . getColumnId ( ) ) ; switch ( columnMissingInfo . getMissingInfoType ( ) ) { case NAME : column . setName ( missedInfo ) ; break ; case FORMAT : column . setFormat ( new ColumnFormat ( missedInfo ) ) ; break ; case LABEL : column . setLabel ( missedInfo ) ; break ; default : break ; } } }
|
The function to process missing column information .
|
3,446
|
private Object [ ] processByteArrayWithData ( long rowOffset , long rowLength , List < String > columnNames ) { Object [ ] rowElements ; if ( columnNames != null ) { rowElements = new Object [ columnNames . size ( ) ] ; } else { rowElements = new Object [ ( int ) sasFileProperties . getColumnsCount ( ) ] ; } byte [ ] source ; int offset ; if ( sasFileProperties . isCompressed ( ) && rowLength < sasFileProperties . getRowLength ( ) ) { Decompressor decompressor = LITERALS_TO_DECOMPRESSOR . get ( sasFileProperties . getCompressionMethod ( ) ) ; source = decompressor . decompressRow ( ( int ) rowOffset , ( int ) rowLength , ( int ) sasFileProperties . getRowLength ( ) , cachedPage ) ; offset = 0 ; } else { source = cachedPage ; offset = ( int ) rowOffset ; } for ( int currentColumnIndex = 0 ; currentColumnIndex < sasFileProperties . getColumnsCount ( ) && columnsDataLength . get ( currentColumnIndex ) != 0 ; currentColumnIndex ++ ) { if ( columnNames == null ) { rowElements [ currentColumnIndex ] = processElement ( source , offset , currentColumnIndex ) ; } else { String name = columns . get ( currentColumnIndex ) . getName ( ) ; if ( columnNames . contains ( name ) ) { rowElements [ columnNames . indexOf ( name ) ] = processElement ( source , offset , currentColumnIndex ) ; } } } return rowElements ; }
|
The function to convert the array of bytes that stores the data of a row into an array of objects . Each object corresponds to a table cell .
|
3,447
|
private Object processElement ( byte [ ] source , int offset , int currentColumnIndex ) { byte [ ] temp ; int length = columnsDataLength . get ( currentColumnIndex ) ; if ( columns . get ( currentColumnIndex ) . getType ( ) == Number . class ) { temp = Arrays . copyOfRange ( source , offset + ( int ) ( long ) columnsDataOffset . get ( currentColumnIndex ) , offset + ( int ) ( long ) columnsDataOffset . get ( currentColumnIndex ) + length ) ; if ( columnsDataLength . get ( currentColumnIndex ) <= 2 ) { return bytesToShort ( temp ) ; } else { if ( columns . get ( currentColumnIndex ) . getFormat ( ) . getName ( ) . isEmpty ( ) ) { return convertByteArrayToNumber ( temp ) ; } else { if ( DATE_TIME_FORMAT_STRINGS . contains ( columns . get ( currentColumnIndex ) . getFormat ( ) . getName ( ) ) ) { return bytesToDateTime ( temp ) ; } else { if ( DATE_FORMAT_STRINGS . contains ( columns . get ( currentColumnIndex ) . getFormat ( ) . getName ( ) ) ) { return bytesToDate ( temp ) ; } else { return convertByteArrayToNumber ( temp ) ; } } } } } else { byte [ ] bytes = trimBytesArray ( source , offset + columnsDataOffset . get ( currentColumnIndex ) . intValue ( ) , length ) ; if ( byteOutput ) { return bytes ; } else { try { return ( bytes == null ? null : bytesToString ( bytes ) ) ; } catch ( UnsupportedEncodingException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } } return null ; }
|
The function to process element of row .
|
3,448
|
private List < byte [ ] > getBytesFromFile ( Long [ ] offset , Integer [ ] length ) throws IOException { List < byte [ ] > vars = new ArrayList < byte [ ] > ( ) ; if ( cachedPage == null ) { for ( int i = 0 ; i < offset . length ; i ++ ) { byte [ ] temp = new byte [ length [ i ] ] ; long actuallySkipped = 0 ; while ( actuallySkipped < offset [ i ] - currentFilePosition ) { try { actuallySkipped += sasFileStream . skip ( offset [ i ] - currentFilePosition - actuallySkipped ) ; } catch ( IOException e ) { throw new IOException ( EMPTY_INPUT_STREAM ) ; } } try { sasFileStream . readFully ( temp , 0 , length [ i ] ) ; } catch ( EOFException e ) { eof = true ; } currentFilePosition = ( int ) ( long ) offset [ i ] + length [ i ] ; vars . add ( temp ) ; } } else { for ( int i = 0 ; i < offset . length ; i ++ ) { if ( cachedPage . length < offset [ i ] ) { throw new IOException ( EMPTY_INPUT_STREAM ) ; } vars . add ( Arrays . copyOfRange ( cachedPage , ( int ) ( long ) offset [ i ] , ( int ) ( long ) offset [ i ] + length [ i ] ) ) ; } } return vars ; }
|
The function to read the list of bytes arrays from the sas7bdat file . The array of offsets and the array of lengths serve as input data that define the location and number of bytes the function must read .
|
3,449
|
private String bytesToString ( byte [ ] bytes , int offset , int length ) throws UnsupportedEncodingException , StringIndexOutOfBoundsException { return new String ( bytes , offset , length , encoding ) ; }
|
The function to convert a sub - range of an array of bytes into a string .
|
3,450
|
private double bytesToDouble ( byte [ ] bytes ) { ByteBuffer original = byteArrayToByteBuffer ( bytes ) ; if ( bytes . length < BYTES_IN_DOUBLE ) { ByteBuffer byteBuffer = ByteBuffer . allocate ( BYTES_IN_DOUBLE ) ; if ( sasFileProperties . getEndianness ( ) == 1 ) { byteBuffer . position ( BYTES_IN_DOUBLE - bytes . length ) ; } byteBuffer . put ( original ) ; byteBuffer . order ( original . order ( ) ) ; byteBuffer . position ( 0 ) ; original = byteBuffer ; } return original . getDouble ( ) ; }
|
The function to convert an array of bytes into a double number .
|
3,451
|
private byte [ ] trimBytesArray ( byte [ ] source , int offset , int length ) { int lengthFromBegin ; for ( lengthFromBegin = offset + length ; lengthFromBegin > offset ; lengthFromBegin -- ) { if ( source [ lengthFromBegin - 1 ] != ' ' && source [ lengthFromBegin - 1 ] != '\0' && source [ lengthFromBegin - 1 ] != '\t' ) { break ; } } if ( lengthFromBegin - offset != 0 ) { return Arrays . copyOfRange ( source , offset , lengthFromBegin ) ; } else { return null ; } }
|
The function to remove excess symbols from the end of a bytes array . Excess symbols are line end characters tabulation characters and spaces which do not contain useful information .
|
3,452
|
private Object checkRegisteredServicesByLdapFilter ( String filter ) throws InvalidSyntaxException { ServiceReference < ? > [ ] references = getBundleContext ( ) . getServiceReferences ( ( String ) null , filter ) ; if ( isEmptyOrNull ( references ) ) { return null ; } if ( references . length == 1 ) { return getBundleContext ( ) . getService ( references [ 0 ] ) ; } throw new RuntimeException ( "Too many services registered for filter: " + filter ) ; }
|
Checks the OSGi ServiceRegistry if a service matching the given filter is present .
|
3,453
|
private String getPath ( URL url ) { String path = url . toExternalForm ( ) ; return path . replaceAll ( "bundle://[^/]*/" , "" ) ; }
|
remove bundle protocol specific part so that resource can be accessed by path relative to bundle root
|
3,454
|
public static List < PathElement > parseHeader ( String header ) { List < PathElement > elements = new ArrayList < PathElement > ( ) ; if ( header == null || header . trim ( ) . length ( ) == 0 ) { return elements ; } String [ ] clauses = header . split ( "," ) ; for ( String clause : clauses ) { String [ ] tokens = clause . split ( ";" ) ; if ( tokens . length < 1 ) { throw new IllegalArgumentException ( "Invalid header clause: " + clause ) ; } PathElement elem = new PathElement ( tokens [ 0 ] . trim ( ) ) ; elements . add ( elem ) ; for ( int i = 1 ; i < tokens . length ; i ++ ) { int pos = tokens [ i ] . indexOf ( '=' ) ; if ( pos != - 1 ) { if ( pos > 0 && tokens [ i ] . charAt ( pos - 1 ) == ':' ) { String name = tokens [ i ] . substring ( 0 , pos - 1 ) . trim ( ) ; String value = tokens [ i ] . substring ( pos + 1 ) . trim ( ) ; elem . addDirective ( name , value ) ; } else { String name = tokens [ i ] . substring ( 0 , pos ) . trim ( ) ; String value = tokens [ i ] . substring ( pos + 1 ) . trim ( ) ; elem . addAttribute ( name , value ) ; } } else { elem = new PathElement ( tokens [ i ] . trim ( ) ) ; elements . add ( elem ) ; } } } return elements ; }
|
Parse a given OSGi header into a list of paths
|
3,455
|
private static void addEntries ( Bundle bundle , String path , String filePattern , List < URL > pathList ) { Enumeration < ? > e = bundle . findEntries ( path , filePattern , false ) ; while ( e != null && e . hasMoreElements ( ) ) { URL u = ( URL ) e . nextElement ( ) ; pathList . add ( u ) ; } }
|
Searches the bundle for files matching the path and filepattern and puts them into the list .
|
3,456
|
public URLConnection openConnection ( URL url ) throws IOException { if ( url . getPath ( ) == null || url . getPath ( ) . trim ( ) . length ( ) == 0 ) { throw new MalformedURLException ( "Path can not be null or empty. Syntax: " + SYNTAX ) ; } bpmnXmlURL = new URL ( url . getPath ( ) ) ; logger . log ( Level . FINE , "BPMN xml URL is: [" + bpmnXmlURL + "]" ) ; return new Connection ( url ) ; }
|
Open the connection for the given URL .
|
3,457
|
@ SuppressWarnings ( "unchecked" ) private boolean hasPropertiesConfiguration ( Dictionary properties ) { HashMap < Object , Object > mapProperties = new HashMap < Object , Object > ( properties . size ( ) ) ; for ( Object key : Collections . list ( properties . keys ( ) ) ) { mapProperties . put ( key , properties . get ( key ) ) ; } mapProperties . remove ( Constants . SERVICE_PID ) ; mapProperties . remove ( "service.factoryPid" ) ; return ! mapProperties . isEmpty ( ) ; }
|
It happends that the factory get called with properties that only contain service . pid and service . factoryPid . If that happens we don t want to create an engine .
|
3,458
|
public static String baseUrl ( ) { String baseURL = System . getProperty ( BASE_URL_PROPERTY , "/_ah/pipeline/" ) ; if ( ! baseURL . endsWith ( "/" ) ) { baseURL += "/" ; } return baseURL ; }
|
Returns the Pipeline s BASE URL . This must match the URL in web . xml
|
3,459
|
private static String toJson ( Object x ) { try { if ( x == null || x instanceof String || x instanceof Number || x instanceof Character || x . getClass ( ) . isArray ( ) || x instanceof Iterable < ? > ) { return new JSONObject ( ) . put ( "JSON" , x ) . toString ( 2 ) ; } else if ( x instanceof Map < ? , ? > ) { return ( new JSONObject ( ( Map < ? , ? > ) x ) ) . toString ( 2 ) ; } else if ( x instanceof JSONObject ) { return ( ( JSONObject ) x ) . toString ( 2 ) ; } else { return ( new JSONObject ( x ) ) . toString ( 2 ) ; } } catch ( Exception e ) { throw new RuntimeException ( "x=" + x , e ) ; } }
|
Convert an object into its JSON representation .
|
3,460
|
public static Object fromJson ( String json ) { try { JSONObject jsonObject = new JSONObject ( json ) ; if ( jsonObject . has ( "JSON" ) ) { return convert ( jsonObject . get ( "JSON" ) ) ; } else { return convert ( jsonObject ) ; } } catch ( Exception e ) { throw new RuntimeException ( "json=" + json , e ) ; } }
|
Convert a JSON representation into an object
|
3,461
|
public void deletePipeline ( Key rootJobKey , boolean force , boolean async ) throws IllegalStateException { if ( ! force ) { try { JobRecord rootJobRecord = queryJob ( rootJobKey , JobRecord . InflationType . NONE ) ; switch ( rootJobRecord . getState ( ) ) { case FINALIZED : case STOPPED : break ; default : throw new IllegalStateException ( "Pipeline is still running: " + rootJobRecord ) ; } } catch ( NoSuchObjectException ex ) { } } if ( async ) { DeletePipelineTask task = new DeletePipelineTask ( rootJobKey , force , new QueueSettings ( ) ) ; taskQueue . enqueue ( task ) ; return ; } deleteAll ( JobRecord . DATA_STORE_KIND , rootJobKey ) ; deleteAll ( Slot . DATA_STORE_KIND , rootJobKey ) ; deleteAll ( ShardedValue . DATA_STORE_KIND , rootJobKey ) ; deleteAll ( Barrier . DATA_STORE_KIND , rootJobKey ) ; deleteAll ( JobInstanceRecord . DATA_STORE_KIND , rootJobKey ) ; deleteAll ( FanoutTaskRecord . DATA_STORE_KIND , rootJobKey ) ; }
|
Delete all datastore entities corresponding to the given pipeline .
|
3,462
|
public static PipelineObjects queryFullPipeline ( String rootJobHandle ) { Key rootJobKey = KeyFactory . createKey ( JobRecord . DATA_STORE_KIND , rootJobHandle ) ; return backEnd . queryFullPipeline ( rootJobKey ) ; }
|
Returns all the associated PipelineModelObject for a root pipeline .
|
3,463
|
public static JobRecord getJob ( String jobHandle ) throws NoSuchObjectException { checkNonEmpty ( jobHandle , "jobHandle" ) ; Key key = KeyFactory . createKey ( JobRecord . DATA_STORE_KIND , jobHandle ) ; logger . finest ( "getJob: " + key . getName ( ) ) ; return backEnd . queryJob ( key , JobRecord . InflationType . FOR_OUTPUT ) ; }
|
Retrieves a JobRecord for the specified job handle . The returned instance will be only partially inflated . The run and finalize barriers will not be available but the output slot will be .
|
3,464
|
public static void stopJob ( String jobHandle ) throws NoSuchObjectException { checkNonEmpty ( jobHandle , "jobHandle" ) ; Key key = KeyFactory . createKey ( JobRecord . DATA_STORE_KIND , jobHandle ) ; JobRecord jobRecord = backEnd . queryJob ( key , JobRecord . InflationType . NONE ) ; jobRecord . setState ( State . STOPPED ) ; UpdateSpec updateSpec = new UpdateSpec ( jobRecord . getRootJobKey ( ) ) ; updateSpec . getOrCreateTransaction ( "stopJob" ) . includeJob ( jobRecord ) ; backEnd . save ( updateSpec , jobRecord . getQueueSettings ( ) ) ; }
|
Changes the state of the specified job to STOPPED .
|
3,465
|
public static void cancelJob ( String jobHandle ) throws NoSuchObjectException { checkNonEmpty ( jobHandle , "jobHandle" ) ; Key key = KeyFactory . createKey ( JobRecord . DATA_STORE_KIND , jobHandle ) ; JobRecord jobRecord = backEnd . queryJob ( key , InflationType . NONE ) ; CancelJobTask cancelJobTask = new CancelJobTask ( key , jobRecord . getQueueSettings ( ) ) ; try { backEnd . enqueue ( cancelJobTask ) ; } catch ( TaskAlreadyExistsException e ) { } }
|
Sends cancellation request to the root job .
|
3,466
|
public static void deletePipelineRecords ( String pipelineHandle , boolean force , boolean async ) throws NoSuchObjectException , IllegalStateException { checkNonEmpty ( pipelineHandle , "pipelineHandle" ) ; Key key = KeyFactory . createKey ( JobRecord . DATA_STORE_KIND , pipelineHandle ) ; backEnd . deletePipeline ( key , force , async ) ; }
|
Delete all data store entities corresponding to the given pipeline .
|
3,467
|
public static void processTask ( Task task ) { logger . finest ( "Processing task " + task ) ; try { switch ( task . getType ( ) ) { case RUN_JOB : runJob ( ( RunJobTask ) task ) ; break ; case HANDLE_SLOT_FILLED : handleSlotFilled ( ( HandleSlotFilledTask ) task ) ; break ; case FINALIZE_JOB : finalizeJob ( ( FinalizeJobTask ) task ) ; break ; case FAN_OUT : handleFanoutTaskOrAbandonTask ( ( FanoutTask ) task ) ; break ; case CANCEL_JOB : cancelJob ( ( CancelJobTask ) task ) ; break ; case DELETE_PIPELINE : DeletePipelineTask deletePipelineTask = ( DeletePipelineTask ) task ; try { backEnd . deletePipeline ( deletePipelineTask . getRootJobKey ( ) , deletePipelineTask . shouldForce ( ) , false ) ; } catch ( Exception e ) { logger . log ( Level . WARNING , "DeletePipeline operation failed." , e ) ; } break ; case HANDLE_CHILD_EXCEPTION : handleChildException ( ( HandleChildExceptionTask ) task ) ; break ; case DELAYED_SLOT_FILL : handleDelayedSlotFill ( ( DelayedSlotFillTask ) task ) ; break ; default : throw new IllegalArgumentException ( "Unrecognized task type: " + task . getType ( ) ) ; } } catch ( AbandonTaskException ate ) { } }
|
Process an incoming task received from the App Engine task queue .
|
3,468
|
private static void handleDelayedSlotFill ( DelayedSlotFillTask task ) { Key slotKey = task . getSlotKey ( ) ; Slot slot = querySlotOrAbandonTask ( slotKey , true ) ; Key rootJobKey = task . getRootJobKey ( ) ; UpdateSpec updateSpec = new UpdateSpec ( rootJobKey ) ; slot . fill ( null ) ; updateSpec . getNonTransactionalGroup ( ) . includeSlot ( slot ) ; backEnd . save ( updateSpec , task . getQueueSettings ( ) ) ; handleSlotFilled ( new HandleSlotFilledTask ( slotKey , task . getQueueSettings ( ) ) ) ; }
|
Fills the slot with null value and calls handleSlotFilled
|
3,469
|
public void addListArgumentSlots ( Slot initialSlot , List < Slot > slotList ) { if ( ! initialSlot . isFilled ( ) ) { throw new IllegalArgumentException ( "initialSlot must be filled" ) ; } verifyStateBeforAdd ( initialSlot ) ; int groupSize = slotList . size ( ) + 1 ; addSlotDescriptor ( new SlotDescriptor ( initialSlot , groupSize ) ) ; for ( Slot slot : slotList ) { addSlotDescriptor ( new SlotDescriptor ( slot , groupSize ) ) ; } }
|
Adds multiple slots to this barrier s waiting - on list representing a single Job argument of type list .
|
3,470
|
public Entity toEntity ( ) { Entity entity = toProtoEntity ( ) ; entity . setProperty ( JOB_INSTANCE_PROPERTY , jobInstanceKey ) ; entity . setProperty ( FINALIZE_BARRIER_PROPERTY , finalizeBarrierKey ) ; entity . setProperty ( RUN_BARRIER_PROPERTY , runBarrierKey ) ; entity . setProperty ( OUTPUT_SLOT_PROPERTY , outputSlotKey ) ; entity . setProperty ( STATE_PROPERTY , state . toString ( ) ) ; if ( null != exceptionHandlingAncestorKey ) { entity . setProperty ( EXCEPTION_HANDLING_ANCESTOR_KEY_PROPERTY , exceptionHandlingAncestorKey ) ; } if ( exceptionHandlerSpecified ) { entity . setProperty ( EXCEPTION_HANDLER_SPECIFIED_PROPERTY , Boolean . TRUE ) ; } if ( null != exceptionHandlerJobKey ) { entity . setProperty ( EXCEPTION_HANDLER_JOB_KEY_PROPERTY , exceptionHandlerJobKey ) ; } if ( null != exceptionKey ) { entity . setProperty ( EXCEPTION_KEY_PROPERTY , exceptionKey ) ; } if ( null != exceptionHandlerJobGraphGuid ) { entity . setUnindexedProperty ( EXCEPTION_HANDLER_JOB_GRAPH_GUID_PROPERTY , new Text ( exceptionHandlerJobGraphGuid ) ) ; } entity . setUnindexedProperty ( CALL_EXCEPTION_HANDLER_PROPERTY , callExceptionHandler ) ; entity . setUnindexedProperty ( IGNORE_EXCEPTION_PROPERTY , ignoreException ) ; if ( childGraphGuid != null ) { entity . setUnindexedProperty ( CHILD_GRAPH_GUID_PROPERTY , new Text ( childGraphGuid ) ) ; } entity . setProperty ( START_TIME_PROPERTY , startTime ) ; entity . setUnindexedProperty ( END_TIME_PROPERTY , endTime ) ; entity . setProperty ( CHILD_KEYS_PROPERTY , childKeys ) ; entity . setUnindexedProperty ( ATTEMPT_NUM_PROPERTY , attemptNumber ) ; entity . setUnindexedProperty ( MAX_ATTEMPTS_PROPERTY , maxAttempts ) ; entity . setUnindexedProperty ( BACKOFF_SECONDS_PROPERTY , backoffSeconds ) ; entity . setUnindexedProperty ( BACKOFF_FACTOR_PROPERTY , backoffFactor ) ; entity . setUnindexedProperty ( ON_BACKEND_PROPERTY , queueSettings . getOnBackend ( ) ) ; entity . setUnindexedProperty ( ON_MODULE_PROPERTY , queueSettings . getOnModule ( ) ) ; entity . setUnindexedProperty ( MODULE_VERSION_PROPERTY , queueSettings . getModuleVersion ( ) ) ; entity . setUnindexedProperty ( ON_QUEUE_PROPERTY , queueSettings . getOnQueue ( ) ) ; entity . setUnindexedProperty ( STATUS_CONSOLE_URL , statusConsoleUrl ) ; if ( rootJobDisplayName != null ) { entity . setProperty ( ROOT_JOB_DISPLAY_NAME , rootJobDisplayName ) ; } return entity ; }
|
Constructs and returns a Data Store Entity that represents this model object
|
3,471
|
public static JobRecord createRootJobRecord ( Job < ? > jobInstance , JobSetting [ ] settings ) { Key key = generateKey ( null , DATA_STORE_KIND ) ; return new JobRecord ( key , jobInstance , settings ) ; }
|
A factory method for root jobs .
|
3,472
|
public void run ( File file ) throws SAXException , NoSuchAlgorithmException , IOException { XmlEditor editor = new XmlEditor ( ) ; editor . read ( file ) ; run ( editor , new File ( "." ) ) ; }
|
Runs the tool using a configuration provided in the given file parameter . The configuration file is expected to be well formed XML conforming to the Redline configuration syntax .
|
3,473
|
public void run ( XmlEditor editor , File destination ) throws NoSuchAlgorithmException , IOException { editor . startPrefixMapping ( "http://redline-rpm.org/ns" , "rpm" ) ; Contents include = new Contents ( ) ; for ( Node files : editor . findNodes ( "rpm:files" ) ) { try { editor . pushContext ( files ) ; int permission = editor . getInteger ( "@permission" , DEFAULT_FILE_PERMISSION ) ; String parent = editor . getValue ( "@parent" ) ; if ( ! parent . endsWith ( "/" ) ) parent += "/" ; for ( Node file : editor . findNodes ( "rpm:file" ) ) { try { editor . pushContext ( file ) ; File source = new File ( editor . getValue ( "text()" ) ) ; include . addFile ( new File ( parent , source . getName ( ) ) . getPath ( ) , source , editor . getInteger ( "@permission" , permission ) ) ; } finally { editor . popContext ( ) ; } } } finally { editor . popContext ( ) ; } } run ( editor , editor . getValue ( "rpm:name/text()" ) , editor . getValue ( "rpm:version/text()" ) , editor . getValue ( "rpm:release/text()" , "1" ) , include , destination ) ; }
|
Runs the tool using a configuration provided in the given configuration and output file .
|
3,474
|
public void run ( XmlEditor editor , String name , String version , String release , Contents include , File destination ) throws NoSuchAlgorithmException , IOException { Builder builder = new Builder ( ) ; builder . setPackage ( name , version , release ) ; RpmType type = RpmType . valueOf ( editor . getValue ( "rpm:type" , BINARY . toString ( ) ) ) ; builder . setType ( type ) ; Architecture arch = Architecture . valueOf ( editor . getValue ( "rpm:architecture" , NOARCH . toString ( ) ) ) ; Os os = Os . valueOf ( editor . getValue ( "rpm:os" , LINUX . toString ( ) ) ) ; builder . setPlatform ( arch , os ) ; builder . setSummary ( editor . getValue ( "rpm:summary/text()" ) ) ; builder . setDescription ( editor . getValue ( "rpm:description/text()" ) ) ; builder . setBuildHost ( editor . getValue ( "rpm:host/text()" , InetAddress . getLocalHost ( ) . getHostName ( ) ) ) ; builder . setLicense ( editor . getValue ( "rpm:license/text()" ) ) ; builder . setGroup ( editor . getValue ( "rpm:group/text()" ) ) ; builder . setPackager ( editor . getValue ( "rpm:packager/text()" , System . getProperty ( "user.name" ) ) ) ; builder . setVendor ( editor . getValue ( "rpm:vendor/text()" , null ) ) ; builder . setUrl ( editor . getValue ( "rpm:url/text()" , null ) ) ; builder . setProvides ( editor . getValue ( "rpm:provides/text()" , name ) ) ; builder . setFiles ( include ) ; builder . build ( destination ) ; }
|
Runs the tool using the provided settings .
|
3,475
|
public void index ( final ByteBuffer index , final int position ) { index . putInt ( tag ) . putInt ( getType ( ) ) . putInt ( position ) . putInt ( count ) ; }
|
Writes the index entry into the provided buffer at the current position .
|
3,476
|
public static void main ( String [ ] args ) throws Exception { ReadableByteChannel in = Channels . newChannel ( System . in ) ; new Scanner ( ) . run ( new ReadableChannelWrapper ( in ) ) ; FileOutputStream fout = new FileOutputStream ( args [ 0 ] ) ; FileChannel out = fout . getChannel ( ) ; long position = 0 ; long read ; while ( ( read = out . transferFrom ( in , position , 1024 ) ) > 0 ) position += read ; fout . close ( ) ; }
|
Dumps the contents of the payload for an RPM file to the provided file . This method accepts an RPM file from standard input and dumps it s payload out to the file name provided as the first argument .
|
3,477
|
public void addChangeLog ( File changelogFile ) throws IOException , ChangelogParseException { InputStream changelog = new FileInputStream ( changelogFile ) ; ChangelogParser parser = new ChangelogParser ( ) ; List < ChangelogEntry > entries = parser . parse ( changelog ) ; for ( ChangelogEntry entry : entries ) { addChangeLogEntry ( entry ) ; } }
|
Adds the specified Changelog file to the rpm
|
3,478
|
public Key < Integer > start ( ) { final Key < Integer > object = new Key < Integer > ( ) ; consumers . put ( object , new Consumer < Integer > ( ) { int count ; public void consume ( final ByteBuffer buffer ) { count += buffer . remaining ( ) ; } public Integer finish ( ) { return count ; } } ) ; return object ; }
|
Initializes a byte counter on this channel .
|
3,479
|
public Key < byte [ ] > start ( final PrivateKey key ) throws NoSuchAlgorithmException , InvalidKeyException { final Signature signature = Signature . getInstance ( key . getAlgorithm ( ) ) ; signature . initSign ( key ) ; final Key < byte [ ] > object = new Key < byte [ ] > ( ) ; consumers . put ( object , new Consumer < byte [ ] > ( ) { public void consume ( final ByteBuffer buffer ) { try { signature . update ( buffer ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public byte [ ] finish ( ) { try { return signature . sign ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; return object ; }
|
Initialize a signature on this channel .
|
3,480
|
public Key < byte [ ] > start ( final PGPPrivateKey key , int algorithm ) { BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder ( algorithm , SHA1 ) ; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( contentSignerBuilder ) ; try { signatureGenerator . init ( BINARY_DOCUMENT , key ) ; } catch ( PGPException e ) { throw new RuntimeException ( "Could not initialize PGP signature generator" , e ) ; } final Key < byte [ ] > object = new Key < byte [ ] > ( ) ; consumers . put ( object , new Consumer < byte [ ] > ( ) { public void consume ( final ByteBuffer buffer ) { if ( ! buffer . hasRemaining ( ) ) { return ; } try { write ( buffer ) ; } catch ( SignatureException e ) { throw new RuntimeException ( "Could not write buffer to PGP signature generator." , e ) ; } } private void write ( ByteBuffer buffer ) throws SignatureException { if ( buffer . hasArray ( ) ) { byte [ ] bufferBytes = buffer . array ( ) ; int offset = buffer . arrayOffset ( ) ; int position = buffer . position ( ) ; int limit = buffer . limit ( ) ; signatureGenerator . update ( bufferBytes , offset + position , limit - position ) ; buffer . position ( limit ) ; } else { int length = buffer . remaining ( ) ; byte [ ] bytes = new byte [ Util . getTempArraySize ( length ) ] ; while ( length > 0 ) { int chunk = Math . min ( length , bytes . length ) ; buffer . get ( bytes , 0 , chunk ) ; signatureGenerator . update ( bytes , 0 , chunk ) ; length -= chunk ; } } } public byte [ ] finish ( ) { try { return signatureGenerator . generate ( ) . getEncoded ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not generate signature." , e ) ; } } } ) ; return object ; }
|
Initialize a PGP signatue on the channel
|
3,481
|
public Key < byte [ ] > start ( final String algorithm ) throws NoSuchAlgorithmException { final MessageDigest digest = MessageDigest . getInstance ( algorithm ) ; final Key < byte [ ] > object = new Key < byte [ ] > ( ) ; consumers . put ( object , new Consumer < byte [ ] > ( ) { public void consume ( final ByteBuffer buffer ) { try { digest . update ( buffer ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public byte [ ] finish ( ) { try { return digest . digest ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; return object ; }
|
Initialize a digest on this channel .
|
3,482
|
public static ByteBuffer fill ( ReadableByteChannel in , int size ) throws IOException { return fill ( in , ByteBuffer . allocate ( size ) ) ; }
|
Creates a new buffer and fills it with bytes from the provided channel . The amount of data to read is specified in the arguments .
|
3,483
|
public static ByteBuffer fill ( ReadableByteChannel in , ByteBuffer buffer ) throws IOException { while ( buffer . hasRemaining ( ) ) if ( in . read ( buffer ) == - 1 ) throw new BufferUnderflowException ( ) ; buffer . flip ( ) ; return buffer ; }
|
Fills the provided buffer it with bytes from the provided channel . The amount of data to read is dependant on the available space in the provided buffer .
|
3,484
|
public static void empty ( WritableByteChannel out , ByteBuffer buffer ) throws IOException { while ( buffer . hasRemaining ( ) ) out . write ( buffer ) ; }
|
Empties the contents of the given buffer into the writable channel provided . The buffer will be copied to the channel in it s entirety .
|
3,485
|
public static void check ( byte expected , byte actual ) throws IOException { if ( expected != actual ) throw new IOException ( "check expected " + Integer . toHexString ( 0xff & expected ) + ", found " + Integer . toHexString ( 0xff & actual ) ) ; }
|
Checks that two bytes are the same while generating a formatted error message if they are not . The error message will indicate the hex value of the bytes if they do not match .
|
3,486
|
public static void pad ( ByteBuffer buffer , int boundary ) { buffer . position ( round ( buffer . position ( ) , boundary ) ) ; }
|
Pads the given buffer up to the indicated boundary . The RPM file format requires that headers be aligned with various boundaries this method pads output to match the requirements .
|
3,487
|
public static Document readDocument ( File file ) throws SAXException , IOException { InputStream in = new FileInputStream ( file ) ; Document result = readDocument ( in ) ; in . close ( ) ; return result ; }
|
Static API follows
|
3,488
|
public static void main ( String [ ] args ) throws Exception { InputStream fios = new FileInputStream ( args [ 0 ] ) ; ReadableChannelWrapper in = new ReadableChannelWrapper ( Channels . newChannel ( fios ) ) ; Scanner scanner = new Scanner ( System . out ) ; Format format = scanner . run ( in ) ; scanner . log ( format . toString ( ) ) ; Header rpmHeader = format . getHeader ( ) ; scanner . log ( "Payload compression: " + rpmHeader . getEntry ( HeaderTag . PAYLOADCOMPRESSOR ) ) ; InputStream uncompressed = Util . openPayloadStream ( rpmHeader , fios ) ; in = new ReadableChannelWrapper ( Channels . newChannel ( uncompressed ) ) ; CpioHeader header ; int total = 0 ; do { header = new CpioHeader ( ) ; total = header . read ( in , total ) ; scanner . log ( header . toString ( ) ) ; final int skip = header . getFileSize ( ) ; if ( uncompressed . skip ( skip ) != skip ) throw new RuntimeException ( "Skip failed." ) ; total += header . getFileSize ( ) ; } while ( ! header . isLast ( ) ) ; }
|
Scans a file and prints out useful information . This utility reads from standard input and parses the binary contents of the RPM file .
|
3,489
|
public Format run ( ReadableChannelWrapper in ) throws IOException { Format format = new Format ( ) ; Key < Integer > headerStartKey = in . start ( ) ; Key < Integer > lead = in . start ( ) ; format . getLead ( ) . read ( in ) ; log ( "Lead ended at '" + in . finish ( lead ) + "'." ) ; Key < Integer > signature = in . start ( ) ; int count = format . getSignature ( ) . read ( in ) ; Entry < ? > sigEntry = format . getSignature ( ) . getEntry ( SIGNATURES ) ; int expected = sigEntry == null ? 0 : ByteBuffer . wrap ( ( byte [ ] ) sigEntry . getValues ( ) , 8 , 4 ) . getInt ( ) / - 16 ; log ( "Signature ended at '" + in . finish ( signature ) + "' and contained '" + count + "' headers (expected '" + expected + "')." ) ; Integer headerStartPos = in . finish ( headerStartKey ) ; format . getHeader ( ) . setStartPos ( headerStartPos ) ; Key < Integer > headerKey = in . start ( ) ; count = format . getHeader ( ) . read ( in ) ; Entry < ? > immutableEntry = format . getHeader ( ) . getEntry ( HEADERIMMUTABLE ) ; expected = immutableEntry == null ? 0 : ByteBuffer . wrap ( ( byte [ ] ) immutableEntry . getValues ( ) , 8 , 4 ) . getInt ( ) / - 16 ; Integer headerLength = in . finish ( headerKey ) ; format . getHeader ( ) . setEndPos ( headerStartPos + headerLength ) ; log ( "Header ended at '" + headerLength + " and contained '" + count + "' headers (expected '" + expected + "')." ) ; return format ; }
|
Reads the headers of an RPM and returns a description of it and it s format .
|
3,490
|
public int write ( final WritableByteChannel channel , int total ) throws IOException { final ByteBuffer buffer = charset . encode ( CharBuffer . wrap ( name ) ) ; int length = buffer . remaining ( ) + 1 ; ByteBuffer descriptor = ByteBuffer . allocate ( CPIO_HEADER ) ; descriptor . put ( writeSix ( MAGIC ) ) ; descriptor . put ( writeEight ( inode ) ) ; descriptor . put ( writeEight ( getMode ( ) ) ) ; descriptor . put ( writeEight ( uid ) ) ; descriptor . put ( writeEight ( gid ) ) ; descriptor . put ( writeEight ( nlink ) ) ; descriptor . put ( writeEight ( ( int ) ( mtime / 1000 ) ) ) ; descriptor . put ( writeEight ( filesize ) ) ; descriptor . put ( writeEight ( devMajor ) ) ; descriptor . put ( writeEight ( devMinor ) ) ; descriptor . put ( writeEight ( rdevMajor ) ) ; descriptor . put ( writeEight ( rdevMinor ) ) ; descriptor . put ( writeEight ( length ) ) ; descriptor . put ( writeEight ( checksum ) ) ; descriptor . flip ( ) ; total += CPIO_HEADER + length ; Util . empty ( channel , descriptor ) ; Util . empty ( channel , buffer ) ; Util . empty ( channel , ByteBuffer . allocate ( 1 ) ) ; return total + skip ( channel , total ) ; }
|
Write the content for the CPIO header including the name immediately following . The name data is rounded to the nearest 2 byte boundary as CPIO requires by appending a null when needed .
|
3,491
|
public void addDependencyLess ( final CharSequence name , final CharSequence version ) { int flag = LESS | EQUAL ; if ( name . toString ( ) . startsWith ( "rpmlib(" ) ) { flag = flag | RPMLIB ; } addDependency ( name , version , flag ) ; }
|
Adds a dependency to the RPM package . This dependency version will be marked as the maximum allowed and the package will require the named dependency with this version or lower at install time .
|
3,492
|
public void addDependencyMore ( final CharSequence name , final CharSequence version ) { addDependency ( name , version , GREATER | EQUAL ) ; }
|
Adds a dependency to the RPM package . This dependency version will be marked as the minimum allowed and the package will require the named dependency with this version or higher at install time .
|
3,493
|
public void addHeaderEntry ( final Tag tag , final String value ) { format . getHeader ( ) . createEntry ( tag , value ) ; }
|
Adds a header entry value to the header . For example use this to set the source RPM package name on your RPM
|
3,494
|
public void setSourceRpm ( final String rpm ) { if ( rpm != null ) format . getHeader ( ) . createEntry ( SOURCERPM , rpm ) ; }
|
Adds a source rpm .
|
3,495
|
public void setPrefixes ( final String ... prefixes ) { if ( prefixes != null && 0 < prefixes . length ) format . getHeader ( ) . createEntry ( PREFIXES , prefixes ) ; }
|
Sets the package prefix directories to allow any files installed under them to be relocatable .
|
3,496
|
private String readScript ( File file ) throws IOException { if ( file == null ) return null ; StringBuilder script = new StringBuilder ( ) ; BufferedReader in = new BufferedReader ( new FileReader ( file ) ) ; try { String line ; while ( ( line = in . readLine ( ) ) != null ) { script . append ( line ) ; script . append ( "\n" ) ; } } finally { in . close ( ) ; } return script . toString ( ) ; }
|
Return the content of the specified script file as a String .
|
3,497
|
public void addTrigger ( final File script , final String prog , final Map < String , IntString > depends , final int flag ) throws IOException { triggerscripts . add ( readScript ( script ) ) ; if ( null == prog ) { triggerscriptprogs . add ( DEFAULTSCRIPTPROG ) ; } else if ( 0 == prog . length ( ) ) { triggerscriptprogs . add ( DEFAULTSCRIPTPROG ) ; } else { triggerscriptprogs . add ( prog ) ; } for ( Map . Entry < String , IntString > depend : depends . entrySet ( ) ) { triggernames . add ( depend . getKey ( ) ) ; triggerflags . add ( depend . getValue ( ) . getInt ( ) | flag ) ; triggerversions . add ( depend . getValue ( ) . getString ( ) ) ; triggerindexes . add ( triggerCounter ) ; } triggerCounter ++ ; }
|
Adds a trigger to the RPM package .
|
3,498
|
public void addFile ( final String path , final File source , final int mode , final int dirmode , final Directive directive , final String uname , final String gname , final boolean addParents ) throws NoSuchAlgorithmException , IOException { contents . addFile ( path , source , mode , directive , uname , gname , dirmode , addParents ) ; }
|
Add the specified file to the repository payload in order . The required header entries will automatically be generated to record the directory names and file names as well as their digests .
|
3,499
|
public void addDirectory ( final String path , final int permissions , final Directive directive , final String uname , final String gname ) throws NoSuchAlgorithmException , IOException { contents . addDirectory ( path , permissions , directive , uname , gname ) ; }
|
Adds the directory to the repository .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.