signature:
public class XMLEncoder { /** * { @ inheritDoc } */
protected CoderResult encodeArrays ( CharBuffer input , CharBuffer output , boolean endOfInput ) { } }

implementation:
final char [ ] in = input . array ( ) ; final char [ ] out = output . array ( ) ; int i = input . arrayOffset ( ) + input . position ( ) ; final int n = input . arrayOffset ( ) + input . limit ( ) ; int j = output . arrayOffset ( ) + output . position ( ) ; final int m = output . arrayOffset ( ) + output . limit ( ) ; for ( ; i < n ; ++ i ) { final char ch = in [ i ] ; if ( ch < Unicode . DEL ) { if ( ch > '>' || ( ( _validMask & ( 1L << ch ) ) != 0 ) ) { // Common case ( ' > ' . . ' ~ ' ) reached in two branches
if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = ch ; } else { switch ( ch ) { case '&' : if ( j + AMP_LENGTH > m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = '&' ; out [ j ++ ] = 'a' ; out [ j ++ ] = 'm' ; out [ j ++ ] = 'p' ; out [ j ++ ] = ';' ; break ; case '<' : if ( j + LT_LENGTH > m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = '&' ; out [ j ++ ] = 'l' ; out [ j ++ ] = 't' ; out [ j ++ ] = ';' ; break ; case '>' : if ( j + GT_LENGTH > m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = '&' ; out [ j ++ ] = 'g' ; out [ j ++ ] = 't' ; out [ j ++ ] = ';' ; break ; case '\'' : // & apos ; is valid in XML , but not in HTML , and numeric code is shorter
if ( j + APOS_LENGTH > m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = '&' ; out [ j ++ ] = '#' ; out [ j ++ ] = '3' ; out [ j ++ ] = '9' ; out [ j ++ ] = ';' ; break ; case '\"' : // & quot ; is valid in XML and HTML , but numeric code is shorter
if ( j + QUOT_LENGTH > m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = '&' ; out [ j ++ ] = '#' ; out [ j ++ ] = '3' ; out [ j ++ ] = '4' ; out [ j ++ ] = ';' ; break ; default : // invalid character
if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; break ; } } } else if ( ch < Character . MIN_HIGH_SURROGATE ) { if ( j >= m ) { return overflow ( input , i , output , j ) ; } if ( ch > Unicode . MAX_C1_CTRL_CHAR || ch == Unicode . NEL ) { out [ j ++ ] = ch ; } else { // C1 control code
out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; } } else if ( ch <= Character . MAX_HIGH_SURROGATE ) { if ( i + 1 < n ) { if ( Character . isLowSurrogate ( in [ i + 1 ] ) ) { int cp = Character . toCodePoint ( ch , in [ i + 1 ] ) ; if ( Unicode . isNonCharacter ( cp ) ) { // noncharacter
if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; ++ i ; } else { if ( j + 1 >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = ch ; out [ j ++ ] = in [ ++ i ] ; } } else { // high without low
if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; } } else if ( endOfInput ) { // end of input , high without low = invalid
if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; } else { break ; } } else if ( // low surrogate without preceding high surrogate
ch <= Character . MAX_LOW_SURROGATE // or non - characters
|| ch > '\ufffd' || ( '\ufdd0' <= ch && ch <= '\ufdef' ) ) { if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = INVALID_CHARACTER_REPLACEMENT ; } else { if ( j >= m ) { return overflow ( input , i , output , j ) ; } out [ j ++ ] = ch ; } } return underflow ( input , i , output , j ) ;


signature:
public class Encode { /** * See { @ link # forHtmlUnquotedAttribute ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forHtmlUnquotedAttribute ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . HTML_UNQUOTED_ATTRIBUTE_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forCssString ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forCssString ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . CSS_STRING_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forCssUrl ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forCssUrl ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . CSS_URL_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forUri ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer
 * @ deprecated There is never a need to encode a complete URI with this form of encoding . */
@ Deprecated public static void forUri ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . URI_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forUriComponent ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forUriComponent ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . URI_COMPONENT_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forXml ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forXml ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . XML_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forXmlContent ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forXmlContent ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . XML_CONTENT_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forXmlAttribute ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forXmlAttribute ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . XML_ATTRIBUTE_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forXmlComment ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forXmlComment ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . XML_COMMENT_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forCDATA ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forCDATA ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . CDATA_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forJava ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forJava ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . JAVA_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forJavaScript ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forJavaScript ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . JAVASCRIPT_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forJavaScriptAttribute ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forJavaScriptAttribute ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . JAVASCRIPT_ATTRIBUTE_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forJavaScriptBlock ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forJavaScriptBlock ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . JAVASCRIPT_BLOCK_ENCODER , out , input ) ;


signature:
public class Encode { /** * See { @ link # forJavaScriptSource ( String ) } for description of encoding . This
 * version writes directly to a Writer without an intervening string .
 * @ param out where to write encoded output
 * @ param input the input string to encode
 * @ throws IOException if thrown by writer */
public static void forJavaScriptSource ( Writer out , String input ) throws IOException { } }

implementation: encode ( Encoders . JAVASCRIPT_SOURCE_ENCODER , out , input ) ;


signature:
public class Encode { /** * Core encoding loop shared by public methods . It first uses the
 * encoder to scan the input for characters that need encoding . If
 * no characters require encoding , the input string is returned .
 * Otherwise a buffer is used to encode the remainder
 * of the input .
 * @ param encoder the encoder to use
 * @ param str the string to encode
 * @ return the input string encoded with the provided encoder . */
static String encode ( Encoder encoder , String str ) { } }

implementation:
if ( str == null ) { // consistent with String . valueOf ( . . . ) use " null " for null .
str = "null" ; } // quick pass - - see if we need to actually encode anything , if not
// return the value unchanged .
final int n = str . length ( ) ; int j = encoder . firstEncodedOffset ( str , 0 , n ) ; if ( j == n ) { return str ; } // otherwise , we need to encode . We use a buffer to avoid
// excessive memory allocation for these calls . Note : this means that
// an encoder implementation must NEVER call this method internally .
return new Buffer ( ) . encode ( encoder , str , j ) ;


signature:
public class Encode { /** * Core encoding loop shared by public methods . It first uses the
 * encoder to scan the input for characters that need encoding . If no
 * characters require encoding , the input string is written directly to
 * the writer . Otherwise a buffer is used to encode the
 * remainder of the input to the buffers . This version saves a wrapping
 * in an String .
 * @ param encoder the encoder to use
 * @ param out the writer for the encoded output
 * @ param str the string to encode
 * @ throws IOException if thrown by the writer */
static void encode ( Encoder encoder , Writer out , String str ) throws IOException { } }

implementation:
if ( str == null ) { // consistent with String . valueOf ( . . . ) use " null " for null .
str = "null" ; } // quick pass - - see if we need to actually encode anything , if not
// return the value unchanged .
final int n = str . length ( ) ; int j = encoder . firstEncodedOffset ( str , 0 , n ) ; if ( j == n ) { out . write ( str ) ; return ; } // otherwise , we need to encode . We use a buffer to avoid
// excessive memory allocation for these calls . Note : this means that
// an encoder implementation must NEVER call this method internally .
new Buffer ( ) . encode ( encoder , out , str , j ) ;


signature:
public class Encoders { /** * Internal method to setup and map encoder singletons .
 * @ param name - - name of the encoder ( one of the constants above )
 * @ param encoder - - the encoder singleton instance
 * @ param < T > the encoder type
 * @ return the encoder argument . */
private static < T extends Encoder > T map ( String name , T encoder ) { } }

implementation: Encoder old = ENCODERS_MAP . put ( name , encoder ) ; assert old == null ; return encoder ;


signature:
public class Encoders { /** * Returns a new instance of an Encoder for the specified context . The
 * returned instance is thread - safe .
 * @ param contextName the context name ( one of the String constants defined
 * in this class )
 * @ return an encoder for the specified context .
 * @ throws NullPointerException if { @ code contextName } is null
 * @ throws UnsupportedContextException if { @ code contextName } is not
 * recognized . */
public static Encoder forName ( String contextName ) throws NullPointerException , UnsupportedContextException { } }

implementation: if ( contextName == null ) { throw new NullPointerException ( ) ; } Encoder encoder = ENCODERS_MAP . get ( contextName ) ; if ( encoder == null ) { throw new UnsupportedContextException ( contextName ) ; } return encoder ;


signature:
public class HTMLEncoder { /** * Appends a source array verbatim to the output array . Caller must insure
 * there is enough space in the array for the output .
 * @ param src the characters to copy
 * @ param out the output buffer
 * @ param j the offset where to write in the output buffer
 * @ return { @ code j + src . length } */
static int append ( char [ ] src , char [ ] out , int j ) { } }

implementation: System . arraycopy ( src , 0 , out , j , src . length ) ; return j + src . length ;


signature:
public class HTMLEncoder { /** * Appends the numerically encoded version of { @ code codePoint } to the
 * output buffer . Caller must insure there is enough space for the output .
 * @ param codePoint the character to encode
 * @ param out the output buffer
 * @ param j the offset where to write in the output buffer
 * @ return { @ code j } + the encoded length . */
static int encode ( int codePoint , char [ ] out , int j ) { } }


signature:
public class ChainedEncoder { /** * Encodes an input string to an output string .
 * @ param str the string to encode
 * @ return the encoded string . */
public String encode ( String str ) { } }

implementation:
if ( str == null ) { str = "null" ; } int n = str . length ( ) ; int j = _first . firstEncodedOffset ( str , 0 , n ) ; if ( j == n ) { // string is unchanged after encoding with the first encoder
return Encode . encode ( _last , str ) ; } final int remaining = n - j ; final int m = j + _first . maxEncodedLength ( n ) ; CharBuffer input = CharBuffer . allocate ( m ) ; str . getChars ( 0 , j , input . array ( ) , 0 ) ; str . getChars ( j , n , input . array ( ) , m - remaining ) ; input . limit ( m ) . position ( m - remaining ) ; CharBuffer tmp = input . duplicate ( ) ; tmp . position ( j ) ; CoderResult cr = _first . encode ( input , tmp , true ) ; assert cr . isUnderflow ( ) : "maxEncodedLength was incorrect" ; CharBuffer output = CharBuffer . allocate ( _last . maxEncodedLength ( tmp . position ( ) ) ) ; tmp . flip ( ) ; cr = _last . encode ( tmp , output , true ) ; assert cr . isUnderflow ( ) : "maxEncodedLength was incorrect" ; return new String ( output . array ( ) , 0 , output . position ( ) ) ;


signature: public class ChainedEncoder { @ Override public CoderResult encode ( CharBuffer input , CharBuffer output , boolean endOfInput ) { } }

implementation:
for ( ; ; ) { CoderResult cr1 = _first . encode ( input , _buffer , endOfInput ) ; _buffer . flip ( ) ; CoderResult cr2 = _last . encode ( _buffer , output , endOfInput && cr1 . isUnderflow ( ) ) ; _buffer . compact ( ) ; if ( cr2 . isOverflow ( ) ) { // no more room in output , even if we still have buffered input .
return cr2 ; } if ( cr1 . isUnderflow ( ) ) { // we ' ve consumed everything from input
return cr2 ; } }


signature:
public class EncodedWriter { /** * Flushes the contents of the buffer to the writer and resets the buffer to make room for more input .
 * @ throws IOException thrown by the wrapped output . */
private void flushBufferToWriter ( ) throws IOException { } }

implementation: _out . write ( _buffer . array ( ) , 0 , _buffer . position ( ) ) ; _buffer . clear ( ) ;


signature:
public class EncodedWriter { /** * Flushes the left - over buffer . Characters from the input buffer are used to add more data to the _ leftOverBuffer in order to
 * make the flush happen .
 * @ param input the next input to encode , or null if at end of file .
 * @ throws IOException from the underlying writer . */
private void flushLeftOver ( CharBuffer input ) throws IOException { } }

implementation: if ( ! _hasLeftOver ) { return ; } for ( ; ; ) { if ( input != null && input . hasRemaining ( ) ) { _leftOverBuffer . put ( input . get ( ) ) ; } _leftOverBuffer . flip ( ) ; CoderResult cr = _encoder . encode ( _leftOverBuffer , _buffer , input == null ) ; if ( cr . isUnderflow ( ) ) { if ( _leftOverBuffer . hasRemaining ( ) ) { _leftOverBuffer . compact ( ) ; } else { break ; } } if ( cr . isOverflow ( ) ) { flushBufferToWriter ( ) ; } } _hasLeftOver = false ; _leftOverBuffer . clear ( ) ;


signature:
public class ReactiveSensorFilter { /** * Predicate , which can be used in filter ( . . . ) method from RxJava
 * to filter all events in which sensor value has changed
 * @ return BiPredicate < ReactiveSensorEvent , Boolean > predicate indicating if sensor value has
 * changed */
public static Predicate < ReactiveSensorEvent > filterSensorChanged ( ) { } }

implementation: return new Predicate < ReactiveSensorEvent > ( ) { @ Override public boolean test ( ReactiveSensorEvent event ) throws Exception { return event . isSensorChanged ( ) ; } } ;


signature:
public class ReactiveSensorFilter { /** * Predicate , which can be used in filter ( . . . ) method from RxJava
 * to filter all events in which accuracy value has changed
 * @ return BiPredicate < ReactiveSensorEvent , Boolean > predicate indicating if accuracy value has
 * changed */
public static Predicate < ReactiveSensorEvent > filterAccuracyChanged ( ) { } }

implementation: return new Predicate < ReactiveSensorEvent > ( ) { @ Override public boolean test ( ReactiveSensorEvent event ) throws Exception { return event . isAccuracyChanged ( ) ; } } ;


signature:
public class ReactiveSensors { /** * Returns RxJava Observable , which allows to monitor hardware sensors
 * as a stream of ReactiveSensorEvent object with defined sampling period
 * @ param sensorType sensor type from Sensor class from Android SDK
 * @ param samplingPeriodInUs sampling period in microseconds ,
 * @ param handler the Handler the sensor events will be delivered to , use default if it is null
 * you can use predefined values from SensorManager class with prefix SENSOR _ DELAY
 * @ param strategy BackpressureStrategy for RxJava 2 Flowable type
 * @ return RxJava Observable with ReactiveSensorEvent */
public Flowable < ReactiveSensorEvent > observeSensor ( int sensorType , final int samplingPeriodInUs , final Handler handler , final BackpressureStrategy strategy ) { } }

implementation: if ( ! hasSensor ( sensorType ) ) { String format = "Sensor with id = %d is not available on this device" ; String message = String . format ( Locale . getDefault ( ) , format , sensorType ) ; return Flowable . error ( new SensorNotFoundException ( message ) ) ; } final Sensor sensor = sensorManager . getDefaultSensor ( sensorType ) ; final SensorEventListenerWrapper wrapper = new SensorEventListenerWrapper ( ) ; final SensorEventListener listener = wrapper . create ( ) ; return Flowable . create ( new FlowableOnSubscribe < ReactiveSensorEvent > ( ) { @ Override public void subscribe ( final FlowableEmitter < ReactiveSensorEvent > emitter ) throws Exception { wrapper . setEmitter ( emitter ) ; if ( handler == null ) { sensorManager . registerListener ( listener , sensor , samplingPeriodInUs ) ; } else { sensorManager . registerListener ( listener , sensor , samplingPeriodInUs , handler ) ; } } } , strategy ) . doOnCancel ( new Action ( ) { @ Override public void run ( ) throws Exception { sensorManager . unregisterListener ( listener ) ; } } ) ;


signature:
public class ResultDeserializer { /** * Get the text from child node with the given name . Returns null if child node does not exist .
 * @ param node Node to search
 * @ param propertyName Name of the child node
 * @ return The text value of the child node */
private String getText ( JsonNode node , String propertyName ) { } }

implementation: JsonNode childNode = node . get ( propertyName ) ; if ( childNode == null ) { return null ; } return childNode . asText ( ) ;


signature:
public class QueryExecutor { /** * Execute the given query on the specified sonar server .
 * @ param query The query specifying the project and version of the build
 * @ return Result fetched from sonar
 * @ throws SonarBreakException If there is an issues communicating with sonar
 * @ throws IOException If the url is invalid */
public Result execute ( Query query ) throws SonarBreakException , IOException { } }

implementation: URL queryURL = buildURL ( sonarURL , query ) ; log . debug ( "Built a sonar query url of: " + queryURL . toString ( ) ) ; if ( ! isURLAvailable ( sonarURL , SONAR_CONNECTION_RETRIES ) ) { throw new SonarBreakException ( String . format ( "Unable to get a valid response after %d tries" , SONAR_CONNECTION_RETRIES ) ) ; } return fetchSonarStatusWithRetries ( queryURL , query . getVersion ( ) ) ;


signature:
public class QueryExecutor { /** * Creates a url for the specified quality gate query
 * @ param sonarURL The sonar server we will be querying
 * @ param query Holds details on the query we want to make
 * @ return A URL object representing the query
 * @ throws MalformedURLException If the sonar url is not valid
 * @ throws IllegalArgumentException If the sonar key is not valid */
protected static URL buildURL ( URL sonarURL , Query query ) throws MalformedURLException , IllegalArgumentException { } }

implementation: if ( query . getSonarKey ( ) == null || query . getSonarKey ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "No resource specified in the Query" ) ; } String sonarPathWithResource = String . format ( SONAR_FORMAT_PATH , query . getSonarKey ( ) ) ; return new URL ( sonarURL , sonarPathWithResource ) ;


signature:
public class QueryExecutor { /** * Get the status from sonar for the currently executing build . This waits for sonar to complete its processing
 * before returning the results .
 * @ param queryURL The sonar URL to get the results from
 * @ param version The current project version number
 * @ return Matching result object for this build
 * @ throws IOException
 * @ throws SonarBreakException */
private Result fetchSonarStatusWithRetries ( URL queryURL , String version ) throws IOException , SonarBreakException { } }

implementation:
DateTime oneMinuteAgo = DateTime . now ( ) . minusSeconds ( sonarLookBackSeconds ) ; DateTime waitUntil = DateTime . now ( ) . plusSeconds ( waitForProcessingSeconds ) ; do { // If this is the first time the job is running on sonar the URL might not be available . Return null and wait .
if ( isURLAvailable ( queryURL , 1 ) ) { Result result = fetchSonarStatus ( queryURL ) ; if ( result . getVersion ( ) . equals ( version ) && result . getDatetime ( ) . isAfter ( oneMinuteAgo ) ) { log . debug ( "Found a sonar job run that matches version and in the correct time frame" ) ; return result ; } String message = String . format ( "Sleeping while waiting for sonar to process job.  Target Version: %s.  " + "Sonar reporting Version: %s.  Looking back until: %s  Last result time: %s" , version , result . getVersion ( ) , oneMinuteAgo . toString ( ) , result . getDatetime ( ) . toString ( ) ) ; log . debug ( message ) ; } else { log . debug ( String . format ( "Query url not available yet: %s" , queryURL ) ) ; } try { Thread . sleep ( SONAR_PROCESSING_WAIT_TIME ) ; } catch ( InterruptedException e ) { // Do nothing
} } while ( ! waitUntil . isBeforeNow ( ) ) ; String message = String . format ( "Timed out while waiting for Sonar.  Waited %d seconds.  This time can be extended " + "using the \"waitForProcessingSeconds\" configuration parameter." , waitForProcessingSeconds ) ; throw new SonarBreakException ( message ) ;


signature:
public class QueryExecutor { /** * Get the status of a build project from sonar . This returns the current status that sonar has and does not
 * do any checking to ensure it matches the current project
 * @ param queryURL The sonar URL to hit to get the status
 * @ return The sonar response include quality gate status
 * @ throws IOException
 * @ throws SonarBreakException */
private Result fetchSonarStatus ( URL queryURL ) throws IOException , SonarBreakException { } }

implementation: InputStream in = null ; try { URLConnection connection = queryURL . openConnection ( ) ; connection . setRequestProperty ( "Accept" , "application/json" ) ; in = connection . getInputStream ( ) ; String response = IOUtils . toString ( in ) ; return parseResponse ( response ) ; } finally { IOUtils . closeQuietly ( in ) ; }


signature:
public class QueryExecutor { /** * Pings a HTTP URL . This effectively sends a HEAD request and returns < code > true < / code > if the response code is in
 * the 200-399 range .
 * @ param url The HTTP URL to be pinged .
 * @ param retryCount How many times to check for sonar before giving up
 * @ return < code > true < / code > if the given HTTP URL has returned response code 200-399 on a HEAD request ,
 * otherwise < code > false < / code > .
 * @ throws IOException If the sonar server is not available */
protected boolean isURLAvailable ( URL url , int retryCount ) throws IOException { } }

implementation:
boolean serviceFound = false ; for ( int i = 0 ; i < retryCount ; i ++ ) { HttpURLConnection connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setRequestMethod ( "HEAD" ) ; int responseCode = connection . getResponseCode ( ) ; if ( 200 <= responseCode && responseCode <= 399 ) { log . debug ( String . format ( "Got a valid response of %d from %s" , responseCode , url ) ) ; serviceFound = true ; break ; } else if ( i + 1 < retryCount ) { // only sleep if not on last iteration
try { log . debug ( "Sleeping while waiting for sonar to become available" ) ; Thread . sleep ( 2000 ) ; } catch ( InterruptedException e ) { // do nothing
} } } return serviceFound ;


signature:
public class QueryExecutor { /** * Parses the string response from sonar into POJOs .
 * @ param response The json response from the sonar server .
 * @ return Object representing the Sonar response
 * @ throws SonarBreakException Thrown if the response is not JSON or it does not contain quality gate data . */
protected static Result parseResponse ( String response ) throws SonarBreakException { } }

implementation: ObjectMapper mapper = new ObjectMapper ( ) ; final DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss" ) ; mapper . setDateFormat ( df ) ; List < Result > results ; try { results = mapper . readValue ( response , new TypeReference < List < Result > > ( ) { } ) ; } catch ( IOException e ) { throw new SonarBreakException ( "Unable to parse the json into a List of QualityGateResults.  Json is: " + response , e ) ; } if ( results == null || results . size ( ) != 1 ) { throw new SonarBreakException ( "Unable to deserialize JSON response: " + response ) ; } return results . get ( 0 ) ;


signature:
public class ScmUrlValidator { /** * Returns a String with username .
 * ' @ ' character or whatever indicator of it being username is included in the returned value
 * @ param url url to extract username from
 * @ return username if username is specified in the url , null otherwise */
private static String getUsername ( String url ) { } }

implementation: int atIndex = url . lastIndexOf ( USERNAME_INDICATOR ) ; if ( atIndex < 0 ) { return null ; } String username = url . substring ( 0 , atIndex + 1 ) ; int slashIndex = username . lastIndexOf ( '/' ) ; if ( slashIndex > 0 ) { username = username . substring ( slashIndex + 1 ) ; } return username ;


signature:
public class IndyRepositorySession { /** * Retrieve tracking report from repository manager . Add each tracked download to the dependencies of the build result . Add
 * each tracked upload to the built artifacts of the build result . Promote uploaded artifacts to the product - level storage .
 * Finally , clear the tracking report , and delete the hosted repository + group associated with the completed build . */
@ Override public RepositoryManagerResult extractBuildArtifacts ( ) throws RepositoryManagerException { } }

implementation:
TrackedContentDTO report ; try { IndyFoloAdminClientModule foloAdmin = indy . module ( IndyFoloAdminClientModule . class ) ; boolean sealed = foloAdmin . sealTrackingRecord ( buildContentId ) ; if ( ! sealed ) { throw new RepositoryManagerException ( "Failed to seal content-tracking record for: %s." , buildContentId ) ; } report = foloAdmin . getTrackingReport ( buildContentId ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve tracking report for: %s. Reason: %s" , e , buildContentId , e . getMessage ( ) ) ; } if ( report == null ) { throw new RepositoryManagerException ( "Failed to retrieve tracking report for: %s." , buildContentId ) ; } Comparator < Artifact > comp = ( one , two ) -> one . getIdentifier ( ) . compareTo ( two . getIdentifier ( ) ) ; List < Artifact > uploads = processUploads ( report ) ; Collections . sort ( uploads , comp ) ; List < Artifact > downloads = processDownloads ( report ) ; Collections . sort ( downloads , comp ) ; try { StoreKey key = new StoreKey ( packageType , StoreType . group , buildContentId ) ; serviceAccountIndy . stores ( ) . delete ( key , "[Post-Build] Removing build aggregation group: " + buildContentId ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy stores module. Reason: %s" , e , e . getMessage ( ) ) ; } Logger logger = LoggerFactory . getLogger ( getClass ( ) ) ; logger . info ( "Returning built artifacts / dependencies:\nUploads:\n  {}\n\nDownloads:\n  {}\n\n" , StringUtils . join ( uploads , "\n  " ) , StringUtils . join ( downloads , "\n  " ) ) ; String log = "" ; CompletionStatus status = CompletionStatus . SUCCESS ; try { promoteToBuildContentSet ( uploads ) ; } catch ( RepositoryManagerException rme ) { status = CompletionStatus . FAILED ; log = rme . getMessage ( ) ; logger . error ( "Promotion validation error(s): \n" + log ) ; userLog . error ( "Artifact promotion failed. Promotion validation error(s): {}" , log ) ; // prevent saving artifacts and dependencies to a failed build
downloads = Collections . emptyList ( ) ; uploads = Collections . emptyList ( ) ; } return new IndyRepositoryManagerResult ( uploads , downloads , buildContentId , log , status ) ;


signature:
public class IndyRepositorySession { /** * Promote all build dependencies NOT ALREADY CAPTURED to the hosted repository holding store for the shared imports and
 * return dependency artifacts meta data .
 * @ param report The tracking report that contains info about artifacts downloaded by the build
 * @ return List of dependency artifacts meta data
 * @ throws RepositoryManagerException In case of a client API transport error or an error during promotion of artifacts */
private List < Artifact > processDownloads ( TrackedContentDTO report ) throws RepositoryManagerException { } }

implementation:
Logger logger = LoggerFactory . getLogger ( getClass ( ) ) ; IndyContentClientModule content ; try { content = indy . content ( ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy content module. Reason: %s" , e , e . getMessage ( ) ) ; } List < Artifact > deps = new ArrayList < > ( ) ; Set < TrackedContentEntryDTO > downloads = report . getDownloads ( ) ; if ( downloads != null ) { Map < StoreKey , Map < StoreKey , Set < String > > > toPromote = new HashMap < > ( ) ; Map < String , StoreKey > promotionTargets = new HashMap < > ( ) ; for ( TrackedContentEntryDTO download : downloads ) { String path = download . getPath ( ) ; StoreKey source = download . getStoreKey ( ) ; String packageType = source . getPackageType ( ) ; if ( ignoreContent ( packageType , path ) ) { logger . debug ( "Ignoring download (matched in ignored-suffixes): {} (From: {})" , download . getPath ( ) , source ) ; continue ; } // If the entry is from a hosted repository ( also shared - imports ) , it shouldn ' t be auto - promoted .
// New binary imports will be coming from a remote repository . . .
if ( isExternalOrigin ( source ) ) { StoreKey target = null ; Map < StoreKey , Set < String > > sources = null ; Set < String > paths = null ; // this has not been captured , so promote it .
switch ( packageType ) { case MAVEN_PKG_KEY : case NPM_PKG_KEY : target = getPromotionTarget ( packageType , promotionTargets ) ; sources = toPromote . computeIfAbsent ( target , t -> new HashMap < > ( ) ) ; paths = sources . computeIfAbsent ( source , s -> new HashSet < > ( ) ) ; paths . add ( download . getPath ( ) ) ; if ( MAVEN_PKG_KEY . equals ( packageType ) ) { paths . add ( download . getPath ( ) + ".md5" ) ; paths . add ( download . getPath ( ) + ".sha1" ) ; } break ; case GENERIC_PKG_KEY : String remoteName = source . getName ( ) ; String hostedName ; if ( remoteName . startsWith ( "r-" ) ) { hostedName = "h-" + remoteName . substring ( 2 ) ; } else { logger . warn ( "Unexpected generic http remote repo name {}. Using it for hosted repo " + "without change, but it probably doesn't exist." , remoteName ) ; hostedName = remoteName ; } target = new StoreKey ( source . getPackageType ( ) , StoreType . hosted , hostedName ) ; sources = toPromote . computeIfAbsent ( target , t -> new HashMap < > ( ) ) ; paths = sources . computeIfAbsent ( source , s -> new HashSet < > ( ) ) ; paths . add ( download . getPath ( ) ) ; break ; default : // do not promote anything else anywhere
break ; } } String identifier = computeIdentifier ( download ) ; logger . info ( "Recording download: {}" , identifier ) ; String originUrl = download . getOriginUrl ( ) ; if ( originUrl == null ) { // this is from a hosted repository , either shared - imports or a build , or something like that .
originUrl = download . getLocalUrl ( ) ; } TargetRepository targetRepository = getDownloadsTargetRepository ( download , content ) ; Artifact . Builder artifactBuilder = Artifact . Builder . newBuilder ( ) . md5 ( download . getMd5 ( ) ) . sha1 ( download . getSha1 ( ) ) . sha256 ( download . getSha256 ( ) ) . size ( download . getSize ( ) ) . deployPath ( download . getPath ( ) ) . originUrl ( originUrl ) . importDate ( Date . from ( Instant . now ( ) ) ) . filename ( new File ( path ) . getName ( ) ) . identifier ( identifier ) . targetRepository ( targetRepository ) ; Artifact artifact = validateArtifact ( artifactBuilder . build ( ) ) ; deps . add ( artifact ) ; } for ( Map . Entry < StoreKey , Map < StoreKey , Set < String > > > targetToSources : toPromote . entrySet ( ) ) { StoreKey target = targetToSources . getKey ( ) ; for ( Map . Entry < StoreKey , Set < String > > sourceToPaths : targetToSources . getValue ( ) . entrySet ( ) ) { StoreKey source = sourceToPaths . getKey ( ) ; PathsPromoteRequest req = new PathsPromoteRequest ( source , target , sourceToPaths . getValue ( ) ) . setPurgeSource ( false ) ; // set read - only only the generic http proxy hosted repos , not shared - imports
doPromoteByPath ( req , GENERIC_PKG_KEY . equals ( target . getPackageType ( ) ) ) ; } } } return deps ;


signature:
public class IndyRepositorySession { /** * Return output artifacts metadata .
 * @ param report The tracking report that contains info about artifacts uploaded ( output ) from the build
 * @ return List of output artifacts meta data
 * @ throws RepositoryManagerException In case of a client API transport error or an error during promotion of artifacts */
private List < Artifact > processUploads ( TrackedContentDTO report ) throws RepositoryManagerException { } }

implementation: Logger logger = LoggerFactory . getLogger ( getClass ( ) ) ; Set < TrackedContentEntryDTO > uploads = report . getUploads ( ) ; if ( uploads != null ) { List < Artifact > builds = new ArrayList < > ( ) ; for ( TrackedContentEntryDTO upload : uploads ) { String path = upload . getPath ( ) ; StoreKey storeKey = upload . getStoreKey ( ) ; if ( ignoreContent ( storeKey . getPackageType ( ) , path ) ) { logger . debug ( "Ignoring upload (matched in ignored-suffixes): {} (From: {})" , path , storeKey ) ; continue ; } String identifier = computeIdentifier ( upload ) ; logger . info ( "Recording upload: {}" , identifier ) ; IndyContentClientModule content ; try { content = indy . content ( ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy content module. Reason: %s" , e , e . getMessage ( ) ) ; } RepositoryType repoType = toRepoType ( storeKey . getPackageType ( ) ) ; TargetRepository targetRepository = getUploadsTargetRepository ( repoType , content ) ; ArtifactQuality artifactQuality = getArtifactQuality ( isTempBuild ) ; Artifact . Builder artifactBuilder = Artifact . Builder . newBuilder ( ) . md5 ( upload . getMd5 ( ) ) . sha1 ( upload . getSha1 ( ) ) . sha256 ( upload . getSha256 ( ) ) . size ( upload . getSize ( ) ) . deployPath ( upload . getPath ( ) ) . filename ( new File ( path ) . getName ( ) ) . identifier ( identifier ) . targetRepository ( targetRepository ) . artifactQuality ( artifactQuality ) ; Artifact artifact = validateArtifact ( artifactBuilder . build ( ) ) ; builds . add ( artifact ) ; } return builds ; } return Collections . emptyList ( ) ;


signature:
public class IndyRepositorySession { /** * Computes identifier string for an artifact . If the download path is valid for a package - type specific artifact it
 * creates the identifier accordingly .
 * @ param transfer the download or upload that we want to generate identifier for
 * @ return generated identifier */
private String computeIdentifier ( final TrackedContentEntryDTO transfer ) { } }

implementation:
String identifier = null ; switch ( transfer . getStoreKey ( ) . getPackageType ( ) ) { case MAVEN_PKG_KEY : ArtifactPathInfo pathInfo = ArtifactPathInfo . parse ( transfer . getPath ( ) ) ; if ( pathInfo != null ) { ArtifactRef aref = new SimpleArtifactRef ( pathInfo . getProjectId ( ) , pathInfo . getType ( ) , pathInfo . getClassifier ( ) ) ; identifier = aref . toString ( ) ; } break ; case NPM_PKG_KEY : NpmPackagePathInfo npmPathInfo = NpmPackagePathInfo . parse ( transfer . getPath ( ) ) ; if ( npmPathInfo != null ) { NpmPackageRef packageRef = new NpmPackageRef ( npmPathInfo . getName ( ) , npmPathInfo . getVersion ( ) ) ; identifier = packageRef . toString ( ) ; } break ; case GENERIC_PKG_KEY : // handle generic downloads along with other invalid download paths for other package types
break ; default : // do not do anything by default
logger . warn ( "Package type {} is not handled by Indy repository session." , transfer . getStoreKey ( ) . getPackageType ( ) ) ; break ; } if ( identifier == null ) { identifier = computeGenericIdentifier ( transfer . getOriginUrl ( ) , transfer . getLocalUrl ( ) , transfer . getSha256 ( ) ) ; } return identifier ;


signature:
public class IndyRepositorySession { /** * Compute the identifier string for a generic download , that does not match package type specific files structure .
 * It prefers to use the origin URL if it is not empty . In case it is then it uses local URL , which can never be
 * empty , it is the local file mirror in Indy . After that it attaches the sha256 separated by a pipe .
 * @ param originUrl the origin URL of the transfer , it can be null
 * @ param localUrl url where the artifact was backed up in Indy
 * @ param sha256 the SHA - 256 of the transfer
 * @ return the generated identifier */
private String computeGenericIdentifier ( String originUrl , String localUrl , String sha256 ) { } }

implementation:
String identifier = originUrl ; if ( identifier == null ) { // this is from / to a hosted repository , either the build repo or something like that .
identifier = localUrl ; } identifier += '|' + sha256 ; return identifier ;


signature:
public class IndyRepositorySession { /** * Check artifact for any validation errors . If there are constraint violations , then a RepositoryManagerException is thrown .
 * Otherwise the artifact is returned .
 * @ param artifact to validate
 * @ return the same artifact
 * @ throws RepositoryManagerException if there are constraint violations */
private Artifact validateArtifact ( Artifact artifact ) throws RepositoryManagerException { } }

implementation: Set < ConstraintViolation < Artifact > > violations = validator . validate ( artifact ) ; if ( ! violations . isEmpty ( ) ) { throw new RepositoryManagerException ( "Repository manager returned invalid artifact: " + artifact . toString ( ) + " Constraint Violations: %s" , violations ) ; } return artifact ;


signature:
public class IndyRepositorySession { /** * Promotes a set of artifact paths ( or everything , if the path - set is missing ) from a particular Indy artifact store to
 * another , and handle the various error conditions that may arise . If the promote call fails , attempt to rollback before
 * throwing an exception .
 * @ param req The promotion request to process , which contains source and target store keys , and ( optionally ) the set of
 * paths to promote
 * @ param setReadonly flag telling if the target repo should be set to readOnly
 * @ throws RepositoryManagerException When either the client API throws an exception due to something unexpected in
 * transport , or if the promotion process results in an error . */
private void doPromoteByPath ( PathsPromoteRequest req , boolean setReadonly ) throws RepositoryManagerException { } }

implementation: IndyPromoteClientModule promoter ; try { promoter = serviceAccountIndy . module ( IndyPromoteClientModule . class ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy promote client module. Reason: %s" , e , e . getMessage ( ) ) ; } try { PathsPromoteResult result = promoter . promoteByPath ( req ) ; if ( result . getError ( ) == null ) { if ( setReadonly && ! isTempBuild ) { HostedRepository hosted = serviceAccountIndy . stores ( ) . load ( req . getTarget ( ) , HostedRepository . class ) ; hosted . setReadonly ( true ) ; try { serviceAccountIndy . stores ( ) . update ( hosted , "Setting readonly after successful build and promotion." ) ; } catch ( IndyClientException ex ) { try { promoter . rollbackPathPromote ( result ) ; } catch ( IndyClientException ex2 ) { logger . error ( "Failed to set readonly flag on repo: %s. Reason given was: %s." , ex , req . getTarget ( ) , ex . getMessage ( ) ) ; throw new RepositoryManagerException ( "Subsequently also failed to rollback the promotion of paths from %s to %s. Reason given was: %s" , ex2 , req . getSource ( ) , req . getTarget ( ) , ex2 . getMessage ( ) ) ; } throw new RepositoryManagerException ( "Failed to set readonly flag on repo: %s. Reason given was: %s" , ex , req . getTarget ( ) , ex . getMessage ( ) ) ; } } } else { String addendum = "" ; try { PathsPromoteResult rollback = promoter . rollbackPathPromote ( result ) ; if ( rollback . getError ( ) != null ) { addendum = "\nROLLBACK WARNING: Promotion rollback also failed! Reason given: " + result . getError ( ) ; } } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Rollback failed for promotion of: %s. Reason: %s" , e , req , e . getMessage ( ) ) ; } throw new RepositoryManagerException ( "Failed to promote: %s. Reason given was: %s%s" , req , result . getError ( ) , addendum ) ; } } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to promote: %s. Reason: %s" , e , req , e . getMessage ( ) ) ; }


signature:
public class IndyRepositorySession { /** * Promote the build output to the consolidated build repo ( using path promotion , where the build
 * repo contents are added to the repo ' s contents ) and marks the build output as readonly .
 * @ param uploads artifacts to be promoted */
public void promoteToBuildContentSet ( List < Artifact > uploads ) throws RepositoryManagerException { } }

implementation:
IndyPromoteClientModule promoter ; try { promoter = serviceAccountIndy . module ( IndyPromoteClientModule . class ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy promote client module. Reason: %s" , e , e . getMessage ( ) ) ; } StoreKey buildRepoKey = new StoreKey ( packageType , StoreType . hosted , buildContentId ) ; PromoteRequest < ? > request = null ; try { if ( isTempBuild ) { request = new GroupPromoteRequest ( buildRepoKey , buildPromotionTarget ) ; GroupPromoteRequest gpReq = ( GroupPromoteRequest ) request ; GroupPromoteResult result = promoter . promoteToGroup ( gpReq ) ; if ( ! result . succeeded ( ) ) { String reason = result . getError ( ) ; if ( reason == null ) { ValidationResult validations = result . getValidations ( ) ; if ( validations != null ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "One or more validation rules failed in rule-set " ) . append ( validations . getRuleSet ( ) ) . append ( ":\n" ) ; validations . getValidatorErrors ( ) . forEach ( ( rule , error ) -> { sb . append ( "- " ) . append ( rule ) . append ( ":\n" ) . append ( error ) . append ( "\n\n" ) ; } ) ; reason = sb . toString ( ) ; } } throw new RepositoryManagerException ( "Failed to promote: %s to group: %s. Reason given was: %s" , request . getSource ( ) , gpReq . getTargetGroup ( ) , reason ) ; } } else { StoreKey buildTarget = new StoreKey ( packageType , StoreType . hosted , buildPromotionTarget ) ; Set < String > paths = new HashSet < > ( ) ; for ( Artifact a : uploads ) { paths . add ( a . getDeployPath ( ) ) ; paths . add ( a . getDeployPath ( ) + ".md5" ) ; paths . add ( a . getDeployPath ( ) + ".sha1" ) ; } request = new PathsPromoteRequest ( buildRepoKey , buildTarget , paths ) ; PathsPromoteRequest ppReq = ( PathsPromoteRequest ) request ; // TODO request . setPurgeSource ( true ) ;
PathsPromoteResult result = promoter . promoteByPath ( ppReq ) ; if ( result . getError ( ) == null ) { HostedRepository buildRepo = serviceAccountIndy . stores ( ) . load ( buildRepoKey , HostedRepository . class ) ; buildRepo . setReadonly ( true ) ; try { serviceAccountIndy . stores ( ) . update ( buildRepo , "Setting readonly after successful build and promotion." ) ; } catch ( IndyClientException ex ) { logger . error ( "Failed to set readonly flag on repo: %s. Reason given was: %s." + " But the promotion to consolidated repo %s succeeded." , ex , buildRepoKey , ex . getMessage ( ) , buildPromotionTarget ) ; } } else { String reason = result . getError ( ) ; if ( reason == null ) { ValidationResult validations = result . getValidations ( ) ; if ( validations != null ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "One or more validation rules failed in rule-set " ) . append ( validations . getRuleSet ( ) ) . append ( ":\n" ) ; validations . getValidatorErrors ( ) . forEach ( ( rule , error ) -> { sb . append ( "- " ) . append ( rule ) . append ( ":\n" ) . append ( error ) . append ( "\n\n" ) ; } ) ; reason = sb . toString ( ) ; } } throw new RepositoryManagerException ( "Failed to promote files from %s to target %s. Reason given was: %s" , request . getSource ( ) , ppReq . getTarget ( ) , reason ) ; } } } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to promote: %s. Reason: %s" , e , request , e . getMessage ( ) ) ; }


signature:
public class BuildTask { /** * Check if this build task has a build configuration dependency on the given build task .
 * The search include transitive dependencies .
 * @ param buildTask The buildTask with the config to check
 * @ return true if this task ' s build config has a dependency ( including transitive ) on the build config of the given task , otherwise false */
public boolean hasConfigDependencyOn ( BuildTask buildTask ) { } }

implementation: if ( buildTask == null || this . equals ( buildTask ) ) { return false ; } BuildConfiguration buildConfiguration = buildConfigurationAudited . getBuildConfiguration ( ) ; if ( buildConfiguration == null || buildConfiguration . getAllDependencies ( ) == null ) { return false ; } return buildConfiguration . dependsOn ( buildTask . getBuildConfigurationAudited ( ) . getBuildConfiguration ( ) ) ;


signature:
public class BuildTask { /** * Check if this build task has a direct build configuration dependency on the given build task
 * @ param buildTask The buildTask with the config to check
 * @ return true if this task ' s build config has a direct dependency on the build config of the given task , otherwise false */
public boolean hasDirectConfigDependencyOn ( BuildTask buildTask ) { } }

implementation: if ( buildTask == null || this . equals ( buildTask ) ) { return false ; } BuildConfiguration buildConfiguration = buildConfigurationAudited . getBuildConfiguration ( ) ; if ( buildConfiguration == null || buildConfiguration . getDependencies ( ) == null ) { return false ; } return buildConfiguration . getDependencies ( ) . contains ( buildTask . getBuildConfigurationAudited ( ) . getBuildConfiguration ( ) ) ;


signature:
public class HttpUtils { /** * Process HTTP GET request and get the data as type specified as parameter .
 * Client accepts application / json MIME type .
 * @ param clazz Class to which the data are unmarshalled
 * @ param < T > module config
 * @ param url Request URL
 * @ throws Exception Thrown if some error occurs in communication with server
 * @ return Unmarshalled entity data */
public static < T > T processGetRequest ( Class < T > clazz , String url ) throws Exception { } }

implementation: ClientRequest request = new ClientRequest ( url ) ; request . accept ( MediaType . APPLICATION_JSON ) ; ClientResponse < T > response = request . get ( clazz ) ; return response . getEntity ( ) ;


signature:
public class ConfigurationJSONParser { /** * Loads JSON configuration to the module configuration object
 * @ param < T > module config
 * @ param configContent Configuration in JSON
 * @ param provider configuration provider of given module config type
 * @ return Loaded configuration
 * @ throws ConfigurationParseException Thrown if configuration string is malformed */
public < T extends AbstractModuleConfig > T parseJSONPNCConfig ( String configContent , ConfigProvider < T > provider ) throws ConfigurationParseException { } }

implementation: try { ObjectMapper mapper = new ObjectMapper ( ) ; provider . registerProvider ( mapper ) ; PNCModuleGroup pncGroup = getModuleGroup ( mapper , configContent , PNCModuleGroup . class ) ; for ( AbstractModuleConfig config : pncGroup . getConfigs ( ) ) { if ( config . getClass ( ) . isAssignableFrom ( provider . getType ( ) ) ) { return ( T ) config ; } } throw new ConfigurationParseException ( "Did not find config for provider " + provider . getType ( ) . getSimpleName ( ) + "." ) ; } catch ( IOException | RuntimeException e ) { log . error ( e . getMessage ( ) ) ; throw new ConfigurationParseException ( "Config could not be parsed" , e ) ; }


signature:
public class BuildTaskEndpoint { /** * CDI workaround */
@ POST @ Path ( "/{taskId}/completed" ) @ Consumes ( MediaType . APPLICATION_FORM_URLENCODED ) public Response buildTaskCompleted ( @ PathParam ( "taskId" ) Integer buildId , @ FormParam ( "buildResult" ) BuildResultRest buildResult ) throws CoreException { } }

implementation:
// TODO set MDC from request headers instead of business data
// logger . debug ( " Received task completed notification for coordinating task id [ { } ] . " , buildId ) ;
// BuildExecutionConfigurationRest buildExecutionConfiguration = buildResult . getBuildExecutionConfiguration ( ) ;
// buildResult . getRepositoryManagerResult ( ) . getBuildContentId ( ) ;
// if ( buildExecutionConfiguration = = null ) {
// logger . error ( " Missing buildExecutionConfiguration in buildResult for buildTaskId [ { } ] . " , buildId ) ;
// throw new CoreException ( " Missing buildExecutionConfiguration in buildResult for buildTaskId " + buildId ) ;
// MDCUtils . addContext ( buildExecutionConfiguration . getBuildContentId ( ) , buildExecutionConfiguration . isTempBuild ( ) , systemConfig . getTemporalBuildExpireDate ( ) ) ;
logger . info ( "Received build task completed notification for id {}." , buildId ) ; Integer taskId = bpmManager . getTaskIdByBuildId ( buildId ) ; if ( taskId == null ) { logger . error ( "No task for id [{}]." , buildId ) ; throw new CoreException ( "Could not find BPM task for build with ID " + buildId ) ; } // check if task is already completed
// required workaround as we don ' t remove the BpmTasks immediately after the completion
Optional < BpmTask > taskOptional = bpmManager . getTaskById ( taskId ) ; if ( taskOptional . isPresent ( ) ) { BpmBuildTask bpmBuildTask = ( BpmBuildTask ) taskOptional . get ( ) ; BuildTask buildTask = bpmBuildTask . getBuildTask ( ) ; MDCUtils . addBuildContext ( buildTask . getContentId ( ) , buildTask . getBuildOptions ( ) . isTemporaryBuild ( ) , systemConfig . getTemporalBuildExpireDate ( ) ) ; if ( buildTask . getStatus ( ) . isCompleted ( ) ) { logger . warn ( "Task with id: {} is already completed with status: {}" , buildTask . getId ( ) , buildTask . getStatus ( ) ) ; return Response . status ( Response . Status . GONE ) . entity ( "Task with id: " + buildTask . getId ( ) + " is already completed with status: " + buildTask . getStatus ( ) + "." ) . build ( ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Received build result wit full log: {}." , buildResult . toFullLogString ( ) ) ; } logger . debug ( "Will notify for bpmTaskId[{}] linked to buildTaskId [{}]." , taskId , buildId ) ; bpmManager . notify ( taskId , buildResult ) ; logger . debug ( "Notified for bpmTaskId[{}] linked to buildTaskId [{}]." , taskId , buildId ) ; return Response . ok ( ) . build ( ) ;


signature:
public class IndyRunningDeletion { /** * Trigger the repository deletion configured for this instance , and send the result to the appropriate consumer .
 * @ param onComplete The consumer which will handle non - error results
 * @ param onError Handles errors */
@ Override public void monitor ( Consumer < CompletedRepositoryDeletion > onComplete , Consumer < Exception > onError ) { } }

implementation: try { StoreKey fromKey = new StoreKey ( pakageType , fromType , fromId ) ; if ( indy . stores ( ) . exists ( fromKey ) ) { indy . stores ( ) . delete ( fromKey , "Deleting artifacts for PNC build" ) ; } onComplete . accept ( new IndyCompletedDeletion ( true ) ) ; } catch ( IndyClientException e ) { onError . accept ( e ) ; }


signature:
public class DatabaseDataInitializer { /** * Build record needs to be initialized in a separate transaction so that the audited build configuration can be set . */
@ TransactionAttribute ( TransactionAttributeType . REQUIRES_NEW ) public void initiliazeBuildRecordDemoData ( ) { } }

implementation: TargetRepository targetRepository = TargetRepository . newBuilder ( ) . repositoryType ( RepositoryType . MAVEN ) . repositoryPath ( "builds-untested" ) . identifier ( "indy-maven" ) . temporaryRepo ( false ) . build ( ) ; targetRepositoryRepository . save ( targetRepository ) ; Artifact builtArtifact1 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:built-artifact1:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo built artifact 1" ) . md5 ( "4af310bf0ef67bc7d143f35818ea1ed2" ) . sha1 ( "3a8ff25c890f2a4a283876a91037ff6c57474a14" ) . sha256 ( "1660168483cb8a05d1cc2e77c861682a42ed9517ba945159d5538950c5db00fa" ) . size ( 10L ) . build ( ) ; Artifact builtArtifact2 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:built-artifact2:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo built artifact 2" ) . md5 ( "4af310bf0ef67bc7d143f35818ea1ed2" ) . sha1 ( "61dad16e14438d2d8c8cbd18b267d62944f37898" ) . sha256 ( "2fafc2ed0f752ac2540283d48c5cd663254a853c5cb13dec02dce023fc7471a9" ) . size ( 11L ) . build ( ) ; builtArtifact1 = artifactRepository . save ( builtArtifact1 ) ; builtArtifact2 = artifactRepository . save ( builtArtifact2 ) ; Artifact importedArtifact1 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:imported-artifact1:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo imported artifact 1" ) . originUrl ( "http://central/import1.jar" ) . importDate ( Date . from ( Instant . now ( ) ) ) . md5 ( "md-fake-abcd1234" ) . sha1 ( "sha1-fake-abcd1234" ) . sha256 ( "sha256-fake-abcd1234" ) . size ( 10L ) . deployPath ( "http://google.pl/imported1" ) . build ( ) ; Artifact importedArtifact2 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:imported-artifact2:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo imported artifact 2" ) . originUrl ( "http://central/import2.jar" ) . importDate ( Date . from ( Instant . now ( ) ) ) . md5 ( "md-fake-abcd1234" ) . sha1 ( "sha1-fake-abcd1234" ) . sha256 ( "sha256-fake-abcd1234" ) . size ( 10L ) . deployPath ( "http://google.pl/imported2" ) . build ( ) ; importedArtifact1 = artifactRepository . save ( importedArtifact1 ) ; importedArtifact2 = artifactRepository . save ( importedArtifact2 ) ; Set < BuildRecord > buildRecords = new HashSet < > ( ) ; final int INITIAL_REVISION = 1 ; IdRev buildConfig1AuditIdRev = new IdRev ( buildConfiguration1 . getId ( ) , INITIAL_REVISION ) ; BuildConfigurationAudited buildConfigAudited1 = buildConfigurationAuditedRepository . queryById ( buildConfig1AuditIdRev ) ; if ( buildConfigAudited1 != null ) { int nextId = datastore . getNextBuildRecordId ( ) ; log . info ( "####nextId: " + nextId ) ; BuildRecord buildRecord1 = BuildRecord . Builder . newBuilder ( ) . id ( nextId ) . buildConfigurationAudited ( buildConfigAudited1 ) . submitTime ( Timestamp . from ( Instant . now ( ) . minus ( 8 , ChronoUnit . MINUTES ) ) ) . startTime ( Timestamp . from ( Instant . now ( ) . minus ( 5 , ChronoUnit . MINUTES ) ) ) . endTime ( Timestamp . from ( Instant . now ( ) ) ) . builtArtifact ( builtArtifact1 ) . builtArtifact ( builtArtifact2 ) . dependency ( importedArtifact1 ) . dependency ( importedArtifact2 ) . user ( demoUser ) . buildLog ( "Very short demo log: The quick brown fox jumps over the lazy dog." ) . status ( BuildStatus . SUCCESS ) . productMilestone ( demoProductMilestone1 ) . sshCommand ( "ssh worker@localhost -P 9999" ) . sshPassword ( "dontchangeme" ) . buildEnvironment ( buildConfigAudited1 . getBuildEnvironment ( ) ) . executionRootName ( "org.jboss.pnc:parent" ) . executionRootVersion ( "1.2.3" ) . temporaryBuild ( false ) . build ( ) ; buildRecordRepository . save ( buildRecord1 ) ; buildRecords . add ( buildRecord1 ) ; } Artifact builtArtifact3 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:built-artifact3:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo built artifact 3" ) . md5 ( "17353a18678c6c249e3052edec2e4c5c" ) . sha1 ( "61dad16e14438d2d8c8cbd18b267d62944f37898" ) . sha256 ( "1660168483cb8a05d1cc2e77c861682a42ed9517ba945159d5538950c5db00fa" ) . size ( 10L ) . deployPath ( "http://google.pl/built3" ) . build ( ) ; Artifact builtArtifact4 = Artifact . Builder . newBuilder ( ) . identifier ( "demo:built-artifact4:jar:1.0" ) . targetRepository ( targetRepository ) . filename ( "demo built artifact 4" ) . md5 ( "md-fake-abcd1234" ) . sha1 ( "sha1-fake-abcd1234" ) . sha256 ( "sha256-fake-abcd1234" ) . size ( 10L ) . deployPath ( "http://google.pl/built4" ) . build ( ) ; builtArtifact3 = artifactRepository . save ( builtArtifact3 ) ; builtArtifact4 = artifactRepository . save ( builtArtifact4 ) ; Artifact dependencyBuiltArtifact1 = artifactRepository . queryByPredicates ( withIdentifierAndSha256 ( builtArtifact1 . getIdentifier ( ) , builtArtifact1 . getSha256 ( ) ) ) ; IdRev buildConfig2AuditIdRev = new IdRev ( buildConfiguration2 . getId ( ) , INITIAL_REVISION ) ; BuildConfigurationAudited buildConfigAudited2 = buildConfigurationAuditedRepository . queryById ( buildConfig2AuditIdRev ) ; if ( buildConfigAudited2 != null ) { int nextId = datastore . getNextBuildRecordId ( ) ; log . info ( "####nextId: " + nextId ) ; BuildRecord buildRecord2 = BuildRecord . Builder . newBuilder ( ) . id ( nextId ) . buildConfigurationAudited ( buildConfigAudited2 ) . submitTime ( Timestamp . from ( Instant . now ( ) . minus ( 8 , ChronoUnit . MINUTES ) ) ) . startTime ( Timestamp . from ( Instant . now ( ) . minus ( 5 , ChronoUnit . MINUTES ) ) ) . endTime ( Timestamp . from ( Instant . now ( ) ) ) . builtArtifact ( builtArtifact3 ) . builtArtifact ( builtArtifact4 ) . dependency ( dependencyBuiltArtifact1 ) . dependency ( importedArtifact1 ) . user ( demoUser ) . buildLog ( "Very short demo log: The quick brown fox jumps over the lazy dog." ) . status ( BuildStatus . SUCCESS ) . buildEnvironment ( buildConfigAudited2 . getBuildEnvironment ( ) ) . executionRootName ( "org.jboss.pnc:parent" ) . executionRootVersion ( "1.2.4" ) . temporaryBuild ( false ) . build ( ) ; buildRecordRepository . save ( buildRecord2 ) ; buildRecords . add ( buildRecord2 ) ; } BuildConfigSetRecord buildConfigSetRecord1 = BuildConfigSetRecord . Builder . newBuilder ( ) . buildConfigurationSet ( buildConfigurationSet1 ) . startTime ( Timestamp . from ( Instant . now ( ) ) ) . endTime ( Timestamp . from ( Instant . now ( ) ) ) . user ( demoUser ) . status ( BuildStatus . FAILED ) . temporaryBuild ( false ) . build ( ) ; buildConfigSetRecordRepository . save ( buildConfigSetRecord1 ) ; BuildConfigSetRecord buildConfigSetRecord2 = BuildConfigSetRecord . Builder . newBuilder ( ) . buildConfigurationSet ( buildConfigurationSet1 ) . buildRecords ( buildRecords ) . startTime ( Timestamp . from ( Instant . now ( ) ) ) . endTime ( Timestamp . from ( Instant . now ( ) ) ) . user ( demoUser ) . status ( BuildStatus . SUCCESS ) . temporaryBuild ( false ) . build ( ) ; buildConfigSetRecordRepository . save ( buildConfigSetRecord2 ) ; demoProductMilestone1 = productMilestoneRepository . queryById ( demoProductMilestone1 . getId ( ) ) ; demoProductMilestone1 . addDistributedArtifact ( builtArtifact1 ) ; demoProductMilestone1 . addDistributedArtifact ( builtArtifact3 ) ; demoProductMilestone1 . addDistributedArtifact ( importedArtifact2 ) ; demoProductMilestone1 = productMilestoneRepository . save ( demoProductMilestone1 ) ;


signature:
public class BuildSetTask { /** * Notify the set that the state of one of it ' s tasks has changed . */
public void taskStatusUpdatedToFinalState ( ) { } }

implementation:
// If any of the build tasks have failed or all are complete , then the build set is done
if ( buildTasks . stream ( ) . anyMatch ( bt -> bt . getStatus ( ) . equals ( BuildCoordinationStatus . CANCELLED ) ) ) { log . debug ( "Marking build set as CANCELLED as one or more tasks were cancelled. BuildSetTask: {}" , this ) ; if ( log . isDebugEnabled ( ) ) { logTasksStatus ( buildTasks ) ; } buildConfigSetRecord . ifPresent ( r -> r . setStatus ( BuildStatus . CANCELLED ) ) ; finishBuildSetTask ( ) ; } else if ( buildTasks . stream ( ) . anyMatch ( bt -> bt . getStatus ( ) . hasFailed ( ) ) ) { log . debug ( "Marking build set as FAILED as one or more tasks failed. BuildSetTask: {}" , this ) ; if ( log . isDebugEnabled ( ) ) { logTasksStatus ( buildTasks ) ; } buildConfigSetRecord . ifPresent ( r -> r . setStatus ( BuildStatus . FAILED ) ) ; finishBuildSetTask ( ) ; } else if ( buildTasks . stream ( ) . allMatch ( bt -> bt . getStatus ( ) . isCompleted ( ) ) ) { log . debug ( "Marking build set as SUCCESS. BuildSetTask: {}" , this ) ; buildConfigSetRecord . ifPresent ( r -> r . setStatus ( BuildStatus . SUCCESS ) ) ; finishBuildSetTask ( ) ; } else { if ( log . isTraceEnabled ( ) ) { List < Integer > running = buildTasks . stream ( ) . filter ( bt -> ! bt . getStatus ( ) . isCompleted ( ) ) . filter ( bt -> ! bt . getStatus ( ) . hasFailed ( ) ) . map ( BuildTask :: getId ) . collect ( Collectors . toList ( ) ) ; log . trace ( "There are still running or waiting builds [{}]." , running ) ; } }


signature:
public class BuildSetTask { /** * Get the build task which contains the given audited build configuration
 * @ param buildConfigurationAudited A BuildConfigurationAudited entity
 * @ return The build task with the matching configuration , or null if there is none */
public BuildTask getBuildTask ( BuildConfigurationAudited buildConfigurationAudited ) { } }

implementation: return buildTasks . stream ( ) . filter ( ( bt ) -> bt . getBuildConfigurationAudited ( ) . equals ( buildConfigurationAudited ) ) . findFirst ( ) . orElse ( null ) ;


signature:
public class SCMRepositoryProviderImpl { /** * Add item to the list if the string is not null * and * not empty
 * @ param list
 * @ param str
 * @ param item
 * @ param < T > */
private < T > void addToListIfStringNotNullAndNotEmpty ( List < T > list , String str , T item ) { } }

implementation: if ( str != null && ! str . isEmpty ( ) ) { list . add ( item ) ; }


signature:
public class IndyRunningPromotion { /** * Trigger the repository promotion configured for this instance , and send the result to the appropriate consumer .
 * @ param onComplete The consumer which will handle non - error results
 * @ param onError Handles errors */
@ Override public void monitor ( Consumer < CompletedRepositoryPromotion > onComplete , Consumer < Exception > onError ) { } }

implementation: try { StoreKey fromKey = new StoreKey ( pakageType , fromType , fromId ) ; if ( ! indy . stores ( ) . exists ( fromKey ) ) { throw new RepositoryManagerException ( "No such %s repository: %s" , fromType . singularEndpointName ( ) , fromId ) ; } StoreKey toKey = new StoreKey ( pakageType , StoreType . group , toId ) ; Group recordSetGroup = indy . stores ( ) . load ( toKey , Group . class ) ; if ( recordSetGroup == null ) { throw new RepositoryManagerException ( "No such group: %s" , toId ) ; } recordSetGroup . addConstituent ( fromKey ) ; boolean result = indy . stores ( ) . update ( recordSetGroup , "Promoting " + fromType . singularEndpointName ( ) + " repository : " + fromId + " to group: " + toId ) ; onComplete . accept ( new IndyCompletedPromotion ( result ) ) ; } catch ( IndyClientException | RepositoryManagerException e ) { onError . accept ( e ) ; }


signature:
public class GraphUtils { /** * Adds all elements from toMerge to target . */
public static < T > void merge ( Graph < T > target , Graph < T > toMerge ) { } }

implementation:
for ( Vertex < T > vertex : toMerge . getVerticies ( ) ) { target . addVertex ( vertex ) ; } // merge edges
List < Edge < T > > edges = target . getEdges ( ) ; for ( Edge newEdge : toMerge . getEdges ( ) ) { Optional < Edge < T > > any = edges . stream ( ) . filter ( existing -> existing . getFrom ( ) . getName ( ) . equals ( newEdge . getFrom ( ) . getName ( ) ) && existing . getTo ( ) . getName ( ) . equals ( newEdge . getTo ( ) . getName ( ) ) ) . findAny ( ) ; if ( ! any . isPresent ( ) ) { edges . add ( newEdge ) ; } }


signature:
public class ReadEnvProperty { /** * If propertyName has no value ( either specified in system property or environment property ) , then just return
 * the default value . System property value has priority over environment property value .
 * If value can ' t be parsed , just return the default value .
 * @ param propertyName property name to check the value
 * @ param defaultValue default value to use
 * @ return value from property , or default value */
public int getIntValueFromPropertyOrDefault ( String propertyName , int defaultValue ) { } }

implementation: int value = defaultValue ; String valueEnv = System . getenv ( propertyName ) ; String valueSys = System . getProperty ( propertyName ) ; try { if ( valueSys != null ) { value = Integer . parseInt ( valueSys ) ; } else if ( valueEnv != null ) { value = Integer . parseInt ( valueEnv ) ; } return value ; } catch ( NumberFormatException e ) { log . warn ( "Could not parse the '" + propertyName + "' system property. Using default value: " + defaultValue ) ; return value ; }


signature:
public class IoUtils { /** * Reads whole content of file to String
 * @ param fileName Existing file
 * @ return File content
 * @ throws IOException Thrown if data couldn ' t be loaded */
public static String readFileAsString ( File fileName ) throws IOException { } }

implementation: try ( Scanner sc = new Scanner ( fileName , Charset . defaultCharset ( ) . name ( ) ) ) { sc . useDelimiter ( "\\A" ) ; return sc . next ( ) ; }


signature:
public class IoUtils { /** * Reads whole content of input stream to String
 * @ param stream Opened stream
 * @ return Stream content
 * @ throws IOException Thrown if data couldn ' t be loaded */
public static String readStreamAsString ( InputStream stream ) throws IOException { } }

implementation: try ( Scanner sc = new Scanner ( stream , Charset . defaultCharset ( ) . name ( ) ) ) { sc . useDelimiter ( "\\A" ) ; return sc . next ( ) ; }


signature:
public class IoUtils { /** * < p > readFileOrResource . < / p >
 * @ param systemPropertyName Name of system property to override default file name
 * @ param defaultFileName Filename to use if system property doesn ' t exist .
 * @ param classLoader Classloader to use
 * @ return The configuration string
 * @ throws IOException Thrown if data couldn ' t be loaded */
public static String readFileOrResource ( String systemPropertyName , String defaultFileName , ClassLoader classLoader ) throws IOException { } }

implementation:
String templateFileName = System . getProperty ( systemPropertyName ) ; if ( templateFileName == null ) { templateFileName = defaultFileName ; } File file = new File ( templateFileName ) ; // try full path
String configString ; if ( file . exists ( ) ) { try { byte [ ] encoded ; encoded = Files . readAllBytes ( Paths . get ( file . getPath ( ) ) ) ; configString = new String ( encoded , Charset . defaultCharset ( ) ) ; } catch ( IOException e ) { throw new IOException ( "Cannot load " + templateFileName + "." , e ) ; } } else { try { configString = IoUtils . readResource ( templateFileName , classLoader ) ; } catch ( IOException e ) { throw new IOException ( "Cannot load " + templateFileName + "." , e ) ; } } if ( configString == null ) { throw new IOException ( "Cannot load " + templateFileName + "." ) ; } return configString ;


signature:
public class RepositoryConfigurationPredicates { /** * Queries against normalized version with stripped protocol and . git extension */
public static Predicate < RepositoryConfiguration > withInternalScmRepoUrl ( String internalUrl ) { } }

implementation: String urlStripped = StringUtils . stripSuffix ( UrlUtils . keepHostAndPathOnly ( internalUrl ) , ".git" ) ; return ( root , query , cb ) -> cb . equal ( root . get ( RepositoryConfiguration_ . internalUrlNormalized ) , urlStripped ) ;


signature:
public class RepositoryConfigurationPredicates { /** * Queries against normalized version with stripped protocol and . git extension */
public static Predicate < RepositoryConfiguration > withExternalScmRepoUrl ( String externalScmRepoUrl ) { } }

implementation: String urlStripped = StringUtils . stripSuffix ( UrlUtils . keepHostAndPathOnly ( externalScmRepoUrl ) , ".git" ) ; return ( root , query , cb ) -> cb . equal ( root . get ( RepositoryConfiguration_ . externalUrlNormalized ) , urlStripped ) ;


signature:
public class DebugEndpoint { /** * curl - v - X POST http : / / localhost : 8080 / pnc - rest / rest / debug / mq - send - dummy - message
 * curl - v - X POST http : / / localhost : 8080 / pnc - rest / rest / debug / mq - send - dummy - message ? type = status */
@ POST @ Path ( "/mq-send-dummy-message" ) public Response sendDummyMessageToQueue ( @ QueryParam ( "type" ) String type ) { } }

implementation: Optional < MessageSender > messageSender = messageSenderProvider . getMessageSender ( ) ; if ( ! messageSender . isPresent ( ) ) { return Response . status ( Response . Status . SERVICE_UNAVAILABLE ) . entity ( "Message sender is not available to inject." ) . build ( ) ; } else { if ( type != null && type . equals ( "status" ) ) { buildStatusChangedEventNotifier . fire ( new DefaultBuildStatusChangedEvent ( newBuild ( ) , BuildCoordinationStatus . CANCELLED ) ) ; } else { messageSender . get ( ) . sendToTopic ( "Test Message." ) ; } return Response . ok ( ) . build ( ) ; }


signature:
public class ProductMilestoneReleaseManager { /** * Starts milestone release process
 * @ param milestone product milestone to start the release for
 * @ param accessToken */
public void startRelease ( ProductMilestone milestone , String accessToken ) { } }

implementation: ProductMilestoneRelease release = triggerRelease ( milestone , accessToken ) ; productMilestoneReleaseRepository . save ( release ) ;


signature:
public class ProductMilestoneReleaseManager { /** * [ NCL - 3112 ] Mark the milestone provided as not current
 * @ param milestone ProductMilestone to not be current anymore */
private void removeCurrentFlagFromMilestone ( ProductMilestone milestone ) { } }

implementation: ProductVersion productVersion = milestone . getProductVersion ( ) ; if ( productVersion . getCurrentProductMilestone ( ) != null && productVersion . getCurrentProductMilestone ( ) . getId ( ) . equals ( milestone . getId ( ) ) ) { productVersion . setCurrentProductMilestone ( null ) ; productVersionRepository . save ( productVersion ) ; }


signature:
public class BpmManager { /** * Regularly cleans finished BPM tasks asynchronously
 * Immediate cleanup is not usable because of NCL - 2300 */
public void cleanup ( ) { } }

implementation:
// TODO remove tasks immediately after the completion , see : BuildTaskEndpoint . buildTaskCompleted
log . debug ( "Bpm manager tasks cleanup started" ) ; if ( session == null ) { log . error ( "Kie session not available." ) ; } Map < Integer , BpmTask > clonedTaskMap = new HashMap < > ( this . tasks ) ; Set < Integer > toBeRemoved = clonedTaskMap . values ( ) . stream ( ) . filter ( bpmTask -> { if ( bpmTask == null ) { log . warn ( "Listing invalid entry for removal from the tasks list." ) ; return true ; } log . debug ( "Attempting to fetch process instance for bpmTask: {}." , bpmTask . getTaskId ( ) ) ; Long processInstanceId = bpmTask . getProcessInstanceId ( ) ; ProcessInstance processInstance = session . getProcessInstance ( processInstanceId ) ; log . debug ( "fetched: {}" , processInstance ) ; if ( processInstance == null ) // instance has been terminated from outside
return true ; int state = processInstance . getState ( ) ; return state == STATE_COMPLETED || state == STATE_ABORTED ; } ) . map ( BpmTask :: getTaskId ) . collect ( Collectors . toSet ( ) ) ; toBeRemoved . forEach ( id -> { BpmTask removed = tasks . remove ( id ) ; if ( removed != null ) { log . debug ( "Removed bpmTask.id: {}." , removed . getTaskId ( ) ) ; } else { log . warn ( "Unable to remove bpmTask.id: {}." , id ) ; } } ) ; log . debug ( "Bpm manager tasks cleanup finished" ) ;


signature:
public class BpmManager { /** * This method solves backwards compatibility problem .
 * It will be removed soon . */
@ Deprecated public Integer getTaskIdByBuildId ( int buildId ) { } }

implementation: List < Integer > result = tasks . values ( ) . stream ( ) . filter ( t -> t instanceof BpmBuildTask ) . filter ( t -> ( ( BpmBuildTask ) t ) . getBuildTask ( ) . getId ( ) == buildId ) . map ( BpmTask :: getTaskId ) . collect ( Collectors . toList ( ) ) ; if ( result . size ( ) > 1 ) throw new IllegalStateException ( "More that one task with the same build id: " + result ) ; return result . size ( ) == 1 ? result . get ( 0 ) : null ;


signature:
public class StreamCollectors { /** * Collect element ( s ) into a list and then return the single element of this list .
 * If there is not exactly one element , throw an exception .
 * @ param < T > module config
 * @ return */
public static < T > Collector < T , List < T > , T > singletonCollector ( ) { } }

implementation: return Collector . of ( ArrayList :: new , List :: add , ( left , right ) -> { left . addAll ( right ) ; return left ; } , list -> { if ( list . size ( ) == 0 ) { return null ; } if ( list . size ( ) > 1 ) { throw new IllegalStateException ( ) ; } return list . get ( 0 ) ; } ) ;


signature:
public class StreamCollectors { /** * Flattening collector .
 * Look at StreamCollectorsTest for example usage
 * @ param < T > type of elements in the collections
 * @ return flattened list of elements from all of the collections */
public static < T > Collector < Collection < T > , List < T > , List < T > > toFlatList ( ) { } }

implementation: return Collector . of ( ArrayList :: new , List :: addAll , ( left , right ) -> { left . addAll ( right ) ; return left ; } ) ;


signature:
public class TemporaryBuildsCleanupScheduler { /** * Cleanup old temporary builds every midnight */
@ Schedule public void cleanupExpiredTemporaryBuilds ( ) throws ValidationException { } }

implementation: log . info ( "Regular cleanup of expired temporary builds started. Removing builds older than " + TEMPORARY_BUILD_LIFESPAN + " days." ) ; Date expirationThreshold = TimeUtils . getDateXDaysAgo ( TEMPORARY_BUILD_LIFESPAN ) ; String authToken = serviceClient . getAuthToken ( ) ; deleteExpiredBuildConfigSetRecords ( expirationThreshold , authToken ) ; deleteExpiredBuildRecords ( expirationThreshold , authToken ) ; log . info ( "Regular cleanup of expired temporary builds finished." ) ;


signature:
public class RepositoryManagerDriver { /** * Supports RepositoryType # MAVEN and RepositoryType # NPM */
@ Override public boolean canManage ( RepositoryType managerType ) { } }

implementation: return ( managerType == RepositoryType . MAVEN ) || ( managerType == RepositoryType . NPM ) ;


signature:
public class RepositoryManagerDriver { /** * Use the Indy client API to setup global and build - set level repos and groups , then setup the repo / group needed for this
 * build . Calculate the URL to use for resolving artifacts using the Indy Folo API ( Folo is an artifact activity - tracker ) .
 * Return a new session ( { @ link IndyRepositorySession } ) containing this information .
 * @ throws RepositoryManagerException In the event one or more repositories or groups can ' t be created to support the build
 * ( or product , or shared - releases ) . */
@ Override public RepositorySession createBuildRepository ( BuildExecution buildExecution , String accessToken , String serviceAccountToken , RepositoryType repositoryType , Map < String , String > genericParameters ) throws RepositoryManagerException { } }

implementation:
Indy indy = init ( accessToken ) ; Indy serviceAccountIndy = init ( serviceAccountToken ) ; String packageType = getIndyPackageTypeKey ( repositoryType ) ; String buildId = buildExecution . getBuildContentId ( ) ; try { setupBuildRepos ( buildExecution , packageType , serviceAccountIndy , genericParameters ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to setup repository or repository group for this build: %s" , e , e . getMessage ( ) ) ; } // since we ' re setting up a group / hosted repo per build , we can pin the tracking ID to the build repo ID .
String url ; String deployUrl ; try { // manually initialize the tracking record , just in case ( somehow ) nothing gets downloaded / uploaded .
indy . module ( IndyFoloAdminClientModule . class ) . initReport ( buildId ) ; StoreKey groupKey = new StoreKey ( packageType , StoreType . group , buildId ) ; url = indy . module ( IndyFoloContentClientModule . class ) . trackingUrl ( buildId , groupKey ) ; StoreKey hostedKey = new StoreKey ( packageType , StoreType . hosted , buildId ) ; deployUrl = indy . module ( IndyFoloContentClientModule . class ) . trackingUrl ( buildId , hostedKey ) ; logger . info ( "Using '{}' for {} repository access in build: {}" , url , packageType , buildId ) ; } catch ( IndyClientException e ) { throw new RepositoryManagerException ( "Failed to retrieve Indy client module for the artifact tracker: %s" , e , e . getMessage ( ) ) ; } boolean tempBuild = buildExecution . isTempBuild ( ) ; String buildPromotionGroup = tempBuild ? TEMP_BUILD_PROMOTION_GROUP : BUILD_PROMOTION_TARGET ; return new IndyRepositorySession ( indy , serviceAccountIndy , buildId , packageType , new IndyRepositoryConnectionInfo ( url , deployUrl ) , internalRepoPatterns , ignoredPathSuffixes , buildPromotionGroup , tempBuild ) ;


signature:
public class RepositoryManagerDriver { /** * Create the hosted repository and group necessary to support a single build . The hosted repository holds artifacts
 * uploaded from the build , and the group coordinates access to this hosted repository , along with content from the
 * product - level content group with which this build is associated . The group also provides a tracking target , so the
 * repository manager can keep track of downloads and uploads for the build .
 * @ param execution The execution object , which contains the content id for creating the repo , and the build id .
 * @ param packageType the package type key used by Indy
 * @ throws IndyClientException */
private void setupBuildRepos ( BuildExecution execution , String packageType , Indy indy , Map < String , String > genericParameters ) throws IndyClientException { } }

implementation:
String buildContentId = execution . getBuildContentId ( ) ; int id = execution . getId ( ) ; // if the build - level group doesn ' t exist , create it .
StoreKey groupKey = new StoreKey ( packageType , StoreType . group , buildContentId ) ; if ( ! indy . stores ( ) . exists ( groupKey ) ) { // if the product - level storage repo ( for in - progress product builds ) doesn ' t exist , create it .
StoreKey hostedKey = new StoreKey ( packageType , StoreType . hosted , buildContentId ) ; boolean tempBuild = execution . isTempBuild ( ) ; if ( ! indy . stores ( ) . exists ( hostedKey ) ) { HostedRepository buildArtifacts = new HostedRepository ( packageType , buildContentId ) ; buildArtifacts . setAllowSnapshots ( tempBuild ) ; buildArtifacts . setAllowReleases ( true ) ; buildArtifacts . setDescription ( String . format ( "Build output for PNC %s build #%s" , packageType , id ) ) ; indy . stores ( ) . create ( buildArtifacts , "Creating hosted repository for " + packageType + " build: " + id + " (repo: " + buildContentId + ")" , HostedRepository . class ) ; } Group buildGroup = new Group ( packageType , buildContentId ) ; String adjective = tempBuild ? "temporary " : "" ; buildGroup . setDescription ( String . format ( "Aggregation group for PNC %sbuild #%s" , adjective , id ) ) ; // build - local artifacts
buildGroup . addConstituent ( hostedKey ) ; // Global - level repos , for captured / shared artifacts and access to the outside world
addGlobalConstituents ( packageType , buildGroup , tempBuild ) ; // add extra repositories removed from poms by the adjust process and set in BC by user
List < ArtifactRepository > extraDependencyRepositories = extractExtraRepositoriesFromGenericParameters ( genericParameters ) ; if ( execution . getArtifactRepositories ( ) != null ) { extraDependencyRepositories . addAll ( execution . getArtifactRepositories ( ) ) ; } addExtraConstituents ( packageType , extraDependencyRepositories , id , buildContentId , indy , buildGroup ) ; indy . stores ( ) . create ( buildGroup , "Creating repository group for resolving artifacts in build: " + id + " (repo: " + buildContentId + ")" , Group . class ) ; }


signature:
public class NotificationsEndpoint { /** * Expected message format :
 * messageType : ' process - updates ' ,
 * message : {
 * _ typed _ body _
 * Example :
 * messageType : ' process - updates ' ,
 * message : {
 * action : ' subscribe | unsubscribe ' ,
 * topic : ' component - build ' ,
 * id : 123
 * @ param message
 * @ param session */
@ OnMessage public void onMessage ( String message , Session session ) { } }

implementation: RequestParser parser = new RequestParser ( ) ; try { if ( ! parser . parseRequest ( message ) ) { respondWithErrorMessage ( parser . getErrorMessage ( ) , parser . getFailedStatus ( ) , session ) ; return ; } } catch ( IOException e ) { respondWithErrorMessage ( parser . getErrorMessage ( ) + " " + e . getMessage ( ) , parser . getFailedStatus ( ) , session , e ) ; return ; } MessageType messageType = parser . getMessageType ( ) ; if ( MessageType . PROCESS_UPDATES . equals ( messageType ) ) { ProgressUpdatesRequest progressUpdatesRequest = parser . < ProgressUpdatesRequest > getData ( ) ; onProgressUpdateRequest ( progressUpdatesRequest , session ) ; }


signature:
public class BuildRecordPredicates { /** * Only relevant situation is when ( temporary is false ) and whole right side is false .
 * Right side is false when BuildRecord is temporary = > cb . isFalse ( true ) ( true is not false )
 * - > conclusion = in case requested build is not temporary ( persistent ) and record is temporary , record is ignored
 * @ param temporary if requested build is temporary
 * @ return Predicate that filters out temporary records when dealing with persistent builds */
public static Predicate < BuildRecord > includeTemporary ( boolean temporary ) { } }

implementation: return ( root , query , cb ) -> ( temporary ) ? cb . and ( ) : cb . isFalse ( root . get ( BuildRecord_ . temporaryBuild ) ) ;


signature:
public class BpmEndpoint { /** * Given the successful BC creation , add the BC into the BC sets . This solution has been
 * selected because if this was done in BPM process there would have to be a foreach cycle and
 * at least two REST requests for each BC Set ID . The process would become too complicated .
 * Notification listeners are ideal for these kind of operations . */
private void onRCCreationSuccess ( BpmNotificationRest notification , BuildConfigurationRest buildConfigurationRest ) { } }

implementation:
LOG . debug ( "Received BPM event RC_CREATION_SUCCESS: " + notification ) ; BpmStringMapNotificationRest repositoryCreationTaskResult = ( BpmStringMapNotificationRest ) notification ; int repositoryConfigurationId = - 1 ; int buildConfigurationSavedId = - 1 ; try { repositoryConfigurationId = Integer . valueOf ( repositoryCreationTaskResult . getData ( ) . get ( "repositoryConfigurationId" ) ) ; } catch ( NumberFormatException ex ) { String errorMessage = "Receive notification about successful BC creation '" + repositoryCreationTaskResult + "' but the ID of the newly created RC '" + repositoryCreationTaskResult . getData ( ) . get ( "repositoryConfigurationId" ) + "' is not a number. It should be present under 'repositoryConfigurationId' key." ; LOG . error ( errorMessage , ex ) ; sendErrorMessage ( repositoryConfigurationId , buildConfigurationSavedId , errorMessage ) ; return ; } RepositoryConfiguration repositoryConfiguration = repositoryConfigurationRepository . queryById ( repositoryConfigurationId ) ; if ( repositoryConfiguration == null ) { String errorMessage = "Repository Configuration was not found in database." ; LOG . error ( errorMessage ) ; sendErrorMessage ( repositoryConfigurationId , buildConfigurationSavedId , errorMessage ) ; return ; } if ( buildConfigurationRest != null ) { // TODO test me
BuildConfiguration buildConfiguration = buildConfigurationRest . toDBEntityBuilder ( ) . repositoryConfiguration ( repositoryConfiguration ) . build ( ) ; BuildConfiguration buildConfigurationSaved = buildConfigurationRepository . save ( buildConfiguration ) ; buildConfigurationSavedId = buildConfigurationSaved . getId ( ) ; Set < Integer > bcSetIds = buildConfigurationRest . getBuildConfigurationSetIds ( ) ; try { if ( bcSetIds != null ) { addBuildConfigurationToSet ( buildConfigurationSaved , bcSetIds ) ; } } catch ( Exception e ) { LOG . error ( e . getMessage ( ) ) ; sendErrorMessage ( repositoryConfigurationId , buildConfigurationSavedId , e . getMessage ( ) ) ; return ; } } RepositoryCreationResultRest repositoryCreationResultRest = new RepositoryCreationResultRest ( repositoryConfigurationId , buildConfigurationSavedId , RepositoryCreationResultRest . EventType . RC_CREATION_SUCCESS , null ) ; wsNotifier . sendMessage ( repositoryCreationResultRest ) ; // TODO test me !


signature:
public class BpmEndpoint { /** * This method will add listeners to all important RCC event types
 * and forward the event to WS clients . */
private void addWebsocketForwardingListeners ( RepositoryCreationTask task ) { } }

implementation:
Consumer < ? extends BpmNotificationRest > doNotify = ( e ) -> wsNotifier . sendMessage ( e ) ; task . addListener ( BpmEventType . RC_REPO_CREATION_SUCCESS , doNotify ) ; task . addListener ( BpmEventType . RC_REPO_CREATION_ERROR , doNotify ) ; task . addListener ( BpmEventType . RC_REPO_CLONE_SUCCESS , doNotify ) ; task . addListener ( BpmEventType . RC_REPO_CLONE_ERROR , doNotify ) ; // clients are notified from callback in startRCreationTask
// task . addListener ( BpmEventType . RC _ CREATION _ SUCCESS , doNotify ) ;
task . addListener ( BpmEventType . RC_CREATION_ERROR , doNotify ) ;


signature:
public class ArtifactBuilder { /** * Create an artifact with an import date and origin url */
public static Artifact mockImportedArtifact ( int id ) { } }

implementation: return getArtifactBuilder ( id ) . importDate ( Date . from ( Instant . now ( ) ) ) . originUrl ( "http://central.maven.org/org/jboss/mock/artifactFile" + id + ".jar" ) . build ( ) ;


signature:
public class HttpUtil { /** * Sets flag telling if SSL hostname validation should be done which also clears the cached httpClient . This method
 * is not thread - safe and could cause race conditions if the class is used with different settings at the same
 * time , but that is not expected .
 * @ param sslRequired the desired value */
public static void setSslRequired ( boolean sslRequired ) { } }

implementation: if ( HttpUtil . sslRequired != sslRequired ) { HttpUtil . sslRequired = sslRequired ; HttpUtil . httpClient = null ; }


signature:
public class TemporaryBuildsCleaner { /** * Deletes a BuildConfigSetRecord and BuildRecords produced in the build
 * @ param buildConfigSetRecordId BuildConfigSetRecord to be deleted
 * @ param authToken */
public Result deleteTemporaryBuildConfigSetRecord ( Integer buildConfigSetRecordId , String authToken ) throws ValidationException { } }

implementation: BuildConfigSetRecord buildConfigSetRecord = buildConfigSetRecordRepository . queryById ( buildConfigSetRecordId ) ; if ( ! buildConfigSetRecord . isTemporaryBuild ( ) ) { throw new ValidationException ( "Only deletion of the temporary builds is allowed" ) ; } log . info ( "Starting deletion of a temporary build record set " + buildConfigSetRecord ) ; for ( BuildRecord br : buildConfigSetRecord . getBuildRecords ( ) ) { Result result = deleteTemporaryBuild ( br . getId ( ) , authToken ) ; if ( ! result . isSuccess ( ) ) { return result ; } } buildConfigSetRecordRepository . delete ( buildConfigSetRecord . getId ( ) ) ; log . info ( "Deletion of a temporary build record set {} finished successfully." , buildConfigSetRecord ) ; return new Result ( buildConfigSetRecordId . toString ( ) , Result . Status . SUCCESS ) ;


signature:
public class DefaultBuildCoordinator { /** * Run a single build . Uses the settings from the latest saved / audited build configuration .
 * @ param buildConfiguration The build configuration which will be used . The latest version of this
 * build config will be built .
 * @ param user The user who triggered the build .
 * @ param buildOptions Customization of a build specified by user
 * @ return The new build task
 * @ throws BuildConflictException If there is already a build running with the same build configuration Id and version */
@ Override public BuildSetTask build ( BuildConfiguration buildConfiguration , User user , BuildOptions buildOptions ) throws BuildConflictException { } }

implementation: BuildConfigurationAudited buildConfigurationAudited = datastoreAdapter . getLatestBuildConfigurationAuditedInitializeBCDependencies ( buildConfiguration . getId ( ) ) ; return build0 ( user , buildOptions , buildConfigurationAudited ) ;


signature:
public class DefaultBuildCoordinator { /** * Run a single build . Uses the settings from the specific revision of a BuildConfiguration .
 * The dependencies are resolved by the BuildConfiguration relations and are used in the latest revisions
 * @ param buildConfigurationAudited A revision of a BuildConfiguration which will be used .
 * @ param user The user who triggered the build .
 * @ param buildOptions Customization of a build specified by user
 * @ return The new build task
 * @ throws BuildConflictException If there is already a build running with the same build configuration Id and revision */
@ Override public BuildSetTask build ( BuildConfigurationAudited buildConfigurationAudited , User user , BuildOptions buildOptions ) throws BuildConflictException { } }

implementation: return build0 ( user , buildOptions , buildConfigurationAudited ) ;


signature:
public class DefaultBuildCoordinator { /** * Run a set of builds . Only the current / latest version of builds in the given set will be executed . The
 * order of execution is determined by the dependency relations between the build configurations .
 * @ param buildConfigurationSet The set of builds to be executed .
 * @ param user The user who triggered the build .
 * @ param buildOptions Customization of a build specified by user
 * @ return The new build set task
 * @ throws CoreException Thrown if there is a problem initializing the build */
@ Override public BuildSetTask build ( BuildConfigurationSet buildConfigurationSet , User user , BuildOptions buildOptions ) throws CoreException { } }

implementation: synchronized ( buildMethodLock ) { BuildSetTask buildSetTask = buildTasksInitializer . createBuildSetTask ( buildConfigurationSet , user , buildOptions , this :: buildRecordIdSupplier , buildQueue . getUnfinishedTasks ( ) ) ; updateBuildSetTaskStatus ( buildSetTask , BuildSetStatus . NEW ) ; validateAndEnqueueBuildConfigurationSetTasks ( buildConfigurationSet , buildOptions , buildSetTask ) ; return buildSetTask ; }


signature:
public class DefaultBuildCoordinator { /** * Check if the given build set task is empty and update the status message appropriately */
private void checkForEmptyBuildSetTask ( BuildSetTask buildSetTask ) { } }

implementation: if ( buildSetTask . getBuildTasks ( ) == null || buildSetTask . getBuildTasks ( ) . isEmpty ( ) ) { updateBuildSetTaskStatus ( buildSetTask , BuildSetStatus . REJECTED , "Build config set is empty" ) ; }


signature:
public class EnvironmentDriverFactory { /** * Gets environment driver , which can manage requested environment
 * @ return Available driver for given systemImageType
 * @ throws ExecutorException Throw if no suitable driver for selected environment was found */
public EnvironmentDriver getDriver ( SystemImageType systemImageType ) throws ExecutorException { } }

implementation: for ( EnvironmentDriver driver : availableDrivers ) { if ( driver . canRunImageType ( systemImageType ) ) return driver ; } throw new ExecutorException ( "No environment driver available for " + systemImageType + " system image type." ) ;


signature:
public class BuildConfigurationPredicates { /** * Return a predicate which excludes all archived build configurations
 * @ return */
public static Predicate < BuildConfiguration > isNotArchived ( ) { } }

implementation: return ( root , query , cb ) -> cb . isTrue ( root . get ( BuildConfiguration_ . active ) ) ;


signature:
public class DatastoreAdapter { /** * Fetch build configurations of project to be able access it outside transaction
 * @ param buildConfigAudited build config for which the build configurations are to be fetched */
private void loadBuildConfigurations ( BuildConfigurationAudited buildConfigAudited ) { } }

implementation: Project project = buildConfigAudited . getProject ( ) ; project . getBuildConfigurations ( ) . forEach ( BuildConfiguration :: getId ) ;