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.client.SrampAtomApiClient.java

/**
 * Performs a batch operation by uploading an s-ramp package archive to the s-ramp server
 * for processing.  The contents of the s-ramp archive will be processed, and the results
 * will be returned as a Map.  The Map is indexed by the S-RAMP Archive entry path, and each
 * each value in the Map will either be a {@link BaseArtifactType} or an
 * {@link SrampAtomException}, depending on success vs. failure of that entry.
 *
 * @param archive the s-ramp package archive to upload
 * @return the collection of results (one per entry in the s-ramp package)
 * @throws SrampClientException//  w  w  w.ja va2 s. c  o  m
 * @throws SrampAtomException
 */
public Map<String, ?> uploadBatch(SrampArchive archive) throws SrampClientException, SrampAtomException {
    File packageFile = null;
    InputStream packageStream = null;

    ClientResponse<MultipartInput> clientResponse = null;
    try {
        if (archive.getEntries().isEmpty()) {
            return new HashMap<String, Object>();
        }

        packageFile = archive.pack();
        packageStream = FileUtils.openInputStream(packageFile);
        ClientRequest request = createClientRequest(this.endpoint);
        request.header("Content-Type", "application/zip"); //$NON-NLS-1$ //$NON-NLS-2$
        request.body(MediaType.APPLICATION_ZIP, packageStream);

        clientResponse = request.post(MultipartInput.class);
        MultipartInput response = clientResponse.getEntity();
        List<InputPart> parts = response.getParts();

        Map<String, Object> rval = new HashMap<String, Object>(parts.size());
        for (InputPart part : parts) {
            String contentId = part.getHeaders().getFirst("Content-ID"); //$NON-NLS-1$
            String path = contentId.substring(1, contentId.lastIndexOf('@'));
            HttpResponseBean rbean = part.getBody(HttpResponseBean.class, null);
            if (rbean.getCode() == 201) {
                Entry entry = (Entry) rbean.getBody();
                BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(entry);
                rval.put(path, artifact);
            } else if (rbean.getCode() == 409) {
                if (MediaType.APPLICATION_SRAMP_ATOM_EXCEPTION.equals(rbean.getHeaders().get("Content-Type"))) { //$NON-NLS-1$
                    SrampAtomException exception = (SrampAtomException) rbean.getBody();
                    rval.put(path, exception);
                } else {
                    String errorReason = (String) rbean.getBody();
                    SrampAtomException exception = new SrampAtomException(errorReason);
                    rval.put(path, exception);
                }
            } else {
                // Only a non-compliant s-ramp impl could cause this
                SrampAtomException exception = new SrampAtomException(
                        Messages.i18n.format("BAD_RETURN_CODE", rbean.getCode(), contentId)); //$NON-NLS-1$
                rval.put(path, exception);
            }
        }
        return rval;
    } catch (SrampAtomException e) {
        throw e;
    } catch (Throwable e) {
        throw new SrampClientException(e);
    } finally {
        IOUtils.closeQuietly(packageStream);
        FileUtils.deleteQuietly(packageFile);
        closeQuietly(clientResponse);
    }
}

From source file:org.overlord.sramp.repository.jcr.JCRArtifactPersister.java

/**
 * Phase two of artifact persistence consists of creating derived content for the artifact
 * and creating the JCR nodes associated with the derived content.  No relationships are
 * created in this phase./*from w  w  w.  ja  v  a2  s.  c o m*/
 *
 * @param session
 * @param metaData
 * @param classificationHelper
 * @param phase1
 * @throws Exception
 */
public static Phase2Result persistArtifactPhase2(Session session, BaseArtifactType metaData,
        ClassificationHelper classificationHelper, Phase1Result phase1) throws Exception {
    // No need to do any of the artifact deriving in phase2 unless it's a derivable (document
    // style) artifact
    if (!phase1.isDocumentArtifact)
        return null;
    Node artifactNode = phase1.artifactNode;
    ArtifactType artifactType = phase1.artifactType;

    Collection<BaseArtifactType> derivedArtifacts = null;
    InputStream cis = null;
    File tempFile = null;
    try {
        Node artifactContentNode = artifactNode.getNode("jcr:content"); //$NON-NLS-1$
        tempFile = saveToTempFile(artifactContentNode);
        cis = FileUtils.openInputStream(tempFile);
        derivedArtifacts = DerivedArtifactsFactory.newInstance().deriveArtifacts(metaData, cis);
    } finally {
        IOUtils.closeQuietly(cis);
        FileUtils.deleteQuietly(tempFile);
    }

    // Persist any derived artifacts.
    if (derivedArtifacts != null) {
        persistDerivedArtifacts(session, artifactNode, derivedArtifacts, classificationHelper);
    }

    // Update the JCR node again, this time with any properties/relationships added to the meta-data
    // by the deriver
    ArtifactToJCRNodeVisitor visitor = new ArtifactToJCRNodeVisitor(artifactType, artifactNode,
            new JCRReferenceFactoryImpl(session), classificationHelper);
    ArtifactVisitorHelper.visitArtifact(visitor, metaData);
    if (visitor.hasError())
        throw visitor.getError();

    // JCR persist point - phase 2 of artifact create
    session.save();

    Phase2Result result = new Phase2Result();
    result.derivedArtifacts = derivedArtifacts;
    return result;
}

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

/**
 * Test method for {@link org.overlord.sramp.common.server.atom.services.BatchResource#zipPackage(java.lang.String, java.io.InputStream)}.
 *//*from w  w w  .j a va  2 s . c  om*/
@Test
public void testZipPackage() throws Exception {
    SrampArchive archive = null;
    InputStream xsd1ContentStream = null;
    InputStream xsd2ContentStream = null;
    File zipFile = null;
    InputStream zipStream = 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)
        ClientRequest request = new ClientRequest(generateURL("/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
    ClientRequest request = new ClientRequest(generateURL("/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.assertEquals(2, artyNames.size());
    Assert.assertTrue(artyNames.contains("PO.xsd")); //$NON-NLS-1$
    Assert.assertTrue(artyNames.contains("XMLSchema.xsd")); //$NON-NLS-1$
}

From source file:org.overlord.sramp.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.
 *///ww  w. j  a v  a2s  . c o  m
@Test
public void testZipPackage_Multi() throws Exception {
    SrampArchive archive = null;
    InputStream xsd1ContentStream = null;
    InputStream wsdlContentStream = null;
    File zipFile = null;
    InputStream zipStream = 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)
        ClientRequest request = new ClientRequest(generateURL("/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>();
    ClientRequest request = new ClientRequest(generateURL("/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()) {
        request = new ClientRequest(generateURL("/s-ramp/xsd/XsdDocument/" + entry.getId().toString())); //$NON-NLS-1$
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = new ClientRequest(generateURL("/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()) {
        request = new ClientRequest(generateURL("/s-ramp/wsdl/WsdlDocument/" + entry.getId().toString())); //$NON-NLS-1$
        BaseArtifactType artifact = SrampAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity());
        artyMap.put(artifact.getUuid(), artifact);
    }
    request = new ClientRequest(generateURL("/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()) {
        request = new ClientRequest(generateURL("/s-ramp/core/XmlDocument/" + entry.getId().toString())); //$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.shell.commands.archive.AddEntryArchiveCommand.java

/**
 * @see org.overlord.sramp.shell.api.shell.ShellCommand#execute()
 *//*  w w  w. j a  va  2 s  . c  om*/
@Override
public boolean execute() throws Exception {
    String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); //$NON-NLS-1$
    String artifactTypeArg = requiredArgument(1, Messages.i18n.format("AddEntry.InvalidArgMsg.ArtifactType")); //$NON-NLS-1$
    String pathToContent = optionalArgument(2);

    QName varName = new QName("archive", "active-archive"); //$NON-NLS-1$ //$NON-NLS-2$
    SrampArchive archive = (SrampArchive) getContext().getVariable(varName);

    if (archive == null) {
        print(Messages.i18n.format("NO_ARCHIVE_OPEN")); //$NON-NLS-1$
        return false;
    }
    InputStream contentStream = null;
    try {
        ArtifactType type = ArtifactType.valueOf(artifactTypeArg);
        String name = new File(archivePathArg).getName();
        if (pathToContent != null) {
            File contentFile = new File(pathToContent);
            contentStream = FileUtils.openInputStream(contentFile);
        }
        BaseArtifactType artifact = type.newArtifactInstance();
        artifact.setName(name);
        archive.addEntry(archivePathArg, artifact, contentStream);
        print(Messages.i18n.format("AddEntry.Added", archivePathArg)); //$NON-NLS-1$
    } finally {
        IOUtils.closeQuietly(contentStream);
    }

    return true;
}

From source file:org.overlord.sramp.shell.commands.archive.UpdateEntryArchiveCommand.java

/**
 * Can set the content for an entry./*from w w  w  .j a  va 2  s  .co  m*/
 * @param archive
 * @param entryPath
 * @param context
 * @throws Exception
 */
private void executeSetContent(SrampArchive archive, String entryPath, ShellContext context) throws Exception {
    String pathToContentArg = requiredArgument(2,
            Messages.i18n.format("UpdateEntry.InvalidArgMsg.MissingPath")); //$NON-NLS-1$
    File file = new File(pathToContentArg);
    if (!file.isFile()) {
        throw new InvalidCommandArgumentException(2,
                Messages.i18n.format("UpdateEntry.FileNotFound", pathToContentArg)); //$NON-NLS-1$
    }

    InputStream contentStream = null;
    try {
        contentStream = FileUtils.openInputStream(file);
        SrampArchiveEntry entry = archive.getEntry(entryPath);
        archive.updateEntry(entry, contentStream);
        print(Messages.i18n.format("UpdateEntry.SuccessMsg")); //$NON-NLS-1$
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

From source file:org.overlord.sramp.shell.commands.core.UpdateContentCommand.java

/**
 * @see org.overlord.sramp.shell.api.shell.ShellCommand#execute()
 *///  ww w. ja va2s  . c om
@Override
public boolean execute() throws Exception {
    String contentFilePathArg = requiredArgument(0,
            Messages.i18n.format("UpdateContent.InvalidArgMsg.PathToContent")); //$NON-NLS-1$
    QName clientVarName = new QName("s-ramp", "client"); //$NON-NLS-1$ //$NON-NLS-2$
    QName artifactVarName = new QName("s-ramp", "artifact"); //$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;
    }

    BaseArtifactType artifact = (BaseArtifactType) getContext().getVariable(artifactVarName);
    if (artifact == null) {
        print(Messages.i18n.format("NoActiveArtifact")); //$NON-NLS-1$
        return false;
    }

    File file = new File(contentFilePathArg);
    if (!file.isFile()) {
        throw new InvalidCommandArgumentException(0,
                Messages.i18n.format("UpdateContent.InvalidArgMsg.PathToFile")); //$NON-NLS-1$
    }

    InputStream content = null;
    try {
        content = FileUtils.openInputStream(file);
        client.updateArtifactContent(artifact, content);
        print(Messages.i18n.format("UpdateContent.Success", artifact.getName())); //$NON-NLS-1$
    } catch (Exception e) {
        print(Messages.i18n.format("UpdateContent.Failure")); //$NON-NLS-1$
        print("\t" + e.getMessage()); //$NON-NLS-1$
        IOUtils.closeQuietly(content);
        return false;
    }
    return true;
}

From source file:org.overlord.sramp.shell.commands.core.UploadArtifactCommand.java

/**
 * @see org.overlord.sramp.shell.api.shell.ShellCommand#execute()
 *///from  w w  w  . j a  va2  s .c om
@Override
public boolean execute() throws Exception {
    String filePathArg = this.requiredArgument(0, Messages.i18n.format("Upload.InvalidArgMsg.LocalFile")); //$NON-NLS-1$
    String artifactTypeArg = this.optionalArgument(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;
    ZipToSrampArchive expander = null;
    SrampArchive archive = null;
    try {
        File file = new File(filePathArg);
        ArtifactType artifactType = null;
        if (artifactTypeArg != null) {
            artifactType = ArtifactType.valueOf(artifactTypeArg);
            if (artifactType.isExtendedType()) {
                artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType());
            }
        } else {
            artifactType = determineArtifactType(file);
        }
        content = FileUtils.openInputStream(file);
        BaseArtifactType artifact = client.uploadArtifact(artifactType, content, file.getName());
        IOUtils.closeQuietly(content);

        // Now also add "expanded" content to the s-ramp repository
        expander = ZipToSrampArchiveRegistry.createExpander(artifactType, file);
        if (expander != null) {
            expander.setContextParam(DefaultMetaDataFactory.PARENT_UUID, artifact.getUuid());
            archive = expander.createSrampArchive();
            client.uploadBatch(archive);
        }

        // Put the artifact in the session as the active artifact
        QName artifactVarName = new QName("s-ramp", "artifact"); //$NON-NLS-1$ //$NON-NLS-2$
        getContext().setVariable(artifactVarName, artifact);
        print(Messages.i18n.format("Upload.Success")); //$NON-NLS-1$
        PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor();
        ArtifactVisitorHelper.visitArtifact(visitor, artifact);
    } catch (Exception e) {
        print(Messages.i18n.format("Upload.Failure")); //$NON-NLS-1$
        print("\t" + e.getMessage()); //$NON-NLS-1$
        IOUtils.closeQuietly(content);
        return false;
    }
    return true;
}

From source file:org.overlord.sramp.shell.commands.maven.DeployCommand.java

/**
 * Execute.//  w w  w .  j  a  v a 2  s . c o  m
 *
 * @return true, if successful
 * @throws Exception
 *             the exception
 */
@Override
public boolean execute() throws Exception {
    String filePathArg = this.requiredArgument(0,
            Messages.i18n.format("DeployCommand.InvalidArgMsg.LocalFile")); //$NON-NLS-1$
    String gavArg = this.requiredArgument(1, Messages.i18n.format("DeployCommand.InvalidArgMsg.GAVInfo")); //$NON-NLS-1$
    String artifactTypeArg = this.optionalArgument(2);

    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;
    }

    // Validate the file
    File file = new File(filePathArg);
    if (!file.isFile()) {
        print(Messages.i18n.format("DeployCommand.FileNotFound", filePathArg)); //$NON-NLS-1$
        return false;
    }

    InputStream content = null;
    try {
        ArtifactType artifactType = null;
        if (artifactTypeArg != null) {
            artifactType = ArtifactType.valueOf(artifactTypeArg);
            if (artifactType.isExtendedType()) {
                artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType());
            }
        }
        // Process GAV and other meta-data, then update the artifact
        MavenGavInfo mavenGavInfo = MavenGavInfo.fromCommandLine(gavArg, file);
        if (mavenGavInfo.getType() == null) {
            print(Messages.i18n.format("DeployCommand.TypeNotSet", file.getName())); //$NON-NLS-1$
            IOUtils.closeQuietly(content);
            return false;
        }
        if (!allowSnapshot && mavenGavInfo.isSnapshot()) {
            print(Messages.i18n.format("DeployCommand.SnapshotNotAllowed", gavArg)); //$NON-NLS-1$
            IOUtils.closeQuietly(content);
            return false;
        }
        BaseArtifactType artifact = findExistingArtifactByGAV(client, mavenGavInfo);
        if (artifact != null) {
            print(Messages.i18n.format("DeployCommand.Failure.ReleaseArtifact.Exist", gavArg)); //$NON-NLS-1$
            IOUtils.closeQuietly(content);
            return false;
        } else {
            content = FileUtils.openInputStream(file);
            artifact = client.uploadArtifact(artifactType, content, file.getName());
            IOUtils.closeQuietly(content);
        }

        // Process GAV and other meta-data, then update the artifact
        String artifactName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion();
        String pomName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion() + ".pom"; //$NON-NLS-1$
        SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_GROUP_ID, mavenGavInfo.getGroupId());
        SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID,
                mavenGavInfo.getArtifactId());
        SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION, mavenGavInfo.getVersion());
        SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_MD5, mavenGavInfo.getMd5());
        SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_SHA1, mavenGavInfo.getSha1());
        if (StringUtils.isNotBlank(mavenGavInfo.getSnapshotId())) {
            SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID,
                    mavenGavInfo.getSnapshotId());
        } else if (mavenGavInfo.isSnapshot()) {
            SrampModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID,
                    generateSnapshotTimestamp());
        }
        if (mavenGavInfo.getClassifier() != null) {
            SrampModelUtils.setCustomProperty(artifact, "maven.classifier", mavenGavInfo.getClassifier()); //$NON-NLS-1$
            artifactName += '-' + mavenGavInfo.getClassifier();
        }
        if (mavenGavInfo.getType() != null) {
            SrampModelUtils.setCustomProperty(artifact, "maven.type", mavenGavInfo.getType()); //$NON-NLS-1$
            artifactName += '.' + mavenGavInfo.getType();
        }
        artifact.setName(artifactName);
        client.updateArtifactMetaData(artifact);

        // Generate and add a POM for the artifact
        String pom = generatePom(mavenGavInfo);
        InputStream pomContent = new ByteArrayInputStream(pom.getBytes("UTF-8")); //$NON-NLS-1$
        BaseArtifactType pomArtifact = ArtifactType.ExtendedDocument(JavaModel.TYPE_MAVEN_POM_XML)
                .newArtifactInstance();
        pomArtifact.setName(pomName);
        SrampModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_TYPE, "pom"); //$NON-NLS-1$
        SrampModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_MD5, DigestUtils.md5Hex(pom));
        SrampModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_SHA1, DigestUtils.shaHex(pom));

        BaseArtifactType returned = client.uploadArtifact(pomArtifact, pomContent);

        // Put the artifact in the session as the active artifact
        QName artifactVarName = new QName("s-ramp", "artifact"); //$NON-NLS-1$ //$NON-NLS-2$
        getContext().setVariable(artifactVarName, artifact);
        print(Messages.i18n.format("DeployCommand.Success")); //$NON-NLS-1$
        PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor();
        ArtifactVisitorHelper.visitArtifact(visitor, artifact);
    } catch (Exception e) {
        print(Messages.i18n.format("DeployCommand.Failure")); //$NON-NLS-1$
        print("\t" + e.getMessage()); //$NON-NLS-1$
        IOUtils.closeQuietly(content);
        return false;
    }
    return true;
}

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

/**
 * @see org.overlord.sramp.shell.api.shell.ShellCommand#execute()
 *//*  w  ww . j  a  va  2  s. c o  m*/
@Override
public boolean execute() throws Exception {
    String ontologyIdArg = this.requiredArgument(0,
            Messages.i18n.format("UpdateOntology.InvalidArgMsg.OntologyId")); //$NON-NLS-1$
    String filePathArg = this.requiredArgument(1,
            Messages.i18n.format("UpdateOntology.InvalidArgMsg.MissingPath")); //$NON-NLS-1$

    QName feedVarName = new QName("ontology", "feed"); //$NON-NLS-1$ //$NON-NLS-2$
    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;
    }

    if (!ontologyIdArg.contains(":") || ontologyIdArg.endsWith(":")) { //$NON-NLS-1$ //$NON-NLS-2$
        throw new InvalidCommandArgumentException(0, Messages.i18n.format("InvalidOntologyIdFormat")); //$NON-NLS-1$
    }

    String ontologyUuid = null;
    int colonIdx = ontologyIdArg.indexOf(':');
    String idType = ontologyIdArg.substring(0, colonIdx);
    String idValue = ontologyIdArg.substring(colonIdx + 1);
    if ("feed".equals(idType)) { //$NON-NLS-1$
        @SuppressWarnings("unchecked")
        List<OntologySummary> ontologies = (List<OntologySummary>) getContext().getVariable(feedVarName);
        if (ontologies == null) {
            throw new InvalidCommandArgumentException(0, Messages.i18n.format("DeleteOntology.NoOntologyFeed")); //$NON-NLS-1$
        }
        int feedIdx = Integer.parseInt(idValue) - 1;
        if (feedIdx < 0 || feedIdx >= ontologies.size()) {
            throw new InvalidCommandArgumentException(0, Messages.i18n.format("FeedIndexOutOfRange")); //$NON-NLS-1$
        }
        OntologySummary summary = ontologies.get(feedIdx);
        ontologyUuid = summary.getUuid();
    } else if ("uuid".equals(idType)) { //$NON-NLS-1$
        ontologyUuid = idValue;
    } else {
        throw new InvalidCommandArgumentException(0, Messages.i18n.format("InvalidIdFormat")); //$NON-NLS-1$
    }

    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("UpdateOntology.ReadingOntology", url.toExternalForm())); //$NON-NLS-1$
                content = url.openStream();
            } else {
                print(Messages.i18n.format("UpdateOntology.CannotFind", filePathArg)); //$NON-NLS-1$
            }
        }
        client.updateOntology(ontologyUuid, content);
        print(Messages.i18n.format("UpdateOntology.SuccessfulUpdate")); //$NON-NLS-1$
    } catch (Exception e) {
        print(Messages.i18n.format("UpdateOntology.UpdateFailed")); //$NON-NLS-1$
        print("\t" + e.getMessage()); //$NON-NLS-1$
        IOUtils.closeQuietly(content);
        return false;
    } finally {
        IOUtils.closeQuietly(content);
    }
    return true;
}