org.cyclonedx.CycloneDxSchema Java Examples

The following examples show how to use org.cyclonedx.CycloneDxSchema. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CycloneDxTask.java    From cyclonedx-gradle-plugin with Apache License 2.0 5 votes vote down vote up
private void initialize() {
    schemaVersion = schemaVersion();
    mavenHelper = new MavenHelper(getLogger(), schemaVersion);
    if (schemaVersion == CycloneDxSchema.Version.VERSION_10) {
        includeBomSerialNumber = false;
    } else {
        includeBomSerialNumber = getBooleanParameter("cyclonedx.includeBomSerialNumber", true);
    }
    skip = getBooleanParameter("cyclonedx.skip", false);
}
 
Example #2
Source File: CycloneDxTask.java    From cyclonedx-gradle-plugin with Apache License 2.0 5 votes vote down vote up
private Component convertArtifact(ResolvedArtifact artifact) {
    final Component component = new Component();
    component.setGroup(artifact.getModuleVersion().getId().getGroup());
    component.setName(artifact.getModuleVersion().getId().getName());
    component.setVersion(artifact.getModuleVersion().getId().getVersion());
    component.setType(Component.Type.LIBRARY);
    try {
        getLogger().debug(MESSAGE_CALCULATING_HASHES);
        component.setHashes(BomUtils.calculateHashes(artifact.getFile()));
    } catch(IOException e) {
        getLogger().error("Error encountered calculating hashes", e);
    }
    if (CycloneDxSchema.Version.VERSION_10 == schemaVersion()) {
        component.setModified(mavenHelper.isModified(artifact));
    }
    component.setPurl(generatePackageUrl(artifact));
    //if (CycloneDxSchema.Version.VERSION_10 != schemaVersion()) {
    //    component.setBomRef(component.getPurl());
    //}
    if (mavenHelper.isDescribedArtifact(artifact)) {
        final MavenProject project = mavenHelper.extractPom(artifact);
        if (project != null) {
            mavenHelper.getClosestMetadata(artifact, project, component);
        }
    }

    return component;
}
 
Example #3
Source File: CycloneDxTask.java    From cyclonedx-gradle-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the CycloneDX schema the mojo has been requested to use.
 * @return the CycloneDX schema to use
 */
private CycloneDxSchema.Version schemaVersion() {
    final Project project = super.getProject();
    if (project.hasProperty("cyclonedx.schemaVersion")) {
        final String s = (String)project.getProperties().get("cyclonedx.schemaVersion");
        if ("1.0".equals(s)) {
            return CycloneDxSchema.Version.VERSION_10;
        }
    }
    return CycloneDxSchema.Version.VERSION_11;
}
 
Example #4
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a Maven artifact (dependency or transitive dependency) into a
 * CycloneDX component./
 * @param artifact the artifact to convert
 * @return a CycloneDX component
 */
protected Component convert(Artifact artifact) {
    final Component component = new Component();
    component.setGroup(artifact.getGroupId());
    component.setName(artifact.getArtifactId());
    component.setVersion(artifact.getVersion());
    component.setType(Component.Type.LIBRARY);
    try {
        getLog().debug(MESSAGE_CALCULATING_HASHES);
        component.setHashes(BomUtils.calculateHashes(artifact.getFile()));
    } catch (IOException e) {
        getLog().error("Error encountered calculating hashes", e);
    }
    if (CycloneDxSchema.Version.VERSION_10 == schemaVersion()) {
        component.setModified(isModified(artifact));
    }
    component.setPurl(generatePackageUrl(artifact));
    if (CycloneDxSchema.Version.VERSION_10 != schemaVersion()) {
        component.setBomRef(component.getPurl());
    }
    if (isDescribedArtifact(artifact)) {
        final MavenProject project = extractPom(artifact);
        if (project != null) {
            getClosestMetadata(artifact, project, component);
        }
    }
    return component;
}
 
Example #5
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected void execute(Set<Component> components, Set<Dependency> dependencies) throws MojoExecutionException{
    try {
        getLog().info(MESSAGE_CREATING_BOM);
        final Bom bom = new Bom();
        if (CycloneDxSchema.Version.VERSION_10 != schemaVersion() && includeBomSerialNumber) {
            bom.setSerialNumber("urn:uuid:" + UUID.randomUUID().toString());
        }
        bom.setComponents(new ArrayList<>(components));
        if (getIncludeDependencyGraph() && dependencies != null && !dependencies.isEmpty()) {
            bom.setDependencies(new ArrayList<>(dependencies));
        }
        final BomGenerator bomGenerator = BomGeneratorFactory.create(schemaVersion(), bom);
        bomGenerator.generate();
        final String bomString = bomGenerator.toXmlString();
        final File bomFile = new File(project.getBasedir(), "target/bom.xml");
        getLog().info(MESSAGE_WRITING_BOM);
        FileUtils.write(bomFile, bomString, Charset.forName("UTF-8"), false);

        getLog().info(MESSAGE_VALIDATING_BOM);
        final BomParser bomParser = new BomParser();
        if (!bomParser.isValid(bomFile, schemaVersion())) {
            throw new MojoExecutionException(MESSAGE_VALIDATION_FAILURE);
        }
        if (!skipAttach) {
            mavenProjectHelper.attachArtifact(project, "xml", "cyclonedx", bomFile);
        }
    } catch (ParserConfigurationException | TransformerException | IOException | SAXException e) {
        throw new MojoExecutionException("An error occurred executing " + this.getClass().getName() + ": " + e.getMessage(), e);
    }
}
 
Example #6
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the CycloneDX schema the mojo has been requested to use.
 * @return the CycloneDX schema to use
 */
private CycloneDxSchema.Version schemaVersion() {
    if (schemaVersion != null && schemaVersion.equals("1.0")) {
        return CycloneDxSchema.Version.VERSION_10;
    } else {
        return CycloneDxSchema.Version.VERSION_11;
    }
}
 
Example #7
Source File: BomResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/cyclonedx/project/{uuid}")
@Produces(MediaType.APPLICATION_XML)
@ApiOperation(
        value = "Returns dependency metadata for a project in CycloneDX format",
        response = String.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response exportProjectAsCycloneDx (
        @ApiParam(value = "The UUID of the project to export", required = true)
        @PathParam("uuid") String uuid) {
    try (QueryManager qm = new QueryManager()) {
        final Project project = qm.getObjectByUuid(Project.class, uuid);
        if (project == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
        }
        final List<Dependency> dependencies = qm.getAllDependencies(project);
        final List<Component> components = dependencies.stream().map(Dependency::getComponent).collect(Collectors.toList());
        final List<org.cyclonedx.model.Component> cycloneComponents = components.stream().map(component -> ModelConverter.convert(qm, component)).collect(Collectors.toList());
        try {
            Bom bom = new Bom();
            bom.setSerialNumber("url:uuid:" + UUID.randomUUID().toString());
            bom.setVersion(1);
            bom.setComponents(cycloneComponents);
            final BomGenerator bomGenerator = BomGeneratorFactory.create(CycloneDxSchema.Version.VERSION_11, bom);
            bomGenerator.generate();
            return Response.ok(bomGenerator.toXmlString()).build();
        } catch (ParserConfigurationException | TransformerException e) {
            LOGGER.error("An error occurred while building a CycloneDX document for export", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
 
Example #8
Source File: BomResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/cyclonedx/components")
@Produces(MediaType.APPLICATION_XML)
@ApiOperation(
        value = "Returns dependency metadata for all components in CycloneDX format",
        response = String.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response exportComponentsAsCycloneDx () {
    try (QueryManager qm = new QueryManager()) {
        final List<Component> components = qm.getAllComponents();
        final List<org.cyclonedx.model.Component> cycloneComponents = components.stream().map(component -> ModelConverter.convert(qm, component)).collect(Collectors.toList());
        try {
            Bom bom = new Bom();
            bom.setSerialNumber("url:uuid:" + UUID.randomUUID().toString());
            bom.setVersion(1);
            bom.setComponents(cycloneComponents);
            final BomGenerator bomGenerator = BomGeneratorFactory.create(CycloneDxSchema.Version.VERSION_11, bom);
            bomGenerator.generate();
            return Response.ok(bomGenerator.toXmlString()).build();
        } catch (ParserConfigurationException | TransformerException e) {
            LOGGER.error("An error occurred while building a CycloneDX document for export", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
 
Example #9
Source File: BomResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/cyclonedx/component/{uuid}")
@Produces(MediaType.APPLICATION_XML)
@ApiOperation(
        value = "Returns dependency metadata for a specific component in CycloneDX format",
        response = String.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The component could not be found")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response exportComponentAsCycloneDx (
        @ApiParam(value = "The UUID of the project to export", required = true)
        @PathParam("uuid") String uuid) {
    try (QueryManager qm = new QueryManager()) {
        final Component component = qm.getObjectByUuid(Component.class, uuid);
        if (component == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
        }
        try {
            final List<org.cyclonedx.model.Component> cycloneComponents = new ArrayList<>();
            cycloneComponents.add(ModelConverter.convert(qm, component));
            Bom bom = new Bom();
            bom.setSerialNumber("url:uuid:" + UUID.randomUUID().toString());
            bom.setVersion(1);
            bom.setComponents(cycloneComponents);
            final BomGenerator bomGenerator = BomGeneratorFactory.create(CycloneDxSchema.Version.VERSION_11, bom);
            bomGenerator.generate();
            return Response.ok(bomGenerator.toXmlString()).build();
        } catch (ParserConfigurationException | TransformerException e) {
            LOGGER.error("An error occurred while building a CycloneDX document for export", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
 
Example #10
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 4 votes vote down vote up
public MavenHelper(Logger logger, CycloneDxSchema.Version schemaVersion) {
    this.logger = logger;
    this.schemaVersion = schemaVersion;
}
 
Example #11
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts data from a project and adds the data to the component.
 * @param project the project to extract data from
 * @param component the component to add data to
 */
private void extractMetadata(MavenProject project, Component component) {
    if (component.getPublisher() == null) {
        // If we don't already have publisher information, retrieve it.
        if (project.getOrganization() != null) {
            component.setPublisher(project.getOrganization().getName());
        }
    }
    if (component.getDescription() == null) {
        // If we don't already have description information, retrieve it.
        component.setDescription(project.getDescription());
    }
    if (component.getLicenseChoice() == null || component.getLicenseChoice().getLicenses() == null || component.getLicenseChoice().getLicenses().isEmpty()) {
        // If we don't already have license information, retrieve it.
        if (project.getLicenses() != null) {
            component.setLicenseChoice(resolveMavenLicenses(project.getLicenses()));
        }
    }
    if (CycloneDxSchema.Version.VERSION_10 != schemaVersion) {
        if (project.getOrganization() != null && project.getOrganization().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.WEBSITE)) {
                addExternalReference(ExternalReference.Type.WEBSITE, project.getOrganization().getUrl(), component);
            }
        }
        if (project.getCiManagement() != null && project.getCiManagement().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.BUILD_SYSTEM)) {
                addExternalReference(ExternalReference.Type.BUILD_SYSTEM, project.getCiManagement().getUrl(), component);
            }
        }
        if (project.getDistributionManagement() != null && project.getDistributionManagement().getDownloadUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.DISTRIBUTION)) {
                addExternalReference(ExternalReference.Type.DISTRIBUTION, project.getDistributionManagement().getDownloadUrl(), component);
            }
        }
        if (project.getDistributionManagement() != null && project.getDistributionManagement().getRepository() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.DISTRIBUTION)) {
                addExternalReference(ExternalReference.Type.DISTRIBUTION, project.getDistributionManagement().getRepository().getUrl(), component);
            }
        }
        if (project.getIssueManagement() != null && project.getIssueManagement().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.ISSUE_TRACKER)) {
                addExternalReference(ExternalReference.Type.ISSUE_TRACKER, project.getIssueManagement().getUrl(), component);
            }
        }
        if (project.getMailingLists() != null && project.getMailingLists().size() > 0) {
            for (MailingList list : project.getMailingLists()) {
                if (list.getArchive() != null) {
                    if (!doesComponentHaveExternalReference(component, ExternalReference.Type.MAILING_LIST)) {
                        addExternalReference(ExternalReference.Type.MAILING_LIST, list.getArchive(), component);
                    }
                } else if (list.getSubscribe() != null) {
                    if (!doesComponentHaveExternalReference(component, ExternalReference.Type.MAILING_LIST)) {
                        addExternalReference(ExternalReference.Type.MAILING_LIST, list.getSubscribe(), component);
                    }
                }
            }
        }
        if (project.getScm() != null && project.getScm().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.VCS)) {
                addExternalReference(ExternalReference.Type.VCS, project.getScm().getUrl(), component);
            }
        }
    }
}
 
Example #12
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 4 votes vote down vote up
LicenseChoice resolveMavenLicenses(final List<org.apache.maven.model.License> projectLicenses) {
    final boolean includeLicenseText = true; // TODO: Make this configurable
    final LicenseChoice licenseChoice = new LicenseChoice();
    for (org.apache.maven.model.License artifactLicense : projectLicenses) {
        boolean resolved = false;
        if (artifactLicense.getName() != null) {
            final LicenseChoice resolvedByName = LicenseResolver.resolve(artifactLicense.getName(), includeLicenseText);
            if (resolvedByName != null) {
                if (resolvedByName.getLicenses() != null && !resolvedByName.getLicenses().isEmpty()) {
                    resolved = true;
                    licenseChoice.addLicense(resolvedByName.getLicenses().get(0));
                } else if (resolvedByName.getExpression() != null && CycloneDxSchema.Version.VERSION_10 != schemaVersion) {
                    resolved = true;
                    licenseChoice.setExpression(resolvedByName.getExpression());
                }
            }
        }
        if (artifactLicense.getUrl() != null && !resolved) {
            final LicenseChoice resolvedByUrl = LicenseResolver.resolve(artifactLicense.getUrl(), includeLicenseText);
            if (resolvedByUrl != null) {
                if (resolvedByUrl.getLicenses() != null && !resolvedByUrl.getLicenses().isEmpty()) {
                    resolved = true;
                    licenseChoice.addLicense(resolvedByUrl.getLicenses().get(0));
                } else if (resolvedByUrl.getExpression() != null && CycloneDxSchema.Version.VERSION_10 != schemaVersion) {
                    resolved = true;
                    licenseChoice.setExpression(resolvedByUrl.getExpression());
                }
            }
        }
        if (artifactLicense.getName() != null && !resolved) {
            final org.cyclonedx.model.License license = new org.cyclonedx.model.License();;
            license.setName(artifactLicense.getName().trim());
            if (StringUtils.isNotBlank(artifactLicense.getUrl())) {
                try {
                    new URL(artifactLicense.getUrl());
                    license.setUrl(artifactLicense.getUrl().trim());
                } catch (MalformedURLException e) {
                    // throw it away
                }
            }
            licenseChoice.addLicense(license);
        }
    }
    return licenseChoice;
}
 
Example #13
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts data from a project and adds the data to the component.
 * @param project the project to extract data from
 * @param component the component to add data to
 */
private void extractMetadata(MavenProject project, Component component) {
    if (component.getPublisher() == null) {
        // If we don't already have publisher information, retrieve it.
        if (project.getOrganization() != null) {
            component.setPublisher(project.getOrganization().getName());
        }
    }
    if (component.getDescription() == null) {
        // If we don't already have description information, retrieve it.
        component.setDescription(project.getDescription());
    }
    if (component.getLicenseChoice() == null || component.getLicenseChoice().getLicenses() == null || component.getLicenseChoice().getLicenses().isEmpty()) {
        // If we don't already have license information, retrieve it.
        if (project.getLicenses() != null) {
            component.setLicenseChoice(resolveMavenLicenses(project.getLicenses()));
        }
    }
    if (CycloneDxSchema.Version.VERSION_10 != schemaVersion()) {
        if (project.getOrganization() != null && project.getOrganization().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.WEBSITE)) {
                addExternalReference(ExternalReference.Type.WEBSITE, project.getOrganization().getUrl(), component);
            }
        }
        if (project.getCiManagement() != null && project.getCiManagement().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.BUILD_SYSTEM)) {
                addExternalReference(ExternalReference.Type.BUILD_SYSTEM, project.getCiManagement().getUrl(), component);
            }
        }
        if (project.getDistributionManagement() != null && project.getDistributionManagement().getDownloadUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.DISTRIBUTION)) {
                addExternalReference(ExternalReference.Type.DISTRIBUTION, project.getDistributionManagement().getDownloadUrl(), component);
            }
        }
        if (project.getDistributionManagement() != null && project.getDistributionManagement().getRepository() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.DISTRIBUTION)) {
                addExternalReference(ExternalReference.Type.DISTRIBUTION, project.getDistributionManagement().getRepository().getUrl(), component);
            }
        }
        if (project.getIssueManagement() != null && project.getIssueManagement().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.ISSUE_TRACKER)) {
                addExternalReference(ExternalReference.Type.ISSUE_TRACKER, project.getIssueManagement().getUrl(), component);
            }
        }
        if (project.getMailingLists() != null && project.getMailingLists().size() > 0) {
            for (MailingList list : project.getMailingLists()) {
                if (list.getArchive() != null) {
                    if (!doesComponentHaveExternalReference(component, ExternalReference.Type.MAILING_LIST)) {
                        addExternalReference(ExternalReference.Type.MAILING_LIST, list.getArchive(), component);
                    }
                } else if (list.getSubscribe() != null) {
                    if (!doesComponentHaveExternalReference(component, ExternalReference.Type.MAILING_LIST)) {
                        addExternalReference(ExternalReference.Type.MAILING_LIST, list.getSubscribe(), component);
                    }
                }
            }
        }
        if (project.getScm() != null && project.getScm().getUrl() != null) {
            if (!doesComponentHaveExternalReference(component, ExternalReference.Type.VCS)) {
                addExternalReference(ExternalReference.Type.VCS, project.getScm().getUrl(), component);
            }
        }
    }
}
 
Example #14
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 4 votes vote down vote up
private LicenseChoice resolveMavenLicenses(final List<org.apache.maven.model.License> projectLicenses) {
    final LicenseChoice licenseChoice = new LicenseChoice();
    for (org.apache.maven.model.License artifactLicense : projectLicenses) {
        boolean resolved = false;
        if (artifactLicense.getName() != null) {
            final LicenseChoice resolvedByName = LicenseResolver.resolve(artifactLicense.getName(), includeLicenseText);
            if (resolvedByName != null) {
                if (resolvedByName.getLicenses() != null && !resolvedByName.getLicenses().isEmpty()) {
                    resolved = true;
                    licenseChoice.addLicense(resolvedByName.getLicenses().get(0));
                } else if (resolvedByName.getExpression() != null && CycloneDxSchema.Version.VERSION_10 != schemaVersion()) {
                    resolved = true;
                    licenseChoice.setExpression(resolvedByName.getExpression());
                }
            }
        }
        if (artifactLicense.getUrl() != null && !resolved) {
            final LicenseChoice resolvedByUrl = LicenseResolver.resolve(artifactLicense.getUrl(), includeLicenseText);
            if (resolvedByUrl != null) {
                if (resolvedByUrl.getLicenses() != null && !resolvedByUrl.getLicenses().isEmpty()) {
                    resolved = true;
                    licenseChoice.addLicense(resolvedByUrl.getLicenses().get(0));
                } else if (resolvedByUrl.getExpression() != null && CycloneDxSchema.Version.VERSION_10 != schemaVersion()) {
                    resolved = true;
                    licenseChoice.setExpression(resolvedByUrl.getExpression());
                }
            }
        }
        if (artifactLicense.getName() != null && !resolved) {
            final License license = new License();;
            license.setName(artifactLicense.getName().trim());
            if (StringUtils.isNotBlank(artifactLicense.getUrl())) {
                try {
                    new URL(artifactLicense.getUrl());
                    license.setUrl(artifactLicense.getUrl().trim());
                } catch (MalformedURLException e) {
                    // throw it away
                }
            }
            licenseChoice.addLicense(license);
        }
    }
    return licenseChoice;
}