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 ( "T...
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" ) ; } re...
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 ...
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." ) ; } httpParameter...
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 listen...
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 . TE...
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 . equalsIgnoreCa...
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 ( COOKI...
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 { i...
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 =...
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 ( ) ; } retu...
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 , ...
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 . fi...
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 ) { t...
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 = sto...
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 ? outputC...
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 ( "Endiannes...
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 = convertDateE...
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 , ENCO...
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 . getPr...
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_S...
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...
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 P...
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 ...
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 . ge...
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 [ ] s...
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 ) columnsDa...
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 ( a...
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 . le...
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'...
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 getBundle...
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 = cl...
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 , ...
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 . g...
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 < ? , ? > ) { retur...
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...
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 ....
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 . S...
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 CancelJo...
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 ( k...
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 ( ( Finalize...
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 . getNonTransaction...
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 ( initialS...
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 , outpu...
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 permiss...
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:t...
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 r...
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 ) { addC...
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 Consume...
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...
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...
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 ( forma...
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 . ...
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 ) ) ; descript...
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 . appe...
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 ( ) ) { triggerscriptpr...
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 , dirm...
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 .