|
| 1 | +package com.redhat.digkins.services; |
| 2 | + |
| 3 | +import com.offbytwo.jenkins.JenkinsServer; |
| 4 | +import com.offbytwo.jenkins.model.Artifact; |
| 5 | +import com.offbytwo.jenkins.model.Build; |
| 6 | +import com.offbytwo.jenkins.model.BuildWithDetails; |
| 7 | +import org.jtwig.JtwigModel; |
| 8 | +import org.jtwig.JtwigTemplate; |
| 9 | +import org.slf4j.Logger; |
| 10 | +import org.slf4j.LoggerFactory; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.io.InputStream; |
| 14 | +import java.net.URI; |
| 15 | +import java.net.URISyntaxException; |
| 16 | +import java.util.List; |
| 17 | + |
| 18 | +/** |
| 19 | + * Service used to retrieve artifacts |
| 20 | + */ |
| 21 | +public class ArtifactsService { |
| 22 | + |
| 23 | + private JenkinsServer jenkins; |
| 24 | + |
| 25 | + /** |
| 26 | + * @param jenkins jenkins api instance |
| 27 | + */ |
| 28 | + public ArtifactsService(JenkinsServer jenkins) { |
| 29 | + this.jenkins = jenkins; |
| 30 | + } |
| 31 | + |
| 32 | + private static final Logger LOG = LoggerFactory.getLogger(ArtifactsService.class); |
| 33 | + |
| 34 | + /** |
| 35 | + * Fetch artifacts urls for specific job and build number |
| 36 | + * |
| 37 | + * @param jobName name of the job |
| 38 | + * @param buildNumber job build number |
| 39 | + * @param artifactName - name of the artifact to fetch - can be regexp |
| 40 | + * @return InputStream with file contents |
| 41 | + */ |
| 42 | + public InputStream fetchArtifact(String jobName, long buildNumber, String artifactName) { |
| 43 | + try { |
| 44 | + Build build = jenkins.getBuild(jobName, buildNumber); |
| 45 | + if (build instanceof BuildWithDetails) { |
| 46 | + BuildWithDetails buildWithDetails = ((BuildWithDetails) build); |
| 47 | + List<Artifact> artifacts = buildWithDetails.getArtifacts(); |
| 48 | + for (Artifact artifact : artifacts) { |
| 49 | + if (artifact.getFileName().matches(artifactName)) { |
| 50 | + LOG.debug("Streaming artifact {0}", artifactName); |
| 51 | + return buildWithDetails.downloadArtifact(artifact); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + } |
| 56 | + } catch (Exception e) { |
| 57 | + LOG.error("Problem when fetching artifacts for {0} {1} {2}", jobName, buildNumber, artifactName, e); |
| 58 | + } |
| 59 | + LOG.debug("Cannot find build for ", jobName, buildNumber, artifactName); |
| 60 | + return null; |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments