/**
  * Try to figure out what kind of artifact we're dealing with.
  *
  * @param fileName the file name
  * @return the artifact type
  */
 private ArtifactType determineArtifactType(String fileName) {
   ArtifactType type = null;
   String extension = FilenameUtils.getExtension(fileName);
   if ("jar".equals(extension)) { // $NON-NLS-1$
     type = ArtifactType.ExtendedDocument(JavaModel.TYPE_ARCHIVE);
   } else if ("war".equals(extension)) { // $NON-NLS-1$
     type = ArtifactType.ExtendedDocument(JavaModel.TYPE_WEB_APPLICATION);
   } else if ("ear".equals(extension)) { // $NON-NLS-1$
     type = ArtifactType.ExtendedDocument(JavaModel.TYPE_ENTERPRISE_APPLICATION);
   } else if ("pom".equals(extension)) { // $NON-NLS-1$
     type = ArtifactType.ExtendedDocument(JavaModel.TYPE_MAVEN_POM_XML);
   } else {
     type = ArtifactType.Document();
   }
   return type;
 }
  /** @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;
  }
  /**
   * 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);
    }
  }
Exemple #5
0
  /**
   * Generates the maven-metadata.xml file dynamically for a given
   * groupId/artifactId/snapshot-version. This will list all of the snapshot versions available.
   *
   * @param gavInfo
   * @param inputData
   * @throws ResourceDoesNotExistException
   */
  private void doGenerateSnapshotMavenMetaData(MavenGavInfo gavInfo, InputData inputData)
      throws ResourceDoesNotExistException {
    // 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());
    try {
      String artyPath = gavInfo.getFullName();
      if (gavInfo.isHash()) {
        artyPath = artyPath.substring(0, artyPath.lastIndexOf('.'));
      }
      SrampArchiveEntry entry = this.archive.getEntry(artyPath);
      if (entry == null) {
        QueryResultSet resultSet =
            client
                .buildQuery(
                    "/s-ramp[@maven.groupId = ? and @maven.artifactId = ? and @maven.version = ?]") //$NON-NLS-1$
                .parameter(gavInfo.getGroupId())
                .parameter(gavInfo.getArtifactId())
                .parameter(gavInfo.getVersion())
                .propertyName("maven.classifier")
                .propertyName("maven.type") // $NON-NLS-1$ //$NON-NLS-2$
                .count(500)
                .orderBy("createdTimestamp")
                .ascending()
                .query(); //$NON-NLS-1$
        if (resultSet.size() == 0) {
          throw new Exception(Messages.i18n.format("NO_ARTIFACTS_FOUND")); // $NON-NLS-1$
        }

        SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMdd.HHmmss"); // $NON-NLS-1$
        SimpleDateFormat updatedFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // $NON-NLS-1$

        StringBuilder snapshotVersions = new StringBuilder();
        snapshotVersions.append("    <snapshotVersions>\n"); // $NON-NLS-1$
        Set<String> processed = new HashSet<String>();
        Date latestDate = null;
        for (ArtifactSummary artifactSummary : resultSet) {
          String extension = artifactSummary.getCustomPropertyValue("maven.type"); // $NON-NLS-1$
          String classifier =
              artifactSummary.getCustomPropertyValue("maven.classifier"); // $NON-NLS-1$
          String value = gavInfo.getVersion();
          Date updatedDate = artifactSummary.getLastModifiedTimestamp();
          String updated = updatedFormat.format(updatedDate);
          String pkey = classifier + "::" + extension; // $NON-NLS-1$
          if (processed.add(pkey)) {
            snapshotVersions.append("      <snapshotVersion>\n"); // $NON-NLS-1$
            if (classifier != null)
              snapshotVersions
                  .append("        <classifier>")
                  .append(classifier)
                  .append("</classifier>\n"); // $NON-NLS-1$ //$NON-NLS-2$
            snapshotVersions
                .append("        <extension>")
                .append(extension)
                .append("</extension>\n"); // $NON-NLS-1$ //$NON-NLS-2$
            snapshotVersions
                .append("        <value>")
                .append(value)
                .append("</value>\n"); // $NON-NLS-1$ //$NON-NLS-2$
            snapshotVersions
                .append("        <updated>")
                .append(updated)
                .append("</updated>\n"); // $NON-NLS-1$ //$NON-NLS-2$
            snapshotVersions.append("      </snapshotVersion>\n"); // $NON-NLS-1$
            if (latestDate == null || latestDate.before(updatedDate)) {
              latestDate = updatedDate;
            }
          }
        }
        snapshotVersions.append("    </snapshotVersions>\n"); // $NON-NLS-1$

        String groupId = gavInfo.getGroupId();
        String artifactId = gavInfo.getArtifactId();
        String version = gavInfo.getVersion();
        String lastUpdated = updatedFormat.format(latestDate);

        StringBuilder mavenMetadata = new StringBuilder();
        mavenMetadata.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // $NON-NLS-1$
        mavenMetadata.append("<metadata>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("  <groupId>")
            .append(groupId)
            .append("</groupId>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata
            .append("  <artifactId>")
            .append(artifactId)
            .append("</artifactId>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata
            .append("  <version>")
            .append(version)
            .append("</version>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append("  <versioning>\n"); // $NON-NLS-1$
        mavenMetadata.append("    <snapshot>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("      <timestamp>")
            .append(timestampFormat.format(latestDate))
            .append("</timestamp>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append("      <buildNumber>1</buildNumber>\n"); // $NON-NLS-1$
        mavenMetadata.append("    </snapshot>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("    <lastUpdated>")
            .append(lastUpdated)
            .append("</lastUpdated>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append(snapshotVersions.toString());
        mavenMetadata.append("  </versioning>\n"); // $NON-NLS-1$
        mavenMetadata.append("</metadata>\n"); // $NON-NLS-1$

        BaseArtifactType artifact =
            ArtifactType.ExtendedDocument("MavenMetaData").newArtifactInstance(); // $NON-NLS-1$
        this.archive.addEntry(artyPath, artifact, IOUtils.toInputStream(mavenMetadata.toString()));

        entry = this.archive.getEntry(artyPath);
      }

      if (!gavInfo.isHash()) {
        inputData.setInputStream(this.archive.getInputStream(entry));
      } else {
        String hash = generateHash(this.archive.getInputStream(entry), gavInfo.getHashAlgorithm());
        inputData.setInputStream(IOUtils.toInputStream(hash));
      }
    } catch (Exception e) {
      throw new ResourceDoesNotExistException(
          Messages.i18n.format("FAILED_TO_GENERATE_METADATA"), e); // $NON-NLS-1$
    } finally {
      Thread.currentThread().setContextClassLoader(oldCtxCL);
    }
  }
Exemple #6
0
  /**
   * Generates the maven-metadata.xml file dynamically for a given groupId/artifactId pair. This
   * will list all of the versions available for that groupId+artifactId, along with the latest
   * release and snapshot versions.
   *
   * @param gavInfo
   * @param inputData
   * @throws ResourceDoesNotExistException
   */
  private void doGenerateArtifactDirMavenMetaData(MavenGavInfo gavInfo, InputData inputData)
      throws ResourceDoesNotExistException {
    // 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());
    try {
      String artyPath = gavInfo.getFullName();
      if (gavInfo.isHash()) {
        artyPath = artyPath.substring(0, artyPath.lastIndexOf('.'));
      }
      SrampArchiveEntry entry = this.archive.getEntry(artyPath);
      if (entry == null) {
        QueryResultSet resultSet =
            client
                .buildQuery("/s-ramp[@maven.groupId = ? and @maven.artifactId = ?]") // $NON-NLS-1$
                .parameter(gavInfo.getGroupId())
                .parameter(gavInfo.getArtifactId())
                .propertyName("maven.version") // $NON-NLS-1$
                .count(500)
                .orderBy("createdTimestamp")
                .ascending()
                .query(); //$NON-NLS-1$
        if (resultSet.size() == 0) {
          throw new Exception(Messages.i18n.format("NO_ARTIFACTS_FOUND")); // $NON-NLS-1$
        }

        String groupId = gavInfo.getGroupId();
        String artifactId = gavInfo.getArtifactId();
        String latest = null;
        String release = null;
        String lastUpdated = null;

        LinkedHashSet<String> versions = new LinkedHashSet<String>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // $NON-NLS-1$
        for (ArtifactSummary artifactSummary : resultSet) {
          String version = artifactSummary.getCustomPropertyValue("maven.version"); // $NON-NLS-1$
          if (versions.add(version)) {
            latest = version;
            if (!version.endsWith("-SNAPSHOT")) { // $NON-NLS-1$
              release = version;
            }
          }
          lastUpdated = format.format(artifactSummary.getCreatedTimestamp());
        }

        StringBuilder mavenMetadata = new StringBuilder();
        mavenMetadata.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // $NON-NLS-1$
        mavenMetadata.append("<metadata>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("  <groupId>")
            .append(groupId)
            .append("</groupId>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata
            .append("  <artifactId>")
            .append(artifactId)
            .append("</artifactId>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append("  <versioning>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("    <latest>")
            .append(latest)
            .append("</latest>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata
            .append("    <release>")
            .append(release)
            .append("</release>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append("    <versions>\n"); // $NON-NLS-1$
        for (String version : versions) {
          mavenMetadata
              .append("      <version>")
              .append(version)
              .append("</version>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        }
        mavenMetadata.append("    </versions>\n"); // $NON-NLS-1$
        mavenMetadata
            .append("    <lastUpdated>")
            .append(lastUpdated)
            .append("</lastUpdated>\n"); // $NON-NLS-1$ //$NON-NLS-2$
        mavenMetadata.append("  </versioning>\n"); // $NON-NLS-1$
        mavenMetadata.append("</metadata>\n"); // $NON-NLS-1$

        BaseArtifactType artifact =
            ArtifactType.ExtendedDocument("MavenMetaData").newArtifactInstance(); // $NON-NLS-1$
        this.archive.addEntry(artyPath, artifact, IOUtils.toInputStream(mavenMetadata.toString()));

        entry = this.archive.getEntry(artyPath);
      }

      if (!gavInfo.isHash()) {
        inputData.setInputStream(this.archive.getInputStream(entry));
      } else {
        String hash = generateHash(this.archive.getInputStream(entry), gavInfo.getHashAlgorithm());
        inputData.setInputStream(IOUtils.toInputStream(hash));
      }
    } catch (Exception e) {
      throw new ResourceDoesNotExistException(
          Messages.i18n.format("FAILED_TO_GENERATE_METADATA"), e); // $NON-NLS-1$
    } finally {
      Thread.currentThread().setContextClassLoader(oldCtxCL);
    }
  }