com.siemens.sw360.vulnerabilities.VulnerabilityHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.siemens.sw360.vulnerabilities.VulnerabilityHandler.java

Source

/*
 * Copyright Siemens AG, 2016.
 * Copyright (c) Bosch Software Innovations GmbH 2016.
 * Part of the SW360 Portal Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package com.siemens.sw360.vulnerabilities;

import com.siemens.sw360.datahandler.common.DatabaseSettings;
import com.siemens.sw360.datahandler.db.ComponentDatabaseHandler;
import com.siemens.sw360.datahandler.db.ProjectDatabaseHandler;
import com.siemens.sw360.datahandler.permissions.PermissionUtils;
import com.siemens.sw360.datahandler.thrift.RequestStatus;
import com.siemens.sw360.datahandler.thrift.SW360Exception;
import com.siemens.sw360.datahandler.thrift.VerificationState;
import com.siemens.sw360.datahandler.thrift.VerificationStateInfo;
import com.siemens.sw360.datahandler.thrift.components.Component;
import com.siemens.sw360.datahandler.thrift.components.Release;
import com.siemens.sw360.datahandler.thrift.projects.Project;
import com.siemens.sw360.datahandler.thrift.users.RequestedAction;
import com.siemens.sw360.datahandler.thrift.users.User;
import com.siemens.sw360.datahandler.thrift.users.UserGroup;
import com.siemens.sw360.datahandler.thrift.vulnerabilities.*;
import com.siemens.sw360.vulnerabilities.common.VulnerabilityMapper;
import com.siemens.sw360.vulnerabilities.db.VulnerabilityDatabaseHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.siemens.sw360.datahandler.common.CommonUtils.nullToEmptyList;
import static com.siemens.sw360.datahandler.common.CommonUtils.nullToEmptySet;
import static org.apache.log4j.Logger.getLogger;

/**
 * Implementation of the Thrift service
 *
 * @author stefan.jaeger@evosoft.com
 */
public class VulnerabilityHandler implements VulnerabilityService.Iface {

    private final static Logger log = getLogger(VulnerabilityHandler.class);

    private final VulnerabilityDatabaseHandler dbHandler;
    private final ComponentDatabaseHandler compHandler;
    private final ProjectDatabaseHandler projectDatabaseHandler;

    public VulnerabilityHandler() throws IOException, SW360Exception {
        dbHandler = new VulnerabilityDatabaseHandler(DatabaseSettings.COUCH_DB_URL, DatabaseSettings.COUCH_DB_VM);
        compHandler = new ComponentDatabaseHandler(DatabaseSettings.COUCH_DB_URL,
                DatabaseSettings.COUCH_DB_DATABASE, DatabaseSettings.COUCH_DB_ATTACHMENTS);
        projectDatabaseHandler = new ProjectDatabaseHandler(DatabaseSettings.COUCH_DB_URL,
                DatabaseSettings.COUCH_DB_DATABASE, DatabaseSettings.COUCH_DB_ATTACHMENTS);
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByReleaseId(String releaseId, User user) throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }

        return getVulsByReleaseId(releaseId, user);
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByComponentId(String componentId, User user) throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }
        List<Release> releases = compHandler.getReleasesFromComponentId(componentId, user);
        if (releases == null || releases.size() == 0) {
            return Collections.emptyList();
        }

        List<VulnerabilityDTO> dtos = new ArrayList<>();
        releases.stream().map(rel -> getVulsByReleaseId(rel.getId(), user)).forEach(list -> dtos.addAll(list));

        return dtos;
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByProjectId(String projectId, User user) throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }
        Set<String> releaseIds = projectDatabaseHandler.getProjectById(projectId, user).getReleaseIdToUsage()
                .keySet();

        return nullToEmptySet(releaseIds).stream().map(id -> getVulsByReleaseId(id, user))
                .flatMap(Collection::stream).collect(Collectors.toList());
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByReleaseIdWithoutIncorrect(String releaseId, User user)
            throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }

        return getVulsByReleaseIdWithoutIncorrect(releaseId, user);
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByComponentIdWithoutIncorrect(String componentId, User user)
            throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }
        List<Release> releases = compHandler.getReleasesFromComponentId(componentId, user);

        return nullToEmptyList(releases).stream().map(rel -> getVulsByReleaseIdWithoutIncorrect(rel.getId(), user))
                .flatMap(Collection::stream).collect(Collectors.toList());
    }

    @Override
    public List<VulnerabilityDTO> getVulnerabilitiesByProjectIdWithoutIncorrect(String projectId, User user)
            throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }
        Set<String> releaseIds = projectDatabaseHandler.getProjectById(projectId, user).getReleaseIdToUsage()
                .keySet();
        if (releaseIds == null || releaseIds.size() == 0) {
            return Collections.emptyList();
        }

        return releaseIds.stream().flatMap(id -> getVulsByReleaseIdWithoutIncorrect(id, user).stream())
                .collect(Collectors.toList());
    }

    private List<VulnerabilityDTO> getVulsByReleaseId(String releaseId, User user) {
        List<ReleaseVulnerabilityRelation> relations = dbHandler.getRelationsByReleaseIds(Arrays.asList(releaseId));
        if (relations == null || relations.size() == 0) {
            return Collections.emptyList();
        }
        List<VulnerabilityDTO> resultDtos = new ArrayList<>();
        for (ReleaseVulnerabilityRelation relation : relations) {
            resultDtos.add(getDtoFromRelation(relation, releaseId, user));
        }
        return resultDtos;
    }

    private boolean releaseVulnerabilityRelationIsIncorrect(ReleaseVulnerabilityRelation relation) {
        if (!relation.isSetVerificationStateInfo()) {
            return false;
        }
        List<VerificationStateInfo> stateHistory = relation.getVerificationStateInfo();
        VerificationStateInfo currentState = stateHistory.get(stateHistory.size() - 1);
        return VerificationState.INCORRECT.equals(currentState.getVerificationState());
    }

    private List<VulnerabilityDTO> getVulsByReleaseIdWithoutIncorrect(String releaseId, User user) {
        List<ReleaseVulnerabilityRelation> relations = dbHandler.getRelationsByReleaseIds(Arrays.asList(releaseId));
        if (relations == null || relations.size() == 0) {
            return Collections.emptyList();
        }
        List<VulnerabilityDTO> resultDtos = new ArrayList<>();
        for (ReleaseVulnerabilityRelation relation : relations) {
            if (!releaseVulnerabilityRelationIsIncorrect(relation)) {
                resultDtos.add(getDtoFromRelation(relation, releaseId, user));
            }
        }
        return resultDtos;
    }

    private VulnerabilityDTO getDtoFromRelation(ReleaseVulnerabilityRelation relation, String releaseId,
            User user) {
        Vulnerability vulnerability = dbHandler.getById(Vulnerability.class, relation.getVulnerabilityId());
        VulnerabilityDTO dto = VulnerabilityMapper.createVulnerabilityDTO(vulnerability);
        enrichVulnerabilityDTO(dto, releaseId, user);
        dto.setReleaseVulnerabilityRelation(relation);
        if (relation.isSetMatchedBy()) {
            dto.setMatchedBy(relation.getMatchedBy());
        }
        if (relation.isSetUsedNeedle()) {
            dto.setUsedNeedle(relation.getUsedNeedle());
        }
        return dto;
    }

    private VulnerabilityDTO enrichVulnerabilityDTO(VulnerabilityDTO dto, String releaseId, User user) {
        if (dto == null) {
            return null;
        }
        dto.setIntReleaseId(releaseId);
        try {
            Release release = compHandler.getRelease(releaseId, user);
            if (release != null) {
                dto.setIntComponentId(release.getComponentId());

                String releaseName = "";
                if (!StringUtils.isEmpty(release.getName())) {
                    releaseName = release.getName() + " ";
                    dto.setIntComponentName(release.getName());
                } else {
                    Component component = compHandler.getComponent(release.getComponentId(), user);
                    if (component != null) {
                        releaseName = component.getName() + " ";
                        dto.setIntComponentName(component.getName());
                    }
                }
                dto.setIntReleaseName(releaseName + release.getVersion());
            }
        } catch (SW360Exception e) {
            log.error(e);
        }
        return dto;
    }

    @Override
    public List<ProjectVulnerabilityRating> getProjectVulnerabilityRatingByProjectId(String projectId, User user) {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return null;
        }
        return projectDatabaseHandler.getProjectVulnerabilityRatingByProjectId(projectId);
    }

    @Override
    public RequestStatus updateProjectVulnerabilityRating(ProjectVulnerabilityRating link, User user) {
        Project project = null;
        try {
            project = projectDatabaseHandler.getProjectById(link.getProjectId(), user);
        } catch (SW360Exception e) {
            log.error("An exception occured when fetching the project with id " + link.getProjectId()
                    + " from the database.", e);
            return RequestStatus.FAILURE;
        }
        if (PermissionUtils.makePermission(project, user).isActionAllowed(RequestedAction.WRITE)) {
            return projectDatabaseHandler.updateProjectVulnerabilityRating(link);
        }
        return RequestStatus.FAILURE;
    }

    @Override
    public ReleaseVulnerabilityRelation getRelationByIds(String releaseId, String vulnerabilityId, User user) {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return null;
        }
        return dbHandler.getRelationByIds(releaseId, vulnerabilityId);
    }

    @Override
    public Vulnerability getVulnerabilityByExternalId(String externalId, User user) {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return null;
        }
        return dbHandler.getByExternalId(Vulnerability.class, externalId);
    }

    @Override
    public RequestStatus updateReleaseVulnerabilityRelation(ReleaseVulnerabilityRelation relation, User user) {
        if (!PermissionUtils.isAdmin(user)) {
            return RequestStatus.FAILURE;
        }
        return dbHandler.update(relation);
    }

    @Override
    public List<Vulnerability> getVulnerabilities(User user) throws TException {
        if (!PermissionUtils.isUserAtLeast(UserGroup.USER, user)) {
            return Collections.emptyList();
        }

        return dbHandler.getAll(Vulnerability.class);
    }
}