code
stringlengths
73
34.1k
label
stringclasses
1 value
public int expect(String pattern) throws MalformedPatternException, Exception { logger.trace("Searching for '" + pattern + "' in the reader stream"); return expect(pattern, null); }
java
protected ExpectState prepareClosure(int pairIndex, MatchResult result) { /* TODO: potentially remove this? { System.out.println( "Begin: " + result.beginOffset(0) ); System.out.println( "Length: " + result.length() ); System.out.println( "Current: " + input.getCurrentOffset() ); System.out.println( "Begin: " + input.getMatchBeginOffset() ); System.out.println( "End: " + input.getMatchEndOffset() ); //System.out.println( "Match: " + input.match() ); //System.out.println( "Pre: >" + input.preMatch() + "<"); //System.out.println( "Post: " + input.postMatch() ); } */ // Prepare Closure environment ExpectState state; Map<String, Object> prevMap = null; if (g_state != null) { prevMap = g_state.getVars(); } int matchedWhere = result.beginOffset(0); String matchedText = result.toString(); // expect_out(0,string) // Unmatched upto end of match // expect_out(buffer) char[] chBuffer = input.getBuffer(); String copyBuffer = new String(chBuffer, 0, result.endOffset(0) ); List<String> groups = new ArrayList<>(); for (int j = 1; j <= result.groups(); j++) { String group = result.group(j); groups.add( group ); } state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap); return state; }
java
public void cmdProc(Interp interp, TclObject argv[]) throws TclException { int currentObjIndex, len, i; int objc = argv.length - 1; boolean doBackslashes = true; boolean doCmds = true; boolean doVars = true; StringBuffer result = new StringBuffer(); String s; char c; for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) { if (!argv[currentObjIndex].toString().startsWith("-")) { break; } int opt = TclIndex.get(interp, argv[currentObjIndex], validCmds, "switch", 0); switch (opt) { case OPT_NOBACKSLASHES: doBackslashes = false; break; case OPT_NOCOMMANDS: doCmds = false; break; case OPT_NOVARS: doVars = false; break; default: throw new TclException(interp, "SubstCrCmd.cmdProc: bad option " + opt + " index to cmds"); } } if (currentObjIndex != objc) { throw new TclNumArgsException(interp, currentObjIndex, argv, "?-nobackslashes? ?-nocommands? ?-novariables? string"); } /* * Scan through the string one character at a time, performing * command, variable, and backslash substitutions. */ s = argv[currentObjIndex].toString(); len = s.length(); i = 0; while (i < len) { c = s.charAt(i); if ((c == '[') && doCmds) { ParseResult res; try { interp.evalFlags = Parser.TCL_BRACKET_TERM; interp.eval(s.substring(i + 1, len)); TclObject interp_result = interp.getResult(); interp_result.preserve(); res = new ParseResult(interp_result, i + interp.termOffset); } catch (TclException e) { i = e.errIndex + 1; throw e; } i = res.nextIndex + 2; result.append( res.value.toString() ); res.release(); /** * Removed (ToDo) may not be portable on Mac } else if (c == '\r') { i++; */ } else if ((c == '$') && doVars) { ParseResult vres = Parser.parseVar(interp, s.substring(i, len)); i += vres.nextIndex; result.append( vres.value.toString() ); vres.release(); } else if ((c == '\\') && doBackslashes) { BackSlashResult bs = Interp.backslash(s, i, len); i = bs.nextIndex; if (bs.isWordSep) { break; } else { result.append( bs.c ); } } else { result.append( c ); i++; } } interp.setResult(result.toString()); }
java
public static void mergeReports(File reportOverall, File... reports) { SessionInfoStore infoStore = new SessionInfoStore(); ExecutionDataStore dataStore = new ExecutionDataStore(); boolean isCurrentVersionFormat = loadSourceFiles(infoStore, dataStore, reports); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(reportOverall))) { Object visitor; if (isCurrentVersionFormat) { visitor = new ExecutionDataWriter(outputStream); } else { visitor = new org.jacoco.previous.core.data.ExecutionDataWriter(outputStream); } infoStore.accept((ISessionInfoVisitor) visitor); dataStore.accept((IExecutionDataVisitor) visitor); } catch (IOException e) { throw new IllegalStateException(String.format("Unable to write overall coverage report %s", reportOverall.getAbsolutePath()), e); } }
java
public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) { if (jacocoExecutionData == null) { return this; } JaCoCoExtensions.logger().info("Analysing {}", jacocoExecutionData); try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) { if (useCurrentBinaryFormat) { ExecutionDataReader reader = new ExecutionDataReader(inputStream); reader.setSessionInfoVisitor(sessionInfoStore); reader.setExecutionDataVisitor(executionDataVisitor); reader.read(); } else { org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream); reader.setSessionInfoVisitor(sessionInfoStore); reader.setExecutionDataVisitor(executionDataVisitor); reader.read(); } } catch (IOException e) { throw new IllegalArgumentException(String.format("Unable to read %s", jacocoExecutionData.getAbsolutePath()), e); } return this; }
java
public ArtifactName build() { String groupId = this.groupId; String artifactId = this.artifactId; String classifier = this.classifier; String packaging = this.packaging; String version = this.version; if (artifact != null && !artifact.isEmpty()) { final String[] artifactSegments = artifact.split(":"); // groupId:artifactId:version[:packaging][:classifier]. String value; switch (artifactSegments.length) { case 5: value = artifactSegments[4].trim(); if (!value.isEmpty()) { classifier = value; } case 4: value = artifactSegments[3].trim(); if (!value.isEmpty()) { packaging = value; } case 3: value = artifactSegments[2].trim(); if (!value.isEmpty()) { version = value; } case 2: value = artifactSegments[1].trim(); if (!value.isEmpty()) { artifactId = value; } case 1: value = artifactSegments[0].trim(); if (!value.isEmpty()) { groupId = value; } } } return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version); }
java
public static Deployment of(final File content) { final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("content", content).toPath()); return new Deployment(deploymentContent, null); }
java
public static Deployment of(final Path content) { final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("content", content)); return new Deployment(deploymentContent, null); }
java
public static Deployment of(final URL url) { final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("url", url)); return new Deployment(deploymentContent, null); }
java
public Deployment setServerGroups(final Collection<String> serverGroups) { this.serverGroups.clear(); this.serverGroups.addAll(serverGroups); return this; }
java
protected void validate(final boolean isDomain) throws MojoDeploymentException { final boolean hasServerGroups = hasServerGroups(); if (isDomain) { if (!hasServerGroups) { throw new MojoDeploymentException( "Server is running in domain mode, but no server groups have been defined."); } } else if (hasServerGroups) { throw new MojoDeploymentException("Server is running in standalone mode, but server groups have been defined."); } }
java
private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) { final ModelNode op = ServerOperations.createAddOperation(address); for (Map.Entry<String, String> prop : properties.entrySet()) { final String[] props = prop.getKey().split(","); if (props.length == 0) { throw new RuntimeException("Invalid property " + prop); } ModelNode node = op; for (int i = 0; i < props.length - 1; ++i) { node = node.get(props[i]); } final String value = prop.getValue() == null ? "" : prop.getValue(); if (value.startsWith("!!")) { handleDmrString(node, props[props.length - 1], value); } else { node.get(props[props.length - 1]).set(value); } } return op; }
java
private void handleDmrString(final ModelNode node, final String name, final String value) { final String realValue = value.substring(2); node.get(name).set(ModelNode.fromString(realValue)); }
java
private ModelNode parseAddress(final String profileName, final String inputAddress) { final ModelNode result = new ModelNode(); if (profileName != null) { result.add(ServerOperations.PROFILE, profileName); } String[] parts = inputAddress.split(","); for (String part : parts) { String[] address = part.split("="); if (address.length != 2) { throw new RuntimeException(part + " is not a valid address segment"); } result.add(address[0], address[1]); } return result; }
java
public static ContainerDescription getContainerDescription(final ModelControllerClient client) throws IOException, OperationExecutionException { return DefaultContainerDescription.lookup(Assert.checkNotNullParam("client", client)); }
java
public static void waitForDomain(final ModelControllerClient client, final long startupTimeout) throws InterruptedException, RuntimeException, TimeoutException { waitForDomain(null, client, startupTimeout); }
java
public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException { // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation. // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to // have this issue. // First shutdown the servers final ModelNode stopServersOp = Operations.createOperation("stop-servers"); stopServersOp.get("blocking").set(true); stopServersOp.get("timeout").set(timeout); ModelNode response = client.execute(stopServersOp); if (!Operations.isSuccessfulOutcome(response)) { throw new OperationExecutionException("Failed to stop servers.", stopServersOp, response); } // Now shutdown the host final ModelNode address = determineHostAddress(client); final ModelNode shutdownOp = Operations.createOperation("shutdown", address); response = client.execute(shutdownOp); if (Operations.isSuccessfulOutcome(response)) { // Wait until the process has died while (true) { if (isDomainRunning(client, true)) { try { TimeUnit.MILLISECONDS.sleep(20L); } catch (InterruptedException e) { LOGGER.trace("Interrupted during sleep", e); } } else { break; } } } else { throw new OperationExecutionException("Failed to shutdown host.", shutdownOp, response); } }
java
public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException { final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, "local-host-name"); ModelNode response = client.execute(op); if (Operations.isSuccessfulOutcome(response)) { return DeploymentOperations.createAddress("host", Operations.readResult(response).asString()); } throw new OperationExecutionException(op, response); }
java
public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout) throws InterruptedException, RuntimeException, TimeoutException { waitForStandalone(null, client, startupTimeout); }
java
public static boolean isStandaloneRunning(final ModelControllerClient client) { try { final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, "server-state")); if (Operations.isSuccessfulOutcome(response)) { final String state = Operations.readResult(response).asString(); return !CONTROLLER_PROCESS_STATE_STARTING.equals(state) && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state); } } catch (RuntimeException | IOException e) { LOGGER.trace("Interrupted determining if standalone is running", e); } return false; }
java
public static void shutdownStandalone(final ModelControllerClient client, final int timeout) throws IOException { final ModelNode op = Operations.createOperation("shutdown"); op.get("timeout").set(timeout); final ModelNode response = client.execute(op); if (Operations.isSuccessfulOutcome(response)) { while (true) { if (isStandaloneRunning(client)) { try { TimeUnit.MILLISECONDS.sleep(20L); } catch (InterruptedException e) { LOGGER.trace("Interrupted during sleep", e); } } else { break; } } } else { throw new OperationExecutionException(op, response); } }
java
public static PackageType resolve(final MavenProject project) { final String packaging = project.getPackaging().toLowerCase(Locale.ROOT); if (DEFAULT_TYPES.containsKey(packaging)) { return DEFAULT_TYPES.get(packaging); } return new PackageType(packaging); }
java
public static String getJavaCommand(final Path javaHome) { final Path resolvedJavaHome = javaHome == null ? findJavaHome() : javaHome; final String exe; if (resolvedJavaHome == null) { exe = "java"; } else { exe = resolvedJavaHome.resolve("bin").resolve("java").toString(); } if (exe.contains(" ")) { return "\"" + exe + "\""; } if (WINDOWS) { return exe + ".exe"; } return exe; }
java
public static UndeployDescription of(final DeploymentDescription deploymentDescription) { Assert.checkNotNullParam("deploymentDescription", deploymentDescription); return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups()); }
java
public static Operation createDeployOperation(final DeploymentDescription deployment) { Assert.checkNotNullParam("deployment", deployment); final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true); addDeployOperationStep(builder, deployment); return builder.build(); }
java
public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) { Assertions.requiresNotNullOrNotEmptyParameter("deployments", deployments); final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true); for (DeploymentDescription deployment : deployments) { addDeployOperationStep(builder, deployment); } return builder.build(); }
java
static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) { final String name = deployment.getName(); final Set<String> serverGroups = deployment.getServerGroups(); // If the server groups are empty this is a standalone deployment if (serverGroups.isEmpty()) { final ModelNode address = createAddress(DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } else { for (String serverGroup : serverGroups) { final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } } }
java
private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) { final String deploymentName = deployment.getName(); final Set<String> serverGroups = deployment.getServerGroups(); if (serverGroups.isEmpty()) { builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName))); } else { for (String serverGroup : serverGroups) { builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName))); } } }
java
public static String getFailureDescriptionAsString(final ModelNode result) { if (isSuccessfulOutcome(result)) { return ""; } final String msg; if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { if (result.hasDefined(ClientConstants.OP)) { msg = String.format("Operation '%s' at address '%s' failed: %s", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result .get(ClientConstants.FAILURE_DESCRIPTION)); } else { msg = String.format("Operation failed: %s", result.get(ClientConstants.FAILURE_DESCRIPTION)); } } else { msg = String.format("An unexpected response was found checking the deployment. Result: %s", result); } return msg; }
java
public static ModelNode createListDeploymentsOperation() { final ModelNode op = createOperation(READ_CHILDREN_NAMES); op.get(CHILD_TYPE).set(DEPLOYMENT); return op; }
java
public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) { final ModelNode op = createRemoveOperation(address); op.get(RECURSIVE).set(recursive); return op; }
java
public static Property getChildAddress(final ModelNode address) { if (address.getType() != ModelType.LIST) { throw new IllegalArgumentException("The address type must be a list."); } final List<Property> addressParts = address.asPropertyList(); if (addressParts.isEmpty()) { throw new IllegalArgumentException("The address is empty."); } return addressParts.get(addressParts.size() - 1); }
java
public static ModelNode getParentAddress(final ModelNode address) { if (address.getType() != ModelType.LIST) { throw new IllegalArgumentException("The address type must be a list."); } final ModelNode result = new ModelNode(); final List<Property> addressParts = address.asPropertyList(); if (addressParts.isEmpty()) { throw new IllegalArgumentException("The address is empty."); } for (int i = 0; i < addressParts.size() - 1; ++i) { final Property property = addressParts.get(i); result.add(property.getName(), property.getValue()); } return result; }
java
public String getController() { final StringBuilder controller = new StringBuilder(); if (getProtocol() != null) { controller.append(getProtocol()).append("://"); } if (getHost() != null) { controller.append(getHost()); } else { controller.append("localhost"); } if (getPort() > 0) { controller.append(':').append(getPort()); } return controller.toString(); }
java
static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException { final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList()); op.get(ClientConstants.INCLUDE_RUNTIME).set(true); final ModelNode result = client.execute(op); if (Operations.isSuccessfulOutcome(result)) { final ModelNode model = Operations.readResult(result); final String productName = getValue(model, "product-name", "WildFly"); final String productVersion = getValue(model, "product-version"); final String releaseVersion = getValue(model, "release-version"); final String launchType = getValue(model, "launch-type"); return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, "DOMAIN".equalsIgnoreCase(launchType)); } throw new OperationExecutionException(op, result); }
java
public static SimpleDeploymentDescription of(final String name, @SuppressWarnings("TypeMayBeWeakened") final Set<String> serverGroups) { final SimpleDeploymentDescription result = of(name); if (serverGroups != null) { result.addServerGroups(serverGroups); } return result; }
java
@Override protected void addBuildInfoProperties(BuildInfoBuilder builder) { if (envVars != null) { for (Map.Entry<String, String> entry : envVars.entrySet()) { builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue()); } } if (sysVars != null) { for (Map.Entry<String, String> entry : sysVars.entrySet()) { builder.addProperty(entry.getKey(), entry.getValue()); } } }
java
@JavaScriptMethod @SuppressWarnings({"UnusedDeclaration"}) public LoadBuildsResponse loadBuild(String buildId) { LoadBuildsResponse response = new LoadBuildsResponse(); // When we load a new build we need also to reset the promotion plugin. // The null plugin is related to 'None' plugin. setPromotionPlugin(null); try { this.currentPromotionCandidate = promotionCandidates.get(buildId); if (this.currentPromotionCandidate == null) { throw new IllegalArgumentException("Can't find build by ID: " + buildId); } List<String> repositoryKeys = getRepositoryKeys(); List<UserPluginInfo> plugins = getPromotionsUserPluginInfo(); PromotionConfig promotionConfig = getPromotionConfig(); String defaultTargetRepository = getDefaultPromotionTargetRepository(); if (StringUtils.isNotBlank(defaultTargetRepository) && repositoryKeys.contains(defaultTargetRepository)) { promotionConfig.setTargetRepo(defaultTargetRepository); } response.addRepositories(repositoryKeys); response.setPlugins(plugins); response.setPromotionConfig(promotionConfig); response.setSuccess(true); } catch (Exception e) { response.setResponseMessage(e.getMessage()); } return response; }
java
@SuppressWarnings({"UnusedDeclaration"}) public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { req.getView(this, chooseAction()).forward(req, resp); }
java
public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID, ArtifactoryServer pipelineServer) { if (artifactoryServerID == null && pipelineServer == null) { return null; } if (artifactoryServerID != null && pipelineServer != null) { return null; } if (pipelineServer != null) { CredentialsConfig credentials = pipelineServer.createCredentialsConfig(); return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials, credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads()); } org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers()); if (server == null) { return null; } return server; }
java
public static BuildInfo appendBuildInfo(CpsScript cpsScript, Map<String, Object> stepVariables) { BuildInfo buildInfo = (BuildInfo) stepVariables.get(BUILD_INFO); if (buildInfo == null) { buildInfo = (BuildInfo) cpsScript.invokeMethod("newBuildInfo", Maps.newLinkedHashMap()); stepVariables.put(BUILD_INFO, buildInfo); } buildInfo.setCpsScript(cpsScript); return buildInfo; }
java
public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener, String buildName, String buildNumber) throws IOException { // If failFast is true, perform dry run first if (promotion.isFailFast()) { promotion.setDryRun(true); listener.getLogger().println("Performing dry run promotion (no changes are made during dry run) ..."); HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion); try { validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener); } catch (IOException e) { listener.error(e.getMessage()); return false; } listener.getLogger().println("Dry run finished successfully.\nPerforming promotion ..."); } // Perform promotion promotion.setDryRun(false); HttpResponse response = client.stageBuild(buildName, buildNumber, promotion); try { validatePromotionSuccessful(response, false, promotion.isFailFast(), listener); } catch (IOException e) { listener.error(e.getMessage()); return false; } listener.getLogger().println("Promotion completed successfully!"); return true; }
java
public static FormValidation validateEmails(String emails) { if (!Strings.isNullOrEmpty(emails)) { String[] recipients = StringUtils.split(emails, " "); for (String email : recipients) { FormValidation validation = validateInternetAddress(email); if (validation != FormValidation.ok()) { return validation; } } } return FormValidation.ok(); }
java
public static FormValidation validateArtifactoryCombinationFilter(String value) throws IOException, InterruptedException { String url = Util.fixEmptyAndTrim(value); if (url == null) return FormValidation.error("Mandatory field - You don`t have any deploy matches"); return FormValidation.ok(); }
java
public static boolean distributeAndCheckResponse(DistributionBuilder distributionBuilder, ArtifactoryBuildInfoClient client, TaskListener listener, String buildName, String buildNumber, boolean dryRun) throws IOException { // do a dry run first listener.getLogger().println("Performing dry run distribution (no changes are made during dry run) ..."); if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, true)) { return false; } listener.getLogger().println("Dry run finished successfully"); if (!dryRun) { listener.getLogger().println("Performing distribution ..."); if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, false)) { return false; } listener.getLogger().println("Distribution completed successfully!"); } return true; }
java
private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) { if (!(flexiblePublisher instanceof FlexiblePublisher)) { throw new IllegalArgumentException(String.format("Publisher should be of type: '%s'. Found type: '%s'", FlexiblePublisher.class, flexiblePublisher.getClass())); } List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers(); for (ConditionalPublisher condition : conditions) { if (type.isInstance(condition.getPublisher())) { return type.cast(condition.getPublisher()); } } return null; }
java
public T find(AbstractProject<?, ?> project, Class<T> type) { // First check that the Flexible Publish plugin is installed: if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) { // Iterate all the project's publishers and find the flexible publisher: for (Publisher publisher : project.getPublishersList()) { // Found the flexible publisher: if (publisher instanceof FlexiblePublisher) { // See if it wraps a publisher of the specified type and if it does, return it: T pub = getWrappedPublisher(publisher, type); if (pub != null) { return pub; } } } } return null; }
java
public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) { return find(project, type) != null; }
java
public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException { build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(), getSvnAuthenticationProvider(build), buildListener)); }
java
public void createTag(final String tagUrl, final String commitMessage) throws IOException, InterruptedException { build.getWorkspace() .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build), buildListener)); }
java
public void revertWorkingCopy() throws IOException, InterruptedException { build.getWorkspace() .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener)); }
java
public void safeRevertWorkingCopy() { try { revertWorkingCopy(); } catch (Exception e) { debuggingLogger.log(Level.FINE, "Failed to revert working copy", e); log("Failed to revert working copy: " + e.getLocalizedMessage()); Throwable cause = e.getCause(); if (!(cause instanceof SVNException)) { return; } SVNException svnException = (SVNException) cause; if (svnException.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) { // work space locked attempt cleanup and try to revert again try { cleanupWorkingCopy(); } catch (Exception unlockException) { debuggingLogger.log(Level.FINE, "Failed to cleanup working copy", e); log("Failed to cleanup working copy: " + e.getLocalizedMessage()); return; } try { revertWorkingCopy(); } catch (Exception revertException) { log("Failed to revert working copy on the 2nd attempt: " + e.getLocalizedMessage()); } } } }
java
public void setIssueTrackerInfo(BuildInfoBuilder builder) { Issues issues = new Issues(); issues.setAggregateBuildIssues(aggregateBuildIssues); issues.setAggregationBuildStatus(aggregationBuildStatus); issues.setTracker(new IssueTracker("JIRA", issueTrackerVersion)); Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues); if (!affectedIssuesSet.isEmpty()) { issues.setAffectedIssues(affectedIssuesSet); } builder.issues(issues); }
java
public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) { BuildRetention buildRetention = new BuildRetention(discardOldArtifacts); LogRotator rotator = null; BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder(); if (buildDiscarder != null && buildDiscarder instanceof LogRotator) { rotator = (LogRotator) buildDiscarder; } if (rotator == null) { return buildRetention; } if (rotator.getNumToKeep() > -1) { buildRetention.setCount(rotator.getNumToKeep()); } if (rotator.getDaysToKeep() > -1) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep()); buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis())); } List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build); buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted); return buildRetention; }
java
public static String getImageIdFromTag(String imageTag, String host) throws IOException { DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); return dockerClient.inspectImageCmd(imageTag).exec().getId(); } finally { closeQuietly(dockerClient); } }
java
public static void pushImage(String imageTag, String username, String password, String host) throws IOException { final AuthConfig authConfig = new AuthConfig(); authConfig.withUsername(username); authConfig.withPassword(password); DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess(); } finally { closeQuietly(dockerClient); } }
java
public static void pullImage(String imageTag, String username, String password, String host) throws IOException { final AuthConfig authConfig = new AuthConfig(); authConfig.withUsername(username); authConfig.withPassword(password); DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); dockerClient.pullImageCmd(imageTag).withAuthConfig(authConfig).exec(new PullImageResultCallback()).awaitSuccess(); } finally { closeQuietly(dockerClient); } }
java
public static String getParentId(String digest, String host) throws IOException { DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); return dockerClient.inspectImageCmd(digest).exec().getParent(); } finally { closeQuietly(dockerClient); } }
java
public static List<String> getLayersDigests(String manifestContent) throws IOException { List<String> dockerLayersDependencies = new ArrayList<String>(); JsonNode manifest = Utils.mapper().readTree(manifestContent); JsonNode schemaVersion = manifest.get("schemaVersion"); if (schemaVersion == null) { throw new IllegalStateException("Could not find 'schemaVersion' in manifest"); } boolean isSchemeVersion1 = schemaVersion.asInt() == 1; JsonNode fsLayers = getFsLayers(manifest, isSchemeVersion1); for (JsonNode fsLayer : fsLayers) { JsonNode blobSum = getBlobSum(isSchemeVersion1, fsLayer); dockerLayersDependencies.add(blobSum.asText()); } dockerLayersDependencies.add(getConfigDigest(manifestContent)); //Add manifest sha1 String manifestSha1 = Hashing.sha1().hashString(manifestContent, Charsets.UTF_8).toString(); dockerLayersDependencies.add("sha1:" + manifestSha1); return dockerLayersDependencies; }
java
public static String digestToFileName(String digest) { if (StringUtils.startsWith(digest, "sha1")) { return "manifest.json"; } return getShaVersion(digest) + "__" + getShaValue(digest); }
java
public static int getNumberOfDependentLayers(String imageContent) throws IOException { JsonNode history = Utils.mapper().readTree(imageContent).get("history"); if (history == null) { throw new IllegalStateException("Could not find 'history' tag"); } int layersNum = history.size(); boolean newImageLayers = true; for (int i = history.size() - 1; i >= 0; i--) { if (newImageLayers) { layersNum--; } JsonNode layer = history.get(i); JsonNode emptyLayer = layer.get("empty_layer"); if (!newImageLayers && emptyLayer != null) { layersNum--; } if (layer.get("created_by") == null) { continue; } String createdBy = layer.get("created_by").textValue(); if (createdBy.contains("ENTRYPOINT") || createdBy.contains("MAINTAINER")) { newImageLayers = false; } } return layersNum; }
java
private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException { FilePath pathToModuleRoot = mavenBuild.getModuleRoot(); FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null)); return pathToPom.act(new MavenModulesExtractor()); }
java
private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) { String relativePath = mavenModule.getRelativePath(); if (StringUtils.isBlank(relativePath)) { return POM_NAME; } // If this is the root module, return the root pom path. if (mavenModule.getModuleName().toString(). equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) { return mavenBuild.getProject().getRootPOM(null); } // to remove the project folder name if exists // keeps only the name of the module String modulePath = relativePath.substring(relativePath.indexOf("/") + 1); for (String moduleName : mavenModules) { if (moduleName.contains(modulePath)) { return createPomPath(relativePath, moduleName); } } // In case this module is not in the parent pom return relativePath + "/" + POM_NAME; }
java
private String createPomPath(String relativePath, String moduleName) { if (!moduleName.contains(".xml")) { // Inside the parent pom, the reference is to the pom.xml file return relativePath + "/" + POM_NAME; } // There is a reference to another xml file, which is not the pom. String dirName = relativePath.substring(0, relativePath.indexOf("/")); return dirName + "/" + moduleName; }
java
public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { MavenProject mavenProject = getMavenProject(f.getAbsolutePath()); return mavenProject.getModel().getModules(); }
java
public static String getVcsRevision(Map<String, String> env) { String revision = env.get("SVN_REVISION"); if (StringUtils.isBlank(revision)) { revision = env.get(GIT_COMMIT); } if (StringUtils.isBlank(revision)) { revision = env.get("P4_CHANGELIST"); } return revision; }
java
public static String getVcsUrl(Map<String, String> env) { String url = env.get("SVN_URL"); if (StringUtils.isBlank(url)) { url = publicGitUrl(env.get("GIT_URL")); } if (StringUtils.isBlank(url)) { url = env.get("P4PORT"); } return url; }
java
private static long daysBetween(Date date1, Date date2) { long diff; if (date2.after(date1)) { diff = date2.getTime() - date1.getTime(); } else { diff = date1.getTime() - date2.getTime(); } return diff / (24 * 60 * 60 * 1000); }
java
public static List<String> getBuildNumbersNotToBeDeleted(Run build) { List<String> notToDelete = Lists.newArrayList(); List<? extends Run<?, ?>> builds = build.getParent().getBuilds(); for (Run<?, ?> run : builds) { if (run.isKeepLog()) { notToDelete.add(String.valueOf(run.getNumber())); } } return notToDelete; }
java
public static String entityToString(HttpEntity entity) throws IOException { if (entity != null) { InputStream is = entity.getContent(); return IOUtils.toString(is, "UTF-8"); } return ""; }
java
public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException { // The token that combines the project name and unique number to create unique workspace directory. String workspaceList = System.getProperty("hudson.slaves.WorkspaceList"); return ws.act(new MasterToSlaveCallable<FilePath, IOException>() { @Override public FilePath call() { final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, "@") + "tmp").child("artifactory"); File tempDirFile = new File(tempDir.getRemote()); tempDirFile.mkdirs(); tempDirFile.deleteOnExit(); return tempDir; } }); }
java
@Override public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) { //listener.getLogger().println("[MavenDependenciesRecorder] mojo: " + mojo.getClass() + ":" + mojo.getGoal()); //listener.getLogger().println("[MavenDependenciesRecorder] dependencies: " + pom.getArtifacts()); recordMavenDependencies(pom.getArtifacts()); return true; }
java
@Override public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { build.executeAsync(new BuildCallable<Void, IOException>() { // record is transient, so needs to make a copy first private final Set<MavenDependency> d = dependencies; public Void call(MavenBuild build) throws IOException, InterruptedException { // add the action //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another //context to store these actions build.getActions().add(new MavenDependenciesRecord(build, d)); return null; } }); return true; }
java
public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) { if (deployerOverrider.isOverridingDefaultDeployer()) { CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig(); if (deployerCredentialsConfig != null) { return deployerCredentialsConfig; } } if (server != null) { CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig(); if (deployerCredentials != null) { return deployerCredentials; } } return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG; }
java
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("Jenkins Artifactory Plugin version: " + ActionableHelper.getArtifactoryPluginVersion()); EnvVars env = build.getEnvironment(listener); FilePath workDir = build.getModuleRoot(); FilePath ws = build.getWorkspace(); FilePath mavenHome = getMavenHome(listener, env, launcher); if (!mavenHome.exists()) { listener.error("Couldn't find Maven home: " + mavenHome.getRemote()); throw new Run.RunnerAbortedException(); } ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws); String[] cmds = cmdLine.toCommandArray(); return RunMaven(build, launcher, listener, env, workDir, cmds); }
java
public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir) throws InterruptedException, IOException { listener.getLogger().println("Jenkins Artifactory Plugin version: " + ActionableHelper.getArtifactoryPluginVersion()); FilePath mavenHome = getMavenHome(listener, env, launcher); if (!mavenHome.exists()) { listener.getLogger().println("Couldn't find Maven home at " + mavenHome.getRemote() + " on agent " + Utils.getAgentName(workDir) + ". This could be because this build is running inside a Docker container."); } ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir); String[] cmds = cmdLine.toCommandArray(); return RunMaven(build, launcher, listener, env, workDir, cmds); }
java
private FilePath copyClassWorldsFile(FilePath ws, URL resource) { try { FilePath remoteClassworlds = ws.createTextTempFile("classworlds", "conf", ""); remoteClassworlds.copyFrom(resource); return remoteClassworlds; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) { // Search for a publisher of the given type in the project and return it if found: T publisher = new PublisherFindImpl<T>().find(project, type); if (publisher != null) { return publisher; } // If not found, the publisher might be wrapped by a "Flexible Publish" publisher. The below searches for it inside the // Flexible Publisher: publisher = new PublisherFlexible<T>().find(project, type); return publisher; }
java
public static String getArtifactoryPluginVersion() { String pluginsSortName = "artifactory"; //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable if (Jenkins.getInstance() != null && Jenkins.getInstance().getPlugin(pluginsSortName) != null && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) { return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion(); } return ""; }
java
public static void deleteFilePath(FilePath workspace, String path) throws IOException { if (StringUtils.isNotBlank(path)) { try { FilePath propertiesFile = new FilePath(workspace, path); propertiesFile.delete(); } catch (Exception e) { throw new IOException("Could not delete temp file: " + path); } } }
java
public String getRemoteUrl(String defaultRemoteUrl) { if (StringUtils.isBlank(defaultRemoteUrl)) { RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0); URIish uri = remoteConfig.getURIs().get(0); return uri.toPrivateString(); } return defaultRemoteUrl; }
java
public String getRepoKey() { String repoKey; if (isDynamicMode()) { repoKey = keyFromText; } else { repoKey = keyFromSelect; } return repoKey; }
java
public void collectVariables(EnvVars env, Run build, TaskListener listener) { EnvVars buildParameters = Utils.extractBuildParameters(build, listener); if (buildParameters != null) { env.putAll(buildParameters); } addAllWithFilter(envVars, env, filter.getPatternFilter()); Map<String, String> sysEnv = new HashMap<>(); Properties systemProperties = System.getProperties(); Enumeration<?> enumeration = systemProperties.propertyNames(); while (enumeration.hasMoreElements()) { String propertyKey = (String) enumeration.nextElement(); sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey)); } addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter()); }
java
protected void append(Env env) { addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter()); addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter()); }
java
private void addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) { for (Object o : fromMap.entrySet()) { Map.Entry entry = (Map.Entry) o; String key = (String) entry.getKey(); if (PatternMatcher.pathConflicts(key, pattern)) { continue; } toMap.put(key, (String) entry.getValue()); } }
java
public void credentialsMigration(T overrider, Class overriderClass) { try { deployerMigration(overrider, overriderClass); resolverMigration(overrider, overriderClass); } catch (NoSuchFieldException | IllegalAccessException | IOException e) { converterErrors.add(getConversionErrorMessage(overrider, e)); } }
java
private ServerDetails createInitialResolveDetailsFromDeployDetails(ServerDetails deployerDetails) { RepositoryConf oldResolveRepositoryConfig = deployerDetails.getResolveReleaseRepository(); RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails.getResolveSnapshotRepository(); RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldResolveRepositoryConfig; RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig; return new ServerDetails(deployerDetails.getArtifactoryName(), deployerDetails.getArtifactoryUrl(), null, null, resolverReleaseRepos, resolveSnapshotRepos, null, null); }
java
private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) { RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository(); RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository(); RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig; RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig; return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(), deployReleaseRepos, deploySnapshotRepos, null, null, null, null); }
java
private static Properties loadGradleProperties(FilePath gradlePropertiesFilePath) throws IOException, InterruptedException { return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() { public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException { Properties gradleProps = new Properties(); if (gradlePropertiesFile.exists()) { debuggingLogger.fine("Gradle properties file exists at: " + gradlePropertiesFile.getAbsolutePath()); FileInputStream stream = null; try { stream = new FileInputStream(gradlePropertiesFile); gradleProps.load(stream); } catch (IOException e) { debuggingLogger.fine("IO exception occurred while trying to read properties file from: " + gradlePropertiesFile.getAbsolutePath()); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(stream); } } return gradleProps; } }); }
java
public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException { if (artifactsProps == null) { artifactsProps = ArrayListMultimap.create(); } artifactsProps.put("build.name", buildName); artifactsProps.put("build.number", buildNumber); artifactsProps.put("build.timestamp", timestamp); String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps); Properties buildInfoItemsProps = new Properties(); buildInfoItemsProps.setProperty("build.name", buildName); buildInfoItemsProps.setProperty("build.number", buildNumber); buildInfoItemsProps.setProperty("build.timestamp", timestamp); ArtifactoryServer server = config.getArtifactoryServer(); CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig(); ArtifactoryDependenciesClient dependenciesClient = null; ArtifactoryBuildInfoClient propertyChangeClient = null; try { dependenciesClient = server.createArtifactoryDependenciesClient( preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()), server.createProxyConfiguration(Jenkins.getInstance().proxy), listener); CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server); propertyChangeClient = server.createArtifactoryClient( preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()), server.createProxyConfiguration(Jenkins.getInstance().proxy)); Module buildInfoModule = new Module(); buildInfoModule.setId(imageTag.substring(imageTag.indexOf("/") + 1)); // If manifest and imagePath not found, return. if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) { return buildInfoModule; } listener.getLogger().println("Fetching details of published docker layers from Artifactory..."); boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION); DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported); listener.getLogger().println("Tagging published docker layers with build properties in Artifactory..."); setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps, dependenciesClient, propertyChangeClient, server); setBuildInfoModuleProps(buildInfoModule); return buildInfoModule; } finally { if (dependenciesClient != null) { dependenciesClient.close(); } if (propertyChangeClient != null) { propertyChangeClient.close(); } } }
java
private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException { String candidateImagePath = DockerUtils.getImagePath(imageTag); String manifestPath; // Try to get manifest, assuming reverse proxy manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, "manifest.json"}, "/"); if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) { return true; } // Try to get manifest, assuming proxy-less candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf("/") + 1); manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, "manifest.json"}, "/"); if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) { return true; } // Couldn't find correct manifest listener.getLogger().println("Could not find corresponding manifest.json file in Artifactory."); return false; }
java
private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException { String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath); if (candidateManifest == null) { return false; } String imageDigest = DockerUtils.getConfigDigest(candidateManifest); if (imageDigest.equals(imageId)) { manifest = candidateManifest; imagePath = candidateImagePath; return true; } listener.getLogger().println(String.format("Found incorrect manifest.json file in Artifactory in the following path: %s\nExpecting: %s got: %s", manifestPath, imageId, imageDigest)); return false; }
java
private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) { return buildFilesStream .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath())) .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath())) .map(org.jfrog.hudson.pipeline.types.File::new) .distinct() .collect(Collectors.toList()); }
java
public List<Integer> getConnectionRetries() { List<Integer> items = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { items.add(i); } return items; }
java
public CredentialsConfig getResolvingCredentialsConfig() { if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) { return getResolverCredentialsConfig(); } if (deployerCredentialsConfig != null) { return getDeployerCredentialsConfig(); } return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG; }
java
public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException { org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName( currentModule.groupId, currentModule.artifactId); Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap(); for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) { modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName( entry.getKey().groupId, entry.getKey().artifactId), entry.getValue()); } org.jfrog.build.extractor.maven.transformer.PomTransformer transformer = new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl, failOnSnapshot); return transformer.transform(pomFile); }
java
public void edit(int currentChangeListId, FilePath filePath) throws Exception { establishConnection().editFile(currentChangeListId, new File(filePath.getRemote())); }
java
private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) { String separator = launcher.isUnix() ? "/" : "\\"; String java_home = extendedEnv.get("JAVA_HOME"); if (StringUtils.isNotEmpty(java_home)) { if (!StringUtils.endsWith(java_home, separator)) { java_home += separator; } extendedEnv.put("PATH+JDK", java_home + "bin"); } }
java
public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) { AbstractBuild<?, ?> rootBuild = null; AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild); while (parentBuild != null) { if (isPassIdentifiedDownstream(parentBuild)) { rootBuild = parentBuild; } parentBuild = getUpstreamBuild(parentBuild); } if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) { return currentBuild; } return rootBuild; }
java
private static AbstractProject<?, ?> getProject(String fullName) { Item item = Hudson.getInstance().getItemByFullName(fullName); if (item != null && item instanceof AbstractProject) { return (AbstractProject<?, ?>) item; } return null; }
java