idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
151,100
public DbInfo info ( ) { return client . couchDbClient . get ( new DatabaseURIHelper ( db . getDBUri ( ) ) . getDatabaseUri ( ) , DbInfo . class ) ; }
Get information about this database .
47
6
151,101
public PartitionInfo partitionInfo ( String partitionKey ) { if ( partitionKey == null ) { throw new UnsupportedOperationException ( "Cannot get partition information for null partition key." ) ; } URI uri = new DatabaseURIHelper ( db . getDBUri ( ) ) . partition ( partitionKey ) . build ( ) ; return client . couchDbClient . get ( uri , PartitionInfo . class ) ; }
Get information about a partition in this database .
90
9
151,102
public static Expression type ( String lhs , Type rhs ) { return new Expression ( lhs , "$type" , rhs . toString ( ) ) ; }
Check the document field s type and object
35
8
151,103
public static PredicateExpression nin ( Object ... rhs ) { PredicateExpression ex = new PredicateExpression ( "$nin" , rhs ) ; if ( rhs . length == 1 ) { ex . single = true ; } return ex ; }
The document field must not exist in the list provided
55
10
151,104
public static PredicateExpression all ( Object ... rhs ) { PredicateExpression ex = new PredicateExpression ( "$all" , rhs ) ; if ( rhs . length == 1 ) { ex . single = true ; } return ex ; }
Matches an array value if it contains all the elements of the argument array
55
15
151,105
public ReplicationResult trigger ( ) { assertNotEmpty ( source , "Source" ) ; assertNotEmpty ( target , "Target" ) ; InputStream response = null ; try { JsonObject json = createJson ( ) ; if ( log . isLoggable ( Level . FINE ) ) { log . fine ( json . toString ( ) ) ; } final URI uri = new DatabaseURIHelper ( client . getBaseUri ( ) ) . path ( "_replicate" ) . build ( ) ; response = client . post ( uri , json . toString ( ) ) ; final InputStreamReader reader = new InputStreamReader ( response , "UTF-8" ) ; return client . getGson ( ) . fromJson ( reader , ReplicationResult . class ) ; } catch ( UnsupportedEncodingException e ) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException ( e ) ; } finally { close ( response ) ; } }
Triggers a replication request .
219
7
151,106
public Replication targetOauth ( String consumerSecret , String consumerKey , String tokenSecret , String token ) { targetOauth = new JsonObject ( ) ; this . consumerSecret = consumerSecret ; this . consumerKey = consumerKey ; this . tokenSecret = tokenSecret ; this . token = token ; return this ; }
Authenticate with the target database using OAuth .
68
10
151,107
public static HttpConnection createPost ( URI uri , String body , String contentType ) { HttpConnection connection = Http . POST ( uri , "application/json" ) ; if ( body != null ) { setEntity ( connection , body , contentType ) ; } return connection ; }
create a HTTP POST request .
63
6
151,108
public static void setEntity ( HttpConnection connnection , String body , String contentType ) { connnection . requestProperties . put ( "Content-type" , contentType ) ; connnection . setRequestBody ( body ) ; }
Sets a JSON String as a request entity .
53
10
151,109
public < T > void setState ( HttpConnectionInterceptor interceptor , String stateName , T stateObjectToStore ) { Map < String , Object > state = interceptorStates . get ( interceptor ) ; if ( state == null ) { interceptorStates . put ( interceptor , ( state = new ConcurrentHashMap < String , Object > ( ) ) ) ; } state . put ( stateName , stateObjectToStore ) ; }
Store some state on this request context associated with the specified interceptor instance . Used where a single interceptor instance needs to associate state with each HTTP request .
94
31
151,110
public < T > T getState ( HttpConnectionInterceptor interceptor , String stateName , Class < T > stateType ) { Map < String , Object > state = interceptorStates . get ( interceptor ) ; if ( state != null ) { return stateType . cast ( state . get ( stateName ) ) ; } else { return null ; } }
Retrieve the state object associated with the specified interceptor instance and property name on this request context .
76
20
151,111
public DesignDocument get ( String id ) { assertNotEmpty ( id , "id" ) ; return db . find ( DesignDocument . class , ensureDesignPrefix ( id ) ) ; }
Gets a design document from the database .
40
9
151,112
public DesignDocument get ( String id , String rev ) { assertNotEmpty ( id , "id" ) ; assertNotEmpty ( id , "rev" ) ; return db . find ( DesignDocument . class , ensureDesignPrefix ( id ) , rev ) ; }
Gets a design document using the id and revision from the database .
56
14
151,113
public Response remove ( String id ) { assertNotEmpty ( id , "id" ) ; id = ensureDesignPrefix ( id ) ; String revision = null ; // Get the revision ID from ETag, removing leading and trailing " revision = client . executeRequest ( Http . HEAD ( new DatabaseURIHelper ( db . getDBUri ( ) ) . documentUri ( id ) ) ) . getConnection ( ) . getHeaderField ( "ETag" ) ; if ( revision != null ) { revision = revision . substring ( 1 , revision . length ( ) - 1 ) ; return db . remove ( id , revision ) ; } else { throw new CouchDbException ( "No ETag header found for design document with id " + id ) ; } }
Removes a design document from the database .
161
9
151,114
public Response remove ( String id , String rev ) { assertNotEmpty ( id , "id" ) ; assertNotEmpty ( id , "rev" ) ; return db . remove ( ensureDesignPrefix ( id ) , rev ) ; }
Removes a design document using the id and rev from the database .
50
14
151,115
public Response remove ( DesignDocument designDocument ) { assertNotEmpty ( designDocument , "DesignDocument" ) ; ensureDesignPrefixObject ( designDocument ) ; return db . remove ( designDocument ) ; }
Removes a design document using DesignDocument object from the database .
43
13
151,116
public List < DesignDocument > list ( ) throws IOException { return db . getAllDocsRequestBuilder ( ) . startKey ( "_design/" ) . endKey ( "_design0" ) . inclusiveEnd ( false ) . includeDocs ( true ) . build ( ) . getResponse ( ) . getDocsAs ( DesignDocument . class ) ; }
Performs a query to retrieve all the design documents defined in the database .
76
15
151,117
public static List < DesignDocument > fromDirectory ( File directory ) throws FileNotFoundException { List < DesignDocument > designDocuments = new ArrayList < DesignDocument > ( ) ; if ( directory . isDirectory ( ) ) { Collection < File > files = FileUtils . listFiles ( directory , null , true ) ; for ( File designDocFile : files ) { designDocuments . add ( fromFile ( designDocFile ) ) ; } } else { designDocuments . add ( fromFile ( directory ) ) ; } return designDocuments ; }
Deserialize a directory of javascript design documents to a List of DesignDocument objects .
113
17
151,118
public static DesignDocument fromFile ( File file ) throws FileNotFoundException { assertNotEmpty ( file , "Design js file" ) ; DesignDocument designDocument ; Gson gson = new Gson ( ) ; InputStreamReader reader = null ; try { reader = new InputStreamReader ( new FileInputStream ( file ) , "UTF-8" ) ; //Deserialize JS file contents into DesignDocument object designDocument = gson . fromJson ( reader , DesignDocument . class ) ; return designDocument ; } catch ( UnsupportedEncodingException e ) { //UTF-8 should be supported on all JVMs throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } }
Deserialize a javascript design document file to a DesignDocument object .
158
14
151,119
static < K , V > ViewQueryParameters < K , V > forwardPaginationQueryParameters ( ViewQueryParameters < K , V > initialQueryParameters , K startkey , String startkey_docid ) { // Copy the initial query parameters ViewQueryParameters < K , V > pageParameters = initialQueryParameters . copy ( ) ; // Now override with the start keys provided pageParameters . setStartKey ( startkey ) ; pageParameters . setStartKeyDocId ( startkey_docid ) ; return pageParameters ; }
Generate query parameters for a forward page with the specified start key .
110
14
151,120
public static HttpConnection connect ( String requestMethod , URL url , String contentType ) { return new HttpConnection ( requestMethod , url , contentType ) ; }
low level http operations
35
4
151,121
public B partialFilterSelector ( Selector selector ) { instance . def . selector = Helpers . getJsonObjectFromSelector ( selector ) ; return returnThis ( ) ; }
Configure a selector to choose documents that should be added to the index .
39
15
151,122
protected B fields ( List < F > fields ) { if ( instance . def . fields == null ) { instance . def . fields = new ArrayList < F > ( fields . size ( ) ) ; } instance . def . fields . addAll ( fields ) ; return returnThis ( ) ; }
Add fields to the text index configuration .
62
8
151,123
public SchedulerDocsResponse . Doc schedulerDoc ( String docId ) { assertNotEmpty ( docId , "docId" ) ; return this . get ( new DatabaseURIHelper ( getBaseUri ( ) ) . path ( "_scheduler" ) . path ( "docs" ) . path ( "_replicator" ) . path ( docId ) . build ( ) , SchedulerDocsResponse . Doc . class ) ; }
Get replication document state for a given replication document ID .
94
11
151,124
public List < String > uuids ( long count ) { final URI uri = new URIBase ( clientUri ) . path ( "_uuids" ) . query ( "count" , count ) . build ( ) ; final JsonObject json = get ( uri , JsonObject . class ) ; return getGson ( ) . fromJson ( json . get ( "uuids" ) . toString ( ) , DeserializationTypes . STRINGS ) ; }
Request a database sends a list of UUIDs .
102
11
151,125
public Response executeToResponse ( HttpConnection connection ) { InputStream is = null ; try { is = this . executeToInputStream ( connection ) ; Response response = getResponse ( is , Response . class , getGson ( ) ) ; response . setStatusCode ( connection . getConnection ( ) . getResponseCode ( ) ) ; response . setReason ( connection . getConnection ( ) . getResponseMessage ( ) ) ; return response ; } catch ( IOException e ) { throw new CouchDbException ( "Error retrieving response code or message." , e ) ; } finally { close ( is ) ; } }
Executes a HTTP request and parses the JSON response into a Response instance .
129
16
151,126
Response delete ( URI uri ) { HttpConnection connection = Http . DELETE ( uri ) ; return executeToResponse ( connection ) ; }
Performs a HTTP DELETE request .
33
9
151,127
public < T > T get ( URI uri , Class < T > classType ) { HttpConnection connection = Http . GET ( uri ) ; InputStream response = executeToInputStream ( connection ) ; try { return getResponse ( response , classType , getGson ( ) ) ; } finally { close ( response ) ; } }
Performs a HTTP GET request .
73
7
151,128
Response put ( URI uri , InputStream instream , String contentType ) { HttpConnection connection = Http . PUT ( uri , contentType ) ; connection . setRequestBody ( instream ) ; return executeToResponse ( connection ) ; }
Performs a HTTP PUT request saves an attachment .
54
11
151,129
private static String loadUA ( ClassLoader loader , String filename ) { String ua = "cloudant-http" ; String version = "unknown" ; final InputStream propStream = loader . getResourceAsStream ( filename ) ; final Properties properties = new Properties ( ) ; try { if ( propStream != null ) { try { properties . load ( propStream ) ; } finally { propStream . close ( ) ; } } ua = properties . getProperty ( "user.agent.name" , ua ) ; version = properties . getProperty ( "user.agent.version" , version ) ; } catch ( IOException e ) { // Swallow exception and use default values. } return String . format ( Locale . ENGLISH , "%s/%s" , ua , version ) ; }
Loads the properties file using the classloader provided . Creating a string from the properties user . agent . name and user . agent . version .
171
29
151,130
private String getBearerToken ( HttpConnectionInterceptorContext context ) { final AtomicReference < String > iamTokenResponse = new AtomicReference < String > ( ) ; boolean result = super . requestCookie ( context , iamServerUrl , iamTokenRequestBody , "application/x-www-form-urlencoded" , "application/json" , new StoreBearerCallable ( iamTokenResponse ) ) ; if ( result ) { return iamTokenResponse . get ( ) ; } else { return null ; } }
get bearer token returned by IAM in JSON format
115
10
151,131
public QueryBuilder useIndex ( String designDocument , String indexName ) { useIndex = new String [ ] { designDocument , indexName } ; return this ; }
Instruct a query to use a specific index .
34
9
151,132
private static String quoteSort ( Sort [ ] sort ) { LinkedList < String > sorts = new LinkedList < String > ( ) ; for ( Sort pair : sort ) { sorts . add ( String . format ( "{%s: %s}" , Helpers . quote ( pair . getName ( ) ) , Helpers . quote ( pair . getOrder ( ) . toString ( ) ) ) ) ; } return sorts . toString ( ) ; }
sorts are a bit more awkward and need a helper ...
97
12
151,133
public < K , V > MultipleRequestBuilder < K , V > newMultipleRequest ( Key . Type < K > keyType , Class < V > valueType ) { return new MultipleRequestBuilderImpl < K , V > ( newViewRequestParameters ( keyType . getType ( ) , valueType ) ) ; }
Create a new builder for multiple unpaginated requests on the view .
66
14
151,134
public < T > T find ( Class < T > classType , String id , String rev ) { assertNotEmpty ( classType , "Class" ) ; assertNotEmpty ( id , "id" ) ; assertNotEmpty ( id , "rev" ) ; final URI uri = new DatabaseURIHelper ( dbUri ) . documentUri ( id , "rev" , rev ) ; return couchDbClient . get ( uri , classType ) ; }
Finds an Object of the specified type .
98
9
151,135
public boolean contains ( String id ) { assertNotEmpty ( id , "id" ) ; InputStream response = null ; try { response = couchDbClient . head ( new DatabaseURIHelper ( dbUri ) . documentUri ( id ) ) ; } catch ( NoDocumentException e ) { return false ; } finally { close ( response ) ; } return true ; }
Checks if a document exist in the database .
78
10
151,136
public List < Response > bulk ( List < ? > objects , boolean allOrNothing ) { assertNotEmpty ( objects , "objects" ) ; InputStream responseStream = null ; HttpConnection connection ; try { final JsonObject jsonObject = new JsonObject ( ) ; if ( allOrNothing ) { jsonObject . addProperty ( "all_or_nothing" , true ) ; } final URI uri = new DatabaseURIHelper ( dbUri ) . bulkDocsUri ( ) ; jsonObject . add ( "docs" , getGson ( ) . toJsonTree ( objects ) ) ; connection = Http . POST ( uri , "application/json" ) ; if ( jsonObject . toString ( ) . length ( ) != 0 ) { connection . setRequestBody ( jsonObject . toString ( ) ) ; } couchDbClient . execute ( connection ) ; responseStream = connection . responseAsInputStream ( ) ; List < Response > bulkResponses = getResponseList ( responseStream , getGson ( ) , DeserializationTypes . LC_RESPONSES ) ; for ( Response response : bulkResponses ) { response . setStatusCode ( connection . getConnection ( ) . getResponseCode ( ) ) ; } return bulkResponses ; } catch ( IOException e ) { throw new CouchDbException ( "Error retrieving response input stream." , e ) ; } finally { close ( responseStream ) ; } }
Performs a Bulk Documents insert request .
310
8
151,137
public < T > List < T > query ( String query , Class < T > classOfT ) { InputStream instream = null ; List < T > result = new ArrayList < T > ( ) ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( query ) , "UTF-8" ) ; JsonObject json = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) ; if ( json . has ( "rows" ) ) { if ( ! includeDocs ) { log . warning ( "includeDocs set to false and attempting to retrieve doc. " + "null object will be returned" ) ; } for ( JsonElement e : json . getAsJsonArray ( "rows" ) ) { result . add ( jsonToObject ( client . getGson ( ) , e , "doc" , classOfT ) ) ; } } else { log . warning ( "No ungrouped result available. Use queryGroups() if grouping set" ) ; } return result ; } catch ( UnsupportedEncodingException e1 ) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException ( e1 ) ; } finally { close ( instream ) ; } }
Queries a Search Index and returns ungrouped results . In case the query used grouping an empty list is returned
278
23
151,138
public < T > Map < String , List < T > > queryGroups ( String query , Class < T > classOfT ) { InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( query ) , "UTF-8" ) ; JsonObject json = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) ; Map < String , List < T > > result = new LinkedHashMap < String , List < T > > ( ) ; if ( json . has ( "groups" ) ) { for ( JsonElement e : json . getAsJsonArray ( "groups" ) ) { String groupName = e . getAsJsonObject ( ) . get ( "by" ) . getAsString ( ) ; List < T > orows = new ArrayList < T > ( ) ; if ( ! includeDocs ) { log . warning ( "includeDocs set to false and attempting to retrieve doc. " + "null object will be returned" ) ; } for ( JsonElement rows : e . getAsJsonObject ( ) . getAsJsonArray ( "rows" ) ) { orows . add ( jsonToObject ( client . getGson ( ) , rows , "doc" , classOfT ) ) ; } result . put ( groupName , orows ) ; } // end for(groups) } // end hasgroups else { log . warning ( "No grouped results available. Use query() if non grouped query" ) ; } return result ; } catch ( UnsupportedEncodingException e1 ) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException ( e1 ) ; } finally { close ( instream ) ; } }
Queries a Search Index and returns grouped results in a map where key of the map is the groupName . In case the query didnt use grouping an empty map is returned
389
34
151,139
public Search groupField ( String fieldName , boolean isNumber ) { assertNotEmpty ( fieldName , "fieldName" ) ; if ( isNumber ) { databaseHelper . query ( "group_field" , fieldName + "<number>" ) ; } else { databaseHelper . query ( "group_field" , fieldName ) ; } return this ; }
Group results by the specified field .
75
7
151,140
public Search counts ( String [ ] countsfields ) { assert ( countsfields . length > 0 ) ; JsonArray countsJsonArray = new JsonArray ( ) ; for ( String countsfield : countsfields ) { JsonPrimitive element = new JsonPrimitive ( countsfield ) ; countsJsonArray . add ( element ) ; } databaseHelper . query ( "counts" , countsJsonArray ) ; return this ; }
Array of fieldNames for which counts should be produced
93
10
151,141
public List < Index < Field > > allIndexes ( ) { List < Index < Field >> indexesOfAnyType = new ArrayList < Index < Field > > ( ) ; indexesOfAnyType . addAll ( listIndexType ( null , ListableIndex . class ) ) ; return indexesOfAnyType ; }
All the indexes defined in the database . Type widening means that the returned Index objects are limited to the name design document and type of the index and the names of the fields .
66
35
151,142
private < T extends Index > List < T > listIndexType ( String type , Class < T > modelType ) { List < T > indexesOfType = new ArrayList < T > ( ) ; Gson g = new Gson ( ) ; for ( JsonElement index : indexes ) { if ( index . isJsonObject ( ) ) { JsonObject indexDefinition = index . getAsJsonObject ( ) ; JsonElement indexType = indexDefinition . get ( "type" ) ; if ( indexType != null && indexType . isJsonPrimitive ( ) ) { JsonPrimitive indexTypePrimitive = indexType . getAsJsonPrimitive ( ) ; if ( type == null || ( indexTypePrimitive . isString ( ) && indexTypePrimitive . getAsString ( ) . equals ( type ) ) ) { indexesOfType . add ( g . fromJson ( indexDefinition , modelType ) ) ; } } } } return indexesOfType ; }
Utility to list indexes of a given type .
211
10
151,143
String encodePath ( String in ) { try { String encodedString = HierarchicalUriComponents . encodeUriComponent ( in , "UTF-8" , HierarchicalUriComponents . Type . PATH_SEGMENT ) ; if ( encodedString . startsWith ( _design_prefix_encoded ) || encodedString . startsWith ( _local_prefix_encoded ) ) { // we replaced the first slash in the design or local doc URL, which we shouldn't // so let's put it back return encodedString . replaceFirst ( "%2F" , "/" ) ; } else { return encodedString ; } } catch ( UnsupportedEncodingException uee ) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException ( "Couldn't encode ID " + in , uee ) ; } }
Encode a path in a manner suitable for a GET request
188
12
151,144
public URI build ( ) { try { String uriString = String . format ( "%s%s" , baseUri . toASCIIString ( ) , ( path . isEmpty ( ) ? "" : path ) ) ; if ( qParams != null && qParams . size ( ) > 0 ) { //Add queries together if both exist if ( ! completeQuery . isEmpty ( ) ) { uriString = String . format ( "%s?%s&%s" , uriString , getJoinedQuery ( qParams . getParams ( ) ) , completeQuery ) ; } else { uriString = String . format ( "%s?%s" , uriString , getJoinedQuery ( qParams . getParams ( ) ) ) ; } } else if ( ! completeQuery . isEmpty ( ) ) { uriString = String . format ( "%s?%s" , uriString , completeQuery ) ; } return new URI ( uriString ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } }
Build and return the complete URI containing values such as the document ID attachment ID and query syntax .
236
19
151,145
public static ClientBuilder account ( String account ) { logger . config ( "Account: " + account ) ; return ClientBuilder . url ( convertStringToURL ( String . format ( "https://%s.cloudant.com" , account ) ) ) ; }
Constructs a new ClientBuilder for building a CloudantClient instance to connect to the Cloudant server with the specified account .
55
25
151,146
public HttpConnection setRequestBody ( final String input ) { try { final byte [ ] inputBytes = input . getBytes ( "UTF-8" ) ; return setRequestBody ( inputBytes ) ; } catch ( UnsupportedEncodingException e ) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException ( e ) ; } }
Set the String of request body data to be sent to the server .
85
14
151,147
public HttpConnection setRequestBody ( final InputStream input , final long inputLength ) { try { return setRequestBody ( new InputStreamWrappingGenerator ( input , inputLength ) , inputLength ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , "Error copying input stream for request body" , e ) ; throw new RuntimeException ( e ) ; } }
Set the InputStream of request body data of known length to be sent to the server .
85
18
151,148
private String getLogRequestIdentifier ( ) { if ( logIdentifier == null ) { logIdentifier = String . format ( "%s-%s %s %s" , Integer . toHexString ( hashCode ( ) ) , numberOfRetries , connection . getRequestMethod ( ) , connection . getURL ( ) ) ; } return logIdentifier ; }
Get a prefix for the log message to help identify which request is which and which responses belong to which requests .
79
22
151,149
private PGPSecretKey getSecretKey ( InputStream input , String keyId ) throws IOException , PGPException { PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection ( PGPUtil . getDecoderStream ( input ) , new JcaKeyFingerprintCalculator ( ) ) ; Iterator rIt = keyrings . getKeyRings ( ) ; while ( rIt . hasNext ( ) ) { PGPSecretKeyRing kRing = ( PGPSecretKeyRing ) rIt . next ( ) ; Iterator kIt = kRing . getSecretKeys ( ) ; while ( kIt . hasNext ( ) ) { PGPSecretKey key = ( PGPSecretKey ) kIt . next ( ) ; if ( key . isSigningKey ( ) && String . format ( "%08x" , key . getKeyID ( ) & 0xFFFFFFFF L ) . equals ( keyId . toLowerCase ( ) ) ) { return key ; } } } return null ; }
Returns the secret key matching the specified identifier .
225
9
151,150
private String trim ( String line ) { char [ ] chars = line . toCharArray ( ) ; int len = chars . length ; while ( len > 0 ) { if ( ! Character . isWhitespace ( chars [ len - 1 ] ) ) { break ; } len -- ; } return line . substring ( 0 , len ) ; }
Trim the trailing spaces .
73
6
151,151
public void validate ( ) throws PackagingException { if ( control == null || ! control . isDirectory ( ) ) { throw new PackagingException ( "The 'control' attribute doesn't point to a directory. " + control ) ; } if ( changesIn != null ) { if ( changesIn . exists ( ) && ( ! changesIn . isFile ( ) || ! changesIn . canRead ( ) ) ) { throw new PackagingException ( "The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable." ) ; } if ( changesOut != null && ! isWritableFile ( changesOut ) ) { throw new PackagingException ( "Cannot write the output for 'changesOut' to " + changesOut ) ; } if ( changesSave != null && ! isWritableFile ( changesSave ) ) { throw new PackagingException ( "Cannot write the output for 'changesSave' to " + changesSave ) ; } } else { if ( changesOut != null || changesSave != null ) { throw new PackagingException ( "The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified." ) ; } } if ( Compression . toEnum ( compression ) == null ) { throw new PackagingException ( "The compression method '" + compression + "' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')" ) ; } if ( deb == null ) { throw new PackagingException ( "You need to specify where the deb file is supposed to be created." ) ; } getDigestCode ( digest ) ; }
Validates the input parameters .
359
6
151,152
protected String getUserDefinedFieldName ( String field ) { int index = field . indexOf ( ' ' ) ; char letter = getUserDefinedFieldLetter ( ) ; for ( int i = 0 ; i < index ; ++ i ) { if ( field . charAt ( i ) == letter ) { return field . substring ( index + 1 ) ; } } return null ; }
Returns the user defined field without its prefix .
82
9
151,153
public static String replaceVariables ( final VariableResolver pResolver , final String pExpression , final String pOpen , final String pClose ) { final char [ ] open = pOpen . toCharArray ( ) ; final char [ ] close = pClose . toCharArray ( ) ; final StringBuilder out = new StringBuilder ( ) ; StringBuilder sb = new StringBuilder ( ) ; char [ ] last = null ; int wo = 0 ; int wc = 0 ; int level = 0 ; for ( char c : pExpression . toCharArray ( ) ) { if ( c == open [ wo ] ) { if ( wc > 0 ) { sb . append ( close , 0 , wc ) ; } wc = 0 ; wo ++ ; if ( open . length == wo ) { // found open if ( last == open ) { out . append ( open ) ; } level ++ ; out . append ( sb ) ; sb = new StringBuilder ( ) ; wo = 0 ; last = open ; } } else if ( c == close [ wc ] ) { if ( wo > 0 ) { sb . append ( open , 0 , wo ) ; } wo = 0 ; wc ++ ; if ( close . length == wc ) { // found close if ( last == open ) { final String variable = pResolver . get ( sb . toString ( ) ) ; if ( variable != null ) { out . append ( variable ) ; } else { out . append ( open ) ; out . append ( sb ) ; out . append ( close ) ; } } else { out . append ( sb ) ; out . append ( close ) ; } sb = new StringBuilder ( ) ; level -- ; wc = 0 ; last = close ; } } else { if ( wo > 0 ) { sb . append ( open , 0 , wo ) ; } if ( wc > 0 ) { sb . append ( close , 0 , wc ) ; } sb . append ( c ) ; wo = wc = 0 ; } } if ( wo > 0 ) { sb . append ( open , 0 , wo ) ; } if ( wc > 0 ) { sb . append ( close , 0 , wc ) ; } if ( level > 0 ) { out . append ( open ) ; } out . append ( sb ) ; return out . toString ( ) ; }
Substitute the variables in the given expression with the values from the resolver
516
16
151,154
public static byte [ ] toUnixLineEndings ( InputStream input ) throws IOException { String encoding = "ISO-8859-1" ; FixCrLfFilter filter = new FixCrLfFilter ( new InputStreamReader ( input , encoding ) ) ; filter . setEol ( FixCrLfFilter . CrLf . newInstance ( "unix" ) ) ; ByteArrayOutputStream filteredFile = new ByteArrayOutputStream ( ) ; Utils . copy ( new ReaderInputStream ( filter , encoding ) , filteredFile ) ; return filteredFile . toByteArray ( ) ; }
Replaces new line delimiters in the input stream with the Unix line feed .
127
17
151,155
public static String movePath ( final String file , final String target ) { final String name = new File ( file ) . getName ( ) ; return target . endsWith ( "/" ) ? target + name : target + ' ' + name ; }
Construct new path by replacing file directory part . No files are actually modified .
52
15
151,156
public static String lookupIfEmpty ( final String value , final Map < String , String > props , final String key ) { return value != null ? value : props . get ( key ) ; }
Extracts value from map if given value is null .
40
12
151,157
public static Collection < String > getKnownPGPSecureRingLocations ( ) { final LinkedHashSet < String > locations = new LinkedHashSet < String > ( ) ; final String os = System . getProperty ( "os.name" ) ; final boolean runOnWindows = os == null || os . toLowerCase ( ) . contains ( "win" ) ; if ( runOnWindows ) { // The user's roaming profile on Windows, via environment final String windowsRoaming = System . getenv ( "APPDATA" ) ; if ( windowsRoaming != null ) { locations . add ( joinLocalPath ( windowsRoaming , "gnupg" , "secring.gpg" ) ) ; } // The user's local profile on Windows, via environment final String windowsLocal = System . getenv ( "LOCALAPPDATA" ) ; if ( windowsLocal != null ) { locations . add ( joinLocalPath ( windowsLocal , "gnupg" , "secring.gpg" ) ) ; } // The Windows installation directory final String windir = System . getProperty ( "WINDIR" ) ; if ( windir != null ) { // Local Profile on Windows 98 and ME locations . add ( joinLocalPath ( windir , "Application Data" , "gnupg" , "secring.gpg" ) ) ; } } final String home = System . getProperty ( "user.home" ) ; if ( home != null && runOnWindows ) { // These are for various flavours of Windows // if the environment variables above have failed // Roaming profile on Vista and later locations . add ( joinLocalPath ( home , "AppData" , "Roaming" , "gnupg" , "secring.gpg" ) ) ; // Local profile on Vista and later locations . add ( joinLocalPath ( home , "AppData" , "Local" , "gnupg" , "secring.gpg" ) ) ; // Roaming profile on 2000 and XP locations . add ( joinLocalPath ( home , "Application Data" , "gnupg" , "secring.gpg" ) ) ; // Local profile on 2000 and XP locations . add ( joinLocalPath ( home , "Local Settings" , "Application Data" , "gnupg" , "secring.gpg" ) ) ; } // *nix, including OS X if ( home != null ) { locations . add ( joinLocalPath ( home , ".gnupg" , "secring.gpg" ) ) ; } return locations ; }
Get the known locations where the secure keyring can be located . Looks through known locations of the GNU PG secure keyring .
543
25
151,158
public static File guessKeyRingFile ( ) throws FileNotFoundException { final Collection < String > possibleLocations = getKnownPGPSecureRingLocations ( ) ; for ( final String location : possibleLocations ) { final File candidate = new File ( location ) ; if ( candidate . exists ( ) ) { return candidate ; } } final StringBuilder message = new StringBuilder ( "Could not locate secure keyring, locations tried: " ) ; final Iterator < String > it = possibleLocations . iterator ( ) ; while ( it . hasNext ( ) ) { message . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) { message . append ( ", " ) ; } } throw new FileNotFoundException ( message . toString ( ) ) ; }
Tries to guess location of the user secure keyring using various heuristics .
167
17
151,159
public static String defaultString ( final String str , final String fallback ) { return isNullOrEmpty ( str ) ? fallback : str ; }
Return fallback if first string is null or empty
31
10
151,160
static TarArchiveEntry defaultFileEntryWithName ( final String fileName ) { TarArchiveEntry entry = new TarArchiveEntry ( fileName , true ) ; entry . setUserId ( ROOT_UID ) ; entry . setUserName ( ROOT_NAME ) ; entry . setGroupId ( ROOT_UID ) ; entry . setGroupName ( ROOT_NAME ) ; entry . setMode ( TarArchiveEntry . DEFAULT_FILE_MODE ) ; return entry ; }
Creates a tar file entry with defaults parameters .
105
10
151,161
static TarArchiveEntry defaultDirEntryWithName ( final String dirName ) { TarArchiveEntry entry = new TarArchiveEntry ( dirName , true ) ; entry . setUserId ( ROOT_UID ) ; entry . setUserName ( ROOT_NAME ) ; entry . setGroupId ( ROOT_UID ) ; entry . setGroupName ( ROOT_NAME ) ; entry . setMode ( TarArchiveEntry . DEFAULT_DIR_MODE ) ; return entry ; }
Creates a tar directory entry with defaults parameters .
105
10
151,162
static void produceInputStreamWithEntry ( final DataConsumer consumer , final InputStream inputStream , final TarArchiveEntry entry ) throws IOException { try { consumer . onEachFile ( inputStream , entry ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } }
Feeds input stream to data consumer using metadata from tar entry .
63
13
151,163
public String format ( String value ) { StringBuilder s = new StringBuilder ( ) ; if ( value != null && value . trim ( ) . length ( ) > 0 ) { boolean continuationLine = false ; s . append ( getName ( ) ) . append ( ":" ) ; if ( isFirstLineEmpty ( ) ) { s . append ( "\n" ) ; continuationLine = true ; } try { BufferedReader reader = new BufferedReader ( new StringReader ( value ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( continuationLine && line . trim ( ) . length ( ) == 0 ) { // put a dot on the empty continuation lines s . append ( " .\n" ) ; } else { s . append ( " " ) . append ( line ) . append ( "\n" ) ; } continuationLine = true ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } return s . toString ( ) ; }
Returns the field with the specified value properly formatted . Multiline values are automatically indented and dots are added on the empty lines .
219
27
151,164
public void initialize ( BinaryPackageControlFile packageControlFile ) { set ( "Binary" , packageControlFile . get ( "Package" ) ) ; set ( "Source" , Utils . defaultString ( packageControlFile . get ( "Source" ) , packageControlFile . get ( "Package" ) ) ) ; set ( "Architecture" , packageControlFile . get ( "Architecture" ) ) ; set ( "Version" , packageControlFile . get ( "Version" ) ) ; set ( "Maintainer" , packageControlFile . get ( "Maintainer" ) ) ; set ( "Changed-By" , packageControlFile . get ( "Maintainer" ) ) ; set ( "Distribution" , packageControlFile . get ( "Distribution" ) ) ; for ( Entry < String , String > entry : packageControlFile . getUserDefinedFields ( ) . entrySet ( ) ) { set ( entry . getKey ( ) , entry . getValue ( ) ) ; } StringBuilder description = new StringBuilder ( ) ; description . append ( packageControlFile . get ( "Package" ) ) ; if ( packageControlFile . get ( "Description" ) != null ) { description . append ( " - " ) ; description . append ( packageControlFile . getShortDescription ( ) ) ; } set ( "Description" , description . toString ( ) ) ; }
Initializes the fields on the changes file with the values of the specified binary package control file .
301
19
151,165
private void initializeSignProperties ( ) { if ( ! signPackage && ! signChanges ) { return ; } if ( key != null && keyring != null && passphrase != null ) { return ; } Map < String , String > properties = readPropertiesFromActiveProfiles ( signCfgPrefix , KEY , KEYRING , PASSPHRASE ) ; key = lookupIfEmpty ( key , properties , KEY ) ; keyring = lookupIfEmpty ( keyring , properties , KEYRING ) ; passphrase = decrypt ( lookupIfEmpty ( passphrase , properties , PASSPHRASE ) ) ; if ( keyring == null ) { try { keyring = Utils . guessKeyRingFile ( ) . getAbsolutePath ( ) ; console . info ( "Located keyring at " + keyring ) ; } catch ( FileNotFoundException e ) { console . warn ( e . getMessage ( ) ) ; } } }
Initializes unspecified sign properties using available defaults and global settings .
200
12
151,166
public Map < String , String > readPropertiesFromActiveProfiles ( final String prefix , final String ... properties ) { if ( settings == null ) { console . debug ( "No maven setting injected" ) ; return Collections . emptyMap ( ) ; } final List < String > activeProfilesList = settings . getActiveProfiles ( ) ; if ( activeProfilesList . isEmpty ( ) ) { console . debug ( "No active profiles found" ) ; return Collections . emptyMap ( ) ; } final Map < String , String > map = new HashMap < String , String > ( ) ; final Set < String > activeProfiles = new HashSet < String > ( activeProfilesList ) ; // Iterate over all active profiles in order for ( final Profile profile : settings . getProfiles ( ) ) { // Check if the profile is active final String profileId = profile . getId ( ) ; if ( activeProfiles . contains ( profileId ) ) { console . debug ( "Trying active profile " + profileId ) ; for ( final String property : properties ) { final String propKey = prefix != null ? prefix + property : property ; final String value = profile . getProperties ( ) . getProperty ( propKey ) ; if ( value != null ) { console . debug ( "Found property " + property + " in profile " + profileId ) ; map . put ( property , value ) ; } } } } return map ; }
Read properties from the active profiles .
307
7
151,167
void buildControl ( BinaryPackageControlFile packageControlFile , File [ ] controlFiles , List < String > conffiles , StringBuilder checksums , File output ) throws IOException , ParseException { final File dir = output . getParentFile ( ) ; if ( dir != null && ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) ) { throw new IOException ( "Cannot write control file at '" + output . getAbsolutePath ( ) + "'" ) ; } final TarArchiveOutputStream outputStream = new TarArchiveOutputStream ( new GZIPOutputStream ( new FileOutputStream ( output ) ) ) ; outputStream . setLongFileMode ( TarArchiveOutputStream . LONGFILE_GNU ) ; boolean foundConffiles = false ; // create the final package control file out of the "control" file, copy all other files, ignore the directories for ( File file : controlFiles ) { if ( file . isDirectory ( ) ) { // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc) if ( ! isDefaultExcludes ( file ) ) { console . warn ( "Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?" ) ; } continue ; } if ( "conffiles" . equals ( file . getName ( ) ) ) { foundConffiles = true ; } if ( CONFIGURATION_FILENAMES . contains ( file . getName ( ) ) || MAINTAINER_SCRIPTS . contains ( file . getName ( ) ) ) { FilteredFile configurationFile = new FilteredFile ( new FileInputStream ( file ) , resolver ) ; configurationFile . setOpenToken ( openReplaceToken ) ; configurationFile . setCloseToken ( closeReplaceToken ) ; addControlEntry ( file . getName ( ) , configurationFile . toString ( ) , outputStream ) ; } else if ( ! "control" . equals ( file . getName ( ) ) ) { // initialize the information stream to guess the type of the file InformationInputStream infoStream = new InformationInputStream ( new FileInputStream ( file ) ) ; Utils . copy ( infoStream , NullOutputStream . NULL_OUTPUT_STREAM ) ; infoStream . close ( ) ; // fix line endings for shell scripts InputStream in = new FileInputStream ( file ) ; if ( infoStream . isShell ( ) && ! infoStream . hasUnixLineEndings ( ) ) { byte [ ] buf = Utils . toUnixLineEndings ( in ) ; in = new ByteArrayInputStream ( buf ) ; } addControlEntry ( file . getName ( ) , IOUtils . toString ( in ) , outputStream ) ; in . close ( ) ; } } if ( foundConffiles ) { console . info ( "Found file 'conffiles' in the control directory. Skipping conffiles generation." ) ; } else if ( ( conffiles != null ) && ( conffiles . size ( ) > 0 ) ) { addControlEntry ( "conffiles" , createPackageConffilesFile ( conffiles ) , outputStream ) ; } else { console . info ( "Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml." ) ; } if ( packageControlFile == null ) { throw new FileNotFoundException ( "No 'control' file found in " + controlFiles . toString ( ) ) ; } addControlEntry ( "control" , packageControlFile . toString ( ) , outputStream ) ; addControlEntry ( "md5sums" , checksums . toString ( ) , outputStream ) ; outputStream . close ( ) ; }
Build control archive of the deb
812
6
151,168
public static String get ( String url , Map < String , String > customHeaders , Map < String , String > params ) throws URISyntaxException , IOException , HTTPException { LOGGER . log ( Level . INFO , "Sending GET request to the url {0}" , url ) ; URIBuilder uriBuilder = new URIBuilder ( url ) ; if ( params != null && params . size ( ) > 0 ) { for ( Map . Entry < String , String > param : params . entrySet ( ) ) { uriBuilder . setParameter ( param . getKey ( ) , param . getValue ( ) ) ; } } HttpGet httpGet = new HttpGet ( uriBuilder . build ( ) ) ; populateHeaders ( httpGet , customHeaders ) ; HttpClient httpClient = HttpClientBuilder . create ( ) . build ( ) ; HttpResponse httpResponse = httpClient . execute ( httpGet ) ; int statusCode = httpResponse . getStatusLine ( ) . getStatusCode ( ) ; if ( isErrorStatus ( statusCode ) ) { String jsonErrorResponse = EntityUtils . toString ( httpResponse . getEntity ( ) , StandardCharsets . UTF_8 ) ; throw new HTTPException ( statusCode , httpResponse . getStatusLine ( ) . getReasonPhrase ( ) , jsonErrorResponse ) ; } return EntityUtils . toString ( httpResponse . getEntity ( ) , StandardCharsets . UTF_8 ) ; }
Send get request .
318
4
151,169
public static String post ( String url , Map < String , String > customHeaders , Map < String , String > params ) throws IOException , HTTPException { LOGGER . log ( Level . INFO , "Sending POST request to the url {0}" , url ) ; HttpPost httpPost = new HttpPost ( url ) ; populateHeaders ( httpPost , customHeaders ) ; if ( params != null && params . size ( ) > 0 ) { List < NameValuePair > nameValuePairs = new ArrayList <> ( ) ; for ( Map . Entry < String , String > param : params . entrySet ( ) ) { nameValuePairs . add ( new BasicNameValuePair ( param . getKey ( ) , param . getValue ( ) ) ) ; } httpPost . setEntity ( new UrlEncodedFormEntity ( nameValuePairs ) ) ; } HttpClient httpClient = HttpClientBuilder . create ( ) . build ( ) ; HttpResponse httpResponse = httpClient . execute ( httpPost ) ; int statusCode = httpResponse . getStatusLine ( ) . getStatusCode ( ) ; if ( isErrorStatus ( statusCode ) ) { String jsonErrorResponse = EntityUtils . toString ( httpResponse . getEntity ( ) , StandardCharsets . UTF_8 ) ; throw new HTTPException ( statusCode , httpResponse . getStatusLine ( ) . getReasonPhrase ( ) , jsonErrorResponse ) ; } return EntityUtils . toString ( httpResponse . getEntity ( ) , StandardCharsets . UTF_8 ) ; }
Send post request .
342
4
151,170
public T reverse ( ) { String id = getId ( ) ; String REVERSE = "_REVERSE" ; if ( id . endsWith ( REVERSE ) ) { setId ( id . substring ( 0 , id . length ( ) - REVERSE . length ( ) ) ) ; } float start = mStart ; float end = mEnd ; mStart = end ; mEnd = start ; mReverse = ! mReverse ; return self ( ) ; }
Reverse how the transition is applied such that the transition previously performed when progress = start of range is only performed when progress = end of range
104
29
151,171
public T transitFloat ( int propertyId , float ... vals ) { String property = getPropertyName ( propertyId ) ; mHolders . put ( propertyId , PropertyValuesHolder . ofFloat ( property , vals ) ) ; mShadowHolders . put ( propertyId , ShadowValuesHolder . ofFloat ( property , vals ) ) ; return self ( ) ; }
Transits a float propertyId from the start value to the end value .
81
15
151,172
public T transitInt ( int propertyId , int ... vals ) { String property = getPropertyName ( propertyId ) ; mHolders . put ( propertyId , PropertyValuesHolder . ofInt ( property , vals ) ) ; mShadowHolders . put ( propertyId , ShadowValuesHolder . ofInt ( property , vals ) ) ; return self ( ) ; }
Transits a float property from the start value to the end value .
81
14
151,173
@ CheckResult public boolean isCompatible ( AbstractTransition another ) { if ( getClass ( ) . equals ( another . getClass ( ) ) && mTarget == another . mTarget && mReverse == another . mReverse && ( ( mInterpolator == null && another . mInterpolator == null ) || mInterpolator . getClass ( ) . equals ( another . mInterpolator . getClass ( ) ) ) ) { return true ; } return false ; }
Checks to see if another AbstractTransition s states is isCompatible for merging .
106
18
151,174
public boolean merge ( AbstractTransition another ) { if ( ! isCompatible ( another ) ) { return false ; } if ( another . mId != null ) { if ( mId == null ) { mId = another . mId ; } else { StringBuilder sb = new StringBuilder ( mId . length ( ) + another . mId . length ( ) ) ; sb . append ( mId ) ; sb . append ( "_MERGED_" ) ; sb . append ( another . mId ) ; mId = sb . toString ( ) ; } } mUpdateStateAfterUpdateProgress |= another . mUpdateStateAfterUpdateProgress ; mSetupList . addAll ( another . mSetupList ) ; Collections . sort ( mSetupList , new Comparator < S > ( ) { @ Override public int compare ( S lhs , S rhs ) { if ( lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder ) { AbstractTransitionBuilder left = ( AbstractTransitionBuilder ) lhs ; AbstractTransitionBuilder right = ( AbstractTransitionBuilder ) rhs ; float startLeft = left . mReverse ? left . mEnd : left . mStart ; float startRight = right . mReverse ? right . mEnd : right . mStart ; return ( int ) ( ( startRight - startLeft ) * 1000 ) ; } return 0 ; } } ) ; return true ; }
Merge another AbstractTransition s states into this object such that the other AbstractTransition can be discarded .
311
22
151,175
public void removeAllAnimations ( ) { for ( int i = 0 , size = mAnimationList . size ( ) ; i < size ; i ++ ) { mAnimationList . get ( i ) . removeAnimationListener ( mAnimationListener ) ; } mAnimationList . clear ( ) ; }
Stops and clears all transitions
62
6
151,176
@ Override public void stopTransition ( ) { //call listeners so they can perform their actions first, like modifying this adapter's transitions for ( int i = 0 , size = mListenerList . size ( ) ; i < size ; i ++ ) { mListenerList . get ( i ) . onTransitionEnd ( this ) ; } for ( int i = 0 , size = mTransitionList . size ( ) ; i < size ; i ++ ) { mTransitionList . get ( i ) . stopTransition ( ) ; } }
Stops all transitions .
115
5
151,177
public void start ( ) { if ( TransitionConfig . isDebug ( ) ) { getTransitionStateHolder ( ) . start ( ) ; } mLastProgress = Float . MIN_VALUE ; TransitionController transitionController ; for ( int i = 0 , size = mTransitionControls . size ( ) ; i < size ; i ++ ) { transitionController = mTransitionControls . get ( i ) ; if ( mInterpolator != null ) { transitionController . setInterpolator ( mInterpolator ) ; } //required for ViewPager transitions to work if ( mTarget != null ) { transitionController . setTarget ( mTarget ) ; } transitionController . setUpdateStateAfterUpdateProgress ( mUpdateStateAfterUpdateProgress ) ; transitionController . start ( ) ; } }
Starts the transition
167
4
151,178
public void end ( ) { if ( TransitionConfig . isPrintDebug ( ) ) { getTransitionStateHolder ( ) . end ( ) ; getTransitionStateHolder ( ) . print ( ) ; } for ( int i = 0 , size = mTransitionControls . size ( ) ; i < size ; i ++ ) { mTransitionControls . get ( i ) . end ( ) ; } }
Ends the transition
89
4
151,179
public void reverse ( ) { for ( int i = 0 , size = mTransitionControls . size ( ) ; i < size ; i ++ ) { mTransitionControls . get ( i ) . reverse ( ) ; } }
Reverses all the TransitionControllers managed by this TransitionManager
50
13
151,180
private LoginContext getClientLoginContext ( ) throws LoginException { Configuration config = new Configuration ( ) { @ Override public AppConfigurationEntry [ ] getAppConfigurationEntry ( String name ) { Map < String , String > options = new HashMap < String , String > ( ) ; options . put ( "multi-threaded" , "true" ) ; options . put ( "restore-login-identity" , "true" ) ; AppConfigurationEntry clmEntry = new AppConfigurationEntry ( ClientLoginModule . class . getName ( ) , LoginModuleControlFlag . REQUIRED , options ) ; return new AppConfigurationEntry [ ] { clmEntry } ; } } ; return getLoginContext ( config ) ; }
Provides a RunAs client login context
153
8
151,181
public static void mainInternal ( String [ ] args ) throws Exception { Options options = new Options ( ) ; CmdLineParser parser = new CmdLineParser ( options ) ; try { parser . parseArgument ( args ) ; } catch ( CmdLineException e ) { helpScreen ( parser ) ; return ; } try { List < String > configs = new ArrayList <> ( ) ; if ( options . configs != null ) { configs . addAll ( Arrays . asList ( options . configs . split ( "," ) ) ) ; } ConfigSupport . applyConfigChange ( ConfigSupport . getJBossHome ( ) , configs , options . enable ) ; } catch ( ConfigException ex ) { ConfigLogger . error ( ex ) ; throw ex ; } catch ( Throwable th ) { ConfigLogger . error ( th ) ; throw th ; } }
Entry point with no system exit
187
6
151,182
public static < T > T assertNull ( T value , String message ) { if ( value != null ) throw new IllegalStateException ( message ) ; return value ; }
Throws an IllegalStateException when the given value is not null .
35
14
151,183
public static < T > T assertNotNull ( T value , String message ) { if ( value == null ) throw new IllegalStateException ( message ) ; return value ; }
Throws an IllegalStateException when the given value is null .
36
13
151,184
public static Boolean assertTrue ( Boolean value , String message ) { if ( ! Boolean . valueOf ( value ) ) throw new IllegalStateException ( message ) ; return value ; }
Throws an IllegalStateException when the given value is not true .
37
14
151,185
public static Boolean assertFalse ( Boolean value , String message ) { if ( Boolean . valueOf ( value ) ) throw new IllegalStateException ( message ) ; return value ; }
Throws an IllegalStateException when the given value is not false .
36
14
151,186
public static < T > T assertNotNull ( T value , String name ) { if ( value == null ) throw new IllegalArgumentException ( "Null " + name ) ; return value ; }
Throws an IllegalArgumentException when the given value is null .
41
14
151,187
public static Boolean assertTrue ( Boolean value , String message ) { if ( ! Boolean . valueOf ( value ) ) throw new IllegalArgumentException ( message ) ; return value ; }
Throws an IllegalArgumentException when the given value is not true .
38
15
151,188
public static Boolean assertFalse ( Boolean value , String message ) { if ( Boolean . valueOf ( value ) ) throw new IllegalArgumentException ( message ) ; return value ; }
Throws an IllegalArgumentException when the given value is not false .
37
15
151,189
public void retrieveEngine ( ) throws GeneralSecurityException , IOException { if ( serverEngineFactory == null ) { return ; } engine = serverEngineFactory . retrieveHTTPServerEngine ( nurl . getPort ( ) ) ; if ( engine == null ) { engine = serverEngineFactory . getHTTPServerEngine ( nurl . getHost ( ) , nurl . getPort ( ) , nurl . getProtocol ( ) ) ; } assert engine != null ; TLSServerParameters serverParameters = engine . getTlsServerParameters ( ) ; if ( serverParameters != null && serverParameters . getCertConstraints ( ) != null ) { CertificateConstraintsType constraints = serverParameters . getCertConstraints ( ) ; if ( constraints != null ) { certConstraints = CertConstraintsJaxBUtils . createCertConstraints ( constraints ) ; } } // When configuring for "http", however, it is still possible that // Spring configuration has configured the port for https. if ( ! nurl . getProtocol ( ) . equals ( engine . getProtocol ( ) ) ) { throw new IllegalStateException ( "Port " + engine . getPort ( ) + " is configured with wrong protocol \"" + engine . getProtocol ( ) + "\" for \"" + nurl + "\"" ) ; } }
Post - configure retreival of server engine .
286
10
151,190
public void finalizeConfig ( ) { assert ! configFinalized ; try { retrieveEngine ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } configFinalized = true ; }
This method is used to finalize the configuration after the configuration items have been set .
51
17
151,191
public File getStylesheetPath ( ) { String path = System . getProperty ( STYLESHEET_KEY ) ; return path == null ? null : new File ( path ) ; }
If a custom CSS file has been specified returns the path . Otherwise returns null .
41
16
151,192
private Collection < TestClassResults > flattenResults ( List < ISuite > suites ) { Map < IClass , TestClassResults > flattenedResults = new HashMap < IClass , TestClassResults > ( ) ; for ( ISuite suite : suites ) { for ( ISuiteResult suiteResult : suite . getResults ( ) . values ( ) ) { // Failed and skipped configuration methods are treated as test failures. organiseByClass ( suiteResult . getTestContext ( ) . getFailedConfigurations ( ) . getAllResults ( ) , flattenedResults ) ; organiseByClass ( suiteResult . getTestContext ( ) . getSkippedConfigurations ( ) . getAllResults ( ) , flattenedResults ) ; // Successful configuration methods are not included. organiseByClass ( suiteResult . getTestContext ( ) . getFailedTests ( ) . getAllResults ( ) , flattenedResults ) ; organiseByClass ( suiteResult . getTestContext ( ) . getSkippedTests ( ) . getAllResults ( ) , flattenedResults ) ; organiseByClass ( suiteResult . getTestContext ( ) . getPassedTests ( ) . getAllResults ( ) , flattenedResults ) ; } } return flattenedResults . values ( ) ; }
Flatten a list of test suite results into a collection of results grouped by test class . This method basically strips away the TestNG way of organising tests and arranges the results by test class .
264
39
151,193
private TestClassResults getResultsForClass ( Map < IClass , TestClassResults > flattenedResults , ITestResult testResult ) { TestClassResults resultsForClass = flattenedResults . get ( testResult . getTestClass ( ) ) ; if ( resultsForClass == null ) { resultsForClass = new TestClassResults ( testResult . getTestClass ( ) ) ; flattenedResults . put ( testResult . getTestClass ( ) , resultsForClass ) ; } return resultsForClass ; }
Look - up the results data for a particular test class .
104
12
151,194
protected VelocityContext createContext ( ) { VelocityContext context = new VelocityContext ( ) ; context . put ( META_KEY , META ) ; context . put ( UTILS_KEY , UTILS ) ; context . put ( MESSAGES_KEY , MESSAGES ) ; return context ; }
Helper method that creates a Velocity context and initialises it with a reference to the ReportNG utils report metadata and localised messages .
65
27
151,195
protected void generateFile ( File file , String templateName , VelocityContext context ) throws Exception { Writer writer = new BufferedWriter ( new FileWriter ( file ) ) ; try { Velocity . mergeTemplate ( classpathPrefix + templateName , ENCODING , context , writer ) ; writer . flush ( ) ; } finally { writer . close ( ) ; } }
Generate the specified output file by merging the specified Velocity template with the supplied context .
77
17
151,196
protected void copyClasspathResource ( File outputDirectory , String resourceName , String targetFileName ) throws IOException { String resourcePath = classpathPrefix + resourceName ; InputStream resourceStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resourcePath ) ; copyStream ( outputDirectory , resourceStream , targetFileName ) ; }
Copy a single named resource from the classpath to the output directory .
76
14
151,197
protected void copyFile ( File outputDirectory , File sourceFile , String targetFileName ) throws IOException { InputStream fileStream = new FileInputStream ( sourceFile ) ; try { copyStream ( outputDirectory , fileStream , targetFileName ) ; } finally { fileStream . close ( ) ; } }
Copy a single named file to the output directory .
64
10
151,198
protected void copyStream ( File outputDirectory , InputStream stream , String targetFileName ) throws IOException { File resourceFile = new File ( outputDirectory , targetFileName ) ; BufferedReader reader = null ; Writer writer = null ; try { reader = new BufferedReader ( new InputStreamReader ( stream , ENCODING ) ) ; writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( resourceFile ) , ENCODING ) ) ; String line = reader . readLine ( ) ; while ( line != null ) { writer . write ( line ) ; writer . write ( ' ' ) ; line = reader . readLine ( ) ; } writer . flush ( ) ; } finally { if ( reader != null ) { reader . close ( ) ; } if ( writer != null ) { writer . close ( ) ; } } }
Helper method to copy the contents of a stream to a file .
181
13
151,199
protected void removeEmptyDirectories ( File outputDirectory ) { if ( outputDirectory . exists ( ) ) { for ( File file : outputDirectory . listFiles ( new EmptyDirectoryFilter ( ) ) ) { file . delete ( ) ; } } }
Deletes any empty directories under the output directory . These directories are created by TestNG for its own reports regardless of whether those reports are generated . If you are using the default TestNG reports as well as ReportNG these directories will not be empty and will be retained . Otherwise they will be removed .
51
60