Skip to content

Commit

Permalink
cleaning code, removed useless prints
Browse files Browse the repository at this point in the history
  • Loading branch information
- committed Feb 19, 2019
1 parent a0e877a commit 56ae0f0
Show file tree
Hide file tree
Showing 26 changed files with 532 additions and 452 deletions.
32 changes: 17 additions & 15 deletions src/main/java/com/synopsys/protecode/sc/jenkins/Configuration.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
/*******************************************************************************
* Copyright (c) 2018 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
*******************************************************************************/

/** *****************************************************************************
* Copyright (c) 2018 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
****************************************************************************** */
package com.synopsys.protecode.sc.jenkins;

/**
* A convenient location to store variables which can easily be found and edited
*/
public class Configuration {

/**
* The maximum simultaneous requests to Protecode SC backend. Current maximum is 4, more requests
* will throw 503, "service unavailable" sometimes
* The maximum simultaneous requests to BDBA backend. Current maximum is 4, more requests will throw 503,
* "service unavailable" sometimes
*/
public static final int MAX_REQUESTS_TO_PROTECODE = 4;

Expand All @@ -43,6 +43,8 @@ public class Configuration {
// TODO: Get name with version also. This could be done by using resources.
public static final String CLIENT_NAME = "Protecode Jenkins Plugin";

/** Convenience for making sure the tool name is correct. */
public static final String TOOL_NAME = "Black Duck Binary Analysis";
/**
* Convenience for making sure the tool name is correct.
*/
public static final String TOOL_NAME = "BDBA";
}
Original file line number Diff line number Diff line change
@@ -1,42 +1,43 @@
/*******************************************************************************
* Copyright (c) 2017 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
*******************************************************************************/
/** *****************************************************************************
* Copyright (c) 2017 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
****************************************************************************** */
package com.synopsys.protecode.sc.jenkins;

import com.synopsys.protecode.sc.jenkins.types.FileResult;
import com.synopsys.protecode.sc.jenkins.types.BuildVerdict;
import com.synopsys.protecode.sc.jenkins.types.FileResult;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ProtecodeEvaluator {

private static final Logger LOGGER = Logger.getLogger(ProtecodeEvaluator.class.getName());

/**
* Evaluates the results. Any vulnerabilities or errors associated to file scans will cause false
* to be returned.
* Evaluates the results. Any vulnerabilities or errors associated to file scans will cause false to be
* returned.
*
* @param results The results for the given scan.
* @param verdict The verdict to further while evaluating the build.
*/
public static void evaluate(List<FileResult> results, BuildVerdict verdict) {
LOGGER.log(Level.INFO, "Evaluating scan results");
boolean hasVulns = results.stream().anyMatch((result) -> {
if (result.verdict()) {
LOGGER.log(Level.INFO, result.getFilename() + " has result: " + result.verdict());
return false;
} else {
LOGGER.log(Level.INFO, result.getFilename() + " has error: " + result.getError());
return true; // has untriaged vulns or an error
}
if (result.verdict()) {
LOGGER.log(Level.INFO, result.getFilename() + " has result: " + result.verdict());
return false;
} else {
LOGGER.log(Level.INFO, result.getFilename() + " has error: " + result.getError());
return true; // has untriaged vulns or an error
}
}
);
verdict.setFilesWithUntriagedVulns(hasVulns);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*******************************************************************************
/** *****************************************************************************
* Copyright (c) 2017 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
Expand All @@ -7,7 +7,7 @@
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
*******************************************************************************/
****************************************************************************** */
package com.synopsys.protecode.sc.jenkins;

import com.cloudbees.plugins.credentials.CredentialsProvider;
Expand Down Expand Up @@ -39,22 +39,24 @@ private ProtecodeScConnection() {
}

/**
* Simple backend for checking the server and such. This backend doesn't use authentication. It
* does not have declarations for any Protecode SC API calls, only server level calls.
* Simple backend for checking the server and such. This backend doesn't use authentication. It does not
* have declarations for any Protecode SC API calls, only server level calls.
*
* @param checkCertificate whether or not to check the server certificate.
* @param url The URL which points to the Protecode SC instance.
* @return the backend to use while communicating to the server with no authentication
*/
public static ProtecodeScServicesApi serviceBackend(URL url, boolean checkCertificate) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url.toExternalForm())
.build();
.baseUrl(url.toExternalForm())
.build();

return retrofit.create(ProtecodeScServicesApi.class);
}

/**
* Main entry point for building a backend implementation in run-time.
*
* @param credentialsId the identifier for the credentials to be used.
* @param url The url which points to the protecode-sc instance.
* @param run The context for getting the credentials
Expand All @@ -74,19 +76,19 @@ public static ProtecodeScApi backend(
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient okHttpClient = httpClientBuilder(checkCertificate).addInterceptor(
(Interceptor.Chain chain) ->
{
Request originalRequest = chain.request();
(Interceptor.Chain chain)
-> {
Request originalRequest = chain.request();

Request.Builder builder = originalRequest.newBuilder()
.addHeader("User-Agent", Configuration.CLIENT_NAME)
.addHeader("Connection", "close");
Request.Builder builder = originalRequest.newBuilder()
.addHeader("User-Agent", Configuration.CLIENT_NAME)
.addHeader("Connection", "close");

builder.header("Authorization", authenticationString(credentialsId, run, url));
builder.header("Authorization", authenticationString(credentialsId, run, url));

Request newRequest = builder.build();
return chain.proceed(newRequest);
}
Request newRequest = builder.build();
return chain.proceed(newRequest);
}
).readTimeout(Configuration.TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Configuration.TIMEOUT_SECONDS, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
Expand All @@ -96,7 +98,7 @@ public static ProtecodeScApi backend(
// a nice fashion.

okHttpClient.dispatcher().setMaxRequests(Configuration.MAX_REQUESTS_TO_PROTECODE);
LOGGER.log(Level.ALL, "Max simultaneous requests to protecode limited to: {0}",
LOGGER.log(Level.ALL, "Max simultaneous requests to " + Configuration.TOOL_NAME + " limited to: {0}",
okHttpClient.dispatcher().getMaxRequests());

Retrofit retrofit = new Retrofit.Builder()
Expand All @@ -112,7 +114,7 @@ public static ProtecodeScApi backend(
* Method returns authentication string based on the credentials type.
*
* @param credentialsId the identifier for the credentials to be used.
* @param url The url which points to the protecode-sc instance.
* @param url The url which points to the BDBA instance.
* @param run The context for getting the credentials
* @return The string to use with authorization header
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,58 +10,45 @@
****************************************************************************** */
package com.synopsys.protecode.sc.jenkins;

import com.synopsys.protecode.sc.jenkins.types.BuildVerdict;
import com.synopsys.protecode.sc.jenkins.types.FileResult;
import com.synopsys.protecode.sc.jenkins.utils.JenkinsConsoler;
import com.synopsys.protecode.sc.jenkins.utils.ReportBuilder;
import com.synopsys.protecode.sc.jenkins.utils.UtilitiesFile;

import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.HostnameRequirement;

import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Launcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.synopsys.protecode.sc.jenkins.Scanner;
import com.synopsys.protecode.sc.jenkins.types.BuildVerdict;
import com.synopsys.protecode.sc.jenkins.types.FileResult;
import com.synopsys.protecode.sc.jenkins.utils.*;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.*;
import hudson.model.*;
import hudson.security.ACL;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.*;
import jenkins.tasks.SimpleBuildStep;

import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.*;
import java.util.Optional;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.servlet.ServletException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.synopsys.protecode.sc.jenkins.utils.*;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.Optional;

import jenkins.tasks.SimpleBuildStep;
import lombok.Getter;
import lombok.Setter;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.*;

/**
* TODO: There are much too many variables stored on the object level. Maybe we could perhaps store
* them in a configuration object or much more preferably as temp variables being moved in the
* methods.
* TODO: There are much too many variables stored on the object level. Maybe we could perhaps store them in a
* configuration object or much more preferably as temp variables being moved in the methods.
*/
public class ProtecodeScPlugin extends Builder implements SimpleBuildStep {

Expand All @@ -72,7 +59,9 @@ public class ProtecodeScPlugin extends Builder implements SimpleBuildStep {
private String customHeader;
private boolean includeSubdirectories;
private String pattern; // Be carefull with this.
/** Will cause the plugin to use a Jenkins service to fetch only artifacts from the specified directory */
/**
* Will cause the plugin to use a Jenkins service to fetch only artifacts from the specified directory
*/
private boolean scanOnlyArtifacts;
private boolean convertToSummary;
private boolean failIfVulns;
Expand Down Expand Up @@ -121,9 +110,9 @@ public ProtecodeScPlugin(
}

/**
* For backward compatibility. The XML persistence will build the instance in memory with out much
* logic and since some values are empty, they will default to null. This method is called right
* after the "resurrection" of the object and checks all non-trivial values.
* For backward compatibility. The XML persistence will build the instance in memory with out much logic and
* since some values are empty, they will default to null. This method is called right after the
* "resurrection" of the object and checks all non-trivial values.
*
* @return a ProtecodeScPlugin object with values which might be null.
*/
Expand Down Expand Up @@ -161,8 +150,7 @@ private ProtecodeScService service(Run<?, ?> run) {
if (service == null
// We need to check whether we need a new instance of the backend.
|| !getDescriptor().getProtecodeScHost().equals(storedHost.toExternalForm())
|| getDescriptor().isDontCheckCert() != storedDontCheckCertificate
) {
|| getDescriptor().isDontCheckCert() != storedDontCheckCertificate) {
LOGGER.finer("Making new " + Configuration.TOOL_NAME + " http connection service");
storedHost = new URL(getDescriptor().getProtecodeScHost());
storedDontCheckCertificate = getDescriptor().isDontCheckCert();
Expand All @@ -182,7 +170,7 @@ private ProtecodeScService service(Run<?, ?> run) {
LOGGER.warning("No URL given for " + Configuration.TOOL_NAME);
listener.error("Cannot read " + Configuration.TOOL_NAME + " URL, please make sure it has been set in the Jenkins"
+ " configuration page.");
// TODO: Add prebuild
// TODO: Add prebuild
}
return service;
}
Expand Down Expand Up @@ -279,7 +267,7 @@ public boolean doPerform(Run<?, ?> run, FilePath workspace)
run.setResult(Result.SUCCESS);
return true;
}
if(endAfterSendingFiles) {
if (endAfterSendingFiles) {
LOGGER.info("Files sent, ending " + Configuration.TOOL_NAME + " phase due to configuration.");
console.log("Files sent, ending phase.");
run.setResult(Result.SUCCESS);
Expand Down Expand Up @@ -348,17 +336,24 @@ public String getTask() {
@Extension
@Symbol("protecodesc")
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> implements ExtensionPoint {
/** Read from jelly */

/**
* Read from jelly
*/
public static final int defaultTimeout = 60;
/** Read from jelly */
/**
* Read from jelly
*/
public static final boolean defaultFailIfVulns = true;
public static final boolean defaultEndAfterSendingFiles = false;
public static final boolean defaultDontZipFiles = false;

@Getter @Setter
@Getter
@Setter
protected String protecodeScHost;

@Getter @Setter
@Getter
@Setter
protected boolean dontCheckCert;

public DescriptorImpl() {
Expand Down Expand Up @@ -433,7 +428,7 @@ public FormValidation doCheckProtecodeScGroup(@QueryParameter String protecodeSc
try {
Integer.parseInt(protecodeScGroup);
return FormValidation.ok();
} catch (Exception e) {
} catch (NumberFormatException e) {
return FormValidation.error("Please provide a valid group. The group should a plain number,"
+ "not a URL or a name.");
}
Expand Down Expand Up @@ -467,14 +462,14 @@ public FormValidation doCheckTimeout(@QueryParameter String timeout) {
try {
Integer.parseInt(timeout);
return FormValidation.ok();
} catch (Exception e) {
} catch (NumberFormatException e) {
return FormValidation.error("Please provide a valid timeout in minutes.");
}
}

@Override
public String getDisplayName() {
return "Protecode SC";
return Configuration.TOOL_NAME;
}

@Override
Expand Down

0 comments on commit 56ae0f0

Please sign in to comment.