com.github.packageurl.MalformedPackageURLException Java Examples

The following examples show how to use com.github.packageurl.MalformedPackageURLException. 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: ExemptionBug.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link PackageURL} from the given {@link String}, whereby URLs of type 'maven' require
 * namespace and name, and URLs of type 'pypi' require a name. All other types are not supported and
 * will result in a {@link MalformedPackageURLException}.
 * 
 * @param _url
 * @return
 * @throws MalformedPackageURLException
 */
public static final PackageURL createPackageUrl(String _url) throws MalformedPackageURLException {
	final PackageURL purl = new PackageURL(_url);
	
	// PURL type == maven
	if("maven".equalsIgnoreCase(purl.getType())) {
		if(purl.getNamespace()==null || purl.getNamespace().equals("") || purl.getName()==null || purl.getName().equals("")) {
			throw new MalformedPackageURLException("Package URLs of type [" + purl.getType() + "] require a valid namespace and name: [" + purl + "]");
		}
	}
	
	// PURL type == pypi
	else if("pypi".equalsIgnoreCase(purl.getType())) {
		if(purl.getName()==null || purl.getName().equals("")) {
			throw new MalformedPackageURLException("Package URLs of type [" + purl.getType() + "] require a valid name: [" + purl + "]");
		}
	}
	
	// Other types are not supported
	else {
		throw new MalformedPackageURLException("Package URLs of type [" + purl.getType() + "] are not supported: [" + purl + "]");
	}
	
	return purl;
}
 
Example #2
Source File: CycloneDxTask.java    From cyclonedx-gradle-plugin with Apache License 2.0 6 votes vote down vote up
private String generatePackageUrl(final ResolvedArtifact artifact) {
    try {
        TreeMap<String, String> qualifiers = null;
        if (artifact.getType() != null || artifact.getClassifier() != null) {
            qualifiers = new TreeMap<>();
            if (artifact.getType() != null) {
                qualifiers.put("type", artifact.getType());
            }
            if (artifact.getClassifier() != null) {
                qualifiers.put("classifier", artifact.getClassifier());
            }
        }
        return new PackageURL(PackageURL.StandardTypes.MAVEN,
                artifact.getModuleVersion().getId().getGroup(),
                artifact.getModuleVersion().getId().getName(),
                artifact.getModuleVersion().getId().getVersion(),
                qualifiers, null).canonicalize();
    } catch (MalformedPackageURLException e) {
        getLogger().warn("An unexpected issue occurred attempting to create a PackageURL for "
                + artifact.getModuleVersion().getId().getGroup() + ":"
                + artifact.getModuleVersion().getId().getName()
                + ":" + artifact.getModuleVersion().getId().getVersion(), e);
    }
    return null;
}
 
Example #3
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private String generatePackageUrl(final Artifact artifact) {
    try {
        TreeMap<String, String> qualifiers = null;
        if (artifact.getType() != null || artifact.getClassifier() != null) {
            qualifiers = new TreeMap<>();
            if (artifact.getType() != null) {
                qualifiers.put("type", artifact.getType());
            }
            if (artifact.getClassifier() != null) {
                qualifiers.put("classifier", artifact.getClassifier());
            }
        }
        return new PackageURL(PackageURL.StandardTypes.MAVEN,
                artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), qualifiers, null).canonicalize();
    } catch (MalformedPackageURLException e) {
        getLog().warn("An unexpected issue occurred attempting to create a PackageURL for "
                + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion(), e);
    }
    return null;
}
 
Example #4
Source File: ExemptionBug.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExempted(VulnerableDependency _vd) {
	// Bug ID
	boolean is_exempted = ALL.equals(this.bugId)  || this.bugId.equalsIgnoreCase(_vd.getBug().getBugId());
	
	// Library
	if(is_exempted) {
		// All
		if(ALL.equals(this.library)) { ; }

		// Package URL according to https://github.com/package-url/purl-spec
		else if(this.library.startsWith(PURL_PREFIX) && _vd.getDep().getLib().getLibraryId()!=null) {
			try {
				final LibraryId libid = _vd.getDep().getLib().getLibraryId();
				final PackageURL purl = ExemptionBug.createPackageUrl(this.library);
				is_exempted = is_exempted &&
						(purl.getNamespace()==null || libid.getMvnGroup().equals(purl.getNamespace())) && // No purl.namespace || purl.namespace==libid.mvnGroup
						libid.getArtifact().equals(purl.getName()) &&
						(purl.getVersion()==null || libid.getVersion().equals(purl.getVersion())); // No purl.version || purl.version==libid.version
			} catch (MalformedPackageURLException e) {
				log.error(e.getMessage());
				is_exempted = false;
			}
		}
		
		// Digest
		else {
			is_exempted = is_exempted && this.library.equals(_vd.getDep().getLib().getDigest());
		}
	}
			 
	return is_exempted;
}
 
Example #5
Source File: OssIndexAnalysisTask.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Sonatype OSS Index currently uses an old/outdated version of the PackageURL specification.
 * Attempt to convert it into the current spec format and return it.
 */
private PackageURL oldPurlResolver(String coordinates) {
    try {
        // Check if OSSIndex has updated their implementation or not
        if (coordinates.startsWith("pkg:")) {
            return new PackageURL(coordinates);
        }
        // Nope, they're still using the 'old' style. Force update it.
        return new PackageURL("pkg:" + coordinates.replaceFirst(":", "/"));
    } catch (MalformedPackageURLException e) {
        return null;
    }
}
 
Example #6
Source File: RepositoryResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/latest")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Attempts to resolve the latest version of the component available in the configured repositories",
        response = RepositoryMetaComponent.class
)
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "The request was successful, but no repositories are configured to support the specified Package URL"),
        @ApiResponse(code = 400, message = "The specified Package URL is invalid and not in the correct format"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The repository metadata for the specified component cannot be found"),
})
public Response getRepositoryMetaComponent(
        @ApiParam(value = "The Package URL for the component to query", required = true)
        @QueryParam("purl") String purl) {
    try {
        final PackageURL packageURL = new PackageURL(purl);
        try (QueryManager qm = new QueryManager(getAlpineRequest())) {
            final RepositoryType type = RepositoryType.resolve(packageURL);
            if (RepositoryType.UNSUPPORTED == type) {
                return Response.noContent().build();
            }
            final RepositoryMetaComponent result = qm.getRepositoryMetaComponent(
                    RepositoryType.resolve(packageURL), packageURL.getNamespace(), packageURL.getName());
            if (result == null) {
                return Response.status(Response.Status.NOT_FOUND).entity("The repository metadata for the specified component cannot be found.").build();
            } else {
                //todo: future enhancement: provide pass-thru capability for component metadata not already present and being tracked
                return Response.ok(result).build();
            }
        }
    } catch (MalformedPackageURLException e) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
 
Example #7
Source File: PackageURLStringConverter.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public PackageURL convertToAttribute(final String str) {
    if (str == null) {
        return null;
    }

    try {
        return new PackageURL(str.trim());
    } catch (MalformedPackageURLException e) {
        LOGGER.warn("A persisted object with a PackageURL string in the datastore failed validation and is not valid. Returning null for: " + str);
    }
    return null;
}
 
Example #8
Source File: ModelConverter.java    From dependency-track with Apache License 2.0 4 votes vote down vote up
public static Component convert(final QueryManager qm, final org.cyclonedx.model.Component cycloneDxComponent) {
    final Component component = new Component();
    component.setGroup(StringUtils.trimToNull(cycloneDxComponent.getGroup()));
    component.setName(StringUtils.trimToNull(cycloneDxComponent.getName()));
    component.setVersion(StringUtils.trimToNull(cycloneDxComponent.getVersion()));
    component.setDescription(StringUtils.trimToNull(cycloneDxComponent.getDescription()));
    component.setCopyright(StringUtils.trimToNull(cycloneDxComponent.getCopyright()));
    component.setCpe(StringUtils.trimToNull(cycloneDxComponent.getCpe()));

    if (StringUtils.isNotBlank(cycloneDxComponent.getPurl())) {
        try {
            component.setPurl(new PackageURL(StringUtils.trimToNull(cycloneDxComponent.getPurl())));
        } catch (MalformedPackageURLException e) {
            LOGGER.warn("Unable to parse PackageURL: " + cycloneDxComponent.getPurl());
        }
    }

    component.setInternal(InternalComponentIdentificationUtil.isInternalComponent(component, qm));

    if (cycloneDxComponent.getType() != null) {
        component.setClassifier(Classifier.valueOf(cycloneDxComponent.getType().name()));
    } else {
        component.setClassifier(Classifier.LIBRARY);
    }

    if (cycloneDxComponent.getHashes() != null && !cycloneDxComponent.getHashes().isEmpty()) {
        for (final Hash hash : cycloneDxComponent.getHashes()) {
            if (hash != null) {
                if (Hash.Algorithm.MD5.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setMd5(StringUtils.trimToNull(hash.getValue()));
                } else if (Hash.Algorithm.SHA1.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setSha1(StringUtils.trimToNull(hash.getValue()));
                } else if (Hash.Algorithm.SHA_256.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setSha256(StringUtils.trimToNull(hash.getValue()));
                } else if (Hash.Algorithm.SHA_512.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setSha512(StringUtils.trimToNull(hash.getValue()));
                } else if (Hash.Algorithm.SHA3_256.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setSha3_256(StringUtils.trimToNull(hash.getValue()));
                } else if (Hash.Algorithm.SHA3_512.getSpec().equalsIgnoreCase(hash.getAlgorithm())) {
                    component.setSha3_512(StringUtils.trimToNull(hash.getValue()));
                }
            }
        }
    }

    final LicenseChoice licenseChoice = cycloneDxComponent.getLicenseChoice();
    if (licenseChoice != null && licenseChoice.getLicenses() != null && !licenseChoice.getLicenses().isEmpty()) {
        for (final org.cyclonedx.model.License cycloneLicense : licenseChoice.getLicenses()) {
            if (cycloneLicense != null) {
                if (StringUtils.isNotBlank(cycloneLicense.getId())) {
                    final License license = qm.getLicense(StringUtils.trimToNull(cycloneLicense.getId()));
                    if (license != null) {
                        component.setResolvedLicense(license);
                    }
                }
                component.setLicense(StringUtils.trimToNull(cycloneLicense.getName()));
            }
        }
    }

    if (cycloneDxComponent.getComponents() != null && !cycloneDxComponent.getComponents().isEmpty()) {
        final Collection<Component> components = new ArrayList<>();
        for (int i = 0; i < cycloneDxComponent.getComponents().size(); i++) {
            final org.cyclonedx.model.Component cycloneDxChildComponent = cycloneDxComponent.getComponents().get(i);
            if (cycloneDxChildComponent != null) {
                components.add(convert(qm, cycloneDxChildComponent));
            }
        }
        if (CollectionUtils.isNotEmpty(components)) {
            component.setChildren(components);
        }
    }
    return component;
}
 
Example #9
Source File: QueryManager.java    From dependency-track with Apache License 2.0 4 votes vote down vote up
public Project clone(UUID from, String newVersion, boolean includeTags, boolean includeProperties,
                     boolean includeDependencies, boolean includeAuditHistory) {
    final Project source = getObjectByUuid(Project.class, from, Project.FetchGroup.ALL.name());
    if (source == null) {
        return null;
    }
    Project project = new Project();
    project.setName(source.getName());
    project.setDescription(source.getDescription());
    project.setVersion(newVersion);
    project.setActive(source.isActive());
    if (project.getPurl() != null && newVersion != null) {
        try {
            final PackageURL sourcePurl = new PackageURL(project.getPurl());
            final PackageURL purl = new PackageURL(
                    sourcePurl.getType(),
                    sourcePurl.getNamespace(),
                    sourcePurl.getName(),
                    newVersion, null, null
            );
            project.setPurl(purl.canonicalize());
        } catch (MalformedPackageURLException e) {
            // throw it away
        }
    }
    project.setParent(source.getParent());
    project = persist(project);

    if (includeTags) {
        for (final Tag tag: source.getTags()) {
            tag.getProjects().add(project);
            persist(tag);
        }
    }

    if (includeProperties && source.getProperties() != null) {
        for (final ProjectProperty sourceProperty: source.getProperties()) {
            final ProjectProperty property = new ProjectProperty();
            property.setProject(project);
            property.setPropertyType(sourceProperty.getPropertyType());
            property.setGroupName(sourceProperty.getGroupName());
            property.setPropertyName(sourceProperty.getPropertyName());
            property.setPropertyValue(sourceProperty.getPropertyValue());
            property.setDescription(sourceProperty.getDescription());
            persist(property);
        }
    }

    if (includeDependencies) {
        final List<Dependency> sourceDependencies = getAllDependencies(source);
        if (sourceDependencies != null) {
            for (final Dependency sourceDependency: sourceDependencies) {
                final Dependency dependency = new Dependency();
                dependency.setProject(project);
                dependency.setComponent(sourceDependency.getComponent());
                dependency.setAddedBy(sourceDependency.getAddedBy());
                dependency.setAddedOn(sourceDependency.getAddedOn());
                dependency.setNotes(sourceDependency.getNotes());
                persist(dependency);
            }
        }
    }

    if (includeAuditHistory) {
        final List<Analysis> analyses = getAnalyses(source);
        if (analyses != null) {
            for (final Analysis sourceAnalysis: analyses) {
                Analysis analysis = new Analysis();
                analysis.setAnalysisState(sourceAnalysis.getAnalysisState());
                analysis.setProject(project);
                analysis.setComponent(sourceAnalysis.getComponent());
                analysis.setVulnerability(sourceAnalysis.getVulnerability());
                analysis.setSuppressed(sourceAnalysis.isSuppressed());
                analysis = persist(analysis);
                if (sourceAnalysis.getAnalysisComments() != null) {
                    for (final AnalysisComment sourceComment: sourceAnalysis.getAnalysisComments()) {
                        final AnalysisComment analysisComment = new AnalysisComment();
                        analysisComment.setAnalysis(analysis);
                        analysisComment.setTimestamp(sourceComment.getTimestamp());
                        analysisComment.setComment(sourceComment.getComment());
                        analysisComment.setCommenter(sourceComment.getCommenter());
                        persist(analysisComment);
                    }
                }
            }
        }
    }

    project = getObjectById(Project.class, project.getId());
    Event.dispatch(new IndexEvent(IndexEvent.Action.CREATE, pm.detachCopy(project)));
    commitSearchIndex(true, Project.class);
    return project;
}