Example #1
0
  private static void deleteServices(Registry govRegistry, String shortName)
      throws FileNotFoundException, IOException, RegistryException, GovernanceException {
    BufferedReader bufferedReader =
        new BufferedReader(new FileReader(rootpath + "resources/" + shortName + "_list.txt"));
    String artifactName;
    GenericArtifactManager manager = new GenericArtifactManager(govRegistry, shortName);

    while ((artifactName = bufferedReader.readLine()) != null) {

      final String name = artifactName;
      GenericArtifact[] artifacts =
          manager.findGenericArtifacts(
              new GenericArtifactFilter() {

                @Override
                public boolean matches(GenericArtifact genericArtifact) throws GovernanceException {
                  return name.equals(genericArtifact.getQName().getLocalPart());
                }
              });
      for (GenericArtifact genericArtifact : artifacts) {
        for (GovernanceArtifact dependency : genericArtifact.getDependencies()) {
          GovernanceUtils.removeArtifact(govRegistry, dependency.getId());
        }
        GovernanceUtils.removeArtifact(govRegistry, genericArtifact.getId());
      }
    }
  }
  @AfterClass(
      groups = "wso2.greg",
      alwaysRun = true,
      description = "cleaning up the artifacts added")
  public void tearDown()
      throws RegistryException, LoginAuthenticationExceptionException, RemoteException,
          ResourceAdminServiceExceptionException {

    String pathPrefix = "/_system/governance";
    Endpoint[] endpoints;

    endpoints = wsdl.getAttachedEndpoints();
    assertNotNull(endpoints, "there should be associated endpoints with the wsdl");

    GovernanceArtifact[] governanceArtifacts = wsdl.getDependents();
    assertNotNull(governanceArtifacts, "there should be dependent of the wsdl");

    for (GovernanceArtifact tmpGovernanceArtifact : governanceArtifacts) {
      wsRegistry.delete(pathPrefix + tmpGovernanceArtifact.getPath());
    }

    for (Endpoint tmpEndpoint : endpoints) {
      GovernanceArtifact[] dependentArtifacts = tmpEndpoint.getDependents();
      for (GovernanceArtifact tmpGovernanceArtifact : dependentArtifacts) {
        wsRegistry.delete(pathPrefix + tmpGovernanceArtifact.getPath());
      }
      wsRegistry.delete(pathPrefix + tmpEndpoint.getPath());
    }
  }
 private boolean checkChanged(GovernanceArtifact fa, String attrName, String attrValue) {
   boolean isChanged = true;
   try {
     String curval = fa.getAttribute(attrName);
     if ((curval == null || curval.isEmpty()) && (attrValue == null || attrValue.isEmpty())) {
       isChanged = false;
     } else if (attrValue != null && curval != null && curval.equals(attrValue)) {
       isChanged = false;
     } else {
       fa.setAttribute(attrName, attrValue);
     }
   } catch (GovernanceException e) {
     log.error("updateAttributes " + e.getMessage());
   }
   return isChanged;
 }
  private boolean createLink(BaseRelation br, GovernanceArtifact src) {
    boolean needsUpdate = false;
    String linkPath = "";
    String uiRelationName = br.getUIRelationName();

    if (br.getDestination() instanceof HostProgram) {
      linkPath = HostProgram.UI_NAME + ":" + getArtifactPath(br.getDestination());
    }
    if (br.getDestination() instanceof Table) {
      linkPath = Table.UI_NAME + ":" + getArtifactPath(br.getDestination());
    }
    if (br.getDestination() instanceof Infrastructure) {
      linkPath = Infrastructure.UI_NAME + ":" + getArtifactPath(br.getDestination());
    }
    if (!checkLinkPathExists(linkPath, uiRelationName, src)) {
      needsUpdate = true;
      String[] links = updateLinkPath(linkPath, uiRelationName, src);
      try {
        src.setAttributes(uiRelationName, links);
      } catch (GovernanceException e) {
        log.error("link creation problem setAttribute " + e.getMessage());
      }
    }
    return needsUpdate;
  }
  private void validateArtifact(GovernanceArtifact artifact) throws GovernanceException {
    if (validationAttributes == null) {
      return;
    }
    Map<String, Object> map;
    for (int i = 0; i < validationAttributes.size(); ++i) {
      map = validationAttributes.get(i);
      String value = "";
      String prop = (String) map.get("properties");
      List<String> keys = (List<String>) map.get("keys");

      if (prop != null && "unbounded".equals(prop)) {
        // assume there are only 1 key
        String[] values = artifact.getAttributes((String) keys.get(0));
        if (values != null) {
          for (int j = 0; j < values.length; ++j) {
            if (!values[j].matches((String) map.get("regexp"))) {
              // return an exception to stop adding artifact
              throw new GovernanceException(
                  (String) map.get("name") + " doesn't match regex: " + (String) map.get("Regexp"));
            }
          }
        }
      } else {
        for (int j = 0; j < keys.size(); ++j) {
          String v = artifact.getAttribute(keys.get(j));
          if (j != 0) value += ":";
          value += (v == null ? "" : v);
        }
        if (!value.matches((String) map.get("regexp"))) {
          // return an exception to stop adding artifact
          throw new GovernanceException(
              (String) map.get("name") + " doesn't match regex: " + (String) map.get("Regexp"));
        }
      }
    }
  }
 private String[] updateLinkPath(
     String linkPath, String linkAttributeName, GovernanceArtifact ga) {
   String[] links = {};
   List<String> result = new ArrayList<String>();
   try {
     links = ga.getAttributes(linkAttributeName);
     if (links != null) {
       for (String link : links) {
         result.add(link);
       }
     }
     result.add(linkPath);
   } catch (GovernanceException e) {
     log.error("checkAndUpdateLinkPath " + e.getMessage());
   }
   return result.toArray(new String[0]);
 }
 private boolean checkLinkPathExists(
     String linkPath, String linkAttributeName, GovernanceArtifact ga) {
   boolean found = false;
   try {
     String[] links = ga.getAttributes(linkAttributeName);
     if (links != null) {
       for (String link : links) {
         if (link.equals(linkPath)) {
           found = true;
         }
       }
     }
   } catch (GovernanceException e) {
     log.error("checkAndUpdateLinkPath " + e.getMessage());
   }
   return found;
 }
  /**
   * Sets content of the given artifact to the given resource on the registry.
   *
   * @param artifact the artifact.
   * @param resource the content resource.
   * @throws GovernanceException if the operation failed.
   */
  protected void setContent(GovernanceArtifact artifact, Resource resource)
      throws GovernanceException {
    try {
      if (artifact instanceof GenericArtifact) {
        byte[] content = ((GenericArtifact) artifact).getContent();
        if (content != null) {
          resource.setContent(content);
          String[] attributeKeys = artifact.getAttributeKeys();
          if (attributeKeys != null) {
            for (String aggregatedKey : attributeKeys) {
              if (!aggregatedKey.equals(artifactNameAttribute)
                  && !aggregatedKey.equals(artifactNamespaceAttribute)) {
                resource.setProperty(
                    aggregatedKey, Arrays.asList(artifact.getAttributes(aggregatedKey)));
              }
            }
          }
          return;
        }
      }
      OMNamespace namespace =
          OMAbstractFactory.getOMFactory().createOMNamespace(artifactElementNamespace, "");
      Map<String, HashMap> mainElementMap = new HashMap<String, HashMap>();
      String[] attributeKeys2 = artifact.getAttributeKeys();
      if (attributeKeys2 != null) {
        for (String aggregatedKey : attributeKeys2) {
          String[] keys = aggregatedKey.split("_");
          String key = null;
          for (int i = 0; i < keys.length; i++) {
            key = keys[i];
            if (mainElementMap.get(key) == null) {
              mainElementMap.put(key, new HashMap<String, String[]>());
            }

            // Handing the situations where we don't have '_' in aggregatedKey
            // and assume we hare having only one '_" in aggregatedKey and not more
            if (keys.length > 1) {
              break;
            }
          }
          String[] attributeValues = artifact.getAttributes(aggregatedKey);
          String elementName = keys[keys.length - 1];
          mainElementMap.get(key).put(elementName, attributeValues);
        }
      }

      OMElement contentElement =
          OMAbstractFactory.getOMFactory().createOMElement(artifactElementRoot, namespace);

      Iterator it = mainElementMap.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<String, HashMap> pairs = (Map.Entry) it.next();

        Map<String, Map> subElementMap = pairs.getValue();
        Iterator subit = subElementMap.entrySet().iterator();
        int size = 0;
        while (subit.hasNext()) {
          Map.Entry<String, String[]> subpairs = (Map.Entry) subit.next();
          if (size < subpairs.getValue().length) {
            size = subpairs.getValue().length;
          }
        }
        for (int i = 0; i < size; i++) {
          OMElement keyElement =
              OMAbstractFactory.getOMFactory().createOMElement(pairs.getKey(), namespace);
          Iterator subit2 = subElementMap.entrySet().iterator();
          int a = 0;
          while (subit2.hasNext()) {

            Map.Entry<String, String[]> subpairs = (Map.Entry) subit2.next();
            String value;
            try {
              value = subpairs.getValue()[i];
            } catch (Exception ex) {
              value = null;
            }

            OMElement subkeyElement =
                OMAbstractFactory.getOMFactory().createOMElement(subpairs.getKey(), namespace);
            OMText textElement = OMAbstractFactory.getOMFactory().createOMText(value);
            subkeyElement.addChild(textElement);
            keyElement.addChild(subkeyElement);

            a++;
          }
          contentElement.addChild(keyElement);
        }
      }
      String updatedContent = GovernanceUtils.serializeOMElement(contentElement);
      resource.setContent(updatedContent);

    } catch (RegistryException e) {
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Error in saving attributes for the artifact. id: "
                + artifact.getId()
                + ", path: "
                + artifact.getPath()
                + ".";
      } else {
        msg = "Error in saving attributes for the artifact. id: " + artifact.getId() + ".";
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    }
  }
  /**
   * Updates the given artifact on the registry.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void updateGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      validateArtifact(artifact);
      GovernanceArtifact oldArtifact = getGovernanceArtifact(artifact.getId());
      // first check for the old artifact and remove it.
      String oldPath = null;
      if (oldArtifact != null) {
        QName oldName = oldArtifact.getQName();
        if (!oldName.equals(artifact.getQName())) {
          String temp = oldArtifact.getPath();
          // then it is analogue to moving the resource for the new location
          // so just delete the old path
          registry.delete(temp);

          String artifactName = artifact.getQName().getLocalPart();
          artifact.setAttributes(artifactNameAttribute, new String[] {artifactName});
          String namespace = artifact.getQName().getNamespaceURI();
          if (artifactNamespaceAttribute != null) {
            artifact.setAttributes(artifactNamespaceAttribute, new String[] {namespace});
          }
        } else {
          oldPath = oldArtifact.getPath();
        }
      } else {
        throw new GovernanceException(
            "No artifact found for the artifact id :" + artifact.getId() + ".");
      }

      String artifactId = artifact.getId();
      Resource resource = registry.newResource();
      resource.setMediaType(mediaType);
      setContent(artifact, resource);
      String path = GovernanceUtils.getPathFromPathExpression(pathExpression, artifact);

      if (oldPath != null) {
        path = oldPath;
      }
      if (registry.resourceExists(path)) {
        Resource oldResource = registry.get(path);
        Properties properties = (Properties) oldResource.getProperties().clone();
        resource.setProperties(properties);

        // persisting resource description at artifact update
        String description = oldResource.getDescription();
        if (description != null) {
          resource.setDescription(description);
        }

        String oldContent;
        Object content = oldResource.getContent();
        if (content instanceof String) {
          oldContent = (String) content;
        } else {
          oldContent = new String((byte[]) content);
        }
        String newContent;
        content = resource.getContent();
        if (content instanceof String) {
          newContent = (String) content;
        } else {
          newContent = new String((byte[]) content);
        }
        if (newContent.equals(oldContent)) {
          artifact.setId(oldResource.getUUID());
          addRelationships(path, artifact);
          succeeded = true;
          return;
        }
      }
      resource.setUUID(artifactId);
      registry.put(path, resource);
      //            artifact.setId(resource.getUUID()); //This is done to get the UUID of a existing
      // resource.
      addRelationships(oldPath, artifact);
      ((GovernanceArtifactImpl) artifact).updatePath(artifactId);
      succeeded = true;
    } catch (RegistryException e) {
      if (e instanceof GovernanceException) {
        throw (GovernanceException) e;
      }
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Error in updating the artifact, artifact id: "
                + artifact.getId()
                + ", artifact path: "
                + artifact.getPath()
                + "."
                + e.getMessage()
                + ".";
      } else {
        msg =
            "Error in updating the artifact, artifact id: "
                + artifact.getId()
                + "."
                + e.getMessage()
                + ".";
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg;
          if (artifact.getPath() != null) {
            msg =
                "Error in committing transactions. Update artifact failed: artifact "
                    + "id: "
                    + artifact.getId()
                    + ", path: "
                    + artifact.getPath()
                    + ".";
          } else {
            msg =
                "Error in committing transactions. Update artifact failed: artifact "
                    + "id: "
                    + artifact.getId()
                    + ".";
          }

          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Update artifact failed: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
  /**
   * Adds the given artifact to the registry. Please do not use this method to update an existing
   * artifact use the update method instead. If this method is used to update an existing artifact,
   * all existing properties (such as lifecycle details) will be removed from the existing artifact.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void addGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    // adding the attributes for name, namespace + artifact
    if (artifact.getQName() == null || artifact.getQName().getLocalPart() == null) {
      String msg = "A valid qualified name was not set for this artifact";
      log.error(msg);
      throw new GovernanceException(msg);
    }
    validateArtifact(artifact);
    String artifactName = artifact.getQName().getLocalPart();
    artifact.setAttributes(artifactNameAttribute, new String[] {artifactName});
    // namespace can be null
    String namespace = artifact.getQName().getNamespaceURI();
    if (artifactNamespaceAttribute != null) {
      artifact.setAttributes(artifactNamespaceAttribute, new String[] {namespace});
    }

    ((GovernanceArtifactImpl) artifact).associateRegistry(registry);
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      Resource resource = registry.newResource();

      resource.setMediaType(mediaType);
      setContent(artifact, resource);
      // the artifact will not actually stored in the tmp path.
      String path = GovernanceUtils.getPathFromPathExpression(pathExpression, artifact);

      if (registry.resourceExists(path)) {
        throw new GovernanceException(
            "Governance artifact " + artifactName + " already exists at " + path);
      }

      String artifactId = artifact.getId();
      resource.setUUID(artifactId);
      registry.put(path, resource);

      if (lifecycle != null) {
        registry.associateAspect(path, lifecycle);
      }

      ((GovernanceArtifactImpl) artifact).updatePath();
      //            artifact.setId(resource.getUUID()); //This is done to get the UUID of a existing
      // resource.
      addRelationships(path, artifact);

      succeeded = true;
    } catch (RegistryException e) {
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Failed to add artifact: artifact id: "
                + artifact.getId()
                + ", path: "
                + artifact.getPath()
                + ". "
                + e.getMessage();
      } else {
        msg = "Failed to add artifact: artifact id: " + artifact.getId() + ". " + e.getMessage();
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg;
          if (artifact.getPath() != null) {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ", path: "
                    + artifact.getPath()
                    + ".";
          } else {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ".";
          }
          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Failed to add artifact: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }