Exemple #1
0
  public void ResourceCopyTest() throws RegistryException {

    Resource r1 = registry.newResource();
    r1.setProperty("test", "copy");
    r1.setContent("c");
    registry.put("/test1/copy/c1/copy1", r1);

    Collection c1 = registry.newCollection();
    registry.put("/test1/move", c1);

    registry.copy("/test1/copy/c1/copy1", "/test1/copy/c2/copy2");

    Resource newR1 = registry.get("/test1/copy/c2/copy2");
    assertEquals(
        "Copied resource should have a property named 'test' with value 'copy'.",
        newR1.getProperty("test"),
        "copy");

    Resource oldR1 = registry.get("/test1/copy/c1/copy1");
    assertEquals(
        "Original resource should have a property named 'test' with value 'copy'.",
        oldR1.getProperty("test"),
        "copy");

    String newContent = new String((byte[]) newR1.getContent());
    String oldContent = new String((byte[]) oldR1.getContent());
    assertEquals("Contents are not equal in copied resources", newContent, oldContent);
  }
 public static boolean generateHandler(Registry configSystemRegistry, String resourceFullPath)
     throws RegistryException, XMLStreamException {
   RegistryContext registryContext = configSystemRegistry.getRegistryContext();
   if (registryContext == null) {
     return false;
   }
   Resource resource = configSystemRegistry.get(resourceFullPath);
   if (resource != null) {
     String content = null;
     if (resource.getContent() != null) {
       content = RegistryUtils.decodeBytes((byte[]) resource.getContent());
     }
     if (content != null) {
       OMElement handler = AXIOMUtil.stringToOM(content);
       if (handler != null) {
         OMElement dummy = OMAbstractFactory.getOMFactory().createOMElement("dummy", null);
         dummy.addChild(handler);
         try {
           configSystemRegistry.beginTransaction();
           boolean status =
               RegistryConfigurationProcessor.updateHandler(
                   dummy,
                   configSystemRegistry.getRegistryContext(),
                   HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
           configSystemRegistry.commitTransaction();
           return status;
         } catch (Exception e) {
           configSystemRegistry.rollbackTransaction();
           throw new RegistryException("Unable to add handler", e);
         }
       }
     }
   }
   return false;
 }
  @Test(groups = {"wso2.greg"})
  public void ContinuousDelete() throws RegistryException, InterruptedException {
    int iterations = 100;

    for (int i = 0; i < iterations; i++) {

      Resource res1 = registry.newResource();
      byte[] r1content = "R2 content".getBytes();
      res1.setContent(r1content);
      String path = "/con-delete/test/" + i + 1;

      registry.put(path, res1);

      Resource resource1 = registry.get(path);

      assertEquals(
          new String((byte[]) resource1.getContent()),
          new String((byte[]) res1.getContent()),
          "File content is not matching");

      registry.delete(path);

      boolean value = false;

      if (registry.resourceExists(path)) {
        value = true;
      }

      assertFalse(value, "Resource found at the path");

      res1.discard();
      resource1.discard();
      Thread.sleep(100);
    }
  }
  public void testResourceContentVersioning() throws Exception {

    Resource r1 = registry.newResource();
    r1.setContent("content 1".getBytes());
    registry.put("/v2/r1", r1);

    Resource r12 = registry.get("/v2/r1");
    r12.setContent("content 2".getBytes());
    registry.put("/v2/r1", r12);
    registry.put("/v2/r1", r12);

    String[] r1Versions = registry.getVersions("/v2/r1");

    Resource r1vv1 = registry.get(r1Versions[1]);

    assertEquals(
        "r1's first version's content should be 'content 1'",
        new String((byte[]) r1vv1.getContent()),
        "content 1");

    Resource r1vv2 = registry.get(r1Versions[0]);

    assertEquals(
        "r1's second version's content should be 'content 2'",
        new String((byte[]) r1vv2.getContent()),
        "content 2");
  }
  public void testDefaultQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c3/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c3/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c3/r3";
    registry.put(r3Path, r3);

    registry.applyTag("/c3/r1", "java");
    registry.applyTag("/c3/r2", "jsp");
    registry.applyTag("/c3/r3", "ajax");

    String sql1 =
        "SELECT RT.REG_TAG_ID FROM REG_RESOURCE_TAG RT, REG_RESOURCE R "
            + "WHERE (R.REG_VERSION=RT.REG_VERSION OR "
            + "(R.REG_PATH_ID=RT.REG_PATH_ID AND R.REG_NAME=RT.REG_RESOURCE_NAME)) "
            + "AND R.REG_DESCRIPTION LIKE ? ORDER BY RT.REG_TAG_ID";

    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAGS_RESULT_TYPE);
    systemRegistry.put("/qs/q3", q1);

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("1", "%production%");
    Collection result = registry.executeQuery("/qs/q3", parameters);

    String[] tagPaths = result.getChildren();
    assertEquals("There should be two matching tags.", tagPaths.length, 2);

    Resource tag2 = registry.get(tagPaths[0]);
    assertEquals("First matching tag should be 'java'", (String) tag2.getContent(), "java");

    Resource tag1 = registry.get(tagPaths[1]);
    assertEquals("Second matching tag should be 'jsp'", (String) tag1.getContent(), "jsp");
  }
  /**
   * This method is used to get wsdl difference comparison.
   *
   * @param WSDLOne wsdl one.
   * @param WSDLTwo wsdl two.
   * @return Comparison object which includes the difference parameters.
   * @throws ComparisonException
   * @throws WSDLException
   * @throws RegistryException
   * @throws UnsupportedEncodingException
   */
  private Comparison getWSDLComparison(Resource WSDLOne, Resource WSDLTwo)
      throws ComparisonException, WSDLException, RegistryException, UnsupportedEncodingException {
    GovernanceDiffGeneratorFactory diffGeneratorFactory = new GovernanceDiffGeneratorFactory();
    DiffGenerator flow = diffGeneratorFactory.getDiffGenerator();
    WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();

    InputSource inputSourceOne =
        new InputSource(new ByteArrayInputStream((byte[]) WSDLOne.getContent()));
    Definition originalWSDL = wsdlReader.readWSDL(null, inputSourceOne);

    InputSource inputSourceTwo =
        new InputSource(new ByteArrayInputStream((byte[]) WSDLTwo.getContent()));
    Definition changedWSDL = wsdlReader.readWSDL(null, inputSourceTwo);

    return flow.compare(originalWSDL, changedWSDL, ComparatorConstants.WSDL_MEDIA_TYPE);
  }
 public static String getHandlerConfiguration(Registry configSystemRegistry, String name)
     throws RegistryException, XMLStreamException {
   String path = getContextRoot() + name;
   Resource resource;
   if (handlerExists(configSystemRegistry, name)) {
     resource = configSystemRegistry.get(path);
     return RegistryUtils.decodeBytes((byte[]) resource.getContent());
   }
   return null;
 }
  @Test(groups = {"wso2.greg"})
  public void ContinuousUpdate() throws RegistryException, InterruptedException {

    int iterations = 100;

    for (int i = 0; i < iterations; i++) {

      Resource res1 = registry.newResource();
      byte[] r1content = "R2 content".getBytes();
      res1.setContent(r1content);
      String path = "/con-delete/test-update/" + i + 1;

      registry.put(path, res1);

      Resource resource1 = registry.get(path);

      assertEquals(
          new String((byte[]) resource1.getContent()),
          new String((byte[]) res1.getContent()),
          "File content is not matching");

      Resource resource = new ResourceImpl();
      byte[] r1content1 = "R2 content updated".getBytes();
      resource.setContent(r1content1);
      resource.setProperty("abc", "abc");

      registry.put(path, resource);

      Resource resource2 = registry.get(path);

      assertEquals(
          new String((byte[]) resource2.getContent()),
          new String((byte[]) resource.getContent()),
          "File content is not matching");

      resource.discard();
      res1.discard();
      resource1.discard();
      resource2.discard();
      Thread.sleep(100);
    }
  }
 public void policyContentAssertion(String keyword1, String keyword2, String policy_path)
     throws RegistryException {
   Resource r1 = registry.newResource();
   String content = null;
   try {
     r1 = registry.get(policy_path);
     content = new String((byte[]) r1.getContent());
     assertTrue(content.indexOf(keyword1) > 0, "Assert Content Policy file - keyword1");
     assertTrue(content.indexOf(keyword2) > 0, "Assert Content Policy file - keyword2");
   } catch (RegistryException e) {
     log.error("Registry Exception thrown:" + e);
     throw new RegistryException("Failed to Assert Properties :" + e);
   }
 }
  /**
   * This method is used to get the text difference of two strings.
   *
   * @param resourcePathOne resource path one.
   * @param resourcePathTwo resource path two.
   * @return Comparison object which includes the difference parameters.
   * @throws ComparisonException
   * @throws WSDLException
   * @throws RegistryException
   * @throws UnsupportedEncodingException
   */
  public Comparison getArtifactTextDiff(String resourcePathOne, String resourcePathTwo)
      throws ComparisonException, WSDLException, RegistryException, UnsupportedEncodingException {

    String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    Registry registry =
        RegistryCoreServiceComponent.getRegistryService().getRegistry(username, tenantId);
    Resource resourceOne = registry.get(resourcePathOne);
    Resource resourceTwo = registry.get(resourcePathTwo);

    DiffGeneratorFactory factory = new TextDiffGeneratorFactory();
    DiffGenerator flow = factory.getDiffGenerator();

    String resourceOneText = new String((byte[]) resourceOne.getContent(), "UTF-8");
    String resourceTwoText = new String((byte[]) resourceTwo.getContent(), "UTF-8");

    String resourceOneFormattedText = prettyFormatText(resourceOneText, resourceOne.getMediaType());
    String resourceTwoFormattedText = prettyFormatText(resourceTwoText, resourceTwo.getMediaType());
    return flow.compare(
        resourceOneFormattedText,
        resourceTwoFormattedText,
        ComparatorConstants.TEXT_PLAIN_MEDIA_TYPE);
  }
  public void testWithoutTableParamsQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c1/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c2/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c2/r3";
    registry.put(r3Path, r3);

    String sql1 =
        "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE, " + "REG_TAG WHERE REG_DESCRIPTION LIKE ?";
    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
    systemRegistry.put("/qs/q1", q1);

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("1", "%production%");
    Resource result = registry.executeQuery("/qs/q1", parameters);

    assertTrue(
        "Search with result type Resource should return a directory.",
        result instanceof org.wso2.carbon.registry.core.Collection);

    List<String> matchingPaths = new ArrayList<String>();
    String[] paths = (String[]) result.getContent();
    matchingPaths.addAll(Arrays.asList(paths));

    assertTrue("Path /c1/r1 should be in the results.", matchingPaths.contains("/c1/r1"));
    assertTrue("Path /c2/r2 should be in the results.", matchingPaths.contains("/c2/r2"));
  }
  /**
   * Saves a swagger document in the registry.
   *
   * @param contentStream resource content.
   * @param path resource path.
   * @param documentVersion version of the swagger document.
   * @throws RegistryException If fails to add the swagger document to registry.
   */
  private boolean addSwaggerDocumentToRegistry(
      ByteArrayOutputStream contentStream, String path, String documentVersion)
      throws RegistryException {
    Resource resource;
    /*
    Checks if a resource is already exists in the given path.
    If exists,
    	Compare resource contents and if updated, updates the document, if not skip the updating process
    If not exists,
    	Creates a new resource and add to the resource path.
     */
    if (registry.resourceExists(path)) {
      resource = registry.get(path);
      Object resourceContentObj = resource.getContent();
      String resourceContent;
      if (resourceContentObj instanceof String) {
        resourceContent = (String) resourceContentObj;
        resource.setContent(RegistryUtils.encodeString(resourceContent));
      } else if (resourceContentObj instanceof byte[]) {
        resourceContent = RegistryUtils.decodeBytes((byte[]) resourceContentObj);
      } else {
        throw new RegistryException(CommonConstants.INVALID_CONTENT);
      }
      if (resourceContent.equals(contentStream.toString())) {
        log.info("Old content is same as the new content. Skipping the put action.");
        return false;
      }
    } else {
      // If a resource does not exist in the given path.
      resource = new ResourceImpl();
    }

    String resourceId =
        (resource.getUUID() == null) ? UUID.randomUUID().toString() : resource.getUUID();

    resource.setUUID(resourceId);
    resource.setMediaType(CommonConstants.SWAGGER_MEDIA_TYPE);
    resource.setContent(contentStream.toByteArray());
    resource.addProperty(RegistryConstants.VERSION_PARAMETER_NAME, documentVersion);
    CommonUtil.copyProperties(this.requestContext.getResource(), resource);
    registry.put(path, resource);

    return true;
  }
  public void testResourceRestore() throws Exception {

    Resource r1 = registry.newResource();
    r1.setContent("content 1".getBytes());
    registry.put("/test/v10/r1", r1);

    Resource r1e1 = registry.get("/test/v10/r1");
    r1e1.setContent("content 2".getBytes());
    registry.put("/test/v10/r1", r1e1);
    registry.put("/test/v10/r1", r1e1);

    String[] r1Versions = registry.getVersions("/test/v10/r1");
    registry.restoreVersion(r1Versions[1]);

    Resource r1r1 = registry.get("/test/v10/r1");

    assertEquals(
        "Restored resource should have content 'content 1'",
        "content 1",
        new String((byte[]) r1r1.getContent()));
  }
  public void testWithoutWhereQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c1/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c2/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c2/r3";
    registry.put(r3Path, r3);

    String sql1 = "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE, REG_TAG";
    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
    systemRegistry.put("/qs/q1", q1);

    Map parameters = new HashMap();
    Resource result = registry.executeQuery("/qs/q1", parameters);

    assertTrue(
        "Search with result type Resource should return a directory.",
        result instanceof org.wso2.carbon.registry.core.Collection);

    String[] paths = (String[]) result.getContent();
    assertTrue("Should return all the resources", paths.length >= 3);
  }
  public Object retrieve(String resourcePath) throws RegistryException {

    UserRegistry registry = initRegistry();

    Resource resource;

    try {
      resource = registry.get(resourcePath);

    } catch (ResourceNotFoundException ignore) {
      // nothing has been persisted in the registry yet
      if (log.isDebugEnabled()) {
        log.debug("No resource found in the registry path " + resourcePath);
      }
      return null;

    } catch (RegistryException e) {
      String errorMsg = "Failed to retrieve the Resource at " + resourcePath + " from registry.";
      log.error(errorMsg, e);
      throw e;
    }

    return resource.getContent();
  }
  public String addWadlToRegistry(
      RequestContext requestContext, Resource resource, String resourcePath, boolean skipValidation)
      throws RegistryException {
    String wadlName = RegistryUtils.getResourceName(resourcePath);
    String version =
        requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME);

    if (version == null) {
      version = CommonConstants.WADL_VERSION_DEFAULT_VALUE;
      requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version);
    }

    OMElement wadlElement;
    String wadlContent;
    Object resourceContent = resource.getContent();
    if (resourceContent instanceof String) {
      wadlContent = (String) resourceContent;
    } else {
      wadlContent = new String((byte[]) resourceContent);
    }

    try {
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(wadlContent));
      StAXOMBuilder builder = new StAXOMBuilder(reader);
      wadlElement = builder.getDocumentElement();
    } catch (XMLStreamException e) {
      // This exception is unexpected because the WADL already validated
      String msg = "Unexpected error occured " + "while reading the WADL at " + resourcePath + ".";
      log.error(msg);
      throw new RegistryException(msg, e);
    }

    String wadlNamespace = wadlElement.getNamespace().getNamespaceURI();
    String namespaceSegment =
        CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/");
    String actualPath =
        getChrootedWadlLocation(requestContext.getRegistryContext())
            + namespaceSegment
            + version
            + "/"
            + wadlName;

    OMElement grammarsElement =
        wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars"));

    if (StringUtils.isNotBlank(requestContext.getSourceURL())) {
      String uri = requestContext.getSourceURL();
      if (!skipValidation) {
        validateWADL(uri);
      }

      if (resource.getUUID() == null) {
        resource.setUUID(UUID.randomUUID().toString());
      }

      String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1);
      if (grammarsElement != null) {
        // This is to avoid evaluating the grammars import when building AST
        grammarsElement.detach();
        wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version));
      }
    } else {
      if (!skipValidation) {
        File tempFile = null;
        BufferedWriter bufferedWriter = null;
        try {
          tempFile = File.createTempFile(wadlName, null);
          bufferedWriter = new BufferedWriter(new FileWriter(tempFile));
          bufferedWriter.write(wadlElement.toString());
          bufferedWriter.flush();
        } catch (IOException e) {
          String msg = "Error occurred while reading the WADL File";
          log.error(msg, e);
          throw new RegistryException(msg, e);
        } finally {
          if (bufferedWriter != null) {
            try {
              bufferedWriter.close();
            } catch (IOException e) {
              String msg = "Error occurred while closing File writer";
              log.warn(msg, e);
            }
          }
        }
        validateWADL(tempFile.toURI().toString());
        try {
          delete(tempFile);
        } catch (IOException e) {
          String msg =
              "An error occurred while deleting the temporary files from local file system.";
          log.warn(msg, e);
          throw new RegistryException(msg, e);
        }
      }

      if (grammarsElement != null) {
        grammarsElement = resolveImports(grammarsElement, null, version);
        wadlElement.addChild(grammarsElement);
      }
    }

    requestContext.setResourcePath(new ResourcePath(actualPath));
    if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) {
      resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
    }
    registry.put(actualPath, resource);
    addImportAssociations(actualPath);
    if (getCreateService()) {
      OMElement serviceElement =
          RESTServiceUtils.createRestServiceArtifact(
              wadlElement,
              wadlName,
              version,
              RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath));
      String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement);
      registry.addAssociation(servicePath, actualPath, CommonConstants.DEPENDS);
      registry.addAssociation(actualPath, servicePath, CommonConstants.USED_BY);
      String endpointPath = createEndpointElement(requestContext, wadlElement, version);
      if (endpointPath != null) {
        registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS);
        registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY);
      }
    }

    return resource.getPath();
  }
  public void put(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    Object content = resource.getContent();
    String contentString;
    if (content instanceof String) {
      contentString = (String) content;
    } else {
      contentString = RegistryUtils.decodeBytes((byte[]) content);
    }
    OMElement payload;
    try {
      payload = AXIOMUtil.stringToOM(contentString);
    } catch (XMLStreamException e) {
      String msg = "Unable to serialize resource content";
      log.error(msg, e);
      throw new RegistryException(msg, e);
    }
    OMNamespace namespace = payload.getNamespace();
    String namespaceURI = namespace.getNamespaceURI();
    OMElement definition = payload.getFirstChildWithName(new QName(namespaceURI, "definition"));
    OMElement projectPath =
        definition.getFirstChildWithName(new QName(namespaceURI, "projectPath"));
    String projectMetadataPath = null;
    if (projectPath != null) {
      projectMetadataPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + projectPath.getText();
    }

    Resource metadataResource = requestContext.getRegistry().get(projectMetadataPath);

    String remainingWork = metadataResource.getProperty("Remaining Work");
    String scheduledWork = metadataResource.getProperty("Scheduled Work");
    String actualWork = metadataResource.getProperty("Actual Work");

    String remainingCost = metadataResource.getProperty("Remaining Cost");
    String scheduledCost = metadataResource.getProperty("Scheduled Cost");
    String actualCost = metadataResource.getProperty("Actual Cost");

    String duration = metadataResource.getProperty("Duration");
    String startDate = metadataResource.getProperty("Start Date");
    String endDate = metadataResource.getProperty("Finish Date");

    OMFactory factory = payload.getOMFactory();
    OMElement work = payload.getFirstChildWithName(new QName(namespaceURI, "work"));
    if (work == null) {
      work = factory.createOMElement("work", namespace, payload);
    }
    OMElement remainingWorkElement =
        work.getFirstChildWithName(new QName(namespaceURI, "remaining"));
    if (remainingWorkElement == null) {
      remainingWorkElement = factory.createOMElement("remaining", namespace, work);
    }
    remainingWorkElement.setText(remainingWork);
    OMElement actualWorkElement = work.getFirstChildWithName(new QName(namespaceURI, "actual"));
    if (actualWorkElement == null) {
      actualWorkElement = factory.createOMElement("actual", namespace, work);
    }
    actualWorkElement.setText(remainingWork);
    OMElement scheduledWorkElement =
        work.getFirstChildWithName(new QName(namespaceURI, "scheduled"));
    if (scheduledWorkElement == null) {
      scheduledWorkElement = factory.createOMElement("scheduled", namespace, work);
    }
    scheduledWorkElement.setText(remainingWork);

    OMElement cost = payload.getFirstChildWithName(new QName(namespaceURI, "cost"));
    if (cost == null) {
      cost = factory.createOMElement("cost", namespace, payload);
    }
    OMElement remainingCostElement =
        cost.getFirstChildWithName(new QName(namespaceURI, "remaining"));
    if (remainingCostElement == null) {
      remainingCostElement = factory.createOMElement("remaining", namespace, cost);
    }
    remainingCostElement.setText(remainingCost);
    OMElement actualCostElement = cost.getFirstChildWithName(new QName(namespaceURI, "actual"));
    if (actualCostElement == null) {
      actualCostElement = factory.createOMElement("actual", namespace, cost);
    }
    actualCostElement.setText(remainingCost);
    OMElement scheduledCostElement =
        cost.getFirstChildWithName(new QName(namespaceURI, "scheduled"));
    if (scheduledCostElement == null) {
      scheduledCostElement = factory.createOMElement("scheduled", namespace, cost);
    }
    scheduledCostElement.setText(remainingCost);

    OMElement timeline = payload.getFirstChildWithName(new QName(namespaceURI, "timeline"));
    if (timeline == null) {
      timeline = factory.createOMElement("timeline", namespace, payload);
    }
    OMElement durationElement = timeline.getFirstChildWithName(new QName(namespaceURI, "duration"));
    if (durationElement == null) {
      durationElement = factory.createOMElement("duration", namespace, timeline);
    }
    durationElement.setText(duration);
    OMElement startDateElement =
        timeline.getFirstChildWithName(new QName(namespaceURI, "startDate"));
    if (startDateElement == null) {
      startDateElement = factory.createOMElement("startDate", namespace, timeline);
    }
    startDateElement.setText(startDate);
    OMElement endDateElement = timeline.getFirstChildWithName(new QName(namespaceURI, "endDate"));
    if (endDateElement == null) {
      endDateElement = factory.createOMElement("endDate", namespace, timeline);
    }
    endDateElement.setText(endDate);

    resource.setContent(payload.toString());
  }
  public void testAdvancedCollectionRestore() throws Exception {

    Collection c1 = registry.newCollection();
    registry.put("/test/v12/c1", c1);

    registry.createVersion("/test/v12/c1");

    Resource r1 = registry.newResource();
    r1.setContent("r1c1".getBytes());
    registry.put("/test/v12/c1/c11/r1", r1);

    registry.createVersion("/test/v12/c1");

    Collection c2 = registry.newCollection();
    registry.put("/test/v12/c1/c11/c2", c2);

    registry.createVersion("/test/v12/c1");

    Resource r1e1 = registry.get("/test/v12/c1/c11/r1");
    r1e1.setContent("r1c2".getBytes());
    registry.put("/test/v12/c1/c11/r1", r1e1);

    registry.createVersion("/test/v12/c1");

    String[] c1Versions = registry.getVersions("/test/v12/c1");
    assertEquals("c1 should have 4 versions", c1Versions.length, 4);

    registry.restoreVersion(c1Versions[3]);

    try {
      registry.get("/test/v12/c1/c11");
      fail("Version 1 of c1 should not have child c11");
    } catch (Exception e) {
    }

    registry.restoreVersion(c1Versions[2]);

    try {
      registry.get("/test/v12/c1/c11");
    } catch (Exception e) {
      fail("Version 2 of c1 should have child c11");
    }

    try {
      registry.get("/test/v12/c1/c11/r1");
    } catch (Exception e) {
      fail("Version 2 of c1 should have child c11/r1");
    }

    registry.restoreVersion(c1Versions[1]);

    Resource r1e2 = null;
    try {
      r1e2 = registry.get("/test/v12/c1/c11/r1");
    } catch (Exception e) {
      fail("Version 2 of c1 should have child c11/r1");
    }

    try {
      registry.get("/test/v12/c1/c11/c2");
    } catch (Exception e) {
      fail("Version 2 of c1 should have child c11/c2");
    }

    String r1e2Content = new String((byte[]) r1e2.getContent());
    assertEquals("c11/r1 content should be 'r1c1", r1e2Content, "r1c1");

    registry.restoreVersion(c1Versions[0]);

    Resource r1e3 = registry.get("/test/v12/c1/c11/r1");
    String r1e3Content = new String((byte[]) r1e3.getContent());
    assertEquals("c11/r1 content should be 'r1c2", r1e3Content, "r1c2");
  }
Exemple #19
0
  @Test(groups = {"wso2.greg"})
  public void AddComment() throws Exception {
    Resource r1 = registry.newResource();
    String path = "/d112/r3";
    byte[] r1content = "R1 content".getBytes();
    r1.setContent(r1content);
    registry.put(path, r1);

    String comment1 = "this is qa comment 4";
    String comment2 = "this is qa comment 5";
    Comment c1 = new Comment();
    c1.setResourcePath(path);
    c1.setText("This is default comment");
    c1.setUser("admin1");

    registry.addComment(path, c1);
    registry.addComment(path, new Comment(comment1));
    registry.addComment(path, new Comment(comment2));

    Comment[] comments = registry.getComments(path);

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(comment1)) {
        commentFound = true;
        // System.out.println(comment.getPath());
        assertEquals(comment.getText(), comment1);
        assertEquals(comment.getUser(), "admin");
        assertEquals(comment.getResourcePath(), path);
        // System.out.println(comment.getPath());
        // break;
      }

      if (comment.getText().equals(comment2)) {
        commentFound = true;
        assertEquals(comment.getText(), comment2);
        assertEquals(comment.getUser(), "admin");
        assertEquals(comment.getResourcePath(), path);
        // break;
      }

      if (comment.getText().equals("This is default comment")) {
        commentFound = true;
        assertEquals(comment.getText(), "This is default comment");
        assertEquals(comment.getUser(), "admin");
        // break;
      }
    }

    assertTrue(commentFound, "No comment is associated with the resource" + path);

    Resource commentsResource = registry.get("/d112/r3;comments");
    assertTrue(
        commentsResource instanceof Collection,
        "Comment collection resource should be a directory.");
    comments = (Comment[]) commentsResource.getContent();

    List commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(new String((byte[]) commentResource.getContent()));
    }

    assertTrue(
        commentTexts.contains(comment1),
        comment1 + " is not associated with the resource /d112/r3.");
    assertTrue(
        commentTexts.contains(comment2),
        comment2 + " is not associated with the resource /d112/r3.");
  }
Exemple #20
0
  @Test(groups = {"wso2.greg"})
  public void EditComment() throws Exception {
    Resource r1 = registry.newResource();
    byte[] r1content = "R1 content".getBytes();
    r1.setContent(r1content);
    r1.setDescription("this is a resource to edit comment");
    registry.put("/c101/c11/r1", r1);

    Comment c1 = new Comment();
    c1.setResourcePath("/c10/c11/r1");
    c1.setText("This is default comment ");
    c1.setUser("admin");

    registry.addComment("/c101/c11/r1", c1);

    Comment[] comments = registry.getComments("/c101/c11/r1");

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(c1.getText())) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        //                //System.out.println("\n");
        // break;
      }
    }

    assertTrue(
        commentFound,
        "comment:" + c1.getText() + " is not associated with the artifact /c101/c11/r1");

    try {

      Resource commentsResource = registry.get("/c101/c11/r1;comments");

      assertTrue(commentsResource instanceof Collection, "Comment resource should be a directory.");
      comments = (Comment[]) commentsResource.getContent();

      List commentTexts = new ArrayList();
      for (Comment comment : comments) {
        Resource commentResource = registry.get(comment.getPath());
        commentTexts.add(new String((byte[]) commentResource.getContent()));
      }

      assertTrue(
          commentTexts.contains(c1.getText()),
          c1.getText() + " is not associated for resource /c101/c11/r1.");
      registry.editComment(comments[0].getPath(), "This is the edited comment");
      comments = registry.getComments("/c101/c11/r1");
      //            System.out.println(comments);
      Resource resource = registry.get(comments[0].getPath());
      assertEquals(new String((byte[]) resource.getContent()), "This is the edited comment");
    } catch (RegistryException e) {
      e.printStackTrace();
      fail("Failed to get comments form URL:/c101/c11/r1;comments");
    }

    /*Edit comment goes here*/

    registry.editComment("/c101/c11/r1", "This is the edited comment");
  }
  public void put(RequestContext requestContext) throws RegistryException {
    WSDLProcessor wsdl = null;

    if (!CommonUtil.isUpdateLockAvailable()) {
      return;
    }
    CommonUtil.acquireUpdateLock();
    try {
      Registry registry = requestContext.getRegistry();
      Resource resource = requestContext.getResource();
      if (resource == null) {
        throw new RegistryException("The resource is not available.");
      }
      String originalServicePath = requestContext.getResourcePath().getPath();
      String resourceName = RegistryUtils.getResourceName(originalServicePath);

      OMElement serviceInfoElement, previousServiceInfoElement = null;
      Object resourceContent = resource.getContent();
      String serviceInfo;
      if (resourceContent instanceof String) {
        serviceInfo = (String) resourceContent;
      } else {
        serviceInfo = RegistryUtils.decodeBytes((byte[]) resourceContent);
      }
      try {
        XMLStreamReader reader =
            XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(serviceInfo));
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        serviceInfoElement = builder.getDocumentElement();
      } catch (Exception e) {
        String msg =
            "Error in parsing the service content of the service. "
                + "The requested path to store the service: "
                + originalServicePath
                + ".";
        log.error(msg);
        throw new RegistryException(msg, e);
      }
      // derive the service path that the service should be saved.
      String serviceName = CommonUtil.getServiceName(serviceInfoElement);
      String serviceNamespace = CommonUtil.getServiceNamespace(serviceInfoElement);

      String servicePath = "";
      if (serviceInfoElement.getChildrenWithLocalName("newServicePath").hasNext()) {
        Iterator OmElementIterator = serviceInfoElement.getChildrenWithLocalName("newServicePath");

        while (OmElementIterator.hasNext()) {
          OMElement next = (OMElement) OmElementIterator.next();
          servicePath = next.getText();
          break;
        }
      } else {
        if (registry.resourceExists(originalServicePath)) {
          // Fixing REGISTRY-1790. Save the Service to the given original
          // service path if there is a service already exists there
          servicePath = originalServicePath;
        } else {
          servicePath =
              RegistryUtils.getAbsolutePath(
                  registry.getRegistryContext(),
                  registry.getRegistryContext().getServicePath()
                      + (serviceNamespace == null
                          ? ""
                          : CommonUtil.derivePathFragmentFromNamespace(serviceNamespace))
                      + serviceName);
        }
      }
      String serviceVersion =
          org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion(serviceInfoElement);

      if (serviceVersion.length() == 0) {
        serviceVersion = defaultServiceVersion;
        CommonUtil.setServiceVersion(serviceInfoElement, serviceVersion);
        resource.setContent(serviceInfoElement.toString());
      }
      // saving the artifact id.
      String serviceId = resource.getUUID();
      if (serviceId == null) {
        // generate a service id
        serviceId = UUID.randomUUID().toString();
        resource.setUUID(serviceId);
      }

      if (registry.resourceExists(servicePath)) {
        Resource oldResource = registry.get(servicePath);
        String oldContent;
        Object content = oldResource.getContent();
        if (content instanceof String) {
          oldContent = (String) content;
        } else {
          oldContent = RegistryUtils.decodeBytes((byte[]) content);
        }
        OMElement oldServiceInfoElement = null;
        if (serviceInfo.equals(oldContent)) {
          // TODO: This needs a better solution. This fix was put in place to avoid
          // duplication of services under /_system/governance, when no changes were made.
          // However, the fix is not perfect and needs to be rethought. Perhaps the logic
          // below can be reshaped a bit, or may be we don't need to compare the
          // difference over here with a little fix to the Governance API end. - Janaka.

          // We have fixed this assuming that the temp path where services are stored is under
          // /_system/governance/[serviceName]
          // Hence if we are to change that location, then we need to change the following code
          // segment as well
          String tempPath =
              RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
                  + RegistryConstants.PATH_SEPARATOR
                  + resourceName;

          if (!originalServicePath.equals(tempPath)) {
            String path =
                RegistryUtils.getRelativePathToOriginal(
                    servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
            ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path);
            return;
          }
          requestContext.setProcessingComplete(true);
          return;
        }
        if ("true".equals(resource.getProperty("registry.DefinitionImport"))) {
          resource.removeProperty("registry.DefinitionImport");
          try {
            XMLStreamReader reader =
                XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(oldContent));
            StAXOMBuilder builder = new StAXOMBuilder(reader);
            oldServiceInfoElement = builder.getDocumentElement();
            CommonUtil.setServiceName(
                oldServiceInfoElement, CommonUtil.getServiceName(serviceInfoElement));
            CommonUtil.setServiceNamespace(
                oldServiceInfoElement, CommonUtil.getServiceNamespace(serviceInfoElement));
            CommonUtil.setDefinitionURL(
                oldServiceInfoElement, CommonUtil.getDefinitionURL(serviceInfoElement));
            CommonUtil.setEndpointEntries(
                oldServiceInfoElement, CommonUtil.getEndpointEntries(serviceInfoElement));
            CommonUtil.setServiceVersion(
                oldServiceInfoElement,
                org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion(
                    serviceInfoElement));
            serviceInfoElement = oldServiceInfoElement;
            resource.setContent(serviceInfoElement.toString());
            resource.setDescription(oldResource.getDescription());
          } catch (Exception e) {
            String msg =
                "Error in parsing the service content of the service. "
                    + "The requested path to store the service: "
                    + originalServicePath
                    + ".";
            log.error(msg);
            throw new RegistryException(msg, e);
          }
        }

        try {
          previousServiceInfoElement = AXIOMUtil.stringToOM(oldContent);
        } catch (XMLStreamException e) {
          String msg =
              "Error in parsing the service content of the service. "
                  + "The requested path to store the service: "
                  + originalServicePath
                  + ".";
          log.error(msg);
          throw new RegistryException(msg, e);
        }
      } else if ("true".equals(resource.getProperty("registry.DefinitionImport"))) {
        resource.removeProperty("registry.DefinitionImport");
      }
      //            CommonUtil.addGovernanceArtifactEntryWithAbsoluteValues(
      //                    CommonUtil.getUnchrootedSystemRegistry(requestContext),
      //                    serviceId, servicePath);

      String definitionURL = CommonUtil.getDefinitionURL(serviceInfoElement);
      if (previousServiceInfoElement != null) {
        String oldDefinition = CommonUtil.getDefinitionURL(previousServiceInfoElement);
        if ((!"".equals(oldDefinition) && "".equals(definitionURL))
            || (!"".endsWith(oldDefinition) && !oldDefinition.equals(definitionURL))) {
          try {
            registry.removeAssociation(servicePath, oldDefinition, CommonConstants.DEPENDS);
            registry.removeAssociation(oldDefinition, servicePath, CommonConstants.USED_BY);
            EndpointUtils.removeEndpointEntry(oldDefinition, serviceInfoElement, registry);
            resource.setContent(
                RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes()));
          } catch (RegistryException e) {
            throw new RegistryException(
                "Failed to remove endpoints from Service UI : " + serviceName, e);
          }
        }
      }

      boolean alreadyAdded = false;
      if (definitionURL != null
          && (definitionURL.startsWith("http://") || definitionURL.startsWith("https://"))) {
        String definitionPath;
        if (definitionURL.toLowerCase().endsWith("wsdl")) {
          wsdl = buildWSDLProcessor(requestContext);
          RequestContext context =
              new RequestContext(
                  registry, requestContext.getRepository(), requestContext.getVersionRepository());
          context.setResourcePath(
              new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wsdl"));
          context.setSourceURL(definitionURL);
          context.setResource(new ResourceImpl());
          definitionPath =
              wsdl.addWSDLToRegistry(
                  context,
                  definitionURL,
                  null,
                  false,
                  false,
                  disableWSDLValidation,
                  disableSymlinkCreation);

        } else if (definitionURL.toLowerCase().endsWith("wadl")) {
          WADLProcessor wadlProcessor = buildWADLProcessor(requestContext);
          wadlProcessor.setCreateService(false);
          RequestContext context =
              new RequestContext(
                  registry, requestContext.getRepository(), requestContext.getVersionRepository());
          context.setResourcePath(
              new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wadl"));
          context.setSourceURL(definitionURL);
          context.setResource(new ResourceImpl());
          definitionPath = wadlProcessor.importWADLToRegistry(context, null, disableWADLValidation);
        } else {
          throw new RegistryException(
              "Invalid service definition found. " + "Please enter a valid WSDL/WADL URL");
        }

        if (definitionPath == null) {
          return;
        }
        definitionURL =
            RegistryUtils.getRelativePath(requestContext.getRegistryContext(), definitionPath);
        CommonUtil.setDefinitionURL(serviceInfoElement, definitionURL);
        resource.setContent(RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes()));
        // updating the wsdl/wadl url
        ((ResourceImpl) resource).prepareContentForPut();
        persistServiceResource(registry, resource, servicePath);
        alreadyAdded = true;
        // and make the associations
        registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS);
        registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY);

      } else if (definitionURL != null && definitionURL.startsWith(RegistryConstants.ROOT_PATH)) {
        // it seems definitionUrl is a registry path..
        String definitionPath =
            RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(), definitionURL);
        if (!definitionPath.startsWith(
            RegistryUtils.getAbsolutePath(
                requestContext.getRegistryContext(),
                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH))) {

          definitionPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + definitionPath;
        }
        boolean addItHere = false;
        if (!registry.resourceExists(definitionPath)) {
          String msg =
              "Associating service to a non-existing WSDL. wsdl url: "
                  + definitionPath
                  + ", "
                  + "service path: "
                  + servicePath
                  + ".";
          log.error(msg);
          throw new RegistryException(msg);
        }
        if (!registry.resourceExists(servicePath)) {
          addItHere = true;
        } else {
          Association[] dependencies =
              registry.getAssociations(servicePath, CommonConstants.DEPENDS);
          boolean dependencyFound = false;
          if (dependencies != null) {
            for (Association dependency : dependencies) {
              if (definitionPath.equals(dependency.getDestinationPath())) {
                dependencyFound = true;
              }
            }
          }
          if (!dependencyFound) {
            addItHere = true;
          }
        }
        if (addItHere) { // add the service right here..
          ((ResourceImpl) resource).prepareContentForPut();
          persistServiceResource(registry, resource, servicePath);
          alreadyAdded = true;
          // and make the associations

          registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS);
          registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY);
        }
      }

      if (!alreadyAdded) {
        // we are adding the resource anyway.
        ((ResourceImpl) resource).prepareContentForPut();
        persistServiceResource(registry, resource, servicePath);
      }

      /*
                  if (!servicePath.contains(registry.getRegistryContext().getServicePath())) {
                      if (defaultEnvironment == null) {
                          String serviceDefaultEnvironment = registry.getRegistryContext().getServicePath();
                          String relativePath = serviceDefaultEnvironment.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH, "");
                          relativePath = relativePath.replace(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace),"");
                          defaultEnvironment = relativePath;
                      }

                      String currentRelativePath = servicePath.substring(0, servicePath.indexOf(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace)));
                      currentRelativePath = currentRelativePath.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH,"");

                      String endpointEnv = EndpointUtils.getEndpointLocation();

                      String[] pathSegments = defaultEnvironment.split(RegistryConstants.PATH_SEPARATOR);

                      for (String pathSegment : pathSegments) {
                          endpointEnv = endpointEnv.replace(pathSegment,"");
                          currentRelativePath = currentRelativePath.replace(pathSegment,"");
                      }

                      while(endpointEnv.startsWith(RegistryConstants.PATH_SEPARATOR)){
                          endpointEnv = endpointEnv.replaceFirst(RegistryConstants.PATH_SEPARATOR,"");
                      }

                      environment = currentRelativePath + endpointEnv;
                  }
      */

      EndpointUtils.saveEndpointsFromServices(
          servicePath,
          serviceInfoElement,
          registry,
          CommonUtil.getUnchrootedSystemRegistry(requestContext));

      String symlinkLocation =
          RegistryUtils.getAbsolutePath(
              requestContext.getRegistryContext(),
              requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME));
      if (!servicePath.equals(originalServicePath)) {
        // we are creating a sym link from service path to original service path.
        Resource serviceResource =
            requestContext.getRegistry().get(RegistryUtils.getParentPath(originalServicePath));
        String isLink = serviceResource.getProperty("registry.link");
        String mountPoint = serviceResource.getProperty("registry.mountpoint");
        String targetPoint = serviceResource.getProperty("registry.targetpoint");
        String actualPath = serviceResource.getProperty("registry.actualpath");
        if (isLink != null && mountPoint != null && targetPoint != null) {
          symlinkLocation = actualPath + RegistryConstants.PATH_SEPARATOR;
        }
        if (symlinkLocation != null) {
          requestContext
              .getSystemRegistry()
              .createLink(symlinkLocation + resourceName, servicePath);
        }
      }
      // in this flow the resource is already added. marking the process completed..
      requestContext.setProcessingComplete(true);

      if (wsdl != null
          && CommonConstants.ENABLE.equals(
              System.getProperty(CommonConstants.UDDI_SYSTEM_PROPERTY))) {
        AuthToken authToken = UDDIUtil.getPublisherAuthToken();
        if (authToken == null) {
          return;
        }

        // creating the business service info bean
        BusinessServiceInfo businessServiceInfo = new BusinessServiceInfo();
        // Following lines removed  for fixing REGISTRY-1898.
        //              businessServiceInfo.setServiceName(serviceName.trim());
        //              businessServiceInfo.setServiceNamespace(serviceNamespace.trim());
        //
        // businessServiceInfo.setServiceEndpoints(CommonUtil.getEndpointEntries(serviceInfoElement));
        //
        // businessServiceInfo.setDocuments(CommonUtil.getDocLinks(serviceInfoElement));

        businessServiceInfo.setServiceDescription(
            CommonUtil.getServiceDescription(serviceInfoElement));
        WSDLInfo wsdlInfo = wsdl.getMasterWSDLInfo();
        businessServiceInfo.setServiceWSDLInfo(wsdlInfo);
        UDDIPublisher publisher = new UDDIPublisher();
        publisher.publishBusinessService(authToken, businessServiceInfo);
      }

      String path =
          RegistryUtils.getRelativePathToOriginal(
              servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
      ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path);
    } finally {
      CommonUtil.releaseUpdateLock();
    }
  }
Exemple #22
0
  /**
   * @param args
   * @throws RegistryException
   * @throws IOException
   */
  public static void main(String[] args) throws RegistryException, IOException {

    System.setProperty(
        "javax.net.ssl.trustStore",
        "/home/saminda/Downloads/wso2esb-3.0.0-SNAPSHOT/resources/security/client-truststore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    RemoteRegistry registry =
        new RemoteRegistry(new URL("https://localhost:9443/registry"), "admin", "admin");
    Resource resource3 =
        registry.get("/repository/components/org.wso2.carbon.event/index/TopicIndex;version:600");
    new FileOutputStream(new File("/home/saminda/tmp/test123356.txt"))
        .write((byte[]) resource3.getContent());
    System.exit(0);

    //      Map parameters2 = new HashMap();
    //      parameters2.put("query", "SELECT A.REG_PATH_ID, A.REG_NAME FROM REG_RESOURCE A WHERE
    // A.REG_NAME LIKE ?");
    //      parameters2.put("1","%wsdl%");
    //      Resource result2 = registry.executeQuery("/custom-queries3", parameters2);
    //
    //      System.exit(1);
    String sql1 =
        "SELECT A.REG_PATH_ID, A.REG_NAME FROM REG_PATH B, REG_RESOURCE A WHERE ((A.REG_NAME LIKE 'abc') OR ((A.REG_NAME IS NULL) AND (B.REG_PATH_VALUE LIKE 'abc') AND (A.REG_PATH_ID=B.REG_PATH_ID)))";

    Resource q1 = registry.newResource();

    q1.setContent(sql1);

    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);

    q1.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);

    registry.put("/custom-queries", q1);

    // then you should give the parameters and the query location you just put

    Map parameters = new HashMap();

    //        parameters.put("1", "%coll%ctio%");

    Resource result = registry.executeQuery("/custom-queries", parameters);

    String[] paths = (String[]) result.getContent();

    for (String path : paths) {
      System.out.println(path);
    }

    //		ResourceImpl r=(ResourceImpl)registry.get("/AuthenticationAdminService.wsdl");
    ////		System.out.println(r.get);
    //		String[] versions = registry.getVersions("/AuthenticationAdminService.wsdl");
    //		for (String v : versions) {
    //			System.out.println(v);
    //		}
    System.exit(0);

    Resource resource = registry.get("/carbon");
    // ResourceImpl r=(ResourceImpl)resource;

    System.out.println(resource.getMediaType());
    resource.setMediaType("samindaaaaaaaaaaaaa");
    registry.put("/carbon", resource);
    resource = registry.get("/carbon");
    System.out.println(resource.getMediaType());

    System.exit(0);
    File file = new File("/home/saminda/tmp/testexport");
    registry.get("/");
    // RegistryClientUtils.exportFromRegistry(file, "/carbon", registry);

    //		ClientOptions.getClientOptions().setUsername("admin");
    //		ClientOptions.getClientOptions().setPassword("admin");
    //		ClientOptions.getClientOptions().setWorkingDir(file.getAbsolutePath());
    //		ClientOptions.getClientOptions().setRegistryUrl("https://localhost:9445/registry");
    //		ClientOptions.getClientOptions().setCheckoutPath("/carbon");
    //
    ////		ClientOptions.getClientOptions().setUserUrl("https://localhost:9445/registry/carbon");
    //
    //	ClientOptions.getClientOptions().setUserUrl(ClientOptions.getClientOptions().getRegistryUrl()+ClientOptions.getClientOptions().getCheckoutPath());
    //
    //
    //		new Checkout().execute();
    //		Object content = registry.get("/carbon/xslt/LocalEntry.xslt").getContent();
    //		byte[] b=(byte[])content;
    //
    //		FileOutputStream fos = new FileOutputStream("/home/saminda/tmp/abc.txt");
    //		fos.write(b);
    //		fos.close();
    //		String a="/carbon/";
    //		String[] s = a.split("/");
    //		for (String p : s) {
    //			System.out.println(p);
    //		}
  }
  /**
   * 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);
        }
      }
    }
  }
  private TenantRegistrationConfig getTenantSignUpConfig(int tenantId) throws IdentityException {
    TenantRegistrationConfig config;
    NodeList nodes;
    try {
      // start tenant flow to load tenant registry
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
      PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
      Registry registry =
          (Registry)
              PrivilegedCarbonContext.getThreadLocalCarbonContext()
                  .getRegistry(RegistryType.SYSTEM_GOVERNANCE);
      if (registry.resourceExists(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH)) {
        Resource resource = registry.get(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH);
        // build config from tenant registry resource
        DocumentBuilder builder = getSecuredDocumentBuilder();
        String configXml = new String((byte[]) resource.getContent());
        InputSource configInputSource = new InputSource();
        configInputSource.setCharacterStream(new StringReader(configXml.trim()));
        Document doc = builder.parse(configInputSource);
        nodes = doc.getElementsByTagName(SelfRegistrationConstants.SELF_SIGN_UP_ELEMENT);
        if (nodes.getLength() > 0) {
          config = new TenantRegistrationConfig();
          config.setSignUpDomain(
              ((Element) nodes.item(0))
                  .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_DOMAIN_ELEMENT)
                  .item(0)
                  .getTextContent());
          // there can be more than one <SignUpRole> elements, iterate through all elements
          NodeList rolesEl =
              ((Element) nodes.item(0))
                  .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_ROLE_ELEMENT);
          for (int i = 0; i < rolesEl.getLength(); i++) {
            Element tmpEl = (Element) rolesEl.item(i);
            String tmpRole =
                tmpEl
                    .getElementsByTagName(SelfRegistrationConstants.ROLE_NAME_ELEMENT)
                    .item(0)
                    .getTextContent();
            boolean tmpIsExternal =
                Boolean.parseBoolean(
                    tmpEl
                        .getElementsByTagName(SelfRegistrationConstants.IS_EXTERNAL_ELEMENT)
                        .item(0)
                        .getTextContent());
            config.getRoles().put(tmpRole, tmpIsExternal);
          }
          return config;
        } else {
          return null;
        }
      }
    } catch (RegistryException e) {
      throw new IdentityException(
          "Error retrieving sign up config from registry " + e.getMessage(), e);
    } catch (ParserConfigurationException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (SAXException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (IOException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }

    return null;
  }
Exemple #25
0
  @Test(groups = {"wso2.greg"})
  public void AddCommentToResource() throws Exception {
    Resource r1 = registry.newResource();
    byte[] r1content = "R1 content".getBytes();
    r1.setContent(r1content);
    registry.put("/d1/r3", r1);

    String comment1 = "this is qa comment 4";
    String comment2 = "this is qa comment 5";
    Comment c1 = new Comment();
    c1.setResourcePath("/d1/r3");
    c1.setText("This is default comment");
    c1.setUser("admin");

    registry.addComment("/d1/r3", c1);
    registry.addComment("/d1/r3", new Comment(comment1));
    registry.addComment("/d1/r3", new Comment(comment2));

    Comment[] comments = registry.getComments("/d1/r3");

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(comment1)) {
        commentFound = true;

        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        // break;
      }

      if (comment.getText().equals(comment2)) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        // break;
      }

      if (comment.getText().equals("This is default comment")) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        // break;
      }
    }

    assertTrue(
        commentFound, "comment '" + comment1 + " is not associated with the artifact /d1/r3");

    Resource commentsResource = registry.get("/d1/r3;comments");
    assertTrue(
        commentsResource instanceof Collection,
        "Comment collection resource should be a directory.");
    comments = (Comment[]) commentsResource.getContent();

    List commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(new String((byte[]) commentResource.getContent()));
    }

    assertTrue(
        commentTexts.contains(comment1), comment1 + " is not associated for resource /d1/r3.");
    assertTrue(
        commentTexts.contains(comment2), comment2 + " is not associated for resource /d1/r3.");

    /*try {
        //registry.delete("/d12");
    } catch (RegistryException e) {
        fail("Failed to delete test resources.");
    } */
  }
  public void testLifecycle() throws RegistryException {

    Resource r1 = registry.newResource();
    byte[] r1content = RegistryUtils.encodeString("R1 content");
    r1.setContent(r1content);
    registry.put("/d12/r1", r1);

    String text1 = "this can be used as a test resource.";
    String text2 = "I like this";
    final Comment comment1 = new Comment(text1);
    comment1.setUser("someone");
    registry.addComment("/d12/r1", comment1);
    final Comment comment2 = new Comment(text2);
    comment2.setUser("someone");
    registry.addComment("/d12/r1", comment2);

    Comment[] comments = registry.getComments("/d12/r1");
    Assert.assertNotNull(registry.get("/d12/r1").getContent());

    boolean commentFound = false;
    for (Comment comment : comments) {
      if (comment.getText().equals(text1)) {
        commentFound = true;
        break;
      }
    }
    Assert.assertTrue(
        "comment '" + text1 + "' is not associated with the artifact /d12/r1", commentFound);

    Resource commentsResource = registry.get("/d12/r1;comments");
    Assert.assertTrue(
        "Comment collection resource should be a directory.",
        commentsResource instanceof Collection);
    comments = (Comment[]) commentsResource.getContent();

    List commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(commentResource.getContent());
    }

    Assert.assertTrue(
        text1 + " is not associated for resource /d12/r1.", commentTexts.contains(text1));
    Assert.assertTrue(
        text2 + " is not associated for resource /d12/r1.", commentTexts.contains(text2));

    registry.associateAspect("/d12/r1", LIFECYCLE_NAME);

    registry.invokeAspect("/d12/r1", LIFECYCLE_NAME, "promote");

    Resource resource = registry.get("/developed/d12/r1");
    Assert.assertNotNull(resource);
    Assert.assertNotNull(resource.getContent());

    comments = registry.getComments("/developed/d12/r1");

    commentFound = false;
    for (Comment comment : comments) {
      if (comment.getText().equals(text1)) {
        commentFound = true;
        break;
      }
    }
    Assert.assertTrue(
        "comment '" + text1 + "' is not associated with the artifact /developed/d12/r1",
        commentFound);

    commentsResource = registry.get("/developed/d12/r1;comments");
    Assert.assertTrue(
        "Comment collection resource should be a directory.",
        commentsResource instanceof Collection);
    comments = (Comment[]) commentsResource.getContent();

    commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(commentResource.getContent());
    }

    Assert.assertTrue(
        text1 + " is not associated for resource /developed/d12/r1.", commentTexts.contains(text1));
    Assert.assertTrue(
        text2 + " is not associated for resource /developed/d12/r1.", commentTexts.contains(text2));
  }
Exemple #27
0
  @Test(groups = {"wso2.greg"})
  public void AddCommenttoRoot() {

    String comment1 = "this is qa comment 1 for root";
    String comment2 = "this is qa comment 2 for root";

    Comment c1 = new Comment();
    c1.setResourcePath("/");
    c1.setText("This is default comment for root");
    c1.setUser("admin");

    try {
      registry.addComment("/", c1);
      registry.addComment("/", new Comment(comment1));
      registry.addComment("/", new Comment(comment2));
    } catch (RegistryException e) {
      fail("Valid commenting for resources scenario failed");
    }

    Comment[] comments = null;

    try {

      comments = registry.getComments("/");
    } catch (RegistryException e) {
      fail("Failed to get comments for the resource /");
    }

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(comment1)) {
        commentFound = true;

        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        //                //System.out.println("\n");
        // break;
      }

      if (comment.getText().equals(comment2)) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        //                //System.out.println("\n");
        // break;
      }

      if (comment.getText().equals(c1.getText())) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        //                //System.out.println("\n");
        // break;
      }
    }

    assertTrue(commentFound, "comment '" + comment1 + " is not associated with the artifact /");

    try {

      Resource commentsResource = registry.get("/;comments");
      assertTrue(
          commentsResource instanceof Collection,
          "Comment collection resource should be a directory.");
      comments = (Comment[]) commentsResource.getContent();

      List commentTexts = new ArrayList();
      for (Comment comment : comments) {
        Resource commentResource = registry.get(comment.getPath());
        commentTexts.add(new String((byte[]) commentResource.getContent()));
      }

      assertTrue(commentTexts.contains(comment1), comment1 + " is not associated for resource /.");
      assertTrue(commentTexts.contains(comment2), comment2 + " is not associated for resource /.");

    } catch (RegistryException e) {
      fail("Failed to get comments form URL: /;comments");
    }
  }