private String generateName(BaseArtifactType artifact) { String artifactId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID); String version = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION); String snapshotId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID); String classifier = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_CLASSIFIER); String type = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_TYPE); if (artifact.getName().contains(artifactId)) { StringBuilder name = new StringBuilder(""); // $NON-NLS-1$ name.append(artifactId); if (version.contains("SNAPSHOT")) { // $NON-NLS-1$ if (StringUtils.isNotBlank(snapshotId)) { name.append(MAVEN_SEPARATOR) .append(version.substring(0, version.indexOf("SNAPSHOT"))) .append(snapshotId); // $NON-NLS-1$ } else { name.append(MAVEN_SEPARATOR).append(version); } } else { name.append(MAVEN_SEPARATOR).append(version); } if (classifier != null) { name.append(MAVEN_SEPARATOR).append(classifier); } name.append(MAVEN_FILE_EXTENSION_SEPARATOR).append(type); return name.toString(); } else { return artifact.getName(); } }
@Test public void testDeleteArtifact() throws Exception { String artifactFileName = "s-ramp-press-release.pdf"; InputStream pdf = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.DOCUMENT); // Add an artifact BaseArtifactType artifact = persistenceManager.persistArtifact(document, pdf); Assert.assertNotNull(artifact); Assert.assertEquals(Document.class, artifact.getClass()); Assert.assertEquals(new Long(18873l), ((DocumentArtifactType) artifact).getContentSize()); log.info( "persisted s-ramp-press-release.pdf to JCR, returned artifact uuid=" + artifact.getUuid()); // Now delete that artifact ArtifactType at = ArtifactType.valueOf(artifact); persistenceManager.deleteArtifact(document.getUuid(), at); // Now make sure we can't load it back up BaseArtifactType deleted = persistenceManager.getArtifact(document.getUuid(), at); Assert.assertNull(deleted); SrampQuery query = queryManager.createQuery("/s-ramp[@uuid = ?]"); query.setString(document.getUuid()); ArtifactSet artifactSet = query.executeQuery(); Assert.assertEquals(0, artifactSet.size()); }
@Test public void testCreateArtifact() throws Exception { prepare(CreateArtifactCommand.class); // failure tests pushToOutput("createArtifact --type ComplexTypeDeclaration --name FooName"); Assert.assertTrue( stream.toString().contains("The artifact you are trying to create is a derived artifact")); pushToOutput("createArtifact --type XmlDocument --name FooName"); Assert.assertTrue( stream.toString().contains("The artifact you are trying to create is a document artifact")); // the initial create needs to return an artifact, its then used to set the context BaseArtifactType extendedArtifact = ArtifactType.ExtendedArtifactType("FooType").newArtifactInstance(); extendedArtifact.setName("FooName"); Mockito.when(clientMock.createArtifact(Mockito.any(BaseArtifactType.class))) .thenReturn(extendedArtifact); // success tests pushToOutput("createArtifact --type FooType --name FooName --description FooDescription"); ArgumentCaptor<BaseArtifactType> artifact = ArgumentCaptor.forClass(BaseArtifactType.class); Mockito.verify(clientMock, Mockito.times(1)).createArtifact(artifact.capture()); Assert.assertEquals("FooName", artifact.getValue().getName()); Assert.assertEquals("FooDescription", artifact.getValue().getDescription()); Assert.assertEquals("FooType", ArtifactType.valueOf(artifact.getValue()).getExtendedType()); // ensure it was set as the current artifact in the context Assert.assertEquals("FooName", getAeshContext().getCurrentArtifact().getName()); }
@Test public void testPersistArtifactPO_XML() throws Exception { String artifactFileName = "PO.xml"; InputStream POXml = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.XML_DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, POXml); Assert.assertNotNull(artifact); log.info("persisted PO.xml to JCR, returned artifact uuid=" + artifact.getUuid()); // print out the derived node if (log.isDebugEnabled()) { persistenceManager.printArtifactGraph(artifact.getUuid(), ArtifactType.XmlDocument()); } Assert.assertEquals(XmlDocument.class, artifact.getClass()); long size = ((DocumentArtifactType) artifact).getContentSize(); Assert.assertTrue( size >= 825L); // Not doing an equals here due to the vagaries of Windows vs *nix line // endings }
@Override public ArtifactBuilder buildArtifacts( BaseArtifactType primaryArtifact, ArtifactContent artifactContent) throws IOException { super.buildArtifacts(primaryArtifact, artifactContent); ClassParser parser = new ClassParser(getContentStream(), primaryArtifact.getName()); JavaClass javaClass = parser.parse(); if (javaClass.isInterface()) { ((ExtendedDocument) primaryArtifact).setExtendedType(JavaModel.TYPE_JAVA_INTERFACE); } else if (javaClass.isClass()) { ((ExtendedDocument) primaryArtifact).setExtendedType(JavaModel.TYPE_JAVA_CLASS); } else if (javaClass.isEnum()) { ((ExtendedDocument) primaryArtifact).setExtendedType(JavaModel.TYPE_JAVA_ENUM); } String packageName = javaClass.getPackageName(); String className = javaClass.getClassName(); primaryArtifact.setName(className); String shortName = className; if (className.lastIndexOf('.') > 0) { shortName = className.substring(className.lastIndexOf('.') + 1); } SrampModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_PACKAGE_NAME, packageName); SrampModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_CLASS_NAME, shortName); return this; }
/** * Called to help the given visitor visit the provided artifact. * * @param visitor * @param artifact */ public static void visitArtifact(ArtifactVisitor visitor, BaseArtifactType artifact) { try { Method method = visitor.getClass().getMethod("visit", artifact.getClass()); method.invoke(visitor, artifact); } catch (Exception e) { // This shouldn't happen unless we've programmed something wrong in the visitor interface. throw new RuntimeException( Messages.i18n.format("VISIT_METHOD_NOT_FOUND", visitor.getClass(), artifact.getClass()), e); } }
/** @see org.overlord.sramp.shell.api.shell.ShellCommand#execute() */ @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; }
/* * (non-Javadoc) * * @see * org.jboss.arquillian.container.sramp.SrampService#deployArchive(java. * lang.String, java.lang.String, java.io.InputStream) */ public BaseArtifactType deployArchive( String archiveId, String archiveName, String artifactTypeArg, InputStream content) { assert content != null; ZipToSrampArchive expander = null; SrampArchive archive = null; BaseArtifactType artifact = null; File tempResourceFile = null; try { // internal integrity check artifactCounter = client.query("/s-ramp").getTotalResults(); // First, stash the content in a temp file - we may need it multiple // times. tempResourceFile = stashResourceContent(content); content = FileUtils.openInputStream(tempResourceFile); ArtifactType artifactType = ArtifactType.valueOf(artifactTypeArg); if (artifactType.isExtendedType()) { artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType()); } artifact = client.uploadArtifact(artifactType, content, archiveName); IOUtils.closeQuietly(content); // for all uploaded files add custom property SrampModelUtils.setCustomProperty(artifact, "arquillian-archive-id", archiveId); client.updateArtifactMetaData(artifact); content = FileUtils.openInputStream(tempResourceFile); // Now also add "expanded" content to the s-ramp repository expander = ZipToSrampArchiveRegistry.createExpander(artifactType, content); if (expander != null) { expander.setContextParam(DefaultMetaDataFactory.PARENT_UUID, artifact.getUuid()); archive = expander.createSrampArchive(); client.uploadBatch(archive); } } catch (Exception e) { log.error("Upload failure:", e); IOUtils.closeQuietly(content); } finally { SrampArchive.closeQuietly(archive); ZipToSrampArchive.closeQuietly(expander); FileUtils.deleteQuietly(tempResourceFile); } return artifact; }
@Override protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception { ArtificerAtomApiClient client = client(commandInvocation); BaseArtifactType artifact = currentArtifact(commandInvocation); try { client.updateArtifactMetaData(artifact); commandInvocation .getShell() .out() .println(Messages.i18n.format("UpdateMetaData.Success", artifact.getName())); } catch (Exception e) { commandInvocation.getShell().out().println(Messages.i18n.format("UpdateMetaData.Failure")); commandInvocation.getShell().out().println("\t" + e.getMessage()); return CommandResult.FAILURE; } return CommandResult.SUCCESS; }
/** * Uploads a single deployment to S-RAMP. * * @param deploymentType * @param fileName * @param client * @param tempFile * @param responseParams * @param version * @throws Exception */ private void uploadSingleDeployment( String deploymentType, String fileName, File tempFile, Map<String, String> responseParams, String version) throws Exception { ArtifactType at = ArtifactType.valueOf(deploymentType); if (at.isExtendedType()) { at = ArtifactType.ExtendedDocument(at.getExtendedType()); } String uuid = null; // First, upload the deployment InputStream contentStream = null; try { contentStream = FileUtils.openInputStream(tempFile); BaseArtifactType artifact = at.newArtifactInstance(); artifact.setName(fileName); artifact.setVersion(version); artifact = clientAccessor.getClient().uploadArtifact(artifact, contentStream); 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); } // Try to expand the artifact (works if an expander is available for the given artifact type). ZipToSrampArchive j2sramp = null; SrampArchive archive = null; try { j2sramp = ZipToSrampArchiveRegistry.createExpander(at, tempFile); if (j2sramp != null) { j2sramp.setContextParam(DefaultMetaDataFactory.PARENT_UUID, uuid); archive = j2sramp.createSrampArchive(); clientAccessor.getClient().uploadBatch(archive); } } finally { SrampArchive.closeQuietly(archive); ZipToSrampArchive.closeQuietly(j2sramp); } }
@Test public void testPersistArtifact_PDF() throws Exception { String artifactFileName = "s-ramp-press-release.pdf"; InputStream pdf = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, pdf); Assert.assertNotNull(artifact); log.info( "persisted s-ramp-press-release.pdf to JCR, returned artifact uuid=" + artifact.getUuid()); // print out the derived node if (log.isDebugEnabled()) { persistenceManager.printArtifactGraph(artifact.getUuid(), ArtifactType.Document()); } Assert.assertEquals(Document.class, artifact.getClass()); Assert.assertEquals(new Long(18873l), ((DocumentArtifactType) artifact).getContentSize()); }
/** * Tests that we can update the content of an s-ramp artifact. * * @throws Exception */ @Test public void testUpdateContent() throws Exception { // First, add an artifact to the repo String artifactFileName = "PO.xsd"; InputStream POXsd = this.getClass().getResourceAsStream("/sample-files/xsd/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, POXsd); Assert.assertNotNull(artifact); log.info("persisted PO.xsd to JCR, returned artifact uuid=" + artifact.getUuid()); Assert.assertEquals(XsdDocument.class, artifact.getClass()); long size = ((DocumentArtifactType) artifact).getContentSize(); Assert.assertTrue( size >= 2376L); // Not doing an equals here due to the vagaries of Windows vs *nix line // endings Assert.assertEquals(artifactFileName, artifact.getName()); // Now update the artifact content InputStream otherXsd = this.getClass().getResourceAsStream("/sample-files/xsd/XMLSchema.xsd"); persistenceManager.updateArtifactContent( artifact.getUuid(), ArtifactType.XsdDocument(), otherXsd); // Now verify the content was updated artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); size = ((DocumentArtifactType) artifact).getContentSize(); Assert.assertTrue( size >= 87677L); // Not doing an equals here due to the vagaries of Windows vs *nix line // endings }
/** * * Gets the artifact content from the s-ramp repository and stores it in the {@link InputData} * object for use by Maven. * * @param gavInfo * @param inputData * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ private void doGetArtifact(MavenGavInfo gavInfo, InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { // RESTEasy uses the current thread's context classloader to load its logger class. This // fails in Maven because the context classloader is the wagon plugin's classloader, which // doesn't know about any of the RESTEasy JARs. So here we're temporarily setting the // context classloader to the s-ramp wagon extension's classloader, which should have access // to all the right stuff. ClassLoader oldCtxCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(SrampWagon.class.getClassLoader()); try { // Query the artifact meta data using GAV info BaseArtifactType artifact = findExistingArtifact(client, gavInfo); if (artifact == null) throw new ResourceDoesNotExistException( Messages.i18n.format("ARTIFACT_NOT_FOUND", gavInfo.getName())); // $NON-NLS-1$ this.archive.addEntry(gavInfo.getFullName(), artifact, null); ArtifactType type = ArtifactType.valueOf(artifact); // Get the artifact content as an input stream InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); inputData.setInputStream(artifactContent); } catch (ResourceDoesNotExistException e) { throw e; } catch (SrampClientException e) { if (e.getCause() instanceof HttpHostConnectException) { this.debug(Messages.i18n.format("SRAMP_CONNECTION_FAILED", e.getMessage())); // $NON-NLS-1$ } else { this.error(e.getMessage(), e); } throw new ResourceDoesNotExistException( Messages.i18n.format( "FAILED_TO_GET_RESOURCE_FROM_SRAMP", gavInfo.getName())); // $NON-NLS-1$ } catch (Throwable t) { this.error(t.getMessage(), t); } finally { Thread.currentThread().setContextClassLoader(oldCtxCL); } }
@Test public void testPersistArtifact_ExtendedArtifactType() throws Exception { ExtendedArtifactType extendedArtifact = new ExtendedArtifactType(); extendedArtifact.setArtifactType(BaseArtifactEnum.EXTENDED_ARTIFACT_TYPE); extendedArtifact.setExtendedType("FooArtifactType"); extendedArtifact.setName("MyExtendedArtifact"); extendedArtifact.setDescription("This is a simple description for testing."); BaseArtifactType artifact = persistenceManager.persistArtifact(extendedArtifact, null); Assert.assertNotNull(artifact); log.info("persisted extended artifact to JCR, returned artifact uuid=" + artifact.getUuid()); // print out the derived node if (log.isDebugEnabled()) { persistenceManager.printArtifactGraph(artifact.getUuid(), ArtifactType.XmlDocument()); } Assert.assertEquals(ExtendedArtifactType.class, artifact.getClass()); String name = ((ExtendedArtifactType) artifact).getName(); String description = ((ExtendedArtifactType) artifact).getDescription(); Assert.assertEquals("MyExtendedArtifact", name); Assert.assertEquals("This is a simple description for testing.", description); }
/** * This also tests the zipPackage method of the {@link * org.artificer.server.atom.services.BatchResource} class, but it is more thorough. It tests * adding new content, updating existing content, etc. */ @Test public void testZipPackage_Multi() throws Exception { ArtificerArchive 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 ArtificerArchive(); // A new XSD document xsd1ContentStream = this.getClass().getResourceAsStream("/sample-files/xsd/PO.xsd"); BaseArtifactType metaData = new XsdDocument(); metaData.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); metaData.setUuid(UUID.randomUUID().toString()); // will be ignored metaData.setName("PO.xsd"); archive.addEntry("schemas/PO.xsd", metaData, xsd1ContentStream); // Update an existing WSDL document (content and meta-data) wsdlContentStream = this.getClass().getResourceAsStream("/sample-files/wsdl/sample-updated.wsdl"); metaData = wsdlDoc; metaData.setVersion("2.0"); ArtificerModelUtils.setCustomProperty(metaData, "foo", "bar"); archive.addEntry("wsdl/sample.wsdl", metaData, wsdlContentStream); // Update an existing XML document (meta-data only) metaData = xmlDoc; metaData.setVersion("3.0"); ArtificerModelUtils.setCustomProperty(metaData, "far", "baz"); archive.addEntry("core/PO.xml", metaData, null); 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, HttpResponseBean> respMap = new HashMap<String, HttpResponseBean>(); for (InputPart part : parts) { String id = part.getHeaders().getFirst("Content-ID"); 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>")); Assert.assertTrue(respMap.keySet().contains("<wsdl/sample.wsdl@package>")); Assert.assertTrue(respMap.keySet().contains("<core/PO.xml@package>")); // Assertions for artifact 1 (PO.xsd) HttpResponseBean httpResp = respMap.get("<schemas/PO.xsd@package>"); Assert.assertEquals(201, httpResp.getCode()); Assert.assertEquals("Created", httpResp.getStatus()); Entry entry = (Entry) httpResp.getBody(); BaseArtifactType artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry); Assert.assertEquals("PO.xsd", artifact.getName()); 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>"); Assert.assertEquals(200, httpResp.getCode()); Assert.assertEquals("OK", httpResp.getStatus()); entry = (Entry) httpResp.getBody(); artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry); Assert.assertEquals("sample.wsdl", artifact.getName()); Assert.assertEquals("2.0", artifact.getVersion()); wsdlUuid = artifact.getUuid(); // Assertions for artifact 3 (PO.xml) httpResp = respMap.get("<core/PO.xml@package>"); Assert.assertEquals(200, httpResp.getCode()); Assert.assertEquals("OK", httpResp.getStatus()); entry = (Entry) httpResp.getBody(); artifact = ArtificerAtomUtils.unwrapSrampArtifact(entry); Assert.assertEquals("PO.xml", artifact.getName()); Assert.assertEquals("3.0", artifact.getVersion()); xmlUuid = artifact.getUuid(); } finally { IOUtils.closeQuietly(xsd1ContentStream); IOUtils.closeQuietly(wsdlContentStream); ArtificerArchive.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"); 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); BaseArtifactType artifact = ArtificerAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity()); artyMap.put(artifact.getUuid(), artifact); } request = clientRequest("/s-ramp/wsdl/WsdlDocument"); 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); BaseArtifactType artifact = ArtificerAtomUtils.unwrapSrampArtifact(request.get(Entry.class).getEntity()); artyMap.put(artifact.getUuid(), artifact); } request = clientRequest("/s-ramp/core/XmlDocument"); 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); BaseArtifactType artifact = ArtificerAtomUtils.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()); Assert.assertNull(artifact.getVersion()); // Assertions for artifact 2 (sample.wsdl) artifact = artyMap.get(wsdlUuid); Assert.assertEquals("sample.wsdl", artifact.getName()); Assert.assertEquals("2.0", artifact.getVersion()); // Assertions for artifact 3 (PO.xml) artifact = artyMap.get(xmlUuid); Assert.assertEquals("PO.xml", artifact.getName()); Assert.assertEquals("3.0", artifact.getVersion()); }
private String uploadArtifact(MavenMetaData metadata, InputStream content) throws MavenRepositoryException { String uuid = null; if (content == null) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.no.content")); // $NON-NLS-1$ } String fileName = metadata.getFileName(); PersistenceManager persistenceManager = PersistenceFactory.newInstance(); // We need to query firstly to check if there is an existing item. If // there is an existing item, then it would be updated // Adding the criterias and parameters List<String> criteria = new ArrayList<String>(); List<Object> parameters = new ArrayList<Object>(); criteria.add("@maven.artifactId = ?"); // $NON-NLS-1$ criteria.add("@maven.groupId = ?"); // $NON-NLS-1$ criteria.add("@maven.type = ?"); // $NON-NLS-1$ parameters.add(metadata.getArtifactId()); parameters.add(metadata.getGroupId()); if (StringUtils.isNotBlank(metadata.getParentType())) { parameters.add(metadata.getParentType()); } else { parameters.add(metadata.getType()); } if (StringUtils.isNotBlank(metadata.getVersion())) { criteria.add("@maven.version = ?"); // $NON-NLS-1$ parameters.add(metadata.getVersion()); } else { criteria.add("xp2:not(@maven.version)"); // $NON-NLS-1$ } if (StringUtils.isNotBlank(metadata.getParentFileName())) { criteria.add("@name = ?"); // $NON-NLS-1$ parameters.add(metadata.getParentFileName()); } if (StringUtils.isNotBlank(metadata.getSnapshotId())) { criteria.add("@maven.snapshot.id = ?"); // $NON-NLS-1$ parameters.add(metadata.getSnapshotId()); } else { criteria.add("xp2:not(@maven.snapshot.id)"); // $NON-NLS-1$ } ArtifactSet artifactSet = null; BaseArtifactType baseArtifact = null; try { // Query the previous criterias artifactSet = query(criteria, parameters); if (artifactSet.size() >= 1) { // Found some content! baseArtifact = artifactSet.iterator().next(); } } catch (SrampAtomException e) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.sramp.query.error", metadata.toString()), e); //$NON-NLS-1$ } finally { if (artifactSet != null) { artifactSet.close(); } } if (MavenFileExtensionEnum.value(metadata.getType()) != null) { if (baseArtifact != null) { boolean update = false; ArtifactType artifactType = ArtifactType.valueOf(baseArtifact.getArtifactType()); if (metadata.getType().equals(MavenFileExtensionEnum.HASH_MD5.getExtension()) || metadata.getType().equals(MavenFileExtensionEnum.HASH_SHA1.getExtension())) { String content_value = ""; // $NON-NLS-1$ try { content_value = IOUtils.toString(content); } catch (IOException e1) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.sramp.error", metadata.toString()), e1); //$NON-NLS-1$ } if (StringUtils.isNotBlank(content_value)) { if (metadata.getType().equals(MavenFileExtensionEnum.HASH_MD5.getExtension())) { SrampModelUtils.setCustomProperty( baseArtifact, JavaModel.PROP_MAVEN_HASH_MD5, content_value); update = true; } else if (metadata.getType().equals(MavenFileExtensionEnum.HASH_SHA1.getExtension())) { SrampModelUtils.setCustomProperty( baseArtifact, JavaModel.PROP_MAVEN_HASH_SHA1, content_value); update = true; } if (update) { try { persistenceManager.updateArtifact(baseArtifact, artifactType); } catch (SrampException e) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.sramp.error", metadata.toString()), e); //$NON-NLS-1$ } } } } else { try { persistenceManager.updateArtifactContent(baseArtifact.getUuid(), artifactType, content); } catch (SrampException e) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.sramp.error", metadata.toString()), e); //$NON-NLS-1$ } } } } else { BaseArtifactType persisted = null; // If there is an existing artifact in s-ramp it would be updaded // with the new content if (baseArtifact != null) { if (metadata.isSnapshotVersion() || metadata.getFileName().equals("maven-metadata.xml")) { // $NON-NLS-1$ ArtifactType artifactType = ArtifactType.valueOf(baseArtifact); try { persistenceManager.updateArtifactContent(baseArtifact.getUuid(), artifactType, content); } catch (SrampException e) { throw new MavenRepositoryException( Messages.i18n.format( "maven.resource.upload.sramp.update.content.error", //$NON-NLS-1$ baseArtifact.getUuid()), e); } persisted = baseArtifact; } else { throw new MavenRepositoryException( Messages.i18n.format( "maven.resource.upload.sramp.release.artifact.exist", //$NON-NLS-1$ metadata.getFullName())); } } else { // we need to create a new artifact in s-ramp and persist the // content ArtifactType artifactType = determineArtifactType(fileName); BaseArtifactType baseArtifactType = artifactType.newArtifactInstance(); try { persisted = persistenceManager.persistArtifact(baseArtifactType, content); } catch (SrampException e1) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.upload.sramp.new.content.error"), e1); //$NON-NLS-1$ } } // Store the metadata to the persisted artifact SrampModelUtils.setCustomProperty( persisted, JavaModel.PROP_MAVEN_GROUP_ID, metadata.getGroupId()); SrampModelUtils.setCustomProperty( persisted, JavaModel.PROP_MAVEN_ARTIFACT_ID, metadata.getArtifactId()); SrampModelUtils.setCustomProperty( persisted, JavaModel.PROP_MAVEN_VERSION, metadata.getVersion()); if (StringUtils.isNotBlank(metadata.getClassifier())) { SrampModelUtils.setCustomProperty( persisted, JavaModel.PROP_MAVEN_CLASSIFIER, metadata.getClassifier()); } if (StringUtils.isNotBlank(metadata.getType())) { SrampModelUtils.setCustomProperty(persisted, JavaModel.PROP_MAVEN_TYPE, metadata.getType()); } if (StringUtils.isNotBlank(metadata.getSnapshotId())) { SrampModelUtils.setCustomProperty( persisted, JavaModel.PROP_MAVEN_SNAPSHOT_ID, metadata.getSnapshotId()); } try { // Persist the content size, because it will be required when // reading persisted .getOtherAttributes() .put(SrampConstants.SRAMP_CONTENT_SIZE_QNAME, content.available() + ""); // $NON-NLS-1$ } catch (IOException e) { logger.error(""); // $NON-NLS-1$ } persisted.setName(metadata.getFileName()); ArtifactType artifactType = ArtifactType.valueOf(persisted); try { persistenceManager.updateArtifact(persisted, artifactType); } catch (SrampException e) { throw new MavenRepositoryException( Messages.i18n.format( "maven.resource.upload.sramp.update.content.metadata.error", //$NON-NLS-1$ persisted.getUuid()), e); } uuid = persisted.getUuid(); } return uuid; }
private Set<String> getItems(String groupId, String artifactId, String version) throws MavenRepositoryException { // Add the criterias/parameters depends on the method parameters List<String> criteria = new ArrayList<String>(); List<Object> parameters = new ArrayList<Object>(); Set<String> items = new TreeSet<String>(); if (StringUtils.isNotBlank(groupId)) { criteria.add("fn:matches(@maven.groupId, ?)"); // $NON-NLS-1$ parameters.add(groupId + ".*"); // $NON-NLS-1$ } else { criteria.add("@maven.groupId"); // $NON-NLS-1$ } if (StringUtils.isNotBlank(version)) { criteria.add("@maven.version= ?"); // $NON-NLS-1$ parameters.add(version); } if (StringUtils.isNotBlank(artifactId)) { criteria.add("@maven.artifactId= ?"); // $NON-NLS-1$ parameters.add(artifactId); } criteria.add("@derived='false'"); // $NON-NLS-1$ ArtifactSet artifactSet = null; try { // Query the previous added criterias artifactSet = query(criteria, parameters); Iterator<BaseArtifactType> it = artifactSet.iterator(); // Iterate upon all the items retrieved while (it.hasNext()) { BaseArtifactType artifact = it.next(); String artifactGroupId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_GROUP_ID); String artifactArtifactId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID); // If it is supposed to belong to an artifact if (StringUtils.isNotBlank(artifactId)) { String toAdd = ""; // $NON-NLS-1$ // If the request is about listing a version folder if (StringUtils.isNotBlank(version)) { // It is added the artifact toAdd = generateName(artifact); items.add(toAdd); String md5 = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_MD5); String sha1 = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_SHA1); // If the artifact contains an md5 or sha1 then it is // added as another maven entry if (StringUtils.isNotBlank(md5)) { String itemAdded = toAdd + ".md5"; // $NON-NLS-1$ items.add(itemAdded); } if (StringUtils.isNotBlank(sha1)) { String itemAdded = toAdd + ".sha1"; // $NON-NLS-1$ items.add(itemAdded); } } else { // It is being listed the artifact folder, listing // all the files contained (could be contained a // maven-metadata.xml) and all the artifact's // versions String artifactVersionId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION); if (StringUtils.isNotBlank(artifactVersionId)) { items.add(artifactVersionId); } else { items.add(artifact.getName()); } } } else { // In this case, we need to list a part of a groupId // The remaining group id to be listed String restGroupId = artifactGroupId.substring(artifactGroupId.indexOf(groupId) + groupId.length()); // This means it is being listed an element inside of the // groupId if (restGroupId.startsWith(".")) { // $NON-NLS-1$ String removeBegin = restGroupId.substring(1); // Listing next element if (removeBegin.contains(".")) { // $NON-NLS-1$ items.add( removeBegin.substring(0, removeBegin.indexOf(".")) + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } else { items.add(removeBegin + "/"); // $NON-NLS-1$ } } else { if (restGroupId.contains(".")) { // $NON-NLS-1$ items.add( restGroupId.substring(0, restGroupId.indexOf(".")) + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (restGroupId.trim().equals("")) { // $NON-NLS-1$ items.add(artifactArtifactId + "/"); // $NON-NLS-1$ } else { items.add(restGroupId); } } } } } catch (SrampAtomException e) { throw new MavenRepositoryException( Messages.i18n.format("maven.resource.get.items.error", groupId, artifactId, version), e); //$NON-NLS-1$ } finally { if (artifactSet != null) { artifactSet.close(); } } return items; }
private MavenArtifactWrapper getArtifactContent(MavenMetaData metadata) throws MavenRepositoryException { // List of criterias and the parameters associated List<String> criteria = new ArrayList<String>(); List<Object> parameters = new ArrayList<Object>(); criteria.add("@maven.artifactId = ?"); // $NON-NLS-1$ criteria.add("@maven.groupId = ?"); // $NON-NLS-1$ criteria.add("@maven.type = ?"); // $NON-NLS-1$ parameters.add(metadata.getArtifactId()); parameters.add(metadata.getGroupId()); // If there is a parent type (in case of sha1 or md5, it is passed as // parameter if (StringUtils.isNotBlank(metadata.getParentType())) { parameters.add(metadata.getParentType()); } else { parameters.add(metadata.getType()); } // Not always it is passed the maven version. This is the case when it // is requested a file (normally maven-metadata.xml) that is stored in // the artifact subfolder if (StringUtils.isNotBlank(metadata.getVersion())) { criteria.add("@maven.version = ?"); // $NON-NLS-1$ parameters.add(metadata.getVersion()); } // If it is included a classfier it is added as parameter. if (StringUtils.isNotBlank(metadata.getClassifier())) { criteria.add("@maven.classifier = ?"); // $NON-NLS-1$ parameters.add(metadata.getClassifier()); } else { criteria.add("xp2:not(@maven.classifier)"); // $NON-NLS-1$ } if (StringUtils.isNotBlank(metadata.getSnapshotId())) { criteria.add("@maven.snapshot.id = ?"); // $NON-NLS-1$ parameters.add(metadata.getSnapshotId()); } else { criteria.add("xp2:not(@maven.snapshot.id)"); // $NON-NLS-1$ } ArtifactSet artifactSet = null; BaseArtifactType baseArtifact = null; try { // query based on the previous criterias artifactSet = query(criteria, parameters); if (artifactSet.size() >= 1) { // Found some content! baseArtifact = artifactSet.iterator().next(); } } catch (SrampAtomException e) { throw new MavenRepositoryException(Messages.i18n.format(""), e); // $NON-NLS-1$ } finally { if (artifactSet != null) { artifactSet.close(); } } // If the artifact returned is not null, then the content will be // retrieved if (baseArtifact != null) { PersistenceManager persistenceManager = PersistenceFactory.newInstance(); final InputStream artifactContent; ArtifactType artifactType = ArtifactType.valueOf(baseArtifact.getArtifactType()); Date lastModifiedDate = null; if (baseArtifact.getLastModifiedTimestamp() != null) { lastModifiedDate = baseArtifact.getLastModifiedTimestamp().toGregorianCalendar().getTime(); } int contentLength = -1; MavenFileExtensionEnum ext = MavenFileExtensionEnum.value(metadata.getType()); if (ext != null && StringUtils.isNotBlank(ext.getCustomProperty())) { // we need to set the input stream with the value of the custom // property String content = SrampModelUtils.getCustomProperty(baseArtifact, ext.getCustomProperty()); if (StringUtils.isNotBlank(content)) { artifactContent = new ByteArrayInputStream(content.getBytes()); contentLength = content.length(); } else { logger.info( Messages.i18n.format( "maven.resource.get.subcontent.not.found", baseArtifact.getUuid(), ext.getCustomProperty())); // $NON-NLS-1$ return null; } } else { // we need to set the input stream with the artifact content try { artifactContent = persistenceManager.getArtifactContent(baseArtifact.getUuid(), artifactType); } catch (SrampException e) { logger.error( Messages.i18n.format("maven.resource.get.content.error", baseArtifact.getUuid()), e); //$NON-NLS-1$ throw new MavenRepositoryException( Messages.i18n.format( "maven.resource.get.content.error", //$NON-NLS-1$ baseArtifact.getUuid()), e); } String contentSize = baseArtifact.getOtherAttributes().get(SrampConstants.SRAMP_CONTENT_SIZE_QNAME); if (StringUtils.isNotBlank(contentSize)) { contentLength = Integer.parseInt(contentSize); } } MavenArtifactWrapper wrapper = new MavenArtifactWrapper( artifactContent, contentLength, lastModifiedDate, metadata.getFileName(), artifactType.getMimeType()); return wrapper; } else { logger.error( Messages.i18n.format("maven.resource.item.null", metadata.toString())); // $NON-NLS-1$ // Return null so that the servlet can return a 404 return null; } }
@Test public void testGetArtifact_XSD() throws Exception { String artifactFileName = "PO.xsd"; InputStream POXsd = this.getClass().getResourceAsStream("/sample-files/xsd/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, POXsd); Assert.assertNotNull(artifact); log.info("persisted PO.xsd to JCR, returned artifact uuid=" + artifact.getUuid()); Assert.assertEquals(XsdDocument.class, artifact.getClass()); long size = ((DocumentArtifactType) artifact).getContentSize(); Assert.assertTrue( size >= 2376L); // Not doing an equals here due to the vagaries of Windows vs *nix line // endings BaseArtifactType artifact2 = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); Assert.assertEquals(artifact.getUuid(), artifact2.getUuid()); Assert.assertEquals(artifact.getCreatedBy(), artifact2.getCreatedBy()); Assert.assertEquals(artifact.getDescription(), artifact2.getDescription()); Assert.assertEquals(artifact.getLastModifiedBy(), artifact2.getLastModifiedBy()); Assert.assertEquals(artifact.getName(), artifact2.getName()); Assert.assertEquals(artifact.getVersion(), artifact2.getVersion()); Assert.assertEquals(artifact.getLastModifiedTimestamp(), artifact2.getLastModifiedTimestamp()); }
/** * Main. * * @param args */ public static void main(String[] args) throws Exception { System.out.println("\n*** Running Artificer Query Demo ***\n"); String endpoint = System.getProperty("artificer.endpoint"); String username = System.getProperty("artificer.auth.username"); String password = System.getProperty("artificer.auth.password"); if (endpoint == null || endpoint.trim().length() == 0) { endpoint = DEFAULT_ENDPOINT; } if (username == null || username.trim().length() == 0) { username = DEFAULT_USER; } if (password == null || password.trim().length() == 0) { password = DEFAULT_PASSWORD; } System.out.println("Artificer Endpoint: " + endpoint); System.out.println("Artificer User: "******"/s-ramp[@from-demo = ?]") .parameter(PropertyDemo.class.getSimpleName()) .count(1) .query(); if (rs.size() > 0) { System.out.println("It looks like you already ran this demo!"); System.out.println("I'm going to quit, because I don't want to clutter up"); System.out.println("your repository with duplicate stuff."); System.exit(1); } // Before we do anything else, we need to upload some artifacts to the // Artificer repository. ArtifactType type = ArtifactType.valueOf("Document"); System.out.print("Uploading two artifacts..."); BaseArtifactType artifact1 = client.uploadArtifact( type, PropertyDemo.class.getResourceAsStream("property-demo-doc-1.txt"), "property-demo-doc-1.txt"); BaseArtifactType artifact2 = client.uploadArtifact( type, PropertyDemo.class.getResourceAsStream("property-demo-doc-2.txt"), "property-demo-doc-2.txt"); System.out.println("uploaded."); // And then we can change their names if we want! artifact1.setName("property-demo-document-1.txt"); artifact2.setName("property-demo-document-2.txt"); // Now, we can modify the artifacts by adding some custom properties to them. ArtificerModelUtils.setCustomProperty(artifact1, "property-demo", "true"); ArtificerModelUtils.setCustomProperty(artifact1, "artifact-num", "one"); ArtificerModelUtils.setCustomProperty(artifact1, "hello", "world"); ArtificerModelUtils.setCustomProperty(artifact2, "property-demo", "true"); ArtificerModelUtils.setCustomProperty(artifact2, "artifact-num", "two"); ArtificerModelUtils.setCustomProperty(artifact2, "foo", "bar"); // Also tag these artifacts as coming from this demo. ArtificerModelUtils.setCustomProperty( artifact1, "from-demo", PropertyDemo.class.getSimpleName()); ArtificerModelUtils.setCustomProperty( artifact2, "from-demo", PropertyDemo.class.getSimpleName()); // And now update both artifacts so that the repository knows about these // new properties. System.out.print("Updating (meta-data for) both artifacts..."); client.updateArtifactMetaData(artifact1); client.updateArtifactMetaData(artifact2); System.out.println("updated."); // Next, fetch the artifact meta-data from the server and make sure the properties // we set above are really there. System.out.print("Re-fetching (meta-data for) both artifacts..."); BaseArtifactType metaData1 = client.getArtifactMetaData(type, artifact1.getUuid()); BaseArtifactType metaData2 = client.getArtifactMetaData(type, artifact2.getUuid()); System.out.println("fetched."); if (metaData1.getProperty().size() < 3) { System.out.println("Properties not found on artifact 1! Oh noes!"); System.exit(1); } else { System.out.println("All properties accounted for (artifact 1)!"); } if (metaData2.getProperty().size() < 3) { System.out.println("Properties not found on artifact 2! Oh noes!"); System.exit(1); } else { System.out.println("All properties accounted for (artifact 2)!"); } // Now we know that adding properties works. Note that of course you can also // remove properties and change their values, and that will work the same way // (just remember to call updateArtifactMetaData after you make changes). // The next thing I want to show you is how to query for artifacts in the // repository by their properties. You can query by either base property or // by custom user property. String q = "/s-ramp/core/Document[@name = 'property-demo-document-1.txt']"; QueryResultSet resultSet = client.query(q); if (resultSet.size() == 0) { System.out.println("Failed to find property-demo-document-1.txt!"); System.exit(1); } // Find all of the documents with the 'property-demo' property set to 'true' (should // be all of them) q = "/s-ramp/core/Document[@property-demo = 'true']"; resultSet = client.query(q); if (resultSet.size() == 0) { System.out.println("Failed to find document(s) with @property-demo set to 'true'!"); System.exit(1); } else { System.out.println("Search 1 succeeded."); } long total = resultSet.size(); // Find only the ones with 'artifact-num' set to 'one' (should be half of them) q = "/s-ramp/core/Document[@artifact-num = 'one']"; resultSet = client.query(q); if (resultSet.size() == 0) { System.out.println("Failed to find document(s) with @artifact-num set to 'one'!"); System.exit(1); } long ones = resultSet.size(); if (!(total / 2 == ones)) { System.out.println("The wrong number of documents with @artifact-num set to 'one' found!"); System.exit(1); } else { System.out.println("Search 2 succeeded."); } // All done. System.out.println("\n*** Demo Completed Successfully ***\n\n"); Thread.sleep(3000); }
/** * Tests that we can manage s-ramp properties. * * @throws Exception */ @Test public void testUpdateProperties() throws Exception { // First, add an artifact to the repo String artifactFileName = "PO.xsd"; InputStream POXsd = this.getClass().getResourceAsStream("/sample-files/xsd/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, POXsd); Assert.assertNotNull(artifact); log.info("persisted PO.xsd to JCR, returned artifact uuid=" + artifact.getUuid()); Assert.assertEquals(XsdDocument.class, artifact.getClass()); long size = ((DocumentArtifactType) artifact).getContentSize(); Assert.assertTrue( size >= 2376L); // Not doing an equals here due to the vagaries of Windows vs *nix line // endings // Now update the artifact artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); Assert.assertTrue("Expected 0 properties.", artifact.getProperty().isEmpty()); Property prop1 = new Property(); prop1.setPropertyName("prop1"); prop1.setPropertyValue("propval1"); artifact.getProperty().add(prop1); Property prop2 = new Property(); prop2.setPropertyName("prop2"); prop2.setPropertyValue("propval2"); artifact.getProperty().add(prop2); persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); // Now verify that the properties were stored artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); Assert.assertTrue("Expected 2 properties.", artifact.getProperty().size() == 2); String p1 = artifact.getProperty().get(0).getPropertyName() + "=" + artifact.getProperty().get(0).getPropertyValue(); String p2 = artifact.getProperty().get(1).getPropertyName() + "=" + artifact.getProperty().get(1).getPropertyValue(); Set<String> ps = new HashSet<String>(); ps.add(p1); ps.add(p2); Assert.assertTrue("Prop1 missing from properties.", ps.contains("prop1=propval1")); Assert.assertTrue("Prop2 missing from properties.", ps.contains("prop2=propval2")); Assert.assertFalse("Prop3 somehow existed!.", ps.contains("prop3=propval3")); // Now remove one property, add another one, and change the value of one artifact.getProperty().clear(); prop1 = new Property(); prop1.setPropertyName("prop1"); prop1.setPropertyValue("propval1-updated"); artifact.getProperty().add(prop1); Property prop3 = new Property(); prop3.setPropertyName("prop3"); prop3.setPropertyValue("propval3"); artifact.getProperty().add(prop3); persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); // Now verify that the properties were updated artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); Assert.assertTrue("Expected 2 properties.", artifact.getProperty().size() == 2); p1 = artifact.getProperty().get(0).getPropertyName() + "=" + artifact.getProperty().get(0).getPropertyValue(); p2 = artifact.getProperty().get(1).getPropertyName() + "=" + artifact.getProperty().get(1).getPropertyValue(); ps.clear(); ps.add(p1); ps.add(p2); Assert.assertFalse("Prop1 wasn't updated (old value detected).", ps.contains("prop1=propval1")); Assert.assertTrue( "Prop1 wasn't updated (new value not found).", ps.contains("prop1=propval1-updated")); Assert.assertFalse("Prop2 existed unexpectedly.", ps.contains("prop2=propval2")); Assert.assertTrue("Prop3 missing from properties.", ps.contains("prop3=propval3")); }
/** * Tests that we can manage s-ramp properties on a /core/Document. * * @throws Exception */ @Test public void testUpdateProperties_Document() throws Exception { // First, add an artifact to the repo String artifactFileName = "s-ramp-press-release.pdf"; InputStream pdf = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setContentType("application/pdf"); document.setArtifactType(BaseArtifactEnum.DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, pdf); Assert.assertNotNull(artifact); log.info("persisted PDF to JCR, returned artifact uuid=" + artifact.getUuid()); Assert.assertEquals(Document.class, artifact.getClass()); Assert.assertEquals(new Long(18873l), ((DocumentArtifactType) artifact).getContentSize()); // Now update the artifact artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.Document()); Assert.assertTrue("Expected 0 properties.", artifact.getProperty().isEmpty()); Property prop1 = new Property(); prop1.setPropertyName("prop1"); prop1.setPropertyValue("propval1"); artifact.getProperty().add(prop1); Property prop2 = new Property(); prop2.setPropertyName("prop2"); prop2.setPropertyValue("propval2"); artifact.getProperty().add(prop2); persistenceManager.updateArtifact(artifact, ArtifactType.Document()); // Now verify that the properties were stored artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.Document()); Assert.assertTrue("Expected 2 properties.", artifact.getProperty().size() == 2); String p1 = artifact.getProperty().get(0).getPropertyName() + "=" + artifact.getProperty().get(0).getPropertyValue(); String p2 = artifact.getProperty().get(1).getPropertyName() + "=" + artifact.getProperty().get(1).getPropertyValue(); Set<String> ps = new HashSet<String>(); ps.add(p1); ps.add(p2); Assert.assertTrue("Prop1 missing from properties.", ps.contains("prop1=propval1")); Assert.assertTrue("Prop2 missing from properties.", ps.contains("prop2=propval2")); Assert.assertFalse("Prop3 somehow existed!.", ps.contains("prop3=propval3")); // Now remove one property, add another one, and change the value of one artifact.getProperty().clear(); prop1 = new Property(); prop1.setPropertyName("prop1"); prop1.setPropertyValue("propval1-updated"); artifact.getProperty().add(prop1); Property prop3 = new Property(); prop3.setPropertyName("prop3"); prop3.setPropertyValue("propval3"); artifact.getProperty().add(prop3); persistenceManager.updateArtifact(artifact, ArtifactType.Document()); // Now verify that the properties were updated artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.Document()); Assert.assertTrue("Expected 2 properties.", artifact.getProperty().size() == 2); p1 = artifact.getProperty().get(0).getPropertyName() + "=" + artifact.getProperty().get(0).getPropertyValue(); p2 = artifact.getProperty().get(1).getPropertyName() + "=" + artifact.getProperty().get(1).getPropertyValue(); ps.clear(); ps.add(p1); ps.add(p2); Assert.assertFalse("Prop1 wasn't updated (old value detected).", ps.contains("prop1=propval1")); Assert.assertTrue( "Prop1 wasn't updated (new value not found).", ps.contains("prop1=propval1-updated")); Assert.assertFalse("Prop2 existed unexpectedly.", ps.contains("prop2=propval2")); Assert.assertTrue("Prop3 missing from properties.", ps.contains("prop3=propval3")); }
/** * Tests that we can manage s-ramp properties. * * @throws Exception */ @Test public void testGenericRelationships() throws Exception { String uuid1 = null; String uuid2 = null; String uuid3 = null; // First, add an artifact to the repo String artifactFileName = "PO.xsd"; InputStream contentStream = this.getClass().getResourceAsStream("/sample-files/xsd/" + artifactFileName); Document document = new Document(); document.setName(artifactFileName); document.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); BaseArtifactType artifact = persistenceManager.persistArtifact(document, contentStream); Assert.assertNotNull(artifact); uuid1 = artifact.getUuid(); contentStream.close(); // Now update the artifact's generic relationships artifact = persistenceManager.getArtifact(uuid1, ArtifactType.XsdDocument()); Assert.assertTrue("Expected 0 relationships.", artifact.getRelationship().isEmpty()); SrampModelUtils.addGenericRelationship(artifact, "NoTargetRelationship", null); persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); // Now verify that the relationship was stored artifact = persistenceManager.getArtifact(artifact.getUuid(), ArtifactType.XsdDocument()); Assert.assertEquals("Expected 1 relationship.", 1, artifact.getRelationship().size()); Assert.assertEquals( "NoTargetRelationship", artifact.getRelationship().get(0).getRelationshipType()); Assert.assertEquals( Collections.EMPTY_LIST, artifact.getRelationship().get(0).getRelationshipTarget()); // Add a second artifact. artifactFileName = "XMLSchema.xsd"; contentStream = this.getClass().getResourceAsStream("/sample-files/xsd/" + artifactFileName); Document document2 = new Document(); document2.setName(artifactFileName); document2.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT); BaseArtifactType artifact2 = persistenceManager.persistArtifact(document2, contentStream); Assert.assertNotNull(artifact2); uuid2 = artifact2.getUuid(); // Add a second relationship, this time with a target. SrampModelUtils.addGenericRelationship(artifact, "TargetedRelationship", uuid2); persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); // Now verify that the targeted relationship was stored artifact = persistenceManager.getArtifact(uuid1, ArtifactType.XsdDocument()); Assert.assertEquals("Expected 2 relationships.", 2, artifact.getRelationship().size()); Relationship relationship = SrampModelUtils.getGenericRelationship(artifact, "NoTargetRelationship"); Assert.assertNotNull(relationship); Assert.assertEquals("NoTargetRelationship", relationship.getRelationshipType()); Assert.assertEquals(Collections.EMPTY_LIST, relationship.getRelationshipTarget()); relationship = SrampModelUtils.getGenericRelationship(artifact, "TargetedRelationship"); Assert.assertNotNull(relationship); Assert.assertEquals("TargetedRelationship", relationship.getRelationshipType()); Assert.assertEquals(1, relationship.getRelationshipTarget().size()); // has only one target Assert.assertEquals(uuid2, relationship.getRelationshipTarget().get(0).getValue()); // Add a third artifact. artifactFileName = "PO.xml"; contentStream = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); contentStream = this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName); Document document3 = new Document(); document3.setName(artifactFileName); document3.setArtifactType(BaseArtifactEnum.XML_DOCUMENT); BaseArtifactType artifact3 = persistenceManager.persistArtifact(document3, contentStream); Assert.assertNotNull(artifact3); uuid3 = artifact3.getUuid(); // Add a third relationship, again with a target. SrampModelUtils.addGenericRelationship(artifact, "TargetedRelationship", uuid3); persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); // More verifications artifact = persistenceManager.getArtifact(uuid1, ArtifactType.XsdDocument()); Assert.assertEquals("Expected 2 relationships.", 2, artifact.getRelationship().size()); relationship = SrampModelUtils.getGenericRelationship(artifact, "NoTargetRelationship"); Assert.assertNotNull(relationship); Assert.assertEquals("NoTargetRelationship", relationship.getRelationshipType()); Assert.assertEquals(Collections.EMPTY_LIST, relationship.getRelationshipTarget()); relationship = SrampModelUtils.getGenericRelationship(artifact, "TargetedRelationship"); Assert.assertNotNull(relationship); Assert.assertEquals("TargetedRelationship", relationship.getRelationshipType()); Assert.assertEquals(2, relationship.getRelationshipTarget().size()); Set<String> expected = new HashSet<String>(); Set<String> actual = new HashSet<String>(); expected.add(uuid2); expected.add(uuid3); actual.add(relationship.getRelationshipTarget().get(0).getValue()); actual.add(relationship.getRelationshipTarget().get(1).getValue()); Assert.assertEquals(expected, actual); // Add a fourth (bogus) relationship SrampModelUtils.addGenericRelationship(artifact, "TargetedRelationship", "not-a-valid-uuid"); try { persistenceManager.updateArtifact(artifact, ArtifactType.XsdDocument()); Assert.fail("Expected an update failure."); } catch (Exception e) { Assert.assertEquals(ArtifactNotFoundException.class, e.getClass()); Assert.assertEquals("No artifact found with UUID: not-a-valid-uuid", e.getMessage()); } }
/** * Puts the artifact into the s-ramp repository. * * @param gavInfo * @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) { throw new TransferFailedException( Messages.i18n.format( "ARTIFACT_UPDATE_NOT_ALLOWED", gavInfo.getFullName())); // $NON-NLS-1$ } 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$ } if (gavInfo.getSnapshotId() != null && !gavInfo.getSnapshotId().equals("")) { // $NON-NLS-1$ SrampModelUtils.setCustomProperty( artifact, "maven.snapshot.id", gavInfo.getSnapshotId()); // $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", gavInfo.getArtifactId()); // $NON-NLS-1$ 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); } }
@Test public void testZipPackage() throws Exception { ArtificerArchive 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 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")); }