Exemple #1
0
  /**
   * Creating a KieBase from the workflow GAV specified in the config.
   *
   * @return KieBase for package SRAMPPackage
   * @throws SrampClientException
   * @throws SrampAtomException
   */
  public KieContainer getKieContainer(ReleaseId releaseId)
      throws SrampClientException, SrampAtomException {
    KieServices ks = KieServices.Factory.get();
    KieRepository repo = ks.getRepository();
    SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();

    Governance governance = new Governance();
    QueryResultSet results =
        client
            .buildQuery(SRAMP_KIE_JAR_QUERY)
            .parameter(governance.getGovernanceWorkflowGroup())
            .parameter(governance.getGovernanceWorkflowName())
            .parameter(governance.getGovernanceWorkflowVersion())
            .count(1)
            .query();
    if (results.size() > 0) {
      ArtifactSummary artifactSummery = results.get(0);
      InputStream is = client.getArtifactContent(artifactSummery);
      KieModule kModule = repo.addKieModule(ks.getResources().newInputStreamResource(is));
      logger.info(
          Messages.i18n.format(
              "KieSrampUtil.CreatingKieContainer", artifactSummery)); // $NON-NLS-1$
      KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId());
      // Creating the KieBase for the SRAMPPackage
      logger.info(
          Messages.i18n.format(
              "KieSrampUtil.FindKieBase",
              governance.getGovernanceWorkflowPackage())); // $NON-NLS-1$
      return kContainer;
    } else {
      return null;
    }
  }
Exemple #2
0
 /**
  * Ensures that the required ArtifactGrouping is present in the repository.
  *
  * @throws SrampAtomException
  * @throws SrampClientException
  */
 private BaseArtifactType ensureArtifactGrouping()
     throws SrampClientException, SrampAtomException {
   String groupingName = getParamFromRepositoryUrl("artifactGrouping"); // $NON-NLS-1$
   if (groupingName == null || groupingName.trim().length() == 0) {
     logger.warn(Messages.i18n.format("NO_ARTIFACT_GROUPING_NAME")); // $NON-NLS-1$
     return null;
   }
   QueryResultSet query =
       client
           .buildQuery("/s-ramp/ext/ArtifactGrouping[@name = ?]")
           .parameter(groupingName)
           .count(2)
           .query(); //$NON-NLS-1$
   if (query.size() > 1) {
     logger.warn(
         Messages.i18n.format("MULTIPLE_ARTIFACT_GROUPSING_FOUND", groupingName)); // $NON-NLS-1$
     return null;
   } else if (query.size() == 1) {
     ArtifactSummary summary = query.get(0);
     return client.getArtifactMetaData(summary.getType(), summary.getUuid());
   } else {
     ExtendedArtifactType groupingArtifact = new ExtendedArtifactType();
     groupingArtifact.setArtifactType(BaseArtifactEnum.EXTENDED_ARTIFACT_TYPE);
     groupingArtifact.setExtendedType("ArtifactGrouping"); // $NON-NLS-1$
     groupingArtifact.setName(groupingName);
     groupingArtifact.setDescription(
         Messages.i18n.format("ARTIFACT_GROUPING_DESCRIPTION")); // $NON-NLS-1$
     return client.createArtifact(groupingArtifact);
   }
 }
  /** @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;
  }
Exemple #4
0
  /**
   * Main.
   *
   * @param args
   */
  public static void main(String[] args) throws Exception {
    System.out.println("\n*** Running S-RAMP Simple Client Demo ***\n");

    // Figure out the endpoint of the S-RAMP repository's Atom API
    String endpoint = System.getProperty("sramp.endpoint");
    if (endpoint == null || endpoint.trim().length() == 0) {
      endpoint = DEFAULT_ENDPOINT;
    }
    System.out.println("S-RAMP Endpoint: " + endpoint);

    // Upload some artifacts to the S-RAMP repository
    System.out.println("Uploading some XML schemas...");
    SrampAtomApiClient client = new SrampAtomApiClient(endpoint);
    for (String file : FILES) {
      // Get an InputStream over the file content
      InputStream is = SimpleClientDemo.class.getResourceAsStream(file);

      try {
        // We need to know the artifact type
        ArtifactType type = ArtifactType.XsdDocument;
        if (file.endsWith(".wsdl")) {
          type = ArtifactType.WsdlDocument;
        }

        // Upload that content to S-RAMP
        System.out.print("\tUploading artifact " + file + "...");
        BaseArtifactType artifact = client.uploadArtifact(type, is, file);
        System.out.println("done.");

        // Update the artifact meta-data (set the version and add a custom property)
        artifact.setVersion("1.1");
        SrampModelUtils.setCustomProperty(artifact, "demo", "simple-client");

        // Tell the server about the updated meta-data
        System.out.print("\tUpdating meta-data for artifact " + file + "...");
        client.updateArtifactMetaData(artifact);
        System.out.println("done.");
      } finally {
        is.close();
      }
    }

    // Now query the S-RAMP repository (for the Schemas only)
    System.out.print("Querying the S-RAMP repository for Schemas...");
    QueryResultSet rset = client.query("/s-ramp/xsd/XsdDocument");
    System.out.println("success: " + rset.size() + " Schemas found:");
    for (ArtifactSummary entry : rset) {
      System.out.println("\t * " + entry.getName() + " (" + entry.getUuid() + ")");
    }

    System.out.println("\n*** Demo Completed Successfully ***\n\n");
    Thread.sleep(3000);
  }
  /*
   * (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;
  }
Exemple #6
0
  /** @see org.overlord.sramp.common.shell.ShellCommand#execute() */
  @Override
  public void execute() throws Exception {
    QName clientVarName = new QName("s-ramp", "client");
    QName artifactVarName = new QName("s-ramp", "artifact");
    QName feedVarName = new QName("s-ramp", "feed");

    SrampAtomApiClient client = (SrampAtomApiClient) getContext().getVariable(clientVarName);
    if (client == null) {
      print("No S-RAMP repository connection is currently open.");
      return;
    }

    BaseArtifactType artifact = null;
    String artifactIdArg = this.optionalArgument(0);
    if (artifactIdArg == null) {
      artifact = (BaseArtifactType) getContext().getVariable(artifactVarName);
      if (artifact == null) {
        print("No active S-RAMP artifact exists.  Use s-ramp:getMetaData.");
        return;
      }
    } else {
      String idType = artifactIdArg.substring(0, artifactIdArg.indexOf(':'));
      if ("feed".equals(idType)) {
        QueryResultSet rset = (QueryResultSet) getContext().getVariable(feedVarName);
        int feedIdx = Integer.parseInt(artifactIdArg.substring(artifactIdArg.indexOf(':') + 1)) - 1;
        if (feedIdx < 0 || feedIdx >= rset.size()) {
          throw new InvalidCommandArgumentException(0, "Feed index out of range.");
        }
        ArtifactSummary summary = rset.get(feedIdx);
        String artifactUUID = summary.getUuid();
        artifact = client.getArtifactMetaData(summary.getType(), artifactUUID);
      } else if ("uuid".equals(idType)) {
        throw new InvalidCommandArgumentException(
            0, "uuid: style artifact identifiers not yet implemented.");
      } else {
        throw new InvalidCommandArgumentException(0, "Invalid artifact id format.");
      }
    }

    try {
      client.deleteArtifact(artifact.getUuid(), ArtifactType.valueOf(artifact));
      print("Successfully deleted artifact '%1$s'.", artifact.getName());
    } catch (Exception e) {
      print("FAILED to delete the artifact.");
      print("\t" + e.getMessage());
    }
  }
  /** @see org.overlord.sramp.shell.api.shell.ShellCommand#execute() */
  @SuppressWarnings("unchecked")
  @Override
  public void execute() throws Exception {
    String ontologyIdArg = this.requiredArgument(0, "Please specify a valid ontology identifier.");

    QName feedVarName = new QName("ontology", "feed");
    QName clientVarName = new QName("s-ramp", "client");
    SrampAtomApiClient client = (SrampAtomApiClient) getContext().getVariable(clientVarName);
    if (client == null) {
      print("No S-RAMP repository connection is currently open.");
      return;
    }

    if (!ontologyIdArg.contains(":") || ontologyIdArg.endsWith(":")) {
      throw new InvalidCommandArgumentException(0, "Invalid artifact id format.");
    }
    String ontologyUuid = null;
    int colonIdx = ontologyIdArg.indexOf(':');
    String idType = ontologyIdArg.substring(0, colonIdx);
    String idValue = ontologyIdArg.substring(colonIdx + 1);
    if ("feed".equals(idType)) {
      List<OntologySummary> ontologies =
          (List<OntologySummary>) getContext().getVariable(feedVarName);
      if (ontologies == null) {
        throw new InvalidCommandArgumentException(
            0, "There is no ontology feed available, try 'ontology:list' first.");
      }
      int feedIdx = Integer.parseInt(idValue) - 1;
      if (feedIdx < 0 || feedIdx >= ontologies.size()) {
        throw new InvalidCommandArgumentException(0, "Feed index out of range.");
      }
      OntologySummary summary = ontologies.get(feedIdx);
      ontologyUuid = summary.getUuid();
    } else if ("uuid".equals(idType)) {
      ontologyUuid = idValue;
    } else {
      throw new InvalidCommandArgumentException(0, "Invalid artifact id format.");
    }

    try {
      client.deleteOntology(ontologyUuid);
      print("Successfully deleted the ontology.");
    } catch (Exception e) {
      print("FAILED to get the list of ontologies.");
      print("\t" + e.getMessage());
    }
  }
Exemple #8
0
 /**
  * Returns true if the workflow JAR is deployed to the s-ramp repository.
  *
  * @param groupId
  * @param artifactId
  * @param version
  * @return true or false
  */
 public boolean isSRAMPPackageDeployed(String groupId, String artifactId, String version) {
   try {
     SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
     QueryResultSet results =
         client
             .buildQuery(SRAMP_KIE_JAR_QUERY)
             .parameter(groupId)
             .parameter(artifactId)
             .parameter(version)
             .count(1)
             .query();
     if (results.size() > 0) {
       return Boolean.TRUE;
     }
   } catch (SrampClientException e) {
     logger.error(e.getMessage(), e);
   } catch (SrampAtomException e) {
     logger.error(e.getMessage(), e);
   }
   return Boolean.FALSE;
 }
Exemple #9
0
 /**
  * Finds an existing artifact in the s-ramp repository using 'universal' form. This allows any
  * artifact in the s-ramp repository to be referenced as a Maven dependency using the model.type
  * and UUID of the artifact.
  *
  * @param client
  * @param artifactType
  * @param gavInfo
  * @return an existing s-ramp artifact (if found) or null (if not found)
  * @throws SrampClientException
  * @throws SrampAtomException
  * @throws JAXBException
  */
 private BaseArtifactType findExistingArtifactByUniversal(
     SrampAtomApiClient client, MavenGavInfo gavInfo)
     throws SrampAtomException, SrampClientException, JAXBException {
   String artifactType = gavInfo.getGroupId().substring(gavInfo.getGroupId().indexOf('.') + 1);
   String uuid = gavInfo.getArtifactId();
   try {
     return client.getArtifactMetaData(ArtifactType.valueOf(artifactType), uuid);
   } catch (Throwable t) {
     debug(t.getMessage());
   }
   return null;
 }
Exemple #10
0
  /**
   * Updates an artifact by storing its hash value as an S-RAMP property.
   *
   * @param gavInfo
   * @param resourceInputStream
   * @throws TransferFailedException
   */
  private void doPutHash(MavenGavInfo gavInfo, InputStream resourceInputStream)
      throws TransferFailedException {
    logger.info(Messages.i18n.format("STORING_HASH_AS_PROP", gavInfo.getName())); // $NON-NLS-1$
    try {
      String artyPath = gavInfo.getFullName();
      String hashPropName;
      if (gavInfo.getType().endsWith(".md5")) { // $NON-NLS-1$
        hashPropName = "maven.hash.md5"; // $NON-NLS-1$
        artyPath = artyPath.substring(0, artyPath.length() - 4);
      } else {
        hashPropName = "maven.hash.sha1"; // $NON-NLS-1$
        artyPath = artyPath.substring(0, artyPath.length() - 5);
      }
      String hashValue = IOUtils.toString(resourceInputStream);

      // 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 {
        SrampArchiveEntry entry = this.archive.getEntry(artyPath);
        // Re-fetch the artifact meta-data in case it changed on the server since we uploaded it.
        BaseArtifactType metaData = client.getArtifactMetaData(entry.getMetaData().getUuid());
        SrampModelUtils.setCustomProperty(metaData, hashPropName, hashValue);
        this.archive.updateEntry(entry, null);

        // The meta-data has been updated in the local/temp archive - now send it to the remote repo
        client.updateArtifactMetaData(metaData);
      } catch (Throwable t) {
        throw new TransferFailedException(t.getMessage(), t);
      } finally {
        Thread.currentThread().setContextClassLoader(oldCtxCL);
      }
    } catch (Exception e) {
      throw new TransferFailedException(
          Messages.i18n.format("FAILED_TO_STORE_HASH", gavInfo.getName()), e); // $NON-NLS-1$
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.jboss.arquillian.container.sramp.SrampService#undeployArchives()
   */
  public void undeployArchives(String archiveId) throws SrampClientException, SrampAtomException {

    log.debug("Deleting expanded artifacts");

    // Delete expanded artifacts
    QueryResultSet rset =
        client
            .buildQuery("/s-ramp[expandedFromDocument[@arquillian-archive-id = ?]]")
            .parameter(archiveId)
            .query();

    for (ArtifactSummary artifactSummary : rset) {
      log.debug("Deleting: " + artifactSummary.getName());
      client.deleteArtifact(artifactSummary.getUuid(), artifactSummary.getType());
    }

    // Delete (un)deployment information
    rset =
        client
            .buildQuery("/s-ramp[describesDeployment[@arquillian-archive-id = ?]]")
            .parameter(archiveId)
            .query();
    for (ArtifactSummary artifactSummary : rset) {
      log.debug("Deleting: " + artifactSummary.getName());
      client.deleteArtifact(artifactSummary.getUuid(), artifactSummary.getType());
    }

    // Delete main archive
    // Related are deleted along with the primary
    rset = client.buildQuery("/s-ramp[@arquillian-archive-id = ?]").parameter(archiveId).query();

    ArtifactSummary archiveArtifact = rset.get(0);

    log.debug("Deleting: " + archiveArtifact.getName());

    client.deleteArtifact(archiveArtifact.getUuid(), archiveArtifact.getType());

    // Internal consistency check whether the number of artifacts before
    // deploy and after deploy match
    long artifactCounterTemp = client.query("/s-ramp").getTotalResults();

    if (artifactCounter != artifactCounterTemp) {
      log.warn("Artifact counts does not match!");
      log.warn(
          "Artifacts before deploy: "
              + artifactCounter
              + ". Artifacts after undeploy: "
              + artifactCounterTemp);
      artifactCounter = artifactCounterTemp;
    }
  }
Exemple #12
0
  /**
   * * 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);
    }
  }
Exemple #13
0
  /**
   * Finds an existing artifact in the s-ramp repository that matches the GAV information.
   *
   * @param client
   * @param gavInfo
   * @return an s-ramp artifact (if found) or null (if not found)
   * @throws SrampClientException
   * @throws SrampAtomException
   * @throws JAXBException
   */
  private BaseArtifactType findExistingArtifactByGAV(
      SrampAtomApiClient client, MavenGavInfo gavInfo)
      throws SrampAtomException, SrampClientException, JAXBException {
    SrampClientQuery clientQuery = null;

    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("/s-ramp"); // $NON-NLS-1$
    List<String> criteria = new ArrayList<String>();
    List<Object> params = new ArrayList<Object>();

    criteria.add("@maven.groupId = ?"); // $NON-NLS-1$
    params.add(gavInfo.getGroupId());
    criteria.add("@maven.artifactId = ?"); // $NON-NLS-1$
    params.add(gavInfo.getArtifactId());
    criteria.add("@maven.version = ?"); // $NON-NLS-1$
    params.add(gavInfo.getVersion());

    if (StringUtils.isNotBlank(gavInfo.getType())) {
      criteria.add("@maven.type = ?"); // $NON-NLS-1$
      params.add(gavInfo.getType());
    }
    if (StringUtils.isNotBlank(gavInfo.getClassifier())) {
      criteria.add("@maven.classifier = ?"); // $NON-NLS-1$
      params.add(gavInfo.getClassifier());
    }
    if (StringUtils.isNotBlank(gavInfo.getSnapshotId())) {
      return null;
    } else {
      criteria.add("xp2:not(@maven.snapshot.id)"); // $NON-NLS-1$
    }

    if (criteria.size() > 0) {
      queryBuilder.append("["); // $NON-NLS-1$
      queryBuilder.append(StringUtils.join(criteria, " and ")); // $NON-NLS-1$
      queryBuilder.append("]"); // $NON-NLS-1$
    }
    clientQuery = client.buildQuery(queryBuilder.toString());
    for (Object param : params) {
      if (param instanceof String) {
        clientQuery.parameter((String) param);
      }
      if (param instanceof Calendar) {
        clientQuery.parameter((Calendar) param);
      }
    }

    QueryResultSet rset = clientQuery.count(100).query();
    if (rset.size() > 0) {
      for (ArtifactSummary summary : rset) {
        String uuid = summary.getUuid();
        ArtifactType artifactType = summary.getType();
        BaseArtifactType arty = client.getArtifactMetaData(artifactType, uuid);
        // If no classifier in the GAV info, only return the artifact that also has no classifier
        // TODO replace this with "not(@maven.classifer)" in the query, then force the result set to
        // return 2 items (expecting only 1)
        if (gavInfo.getClassifier() == null) {
          String artyClassifier =
              SrampModelUtils.getCustomProperty(arty, "maven.classifier"); // $NON-NLS-1$
          if (artyClassifier == null) {
            return arty;
          }
        } else {
          // If classifier was supplied in the GAV info, we'll get the first artifact <shrug>
          return arty;
        }
      }
    }
    return null;
  }
Exemple #14
0
  /**
   * 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);
    }
  }
Exemple #15
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 #16
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);
    }
  }