Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.overlord.sramp.shell.commands.ontology.UploadOntologyCommand.java

/**
 * @see org.overlord.sramp.shell.api.shell.ShellCommand#execute()
 *//*from w w w.  ja  va 2 s.  co  m*/
@Override
public boolean execute() throws Exception {
    String filePathArg = this.requiredArgument(0,
            Messages.i18n.format("UploadOntology.InvalidArgMsg.MissingPath")); //$NON-NLS-1$

    QName clientVarName = new QName("s-ramp", "client"); //$NON-NLS-1$ //$NON-NLS-2$
    SrampAtomApiClient client = (SrampAtomApiClient) getContext().getVariable(clientVarName);
    if (client == null) {
        print(Messages.i18n.format("MissingSRAMPConnection")); //$NON-NLS-1$
        return false;
    }
    InputStream content = null;
    try {
        File file = new File(filePathArg);
        if (file.exists()) {
            content = FileUtils.openInputStream(file);
        } else {
            URL url = this.getClass().getResource(filePathArg);
            if (url != null) {
                print(Messages.i18n.format("UploadOntology.ReadingOntology", url.toExternalForm())); //$NON-NLS-1$
                content = url.openStream();
            } else {
                print(Messages.i18n.format("UploadOntology.CannotFind", filePathArg)); //$NON-NLS-1$
            }
        }
        client.uploadOntology(content);
        print(Messages.i18n.format("UploadOntology.SuccessfulUpload")); //$NON-NLS-1$
    } catch (Exception e) {
        print(Messages.i18n.format("UploadOntology.UploadFailed")); //$NON-NLS-1$
        print("\t" + e.getMessage()); //$NON-NLS-1$
        IOUtils.closeQuietly(content);
        return false;
    } finally {
        IOUtils.closeQuietly(content);
    }
    print("**********************************************************************"); //$NON-NLS-1$
    return true;
}

From source file:org.overlord.sramp.shell.FileShellCommandReader.java

/**
 * @see org.overlord.sramp.common.shell.AbstractShellCommandReader#open()
 *///from w w w .j a va 2s  .  co m
@Override
public void open() throws IOException {
    File file = new File(filePath);
    if (!file.isFile()) {
        throw new FileNotFoundException(filePath);
    }
    this.fileReader = new BufferedReader(new InputStreamReader(FileUtils.openInputStream(file)));
}

From source file:org.overlord.sramp.test.server.atom.services.BatchResourceTest.java

/**
 * Test method for {@link org.overlord.sramp.common.server.atom.services.BatchResource#zipPackage(java.lang.String, java.io.InputStream)}.
 *//*  w ww .j ava2  s .  c  o  m*/
@Test
public void testZipPackage() throws Exception {
    SrampArchive archive = null;
    InputStream xsd1ContentStream = null;
    InputStream xsd2ContentStream = null;
    File zipFile = null;
    InputStream zipStream = null;
    ClientRequest request = null;

    try {
        // Create a test s-ramp archive
        archive = new SrampArchive();
        xsd1ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/PO.xsd"); //$NON-NLS-1$
        BaseArtifactType metaData = new XsdDocument();
        metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT);
        metaData.setName("PO.xsd"); //$NON-NLS-1$
        archive.addEntry("schemas/PO.xsd", metaData, xsd1ContentStream); //$NON-NLS-1$
        xsd2ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/XMLSchema.xsd"); //$NON-NLS-1$
        metaData = new XsdDocument();
        metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT);
        metaData.setName("XMLSchema.xsd"); //$NON-NLS-1$
        metaData.setVersion("1.0"); //$NON-NLS-1$
        archive.addEntry("schemas/XMLSchema.xsd", metaData, xsd2ContentStream); //$NON-NLS-1$

        zipFile = archive.pack();
        zipStream = FileUtils.openInputStream(zipFile);

        // Now POST the archive to the s-ramp repository (POST to /s-ramp as application/zip)
        request = clientRequest("/s-ramp"); //$NON-NLS-1$
        request.body(MediaType.APPLICATION_ZIP, zipStream);
        ClientResponse<MultipartInput> clientResponse = request.post(MultipartInput.class);

        // Process the response - it should be multipart/mixed with each part being
        // itself an http response with a code, content-id, and an s-ramp atom entry
        // body
        MultipartInput response = clientResponse.getEntity();
        List<InputPart> parts = response.getParts();
        Map<String, BaseArtifactType> artyMap = new HashMap<String, BaseArtifactType>();
        for (InputPart part : parts) {
            String id = part.getHeaders().getFirst("Content-ID"); //$NON-NLS-1$
            HttpResponseBean rbean = part.getBody(HttpResponseBean.class, null);
            Assert.assertEquals(201, rbean.getCode());
            Entry entry = (Entry) rbean.getBody();
            BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(entry);
            artyMap.put(id, artifact);
        }

        Assert.assertTrue(artyMap.keySet().contains("<schemas/PO.xsd@package>")); //$NON-NLS-1$
        Assert.assertTrue(artyMap.keySet().contains("<schemas/XMLSchema.xsd@package>")); //$NON-NLS-1$

        // Assertions for artifact 1
        BaseArtifactType arty = artyMap.get("<schemas/PO.xsd@package>"); //$NON-NLS-1$
        Assert.assertNotNull(arty);
        Assert.assertEquals("PO.xsd", arty.getName()); //$NON-NLS-1$
        Assert.assertNull(arty.getVersion());

        arty = artyMap.get("<schemas/XMLSchema.xsd@package>"); //$NON-NLS-1$
        Assert.assertNotNull(arty);
        Assert.assertEquals("XMLSchema.xsd", arty.getName()); //$NON-NLS-1$
        Assert.assertEquals("1.0", arty.getVersion()); //$NON-NLS-1$
    } finally {
        IOUtils.closeQuietly(xsd1ContentStream);
        IOUtils.closeQuietly(xsd2ContentStream);
        SrampArchive.closeQuietly(archive);
        IOUtils.closeQuietly(zipStream);
        FileUtils.deleteQuietly(zipFile);
    }

    // Verify by querying
    // Do a query using GET with query params
    request = clientRequest("/s-ramp/xsd/XsdDocument"); //$NON-NLS-1$
    ClientResponse<Feed> response = request.get(Feed.class);
    Feed feed = response.getEntity();
    Assert.assertEquals(2, feed.getEntries().size());
    Set<String> artyNames = new HashSet<String>();
    for (Entry entry : feed.getEntries()) {
        artyNames.add(entry.getTitle());
    }
    Assert.assertTrue(artyNames.contains("PO.xsd")); //$NON-NLS-1$
    Assert.assertTrue(artyNames.contains("XMLSchema.xsd")); //$NON-NLS-1$
}

From source file:org.overlord.sramp.test.server.atom.services.BatchResourceTest.java

/**
 * Test method for {@link org.overlord.sramp.common.server.atom.services.BatchResource#zipPackage(java.lang.String, java.io.InputStream)}.
 *
 * This also tests the zipPackage method of the {@link BatchResource} class, but it is
 * more thorough.  It tests adding new content, updating existing content, etc.
 *///from   ww w  . j a  v  a  2  s .  c om
@Test
public void testZipPackage_Multi() throws Exception {
    SrampArchive archive = null;
    InputStream xsd1ContentStream = null;
    InputStream wsdlContentStream = null;
    File zipFile = null;
    InputStream zipStream = null;
    ClientRequest request = null;

    WsdlDocument wsdlDoc = createWsdlArtifact();
    XmlDocument xmlDoc = createXmlArtifact();

    String xsdUuid = null;
    String wsdlUuid = null;
    String xmlUuid = null;

    try {
        // Create a test s-ramp archive
        archive = new SrampArchive();

        // A new XSD document
        xsd1ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/PO.xsd"); //$NON-NLS-1$
        BaseArtifactType metaData = new XsdDocument();
        metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT);
        metaData.setUuid(UUID.randomUUID().toString()); // will be ignored
        metaData.setName("PO.xsd"); //$NON-NLS-1$
        archive.addEntry("schemas/PO.xsd", metaData, xsd1ContentStream); //$NON-NLS-1$
        // Update an existing WSDL document (content and meta-data)
        wsdlContentStream = this.getClass().getResourceAsStream("/sample-files/wsdl/sample-updated.wsdl"); //$NON-NLS-1$
        metaData = wsdlDoc;
        metaData.setVersion("2.0"); //$NON-NLS-1$
        SrampModelUtils.setCustomProperty(metaData, "foo", "bar"); //$NON-NLS-1$ //$NON-NLS-2$
        archive.addEntry("wsdl/sample.wsdl", metaData, wsdlContentStream); //$NON-NLS-1$
        // Update an existing XML document (meta-data only)
        metaData = xmlDoc;
        metaData.setVersion("3.0"); //$NON-NLS-1$
        SrampModelUtils.setCustomProperty(metaData, "far", "baz"); //$NON-NLS-1$ //$NON-NLS-2$
        archive.addEntry("core/PO.xml", metaData, null); //$NON-NLS-1$

        zipFile = archive.pack();
        zipStream = FileUtils.openInputStream(zipFile);

        // Now POST the archive to the s-ramp repository (POST to /s-ramp as application/zip)
        request = clientRequest("/s-ramp"); //$NON-NLS-1$
        request.body(MediaType.APPLICATION_ZIP, zipStream);
        ClientResponse<MultipartInput> clientResponse = request.post(MultipartInput.class);

        // Process the response - it should be multipart/mixed with each part being
        // itself an http response with a code, content-id, and an s-ramp atom entry
        // body
        MultipartInput response = clientResponse.getEntity();
        List<InputPart> parts = response.getParts();
        Map<String, HttpResponseBean> respMap = new HashMap<String, HttpResponseBean>();
        for (InputPart part : parts) {
            String id = part.getHeaders().getFirst("Content-ID"); //$NON-NLS-1$
            HttpResponseBean rbean = part.getBody(HttpResponseBean.class, null);
            respMap.put(id, rbean);
        }

        // Should be three responses.
        Assert.assertEquals(3, respMap.size());
        Assert.assertTrue(respMap.keySet().contains("<schemas/PO.xsd@package>")); //$NON-NLS-1$
        Assert.assertTrue(respMap.keySet().contains("<wsdl/sample.wsdl@package>")); //$NON-NLS-1$
        Assert.assertTrue(respMap.keySet().contains("<core/PO.xml@package>")); //$NON-NLS-1$

        // Assertions for artifact 1 (PO.xsd)
        HttpResponseBean httpResp = respMap.get("<schemas/PO.xsd@package>"); //$NON-NLS-1$
        Assert.assertEquals(201, httpResp.getCode());
        Assert.assertEquals("Created", httpResp.getStatus()); //$NON-NLS-1$
        Entry entry = (Entry) httpResp.getBody();
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("PO.xsd", artifact.getName()); //$NON-NLS-1$
        Assert.assertNull(artifact.getVersion());
        Long size = ((XsdDocument) artifact).getContentSize();
        Assert.assertTrue(size >= 2376L);
        xsdUuid = artifact.getUuid();

        // Assertions for artifact 2 (sample.wsdl)
        httpResp = respMap.get("<wsdl/sample.wsdl@package>"); //$NON-NLS-1$
        Assert.assertEquals(200, httpResp.getCode());
        Assert.assertEquals("OK", httpResp.getStatus()); //$NON-NLS-1$
        entry = (Entry) httpResp.getBody();
        artifact = SrampAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("sample.wsdl", artifact.getName()); //$NON-NLS-1$
        Assert.assertEquals("2.0", artifact.getVersion()); //$NON-NLS-1$
        wsdlUuid = artifact.getUuid();

        // Assertions for artifact 3 (PO.xml)
        httpResp = respMap.get("<core/PO.xml@package>"); //$NON-NLS-1$
        Assert.assertEquals(200, httpResp.getCode());
        Assert.assertEquals("OK", httpResp.getStatus()); //$NON-NLS-1$
        entry = (Entry) httpResp.getBody();
        artifact = SrampAtomUtils.unwrapSrampArtifact(entry);
        Assert.assertEquals("PO.xml", artifact.getName()); //$NON-NLS-1$
        Assert.assertEquals("3.0", artifact.getVersion()); //$NON-NLS-1$
        xmlUuid = artifact.getUuid();
    } finally {
        IOUtils.closeQuietly(xsd1ContentStream);
        IOUtils.closeQuietly(wsdlContentStream);
        SrampArchive.closeQuietly(archive);
        IOUtils.closeQuietly(zipStream);
        FileUtils.deleteQuietly(zipFile);
    }

    // Verify by querying
    // Do a query using GET with query params
    Map<String, BaseArtifactType> artyMap = new HashMap<String, BaseArtifactType>();
    request = clientRequest("/s-ramp/xsd/XsdDocument"); //$NON-NLS-1$
    ClientResponse<Feed> response = request.get(Feed.class);
    Feed feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/xsd/XsdDocument/" + uuid); //$NON-NLS-1$
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = clientRequest("/s-ramp/wsdl/WsdlDocument"); //$NON-NLS-1$
    response = request.get(Feed.class);
    feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/wsdl/WsdlDocument/" + uuid); //$NON-NLS-1$
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = clientRequest("/s-ramp/core/XmlDocument"); //$NON-NLS-1$
    response = request.get(Feed.class);
    feed = response.getEntity();
    Assert.assertEquals(1, feed.getEntries().size());
    for (Entry entry : feed.getEntries()) {
        String uuid = entry.getId().toString().replace("urn:uuid:", "");
        request = clientRequest("/s-ramp/core/XmlDocument/" + uuid); //$NON-NLS-1$
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }

    Assert.assertEquals(3, artyMap.size());

    // Assertions for artifact 1 (PO.xsd)
    BaseArtifactType artifact = artyMap.get(xsdUuid);
    Assert.assertEquals("PO.xsd", artifact.getName()); //$NON-NLS-1$
    Assert.assertNull(artifact.getVersion());

    // Assertions for artifact 2 (sample.wsdl)
    artifact = artyMap.get(wsdlUuid);
    Assert.assertEquals("sample.wsdl", artifact.getName()); //$NON-NLS-1$
    Assert.assertEquals("2.0", artifact.getVersion()); //$NON-NLS-1$

    // Assertions for artifact 3 (PO.xml)
    artifact = artyMap.get(xmlUuid);
    Assert.assertEquals("PO.xml", artifact.getName()); //$NON-NLS-1$
    Assert.assertEquals("3.0", artifact.getVersion()); //$NON-NLS-1$
}

From source file:org.overlord.sramp.test.wagon.SrampWagonTest.java

/**
 * Verifies that the correct file content was downloaded.
 * @param expected/*from  w w  w.ja va2  s .c o m*/
 * @param actual
 * @throws IOException
 */
private void assertContents(String expected, File actual) throws IOException {
    InputStream expectedStream = null;
    InputStream actualStream = null;
    try {
        expectedStream = getClass().getResourceAsStream(expected);
        actualStream = FileUtils.openInputStream(actual);
        Assert.assertTrue("File contents failed to match: " + actual.getName(), //$NON-NLS-1$
                IOUtils.contentEquals(expectedStream, actualStream));
    } finally {
        IOUtils.closeQuietly(actualStream);
        IOUtils.closeQuietly(expectedStream);
    }
}

From source file:org.overlord.sramp.ui.server.ArtifactUploadServlet.java

/**
 * Upload the artifact to the S-RAMP repository.
 * @param artifactType the type of s-ramp artifact
 * @param fileName the file name of the artifact being uploaded
 * @param artifactContent the content of the artifact
 * @throws Exception/*w w w. j a  va2s .  c  om*/
 */
private Map<String, String> uploadArtifact(String artifactType, String fileName, InputStream artifactContent)
        throws Exception {
    SrampAtomApiClient client = SrampAtomApiClient.getInstance();
    File tempFile = stashResourceContent(artifactContent);
    InputStream contentStream = null;
    String uuid = null;
    Map<String, String> responseParams = new HashMap<String, String>();

    try {
        // First, upload the artifact, no matter what kind
        try {
            contentStream = FileUtils.openInputStream(tempFile);
            ArtifactType at = ArtifactType.valueOf(artifactType);
            BaseArtifactType artifact = client.uploadArtifact(at, contentStream, fileName);
            responseParams.put("model", at.getArtifactType().getModel());
            responseParams.put("type", at.getArtifactType().getType());
            responseParams.put("uuid", artifact.getUuid());
            uuid = artifact.getUuid();
        } finally {
            IOUtils.closeQuietly(contentStream);
        }

        // Check if this is an expandable file type.  If it is, then expand it!
        if (isExpandable(fileName)) {
            JarToSrampArchive j2sramp = null;
            SrampArchive archive = null;
            try {
                final String parentUUID = uuid;
                j2sramp = new JarToSrampArchive(tempFile);
                j2sramp.setMetaDataFactory(new DefaultMetaDataFactory() {
                    @Override
                    public BaseArtifactType createMetaData(DiscoveredArtifact artifact) {
                        BaseArtifactType metaData = super.createMetaData(artifact);
                        SrampModelUtils.addGenericRelationship(metaData, "expandedFromDocument", parentUUID);
                        return metaData;
                    }
                });
                archive = j2sramp.createSrampArchive();
                client.uploadBatch(archive);
            } finally {
                SrampArchive.closeQuietly(archive);
                JarToSrampArchive.closeQuietly(j2sramp);
            }
        }

        return responseParams;
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:org.overlord.sramp.ui.server.servlets.ArtifactUploadServlet.java

/**
 * Uploads a single artifact to the S-RAMP repository.
 * @param artifactType//from   w w w .j  av a2  s .  co m
 * @param fileName
 * @param client
 * @param tempFile
 * @param responseParams
 * @throws Exception
 */
private void uploadSingleArtifact(String artifactType, String fileName, File tempFile,
        Map<String, String> responseParams) throws Exception {
    ArtifactType at = ArtifactType.valueOf(artifactType);
    String uuid = null;
    // First, upload the artifact, no matter what kind
    InputStream contentStream = null;
    try {
        contentStream = FileUtils.openInputStream(tempFile);
        BaseArtifactType artifact = clientAccessor.getClient().uploadArtifact(at, contentStream, fileName);
        responseParams.put("model", at.getArtifactType().getModel()); //$NON-NLS-1$
        responseParams.put("type", at.getArtifactType().getType()); //$NON-NLS-1$
        responseParams.put("uuid", artifact.getUuid()); //$NON-NLS-1$
        uuid = artifact.getUuid();
    } finally {
        IOUtils.closeQuietly(contentStream);
    }

    // Check if this is an expandable file type.  If it is, then expand it!
    ZipToSrampArchive expander = null;
    SrampArchive archive = null;
    try {
        expander = ZipToSrampArchiveRegistry.createExpander(at, tempFile);
        if (expander != null) {
            expander.setContextParam(DefaultMetaDataFactory.PARENT_UUID, uuid);
            archive = expander.createSrampArchive();
            clientAccessor.getClient().uploadBatch(archive);
        }
    } finally {
        SrampArchive.closeQuietly(archive);
        ZipToSrampArchive.closeQuietly(expander);
    }
}

From source file:org.overlord.sramp.ui.server.servlets.OntologyUploadServlet.java

/**
 * Uploads a single ontology to the S-RAMP repository.
 * @param tempFile// w  w  w .  j a v  a 2s  .com
 * @param responseParams
 * @throws Exception
 */
private void uploadSingleOntology(File tempFile, Map<String, String> responseParams) throws Exception {
    InputStream contentStream = null;
    try {
        contentStream = FileUtils.openInputStream(tempFile);
        RDF ontology = clientAccessor.getClient().uploadOntology(contentStream);
        responseParams.put("namespace", //$NON-NLS-1$
                ontology.getOtherAttributes().get(new QName("http://www.w3.org/XML/1998/namespace", "base"))); //$NON-NLS-1$ //$NON-NLS-2$
        responseParams.put("id", ontology.getOntology().getID()); //$NON-NLS-1$
        responseParams.put("label", ontology.getOntology().getLabel()); //$NON-NLS-1$
        responseParams.put("comment", ontology.getOntology().getComment()); //$NON-NLS-1$
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

From source file:org.overlord.sramp.wagon.SrampWagon.java

/**
 * Puts the artifact into the s-ramp repository.
 * @param gavInfo//from w ww .j ava  2  s . co  m
 * @param resourceInputStream
 * @throws TransferFailedException
 */
private void doPutArtifact(final MavenGavInfo gavInfo, InputStream resourceInputStream)
        throws TransferFailedException {

    // See the comment in {@link SrampWagon#fillInputData(InputData)} about why we're doing this
    // context classloader magic.
    ClassLoader oldCtxCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(SrampWagon.class.getClassLoader());
    File tempResourceFile = null;
    ZipToSrampArchive expander = null;
    SrampArchive archive = null;
    BaseArtifactType artifactGrouping = null;
    try {
        // First, stash the content in a temp file - we may need it multiple times.
        tempResourceFile = stashResourceContent(resourceInputStream);
        resourceInputStream = FileUtils.openInputStream(tempResourceFile);

        ArchiveInfo archiveInfo = ZipToSrampArchiveRegistry.inspectArchive(resourceInputStream);
        ArtifactType artifactType = getArtifactType(gavInfo, archiveInfo.type);

        resourceInputStream = FileUtils.openInputStream(tempResourceFile);

        // Is the artifact grouping option enabled?
        if (isPrimaryArtifact(gavInfo) && getParamFromRepositoryUrl("artifactGrouping") != null) { //$NON-NLS-1$
            artifactGrouping = ensureArtifactGrouping();
        }

        // Only search for existing artifacts by GAV info here
        BaseArtifactType artifact = findExistingArtifactByGAV(client, gavInfo);
        // If we found an artifact, we should update its content.  If not, we should upload
        // the artifact to the repository.
        if (artifact != null) {
            this.archive.addEntry(gavInfo.getFullName(), artifact, null);
            client.updateArtifactContent(artifact, resourceInputStream);
            if (ZipToSrampArchiveRegistry.canExpand(artifactType)) {
                final String parentUUID = artifact.getUuid();
                cleanExpandedArtifacts(client, parentUUID);
            }
        } else {
            // Upload the content, then add the maven properties to the artifact
            // as meta-data
            artifact = client.uploadArtifact(artifactType, resourceInputStream, gavInfo.getName());
            SrampModelUtils.setCustomProperty(artifact, "maven.groupId", gavInfo.getGroupId()); //$NON-NLS-1$
            SrampModelUtils.setCustomProperty(artifact, "maven.artifactId", gavInfo.getArtifactId()); //$NON-NLS-1$
            SrampModelUtils.setCustomProperty(artifact, "maven.version", gavInfo.getVersion()); //$NON-NLS-1$
            artifact.setVersion(gavInfo.getVersion());
            if (gavInfo.getClassifier() != null)
                SrampModelUtils.setCustomProperty(artifact, "maven.classifier", gavInfo.getClassifier()); //$NON-NLS-1$
            SrampModelUtils.setCustomProperty(artifact, "maven.type", gavInfo.getType()); //$NON-NLS-1$
            // Also create a relationship to the artifact grouping, if necessary
            if (artifactGrouping != null) {
                SrampModelUtils.addGenericRelationship(artifact, "groupedBy", artifactGrouping.getUuid()); //$NON-NLS-1$
                SrampModelUtils.addGenericRelationship(artifactGrouping, "groups", artifact.getUuid()); //$NON-NLS-1$
                client.updateArtifactMetaData(artifactGrouping);
            }

            client.updateArtifactMetaData(artifact);
            this.archive.addEntry(gavInfo.getFullName(), artifact, null);
        }

        // Now also add "expanded" content to the s-ramp repository
        expander = ZipToSrampArchiveRegistry.createExpander(artifactType, tempResourceFile);
        if (expander != null) {
            expander.setContextParam(DefaultMetaDataFactory.PARENT_UUID, artifact.getUuid());
            expander.addMetaDataProvider(new MetaDataProvider() {
                @Override
                public void provideMetaData(BaseArtifactType artifact) {
                    SrampModelUtils.setCustomProperty(artifact, "maven.parent-groupId", gavInfo.getGroupId()); //$NON-NLS-1$
                    SrampModelUtils.setCustomProperty(artifact, "maven.parent-artifactId", //$NON-NLS-1$
                            gavInfo.getArtifactId());
                    SrampModelUtils.setCustomProperty(artifact, "maven.parent-version", gavInfo.getVersion()); //$NON-NLS-1$
                    SrampModelUtils.setCustomProperty(artifact, "maven.parent-type", gavInfo.getType()); //$NON-NLS-1$
                }
            });
            archive = expander.createSrampArchive();
            client.uploadBatch(archive);
        }
    } catch (Throwable t) {
        throw new TransferFailedException(t.getMessage(), t);
    } finally {
        Thread.currentThread().setContextClassLoader(oldCtxCL);
        SrampArchive.closeQuietly(archive);
        ZipToSrampArchive.closeQuietly(expander);
        FileUtils.deleteQuietly(tempResourceFile);
    }
}

From source file:org.owasp.dependencycheck.analyzer.NodePackageAnalyzer.java

@Override
protected void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
    final File file = dependency.getActualFile();
    JsonReader jsonReader;/*from  www .j  a va2 s  .c om*/
    try {
        jsonReader = Json.createReader(FileUtils.openInputStream(file));
    } catch (IOException e) {
        throw new AnalysisException("Problem occurred while reading dependency file.", e);
    }
    try {
        final JsonObject json = jsonReader.readObject();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        if (json.containsKey("name")) {
            final Object value = json.get("name");
            if (value instanceof JsonString) {
                final String valueString = ((JsonString) value).getString();
                productEvidence.addEvidence(PACKAGE_JSON, "name", valueString, Confidence.HIGHEST);
                vendorEvidence.addEvidence(PACKAGE_JSON, "name_project",
                        String.format("%s_project", valueString), Confidence.LOW);
            } else {
                LOGGER.warn("JSON value not string as expected: {}", value);
            }
        }
        addToEvidence(json, productEvidence, "description");
        addToEvidence(json, vendorEvidence, "author");
        addToEvidence(json, dependency.getVersionEvidence(), "version");
        dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName()));
    } catch (JsonException e) {
        LOGGER.warn("Failed to parse package.json file.", e);
    } finally {
        jsonReader.close();
    }
}