Search in sources :

Example 36 with SW360Exception

use of org.eclipse.sw360.datahandler.thrift.SW360Exception in project sw360portal by sw360.

the class AttachmentPortletUtils method serveAttachmentBundle.

private void serveAttachmentBundle(List<AttachmentContent> attachments, ResourceRequest request, ResourceResponse response, Optional<String> downloadFileName) {
    String filename;
    String contentType;
    if (attachments.size() == 1) {
        filename = downloadFileName.orElse(attachments.get(0).getFilename());
        contentType = attachments.get(0).getContentType();
    } else {
        filename = downloadFileName.orElse(DEFAULT_ATTACHMENT_BUNDLE_NAME);
        contentType = "application/zip";
    }
    User user = UserCacheHolder.getUserFromRequest(request);
    try {
        Optional<Object> context = getContextFromRequest(request, user);
        if (context.isPresent()) {
            try (InputStream attachmentStream = getStreamToServeAFile(attachments, user, context.get())) {
                PortletResponseUtil.sendFile(request, response, filename, attachmentStream, contentType);
            } catch (IOException e) {
                log.error("cannot finish writing response", e);
                response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "500");
            }
        } else {
            log.warn("The user=[" + user.getEmail() + "] tried to download attachment=[" + CommonUtils.joinStrings(attachments.stream().map(AttachmentContent::getId).collect(Collectors.toList())) + "] in context=[" + request.getParameter(PortalConstants.CONTEXT_ID) + "] without read permissions");
            response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "404");
        }
    } catch (SW360Exception e) {
        log.error("Context was not set properly.", e);
        response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "400");
    } catch (TException e) {
        log.error("Problem getting the attachment content from the backend", e);
        response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "500");
    }
}
Also used : TException(org.apache.thrift.TException) User(org.eclipse.sw360.datahandler.thrift.users.User) InputStream(java.io.InputStream) IOException(java.io.IOException) SW360Exception(org.eclipse.sw360.datahandler.thrift.SW360Exception)

Example 37 with SW360Exception

use of org.eclipse.sw360.datahandler.thrift.SW360Exception in project sw360portal by sw360.

the class RemoteAttachmentDownloaderTest method testWithBrokenURL.

@Test
public void testWithBrokenURL() throws Exception {
    AttachmentContent attachmentContent = saveRemoteAttachment(TestUtils.BLACK_HOLE_ADDRESS);
    AttachmentContent attachmentGood = saveRemoteAttachment(url);
    assertThat(repository.getOnlyRemoteAttachments(), hasSize(2));
    assertThat(retrieveRemoteAttachments(DatabaseSettings.getConfiguredHttpClient(), dbName, downloadTimeout), is(1));
    assertThat(repository.getOnlyRemoteAttachments(), hasSize(1));
    assertThat(attachmentConnector.getAttachmentStream(attachmentGood, dummyUser, new Project().setVisbility(Visibility.ME_AND_MODERATORS).setCreatedBy(dummyUser.getEmail()).setAttachments(Collections.singleton(new Attachment().setAttachmentContentId(attachmentGood.getId())))), hasLength(greaterThan(0l)));
    assertThat(repository.getOnlyRemoteAttachments(), hasSize(1));
    assertThat(retrieveRemoteAttachments(DatabaseSettings.getConfiguredHttpClient(), dbName, downloadTimeout), is(0));
    assertThat(repository.getOnlyRemoteAttachments(), hasSize(1));
    try {
        assertThat(attachmentConnector.getAttachmentStream(attachmentContent, dummyUser, new Project().setVisbility(Visibility.ME_AND_MODERATORS).setCreatedBy(dummyUser.getEmail()).setAttachments(Collections.singleton(new Attachment().setAttachmentContentId(attachmentContent.getId())))), hasLength(greaterThan(0l)));
        fail("expected exception not thrown");
    } catch (SW360Exception e) {
        assertThat(e.getWhy(), containsString(attachmentContent.getId()));
    }
}
Also used : Project(org.eclipse.sw360.datahandler.thrift.projects.Project) AttachmentContent(org.eclipse.sw360.datahandler.thrift.attachments.AttachmentContent) Attachment(org.eclipse.sw360.datahandler.thrift.attachments.Attachment) SW360Exception(org.eclipse.sw360.datahandler.thrift.SW360Exception) Test(org.junit.Test)

Example 38 with SW360Exception

use of org.eclipse.sw360.datahandler.thrift.SW360Exception in project sw360portal by sw360.

the class LicenseDatabaseHandler method updateWhitelist.

/**
 * Update the whitelisted todos for an organisation
 */
public RequestStatus updateWhitelist(String licenseId, Set<String> whitelistTodos, User user) throws SW360Exception {
    License license = licenseRepository.get(licenseId);
    assertNotNull(license);
    String organisation = user.getDepartment();
    String businessUnit = SW360Utils.getBUFromOrganisation(organisation);
    if (makePermission(license, user).isActionAllowed(RequestedAction.WRITE)) {
        List<Todo> todos = todoRepository.get(license.todoDatabaseIds);
        for (Todo todo : todos) {
            String todoId = todo.getId();
            Set<String> currentWhitelist = todo.whitelist != null ? todo.whitelist : new HashSet<>();
            // Add to whitelist if necessary
            if (whitelistTodos.contains(todoId) && !currentWhitelist.contains(businessUnit)) {
                todo.addToWhitelist(businessUnit);
                todoRepository.update(todo);
            }
            // Remove from whitelist if necessary
            if (!whitelistTodos.contains(todoId) && currentWhitelist.contains(businessUnit)) {
                currentWhitelist.remove(businessUnit);
                todoRepository.update(todo);
            }
        }
        return RequestStatus.SUCCESS;
    } else {
        // add updated whitelists to todos in moderation request, not yet in database
        License licenseForModerationRequest = getLicenseForOrganisationWithOwnModerationRequests(licenseId, user.getDepartment(), user);
        List<Todo> todos = licenseForModerationRequest.getTodos();
        for (Todo todo : todos) {
            String todoId = todo.getId();
            Set<String> currentWhitelist = todo.whitelist != null ? todo.whitelist : new HashSet<>();
            // Add to whitelist if necessary
            if (whitelistTodos.contains(todoId) && !currentWhitelist.contains(businessUnit)) {
                todo.addToWhitelist(businessUnit);
            }
            // Remove from whitelist if necessary
            if (!whitelistTodos.contains(todoId) && currentWhitelist.contains(businessUnit)) {
                currentWhitelist.remove(businessUnit);
            }
        }
        // Only moderators can edit whitelists!
        return moderator.updateLicense(licenseForModerationRequest, user);
    }
}
Also used : CommonUtils.isTemporaryTodo(org.eclipse.sw360.datahandler.common.CommonUtils.isTemporaryTodo)

Example 39 with SW360Exception

use of org.eclipse.sw360.datahandler.thrift.SW360Exception in project sw360portal by sw360.

the class JSchSessionProvider method doGetSession.

private Session doGetSession(int connectionTimeout) throws SW360Exception {
    synchronized (J_SCH) {
        try {
            Session session = J_SCH.getSession(userName, hostName, hostPort);
            session.setHostKeyRepository(fossologyHostKeyRepository);
            session.connect(connectionTimeout);
            return session;
        } catch (JSchException e) {
            String serverString = getServerString();
            log.error("cannot connect to fossology server: " + serverString, e);
            throw new SW360Exception("cannot connect to Fossology Server");
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) SW360Exception(org.eclipse.sw360.datahandler.thrift.SW360Exception) Session(com.jcraft.jsch.Session)

Example 40 with SW360Exception

use of org.eclipse.sw360.datahandler.thrift.SW360Exception in project sw360portal by sw360.

the class DocxGenerator method generateOutputFile.

@Override
public byte[] generateOutputFile(Collection<LicenseInfoParsingResult> projectLicenseInfoResults, String projectName, String projectVersion, String licenseInfoHeaderText) throws SW360Exception {
    ByteArrayOutputStream docxOutputStream = new ByteArrayOutputStream();
    Optional<byte[]> docxTemplateFile = CommonUtils.loadResource(DocxGenerator.class, DOCX_TEMPLATE_FILE);
    if (docxTemplateFile.isPresent()) {
        try {
            XWPFDocument xwpfDocument = new XWPFDocument(new ByteArrayInputStream(docxTemplateFile.get()));
            switch(getOutputVariant()) {
                case DISCLOSURE:
                    fillDocument(xwpfDocument, projectLicenseInfoResults, projectName, projectVersion, licenseInfoHeaderText, false);
                    break;
                case REPORT:
                    fillDocument(xwpfDocument, projectLicenseInfoResults, projectName, projectVersion, licenseInfoHeaderText, true);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown generator variant type: " + getOutputVariant());
            }
            xwpfDocument.write(docxOutputStream);
            docxOutputStream.close();
        } catch (XmlException e) {
            throw new SW360Exception("Got XmlException while generating docx document: " + e.getMessage());
        } catch (IOException e) {
            throw new SW360Exception("Got IOException when generating docx document: " + e.getMessage());
        } catch (TException e) {
            throw new SW360Exception("Error reading sw360 licenses: " + e.getMessage());
        }
        return docxOutputStream.toByteArray();
    } else {
        throw new SW360Exception("Could not load the template for xwpf document: " + DOCX_TEMPLATE_FILE);
    }
}
Also used : TException(org.apache.thrift.TException) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlException(org.apache.xmlbeans.XmlException) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SW360Exception(org.eclipse.sw360.datahandler.thrift.SW360Exception)

Aggregations

SW360Exception (org.eclipse.sw360.datahandler.thrift.SW360Exception)23 IOException (java.io.IOException)10 InputStream (java.io.InputStream)9 TException (org.apache.thrift.TException)9 AttachmentContent (org.eclipse.sw360.datahandler.thrift.attachments.AttachmentContent)9 Project (org.eclipse.sw360.datahandler.thrift.projects.Project)9 ModerationRequest (org.eclipse.sw360.datahandler.thrift.moderation.ModerationRequest)8 Release (org.eclipse.sw360.datahandler.thrift.components.Release)5 User (org.eclipse.sw360.datahandler.thrift.users.User)5 Test (org.junit.Test)4 CommonUtils.isTemporaryTodo (org.eclipse.sw360.datahandler.common.CommonUtils.isTemporaryTodo)3 SW360Utils.fieldValueAsString (org.eclipse.sw360.datahandler.common.SW360Utils.fieldValueAsString)3 Component (org.eclipse.sw360.datahandler.thrift.components.Component)3 JSchException (com.jcraft.jsch.JSchException)2 Session (com.jcraft.jsch.Session)2 PipedInputStream (java.io.PipedInputStream)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 XPathExpressionException (javax.xml.xpath.XPathExpressionException)2 ConcatClosingInputStream (org.eclipse.sw360.datahandler.common.ConcatClosingInputStream)2 WrappedSW360Exception (org.eclipse.sw360.datahandler.common.WrappedException.WrappedSW360Exception)2