List of usage examples for org.apache.commons.io FileUtils openInputStream
public static FileInputStream openInputStream(File file) throws IOException
new FileInputStream(file)
. From source file:org.artificer.client.ArtificerAtomApiClient.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 ArtificerServerException}, 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 ArtificerClientException/*from ww w . j a v a 2 s . co m*/ * @throws ArtificerServerException */ public Map<String, ?> uploadBatch(ArtificerArchive archive) throws ArtificerClientException, ArtificerServerException { 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(srampEndpoint); request.header("Content-Type", "application/zip"); 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"); 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 = ArtificerAtomUtils.unwrapSrampArtifact(entry); rval.put(path, artifact); } else if (rbean.getCode() == 409) { if (MediaType.APPLICATION_ARTIFICER_SERVER_EXCEPTION .equals(rbean.getHeaders().get("Content-Type"))) { ArtificerServerException exception = (ArtificerServerException) rbean.getBody(); rval.put(path, exception); } else { String errorReason = (String) rbean.getBody(); ArtificerServerException exception = new ArtificerServerException(errorReason); rval.put(path, exception); } } else { // Only a non-compliant s-ramp impl could cause this ArtificerServerException exception = new ArtificerServerException( Messages.i18n.format("BAD_RETURN_CODE", rbean.getCode(), contentId)); rval.put(path, exception); } } return rval; } catch (ArtificerServerException e) { throw e; } catch (Throwable e) { throw new ArtificerClientException(e); } finally { IOUtils.closeQuietly(packageStream); FileUtils.deleteQuietly(packageFile); closeQuietly(clientResponse); } }
From source file:org.artificer.shell.archive.AddEntryArchiveCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { if (CollectionUtils.isEmpty(arguments)) { return doHelp(commandInvocation); }//from ww w .j a v a 2 s . c om String pathToContent = optionalArgument(arguments, 0); InputStream contentStream = null; try { ArtifactType artifactType = ArtifactType.valueOf(type); String name = new File(type).getName(); if (pathToContent != null) { File contentFile = new File(pathToContent); contentStream = FileUtils.openInputStream(contentFile); } BaseArtifactType artifact = artifactType.newArtifactInstance(); artifact.setName(name); currentArchive(commandInvocation).addEntry(entryPath, artifact, contentStream); commandInvocation.getShell().out().println(Messages.i18n.format("AddEntry.Added", entryPath)); } catch (ArtificerArchiveException e) { commandInvocation.getShell().out() .println(Messages.i18n.format("AddEntry.ArtificerArchiveException", e.getLocalizedMessage())); } finally { IOUtils.closeQuietly(contentStream); } return CommandResult.SUCCESS; }
From source file:org.artificer.shell.archive.UpdateEntryArchiveCommand.java
/** * Can set the content for an entry.//from w w w.jav a 2s . c o m * @param commandInvocation * @param archivePathArg * @throws Exception */ private void executeSetContent(CommandInvocation commandInvocation, String archivePathArg) throws Exception { String pathToContentArg = requiredArgument(commandInvocation, arguments, 1); File file = new File(pathToContentArg); if (!file.isFile()) { throw new ArtificerShellException(Messages.i18n.format("UpdateEntry.FileNotFound", pathToContentArg)); } ArtificerArchive archive = currentArchive(commandInvocation); InputStream contentStream = null; try { contentStream = FileUtils.openInputStream(file); ArtificerArchiveEntry entry = archive.getEntry(archivePathArg); archive.updateEntry(entry, contentStream); commandInvocation.getShell().out().println(Messages.i18n.format("UpdateEntry.SuccessMsg")); } finally { IOUtils.closeQuietly(contentStream); } }
From source file:org.artificer.shell.core.UpdateContentCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { ArtificerAtomApiClient client = client(commandInvocation); BaseArtifactType artifact = currentArtifact(commandInvocation); String filePath = requiredArgument(commandInvocation, arguments, 0); File file = new File(filePath); if (!file.isFile()) { commandInvocation.getShell().out() .println(Messages.i18n.format("UpdateContent.InvalidArgMsg.PathToFile")); return CommandResult.FAILURE; }// ww w . j a v a 2 s . c om InputStream content = null; try { content = FileUtils.openInputStream(file); client.updateArtifactContent(artifact, content); commandInvocation.getShell().out() .println(Messages.i18n.format("UpdateContent.Success", artifact.getName())); } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("UpdateContent.Failure")); commandInvocation.getShell().out().println("\t" + e.getMessage()); IOUtils.closeQuietly(content); return CommandResult.FAILURE; } return CommandResult.SUCCESS; }
From source file:org.artificer.shell.core.UploadArtifactCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { if (CollectionUtils.isEmpty(arguments)) { return doHelp(commandInvocation); }// w w w . j a v a2 s . com String filePath = requiredArgument(commandInvocation, arguments, 0); ArtificerAtomApiClient client = client(commandInvocation); InputStream content = null; try { ArtifactType artifactType = null; if (StringUtils.isNotBlank(type)) { artifactType = ArtifactType.valueOf(type); if (artifactType.isExtendedType()) { artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType()); } } File file = new File(filePath); BaseArtifactType artifact; if (local) { String path; if (file.exists()) { path = file.getAbsolutePath(); } else { URL url = this.getClass().getClassLoader().getResource(filePath); if (url != null) { path = url.getPath(); } else { commandInvocation.getShell().out() .println(Messages.i18n.format("Upload.FileNotFound", filePath)); return CommandResult.FAILURE; } } artifact = client.uploadArtifact(artifactType, path); } else { if (file.exists()) { content = FileUtils.openInputStream(file); } else { URL url = this.getClass().getClassLoader().getResource(filePath); if (url != null) { content = url.openStream(); } else { commandInvocation.getShell().out() .println(Messages.i18n.format("Upload.FileNotFound", filePath)); return CommandResult.FAILURE; } } artifact = client.uploadArtifact(artifactType, content, file.getName()); } if (StringUtils.isNotBlank(name) || StringUtils.isNotBlank(description)) { if (StringUtils.isNotBlank(name)) { artifact.setName(name); } if (StringUtils.isNotBlank(description)) { artifact.setDescription(description); } client.updateArtifactMetaData(artifact); } // Put the artifact in the session as the active artifact context(commandInvocation).setCurrentArtifact(artifact); commandInvocation.getShell().out().println(Messages.i18n.format("Upload.Success")); PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(commandInvocation); ArtifactVisitorHelper.visitArtifact(visitor, artifact); return CommandResult.SUCCESS; } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("Upload.Failure")); commandInvocation.getShell().out().println("\t" + e.getMessage()); return CommandResult.FAILURE; } finally { IOUtils.closeQuietly(content); } }
From source file:org.artificer.shell.maven.DeployCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { if (CollectionUtils.isEmpty(arguments)) { return doHelp(commandInvocation); }/* ww w . j a v a2 s . com*/ String filePathArg = requiredArgument(commandInvocation, arguments, 0); ArtificerAtomApiClient client = client(commandInvocation); // Validate the file File file = new File(filePathArg); if (!file.exists()) { URL url = this.getClass().getClassLoader().getResource(filePathArg); if (url != null) { file = new File(url.toURI()); } else { commandInvocation.getShell().out() .println(Messages.i18n.format("DeployCommand.FileNotFound", filePathArg)); return CommandResult.FAILURE; } } ArtifactType artifactType = null; if (StringUtils.isNotBlank(type)) { artifactType = ArtifactType.valueOf(type); if (artifactType.isExtendedType()) { artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType()); } } // Process GAV and other meta-data, then update the artifact MavenGavInfo mavenGavInfo = MavenGavInfo.fromCommandLine(gav, file); if (mavenGavInfo.getType() == null) { commandInvocation.getShell().out() .println(Messages.i18n.format("DeployCommand.TypeNotSet", file.getName())); return CommandResult.FAILURE; } if (!ALLOW_SNAPSHOT && mavenGavInfo.isSnapshot()) { commandInvocation.getShell().out() .println(Messages.i18n.format("DeployCommand.SnapshotNotAllowed", gav)); return CommandResult.FAILURE; } InputStream content = null; try { BaseArtifactType artifact = findExistingArtifactByGAV(client, mavenGavInfo); if (artifact != null) { commandInvocation.getShell().out() .println(Messages.i18n.format("DeployCommand.Failure.ReleaseArtifact.Exist", gav)); return CommandResult.FAILURE; } else { content = FileUtils.openInputStream(file); artifact = client.uploadArtifact(artifactType, content, file.getName()); } // Process GAV and other meta-data, then update the artifact String artifactName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion(); String pomName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion() + ".pom"; ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_GROUP_ID, mavenGavInfo.getGroupId()); ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID, mavenGavInfo.getArtifactId()); ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION, mavenGavInfo.getVersion()); ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_MD5, mavenGavInfo.getMd5()); ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_SHA1, mavenGavInfo.getSha1()); if (StringUtils.isNotBlank(mavenGavInfo.getSnapshotId())) { ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID, mavenGavInfo.getSnapshotId()); } else if (mavenGavInfo.isSnapshot()) { ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID, generateSnapshotTimestamp()); } if (mavenGavInfo.getClassifier() != null) { ArtificerModelUtils.setCustomProperty(artifact, "maven.classifier", mavenGavInfo.getClassifier()); artifactName += '-' + mavenGavInfo.getClassifier(); } if (mavenGavInfo.getType() != null) { ArtificerModelUtils.setCustomProperty(artifact, "maven.type", mavenGavInfo.getType()); 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")); BaseArtifactType pomArtifact = ArtifactType.ExtendedDocument(JavaModel.TYPE_MAVEN_POM_XML) .newArtifactInstance(); pomArtifact.setName(pomName); ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_TYPE, "pom"); ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_MD5, DigestUtils.md5Hex(pom)); ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_SHA1, DigestUtils.shaHex(pom)); client.uploadArtifact(pomArtifact, pomContent); // Put the artifact in the session as the active artifact context(commandInvocation).setCurrentArtifact(artifact); commandInvocation.getShell().out().println(Messages.i18n.format("DeployCommand.Success")); PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(commandInvocation); ArtifactVisitorHelper.visitArtifact(visitor, artifact); return CommandResult.SUCCESS; } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("DeployCommand.Failure")); commandInvocation.getShell().out().println("\t" + e.getMessage()); return CommandResult.FAILURE; } finally { IOUtils.closeQuietly(content); } }
From source file:org.artificer.shell.ontology.UpdateOntologyCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { if (CollectionUtils.isEmpty(arguments)) { return doHelp(commandInvocation); }/*from w ww.j av a2 s .co m*/ String filePath = requiredArgument(commandInvocation, arguments, 0); ArtificerAtomApiClient client = client(commandInvocation); if (StringUtils.isNotBlank(feedIndex)) { OntologySummary ontologySummary = ontologySummaryFromFeed(commandInvocation, feedIndex); ontologyUuid = ontologySummary.getUuid(); } else if (StringUtils.isBlank(ontologyUuid)) { commandInvocation.getShell().out().println(Messages.i18n.format("Ontology.Arguments")); return CommandResult.FAILURE; } InputStream content = null; try { File file = new File(filePath); if (file.exists()) { content = FileUtils.openInputStream(file); } else { URL url = this.getClass().getClassLoader().getResource(filePath); if (url != null) { commandInvocation.getShell().out() .println(Messages.i18n.format("UpdateOntology.ReadingOntology", url.toExternalForm())); content = url.openStream(); } else { commandInvocation.getShell().out() .println(Messages.i18n.format("UpdateOntology.CannotFind", filePath)); return CommandResult.FAILURE; } } client.updateOntology(ontologyUuid, content); commandInvocation.getShell().out().println(Messages.i18n.format("UpdateOntology.SuccessfulUpdate")); } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("UpdateOntology.UpdateFailed")); commandInvocation.getShell().out().println("\t" + e.getMessage()); IOUtils.closeQuietly(content); return CommandResult.FAILURE; } finally { IOUtils.closeQuietly(content); } return CommandResult.SUCCESS; }
From source file:org.artificer.shell.ontology.UploadOntologyCommand.java
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { if (CollectionUtils.isEmpty(arguments)) { return doHelp(commandInvocation); }//from w w w .ja v a 2s . c o m String filePath = requiredArgument(commandInvocation, arguments, 0); ArtificerAtomApiClient client = client(commandInvocation); InputStream content = null; try { File file = new File(filePath); if (file.exists()) { content = FileUtils.openInputStream(file); } else { URL url = this.getClass().getClassLoader().getResource(filePath); if (url != null) { commandInvocation.getShell().out() .println(Messages.i18n.format("UploadOntology.ReadingOntology", url.toExternalForm())); content = url.openStream(); } else { commandInvocation.getShell().out() .println(Messages.i18n.format("UploadOntology.CannotFind", filePath)); return CommandResult.FAILURE; } } client.uploadOntology(content); commandInvocation.getShell().out().println(Messages.i18n.format("UploadOntology.SuccessfulUpload")); } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("UploadOntology.UploadFailed")); commandInvocation.getShell().out().println("\t" + e.getMessage()); IOUtils.closeQuietly(content); return CommandResult.FAILURE; } finally { IOUtils.closeQuietly(content); } commandInvocation.getShell().out() .println("**********************************************************************"); return CommandResult.SUCCESS; }
From source file:org.artificer.test.maven.ArtificerMavenTest.java
/** * Verifies that the correct file content was downloaded. * @param expected/*from w ww . j a v a 2 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(), IOUtils.contentEquals(expectedStream, actualStream)); } finally { IOUtils.closeQuietly(actualStream); IOUtils.closeQuietly(expectedStream); } }
From source file:org.artificer.test.server.atom.services.BatchResourceTest.java
@Test public void testZipPackage() throws Exception { ArtificerArchive archive = null;// w w w . jav a 2s . c o m InputStream xsd1ContentStream = null; InputStream xsd2ContentStream = null; File zipFile = null; InputStream zipStream = null; ClientRequest request = null; try { // Create a test s-ramp archive archive = new ArtificerArchive(); xsd1ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/PO.xsd"); BaseArtifactType metaData = new XsdDocument(); metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); metaData.setName("PO.xsd"); archive.addEntry("schemas/PO.xsd", metaData, xsd1ContentStream); xsd2ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/XMLSchema.xsd"); metaData = new XsdDocument(); metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); metaData.setName("XMLSchema.xsd"); metaData.setVersion("1.0"); archive.addEntry("schemas/XMLSchema.xsd", metaData, xsd2ContentStream); 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"); 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"); HttpResponseBean rbean = part.getBody(HttpResponseBean.class, null); Assert.assertEquals(201, rbean.getCode()); Entry entry = (Entry) rbean.getBody(); BaseArtifactType artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry); artyMap.put(id, artifact); } Assert.assertTrue(artyMap.keySet().contains("<schemas/PO.xsd@package>")); Assert.assertTrue(artyMap.keySet().contains("<schemas/XMLSchema.xsd@package>")); // Assertions for artifact 1 BaseArtifactType arty = artyMap.get("<schemas/PO.xsd@package>"); Assert.assertNotNull(arty); Assert.assertEquals("PO.xsd", arty.getName()); Assert.assertNull(arty.getVersion()); arty = artyMap.get("<schemas/XMLSchema.xsd@package>"); Assert.assertNotNull(arty); Assert.assertEquals("XMLSchema.xsd", arty.getName()); Assert.assertEquals("1.0", arty.getVersion()); } finally { IOUtils.closeQuietly(xsd1ContentStream); IOUtils.closeQuietly(xsd2ContentStream); ArtificerArchive.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"); 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")); Assert.assertTrue(artyNames.contains("XMLSchema.xsd")); }