Exemplo n.º 1
0
 /**
  * Finds all WSDL artifacts on the registry.
  *
  * @return all WSDL artifacts on the registry.
  * @throws GovernanceException if the operation failed.
  */
 public Wsdl[] getAllWsdls() throws GovernanceException {
   List<String> wsdlPaths =
       Arrays.asList(
           GovernanceUtils.getResultPaths(registry, GovernanceConstants.WSDL_MEDIA_TYPE));
   Collections.sort(
       wsdlPaths,
       new Comparator<String>() {
         public int compare(String o1, String o2) {
           // First order by name
           int result =
               RegistryUtils.getResourceName(o1)
                   .compareToIgnoreCase(RegistryUtils.getResourceName(o2));
           if (result != 0) {
             return result;
           }
           // Then order by namespace
           return o1.compareToIgnoreCase(o2);
         }
       });
   List<Wsdl> wsdls = new ArrayList<Wsdl>();
   for (String wsdlPath : wsdlPaths) {
     GovernanceArtifact artifact =
         GovernanceUtils.retrieveGovernanceArtifactByPath(registry, wsdlPath);
     wsdls.add((Wsdl) artifact);
   }
   return wsdls.toArray(new Wsdl[wsdls.size()]);
 }
Exemplo n.º 2
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());
      }
    }
  }
  /**
   * Retrieve all the governance artifacts which associated with the given lifecycle
   *
   * @param lcName Name of the lifecycle
   * @return GovernanceArtifact array
   * @throws GovernanceException
   */
  public GovernanceArtifact[] getAllGovernanceArtifactsByLifecycle(String lcName)
      throws GovernanceException {
    String[] paths = GovernanceUtils.getAllArtifactPathsByLifecycle(registry, lcName, mediaType);
    if (paths == null) {
      return new GovernanceArtifact[0];
    }
    GovernanceArtifact[] artifacts = new GovernanceArtifact[paths.length];
    for (int i = 0; i < paths.length; i++) {
      artifacts[i] = GovernanceUtils.retrieveGovernanceArtifactByPath(registry, paths[i]);
    }

    return artifacts;
  }
 private void addRelationships(String path, GovernanceArtifact artifact) throws RegistryException {
   Map<String, AssociationInteger> typeMap = new LinkedHashMap<String, AssociationInteger>();
   for (Association relationship : relationshipDefinitions) {
     String type = relationship.getAssociationType();
     String source = relationship.getSourcePath();
     String target = relationship.getDestinationPath();
     if (typeMap.containsKey(type)) {
       AssociationInteger associationInteger = typeMap.get(type);
       if (source == null) {
         if (associationInteger.getInteger() < 0) {
           associationInteger.setInteger(0);
         }
         for (String targetPath : GovernanceUtils.getPathsFromPathExpression(target, artifact)) {
           associationInteger.getAssociations().add(new Association(path, targetPath, type));
         }
       } else if (target == null) {
         if (associationInteger.getInteger() > 0) {
           associationInteger.setInteger(0);
         }
         for (String sourcePath : GovernanceUtils.getPathsFromPathExpression(source, artifact)) {
           associationInteger.getAssociations().add(new Association(sourcePath, path, type));
         }
       }
     } else {
       AssociationInteger associationInteger = new AssociationInteger();
       if (source == null) {
         associationInteger.setInteger(1);
         for (String targetPath : GovernanceUtils.getPathsFromPathExpression(target, artifact)) {
           associationInteger.getAssociations().add(new Association(path, targetPath, type));
         }
       } else if (target == null) {
         associationInteger.setInteger(-1);
         for (String sourcePath : GovernanceUtils.getPathsFromPathExpression(source, artifact)) {
           associationInteger.getAssociations().add(new Association(sourcePath, path, type));
         }
       }
       typeMap.put(type, associationInteger);
     }
   }
   for (Map.Entry<String, AssociationInteger> e : typeMap.entrySet()) {
     AssociationInteger value = e.getValue();
     List<Association> associations = value.getAssociations();
     fixAssociations(
         path,
         e.getKey(),
         value.getInteger() >= 0,
         value.getInteger() <= 0,
         associations.toArray(new Association[associations.size()]));
   }
 }
 public void verifyService() throws RegistryException {
   ServiceManager serviceManager = new ServiceManager(governance);
   GovernanceUtils.loadGovernanceArtifacts(
       (UserRegistry) governance,
       GovernanceUtils.findGovernanceArtifactConfigurations(governance));
   Service[] services = serviceManager.getAllServices();
   boolean resourceFound = false;
   for (Service service : services) {
     if (service.getQName().getLocalPart().equals("SimpleStockQuoteService1M")) {
       resourceFound = true;
     }
   }
   Assert.assertTrue(resourceFound);
 }
Exemplo n.º 6
0
  public static void main(String[] args) {
    try {

      setSystemProperties();

      String axis2Configuration =
          System.getProperty("carbon.home")
              + File.separator
              + "repository"
              + File.separator
              + "conf"
              + File.separator
              + "axis2"
              + File.separator
              + "axis2_client.xml";
      ConfigurationContext configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Configuration);

      Registry registry =
          new WSRegistryServiceClient(serverURL, username, password, configContext) {

            public void setCookie(String cookie) {
              CleanUp.cookie = cookie;
              super.setCookie(cookie);
            }
          };
      Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin");
      GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov);
      deleteArtifacts(gov, "wsdl", "wsdl");
      System.out.println("########## Successfully deleted sample wsdls ###########");
      deleteArtifacts(gov, "wadl", "wadl");
      System.out.println("########## Successfully deleted sample wadls ###########");
      deleteArtifacts(gov, "schema", "xsd");
      System.out.println("########## Successfully deleted sample schemas ###########");
      deleteArtifacts(gov, "swagger", "json");
      System.out.println("########## Successfully deleted sample swagger docs ###########");
      deletePolicies(gov);
      System.out.println("########## Successfully deleted sample policies ###########");
      deleteServices(gov, "soapservice");
      System.out.println("########## Successfully deleted sample Soap Services ###########");
      deleteServices(gov, "restservice");
      System.out.println("########## Successfully deleted sample Rest Services ###########");

    } catch (Exception e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
    System.exit(0);
  }
Exemplo n.º 7
0
 /**
  * Create a new WSDL based on content either embedded or passed to a service.
  *
  * @param content the WSDL content
  * @param name the WSDL name
  * @return the artifact added.
  * @throws GovernanceException if the operation failed.
  */
 public Wsdl newWsdl(byte[] content, String name) throws RegistryException {
   String wsdlId = UUID.randomUUID().toString();
   Wsdl wsdl = new Wsdl(wsdlId, name != null ? "name://" + name : null);
   wsdl.associateRegistry(registry);
   wsdl.setWsdlElement(GovernanceUtils.buildOMElement(content));
   return wsdl;
 }
  /**
   * Finds all artifacts of a given type on the registry.
   *
   * @return all artifacts of the given type on the registry.
   * @throws GovernanceException if the operation failed.
   */
  public GovernanceArtifact[] getAllGovernanceArtifacts() throws GovernanceException {
    List<String> paths = getPaginatedGovernanceArtifacts();

    GovernanceArtifact[] artifacts = new GovernanceArtifact[paths.size()];
    for (int i = 0; i < paths.size(); i++) {
      artifacts[i] = GovernanceUtils.retrieveGovernanceArtifactByPath(registry, paths.get(i));
    }
    return artifacts;
  }
Exemplo n.º 9
0
 /**
  * Fetches the given WSDL artifact on the registry.
  *
  * @param wsdlId the identifier of the WSDL artifact.
  * @return the WSDL artifact.
  * @throws GovernanceException if the operation failed.
  */
 public Wsdl getWsdl(String wsdlId) throws GovernanceException {
   GovernanceArtifact artifact = GovernanceUtils.retrieveGovernanceArtifactById(registry, wsdlId);
   if (artifact != null && !(artifact instanceof Wsdl)) {
     String msg = "The artifact request is not a Wsdl. id: " + wsdlId + ".";
     log.error(msg);
     throw new GovernanceException(msg);
   }
   return (Wsdl) artifact;
 }
  @Test(
      groups = "wso2.greg",
      description = "Upload CApp as Service",
      dependsOnMethods = "cAppWithIncorrectServerRole")
  public void deployNewCApplication()
      throws MalformedURLException, RemoteException, ApplicationAdminExceptionException,
          InterruptedException, RegistryException, ResourceAdminServiceExceptionException,
          LogViewerLogViewerException {

    String resourcePath =
        FrameworkPathUtil.getSystemResourceLocation()
            + "artifacts"
            + File.separator
            + "GREG"
            + File.separator
            + "car"
            + File.separator
            + "wsdl-t_1.0.0.car";

    cAppUploader.uploadCarbonAppArtifact(
        "wsdl-t_1.0.0.car", new DataHandler(new URL("file:///" + resourcePath)));

    assertTrue(
        CAppTestUtils.isCAppDeployed(sessionCookie, wsdl_tCapp, adminServiceApplicationAdmin),
        "Deployed wsdl-t_1.0.0.car not in CApp List");

    LogEvent[] logEvents =
        logViewerClient.getLogs(
            "INFO", "Successfully Deployed Carbon Application : wsdl-t", "", "");

    boolean status = false;
    for (LogEvent event : logEvents) {
      if (event.getMessage().contains("Successfully Deployed Carbon Application : wsdl-t")) {
        status = true;
        break;
      }
    }
    assertTrue(status, "Log info message for cApp deployment not found");

    boolean isService = false;

    //
    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) governance);
    GenericArtifactManager manager = new GenericArtifactManager(governance, "service");

    GenericArtifact[] serviceArtifacts = manager.getAllGenericArtifacts();

    for (GenericArtifact genericArtifact : serviceArtifacts) {
      String name = genericArtifact.getQName().getLocalPart();
      if (name.equalsIgnoreCase("WeatherForecastService")) {
        isService = true;
        break;
      }
    }
    assertTrue(isService);
  }
 @Test(
     groups = {"wso2.greg"},
     description = "edit uri",
     dependsOnMethods = {"testAddTag"})
 public void testEditURI() throws RegistryException {
   GovernanceUtils.loadGovernanceArtifacts((UserRegistry) governance);
   GenericArtifactManager artifactManager = new GenericArtifactManager(governance, "uri");
   GenericArtifact artifact = artifactManager.getGenericArtifact(uriID);
   artifact.addAttribute("overview_description", utfString);
   Assert.assertTrue(artifact.getAttribute("overview_description").equals(utfString));
 }
  @Test(groups = "wso2.greg", dependsOnMethods = "testAddRxt")
  public void testAddResourceThroughRxt() throws RegistryException {
    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) governance);
    GenericArtifactManager artifactManager = new GenericArtifactManager(governance, "person");
    GenericArtifact artifact = artifactManager.newGovernanceArtifact(new QName("testPerson"));

    artifact.setAttribute("ID", "Person_id");
    artifact.setAttribute("Name", "Person_Name");

    artifactManager.addGenericArtifact(artifact);

    assertTrue(artifact.getQName().toString().contains("testPerson"), "artifact name not found");
  }
 private GovernanceArtifact findMatchingArtifact(RBGGovernanceArtifact ga) {
   GovernanceArtifact ret = null;
   String matcher = getArtifactPath(ga);
   try {
     if (registryFactory.getRemoteRegistryInstance().resourceExists(matcher)) {
       ret =
           GovernanceUtils.retrieveGovernanceArtifactByPath(
               registryFactory.getRemoteRegistryInstance(), matcher);
     }
   } catch (RegistryException e) {
     log.error(e.getMessage());
   }
   return ret;
 }
Exemplo n.º 14
0
 /**
  * Finds all artifacts matching the given filter criteria.
  *
  * @param criteria the filter criteria to be matched.
  * @return the artifacts that match.
  * @throws GovernanceException if the operation failed.
  */
 public GovernanceArtifact[] findGovernanceArtifacts(Map<String, List<String>> criteria)
     throws GovernanceException {
   List<GovernanceArtifact> artifacts;
   artifacts =
       GovernanceUtils.findGovernanceArtifacts(
           criteria != null ? criteria : Collections.<String, List<String>>emptyMap(),
           registry,
           mediaType);
   if (artifacts != null) {
     return artifacts.toArray(new GovernanceArtifact[artifacts.size()]);
   } else {
     return new GovernanceArtifact[0];
   }
 }
  public String addURI(String name, String uri, String type) throws RegistryException {
    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) governance);
    GenericArtifactManager artifactManager = new GenericArtifactManager(governance, "uri");
    GenericArtifact artifact = artifactManager.newGovernanceArtifact(new QName(name));

    artifact.setAttribute("overview_uri", uri);

    artifact.setAttribute("overview_type", type);
    artifactManager.addGenericArtifact(artifact);
    uriID = artifact.getId();
    assertTrue(artifact.getAttribute("overview_uri").equals(uri), "artifact URI not found");
    assertTrue(artifact.getAttribute("overview_name").equals(name), "artifact name not found");
    assertTrue(artifact.getAttribute("overview_type").equals(type), "artifact WSDL not found");

    return artifact.getPath();
  }
  @BeforeClass(alwaysRun = true)
  public void init() throws Exception {

    super.init(TestUserMode.SUPER_TENANT_USER);
    String sessionCookie = getSessionCookie();
    lifeCycleAdminServiceClient = new LifeCycleAdminServiceClient(backendURL, sessionCookie);
    governanceServiceClient = new GovernanceServiceClient(backendURL, sessionCookie);
    listMetadataServiceClient = new ListMetaDataServiceClient(backendURL, sessionCookie);
    lifeCycleManagementClient = new LifeCycleManagementClient(backendURL, sessionCookie);
    resourceAdminServiceClient = new ResourceAdminServiceClient(backendURL, sessionCookie);
    wsRegistryServiceClient = registryProviderUtil.getWSRegistry(automationContext);
    Registry reg =
        registryProviderUtil.getGovernanceRegistry(
            new RegistryProviderUtil().getWSRegistry(automationContext), automationContext);
    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) reg);
    serviceManager = new ServiceManager(reg);

    String userName = automationContext.getContextTenant().getContextUser().getUserName();
    userName1WithoutDomain = userName.substring(0, userName.indexOf('@'));
  }
Exemplo n.º 17
0
  private static void deletePolicies(Registry govRegistry)
      throws FileNotFoundException, IOException, RegistryException, GovernanceException {
    GenericArtifactManager manager = new GenericArtifactManager(govRegistry, "policy");

    for (int i = 1; i < 23; i++) {
      final String name = "policy" + i + ".xml";
      GenericArtifact[] artifacts =
          manager.findGenericArtifacts(
              new GenericArtifactFilter() {

                @Override
                public boolean matches(GenericArtifact genericArtifact) throws GovernanceException {
                  return name.equals(genericArtifact.getQName().getLocalPart());
                }
              });
      for (GenericArtifact genericArtifact : artifacts) {
        GovernanceUtils.removeArtifact(govRegistry, genericArtifact.getId());
      }
    }
  }
  /**
   * @throws RemoteException
   * @throws LoginAuthenticationExceptionException
   * @throws RegistryException
   */
  @BeforeClass(alwaysRun = true)
  public void init()
      throws RemoteException, LoginAuthenticationExceptionException, RegistryException {
    EnvironmentBuilder builder = new EnvironmentBuilder().greg(userId);
    ManageEnvironment environment = builder.build();

    lifeCycleAdminServiceClient =
        new LifeCycleAdminServiceClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    governanceServiceClient =
        new GovernanceServiceClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    listMetadataServiceClient =
        new ListMetaDataServiceClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    lifeCycleManagementClient =
        new LifeCycleManagementClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    userManagementClient =
        new UserManagementClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    resourceAdminServiceClient =
        new ResourceAdminServiceClient(
            environment.getGreg().getProductVariables().getBackendUrl(),
            environment.getGreg().getSessionCookie());
    wsRegistryServiceClient =
        registryProviderUtil.getWSRegistry(userId, ProductConstant.GREG_SERVER_NAME);

    Registry reg =
        registryProviderUtil.getGovernanceRegistry(
            new RegistryProviderUtil().getWSRegistry(userId, ProductConstant.GREG_SERVER_NAME),
            userId);
    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) reg);
    serviceManager = new ServiceManager(reg);
  }
  @AfterClass(alwaysRun = true)
  public void clean() throws Exception {
    delete(pathPrefix + uriSchemaPath);

    GovernanceUtils.loadGovernanceArtifacts((UserRegistry) governance);
    GenericArtifactManager artifactManager = new GenericArtifactManager(governance, "uri");
    GenericArtifact[] artifacts = artifactManager.getAllGenericArtifacts();
    boolean uriDeleted = true;
    for (GenericArtifact genericArtifact : artifacts) {
      if (genericArtifact.getPath().equals(pathPrefix + uriSchemaPath)) {
        uriDeleted = false;
      }
    }
    Assert.assertTrue(uriDeleted);
    delete(pathPrefix + uriWsdlPath);
    delete(pathPrefix + uriGenericPath);
    delete(pathPrefix + uriPolicyPath);
    delete("/_system/governance/trunk/services/com/amazon/soap/1.0.0/AmazonSearchService");
    userManagementClient.deleteRole(utfString);
    lifeCycleManagementClient.deleteLifeCycle(LC_NAME);
    delete("/_system/governance/trunk/endpoints/com/amazon/soap/onca/ep-soap2");
    delete("/_system/governance/trunk/endpoints/com");

    utfString = null;
    governance = null;
    resourceAdminServiceClient = null;
    uriGenericPath = null;
    uriPolicyPath = null;
    uriSchemaPath = null;
    uriWsdlPath = null;
    relationAdminServiceClient = null;
    lifeCycleManagementClient = null;
    lifeCycleAdminServiceClient = null;
    wsRegistryServiceClient = null;
    registryProviderUtil = null;
    infoServiceAdminClient = null;
    userManagementClient = null;
  }
Exemplo n.º 20
0
  @Paginate("getPaginatedGovernanceArtifacts")
  public List<String> getPaginatedGovernanceArtifacts() throws GovernanceException {
    List<String> paths = Arrays.asList(GovernanceUtils.getResultPaths(registry, mediaType));
    Collections.sort(
        paths,
        new Comparator<String>() {
          public int compare(String o1, String o2) {
            Long l1 = -1l;
            Long l2 = -1l;

            String temp1 = RegistryUtils.getParentPath(o1);
            String temp2 = RegistryUtils.getParentPath(o2);
            try {
              l1 = Long.parseLong(RegistryUtils.getResourceName(temp1));
              l2 = Long.parseLong(RegistryUtils.getResourceName(temp2));
            } catch (NumberFormatException ignore) {

            }

            // First order by name
            int result =
                RegistryUtils.getResourceName(temp1)
                    .compareToIgnoreCase(RegistryUtils.getResourceName(temp2));
            if (result != 0) {
              return result;
            }
            // Then order by namespace
            result = temp1.compareToIgnoreCase(temp2);
            if (result != 0) {
              return result;
            }
            // Finally by version
            return l2.compareTo(l1);
          }
        });
    return paths;
  }
Exemplo n.º 21
0
 public static void buildMenuItems(HttpServletRequest request, String s, String s1, String s2) {
   int menuOrder = 50;
   if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) {
     HttpSession session = request.getSession();
     String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
     try {
       WSRegistryServiceClient registry = new WSRegistryServiceClient(s2, cookie);
       List<GovernanceArtifactConfiguration> configurations =
           GovernanceUtils.findGovernanceArtifactConfigurations(registry);
       Map<String, String> customAddUIMap = new LinkedHashMap<String, String>();
       Map<String, String> customViewUIMap = new LinkedHashMap<String, String>();
       List<Menu> userCustomMenuItemsList = new LinkedList<Menu>();
       for (GovernanceArtifactConfiguration configuration : configurations) {
         Component component = new Component();
         OMElement uiConfigurations = configuration.getUIConfigurations();
         String key = configuration.getKey();
         String configurationPath =
             RegistryConstants.CONFIG_REGISTRY_BASE_PATH
                 + RegistryConstants.GOVERNANCE_COMPONENT_PATH
                 + "/configuration/";
         String layoutStoragePath = configurationPath + key;
         RealmService realmService = registry.getRegistryContext().getRealmService();
         if (realmService
                 .getTenantUserRealm(realmService.getTenantManager().getTenantId(s1))
                 .getAuthorizationManager()
                 .isUserAuthorized(s, configurationPath, ActionConstants.PUT)
             || registry.resourceExists(layoutStoragePath)) {
           List<Menu> menuList = component.getMenusList();
           if (uiConfigurations != null) {
             ComponentBuilder.processMenus("artifactType", uiConfigurations, component);
             ComponentBuilder.processCustomUIs(uiConfigurations, component);
           }
           if (menuList.size() == 0) {
             // if no menu definitions were present, define the default ones.
             menuOrder = buildMenuList(request, configuration, menuList, key, menuOrder);
           }
           userCustomMenuItemsList.addAll(menuList);
           customAddUIMap.putAll(component.getCustomAddUIMap());
           Map<String, String> viewUIMap = component.getCustomViewUIMap();
           if (viewUIMap.isEmpty()) {
             // if no custom UI definitions were present, define the default.
             buildViewUI(configuration, viewUIMap, key);
           }
           customViewUIMap.putAll(viewUIMap);
           OMElement layout = configuration.getContentDefinition();
           if (layout != null && !registry.resourceExists(layoutStoragePath)) {
             Resource resource = registry.newResource();
             resource.setContent(RegistryUtils.encodeString(layout.toString()));
             resource.setMediaType("application/xml");
             registry.put(layoutStoragePath, resource);
           }
         }
       }
       session.setAttribute(
           MenuAdminClient.USER_CUSTOM_MENU_ITEMS,
           userCustomMenuItemsList.toArray(new Menu[userCustomMenuItemsList.size()]));
       session.setAttribute("customAddUI", customAddUIMap);
       session.setAttribute("customViewUI", customViewUIMap);
     } catch (RegistryException e) {
       log.error("unable to create connection to registry");
     } catch (org.wso2.carbon.user.api.UserStoreException e) {
       log.error("unable to realm service");
     }
   }
 }
Exemplo n.º 22
0
  /**
   * 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);
        }
      }
    }
  }
Exemplo n.º 23
0
  /**
   * 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);
        }
      }
    }
  }
  public ByteArrayOutputStream execute(String template, String type) throws IOException {
    Registry governanceRegistry;

    try {
      Registry registry = getRegistry();
      governanceRegistry =
          GovernanceUtils.getGovernanceUserRegistry(registry, CurrentSession.getUser());
      GenericArtifactManager suiteArtifactManager =
          new GenericArtifactManager(governanceRegistry, "suites");
      GenericArtifact[] genericArtifacts = suiteArtifactManager.getAllGenericArtifacts();
      GenericArtifactManager caseArtifactManager =
          new GenericArtifactManager(governanceRegistry, "case");
      List<TestSuiteReportBean> beanList = new LinkedList<TestSuiteReportBean>();
      for (GenericArtifact artifact : genericArtifacts) {
        TestSuiteReportBean bean = new TestSuiteReportBean();
        String[] attributeKeys = artifact.getAttributeKeys();
        List<String> testCases = new ArrayList<String>();
        for (String key : attributeKeys) {
          if (key.equals("overview_name")) {
            String value = artifact.getAttribute(key);
            bean.setOverview_name(value);
          } else if (key.equals("overview_version")) {
            String value = artifact.getAttribute(key);
            bean.setOverview_version(value);
          } else if (key.equals("overview_type")) {
            String value = artifact.getAttribute(key);
            bean.setOverview_type(value);
          }
          if (key.equals("testCases_entry")) {
            String[] values = artifact.getAttributes(key);
            for (String value : values) {
              Resource r =
                  registry.get(
                      RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + value.split(":")[1]);
              GenericArtifact a = caseArtifactManager.getGenericArtifact(r.getUUID());
              testCases.add(a.getAttribute("overview_name"));
            }
          }
        }
        bean.setTestCases_entry(testCases.toString().replaceAll("[ \\[\\] ]", ""));
        beanList.add(bean);
      }

      String templateContent = new String((byte[]) registry.get(template).getContent());

      JRDataSource dataSource = new JRBeanCollectionDataSource(beanList);
      JasperPrint print =
          new JasperPrintProvider()
              .createJasperPrint(dataSource, templateContent, new ReportParamMap[0]);
      return new ReportStream().getReportStream(print, type.toLowerCase());

    } catch (RegistryException e) {
      log.error("Error while getting the Governance Registry", e);
    } catch (JRException e) {
      log.error("Error occured while creating the jasper print ", e);
    } catch (ReportingException e) {
      log.error("Error while generating the report", e);
    }

    return new ByteArrayOutputStream(0);
  }
Exemplo n.º 25
0
 /**
  * Fetches the given artifact on the registry.
  *
  * @param artifactId the identifier of the artifact.
  * @return the artifact.
  * @throws GovernanceException if the operation failed.
  */
 public GovernanceArtifact getGovernanceArtifact(String artifactId) throws GovernanceException {
   return GovernanceUtils.retrieveGovernanceArtifactById(registry, artifactId);
 }
Exemplo n.º 26
0
 /**
  * Removes the given artifact from the registry.
  *
  * @param artifactId the identifier of the artifact.
  * @throws GovernanceException if the operation failed.
  */
 public void removeGovernanceArtifact(String artifactId) throws GovernanceException {
   GovernanceUtils.removeArtifact(registry, artifactId);
 }
Exemplo n.º 27
0
  /**
   * 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);
    }
  }
  @Test(groups = {"wso2.greg"})
  public void testPaginate() throws Exception {
    try {
      Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin");
      // Should be load the governance artifact.
      GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov);
      addServices(gov);
      // Initialize the pagination context.
      // Top five services, sortBy name , and sort order descending.
      PaginationContext.init(0, 5, "DES", "overview_name", 100);
      WSRegistrySearchClient wsRegistrySearchClient = new WSRegistrySearchClient();
      // This should be execute to initialize the AttributeSearchService.
      ConfigurationContext configContext;
      String axis2Repo = FrameworkPathUtil.getSystemResourceLocation() + "client";
      String axis2Conf =
          FrameworkPathUtil.getSystemResourceLocation()
              + "axis2config"
              + File.separator
              + "axis2_client.xml";
      TestFrameworkUtils.setKeyStoreProperties(automationContext);
      configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(
              axis2Repo, axis2Conf);
      configContext.setProperty(HTTPConstants.CONNECTION_TIMEOUT, TIME_OUT_VALUE);

      wsRegistrySearchClient.init(cookie, backendURL, configContext);

      //            wsRegistrySearchClient.authenticate(configContext, getServiceURL(),
      //                    automationContext.getContextTenant().getContextUser().getUserName(),
      //                    automationContext.getContextTenant().getContextUser().getPassword());

      // Initialize the GenericArtifactManager
      GenericArtifactManager artifactManager = new GenericArtifactManager(gov, "service");
      Map<String, List<String>> listMap = new HashMap<String, List<String>>();
      // Create the search attribute map
      listMap.put(
          "lcName",
          new ArrayList<String>() {
            {
              add("ServiceLifeCycle");
            }
          });
      listMap.put(
          "lcState",
          new ArrayList<String>() {
            {
              add("Development");
            }
          });
      // Find the results.
      GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
      assertTrue(genericArtifacts.length > 0, "No any service found");
      assertTrue(genericArtifacts.length == 5, "Filtered service count should be 5");
      assertTrue(
          genericArtifacts[0].getQName().getLocalPart().equals("FlightService9"),
          "filter results are not sorted");
      assertTrue(
          genericArtifacts[4].getQName().getLocalPart().equals("FlightService5"),
          "filter results are not sorted");
    } finally {
      PaginationContext.destroy();
    }
  }
Exemplo n.º 29
0
 /**
  * Removes the given WSDL artifact from the registry.
  *
  * @param wsdlId the identifier of the WSDL artifact.
  * @throws GovernanceException if the operation failed.
  */
 public void removeWsdl(String wsdlId) throws GovernanceException {
   GovernanceUtils.removeArtifact(registry, wsdlId);
 }
Exemplo n.º 30
0
 /**
  * Sets content of the given WSDL artifact to the given resource on the registry.
  *
  * @param wsdl the WSDL artifact.
  * @param wsdlResource the content resource.
  * @throws GovernanceException if the operation failed.
  */
 protected void setContent(Wsdl wsdl, Resource wsdlResource) throws GovernanceException {
   if (wsdl.getWsdlElement() != null) {
     OMElement contentElement = wsdl.getWsdlElement().cloneOMElement();
     try {
       for (String importType : new String[] {"import", "include"}) {
         List<OMElement> wsdlImports =
             GovernanceUtils.evaluateXPathToElements("//wsdl:" + importType, contentElement);
         for (OMElement wsdlImport : wsdlImports) {
           OMAttribute location = wsdlImport.getAttribute(new QName("location"));
           if (location != null) {
             String path = location.getAttributeValue();
             if (path.indexOf(";version:") > 0) {
               location.setAttributeValue(path.substring(0, path.lastIndexOf(";version:")));
             }
           }
         }
       }
       for (String importType : new String[] {"import", "include", "redefine"}) {
         List<OMElement> schemaImports =
             GovernanceUtils.evaluateXPathToElements("//xsd:" + importType, contentElement);
         for (OMElement schemaImport : schemaImports) {
           OMAttribute location = schemaImport.getAttribute(new QName("schemaLocation"));
           if (location != null) {
             String path = location.getAttributeValue();
             if (path.indexOf(";version:") > 0) {
               location.setAttributeValue(path.substring(0, path.lastIndexOf(";version:")));
             }
           }
         }
       }
     } catch (JaxenException ignore) {
     }
     String wsdlContent = contentElement.toString();
     try {
       wsdlResource.setContent(wsdlContent);
     } catch (RegistryException e) {
       String msg =
           "Error in setting the content from wsdl, wsdl id: "
               + wsdl.getId()
               + ", wsdl path: "
               + wsdl.getPath()
               + ".";
       log.error(msg, e);
       throw new GovernanceException(msg, e);
     }
   }
   // and set all the attributes as properties.
   String[] attributeKeys = wsdl.getAttributeKeys();
   if (attributeKeys != null) {
     Properties properties = new Properties();
     for (String attributeKey : attributeKeys) {
       String[] attributeValues = wsdl.getAttributes(attributeKey);
       if (attributeValues != null) {
         // The list obtained from the Arrays#asList method is
         // immutable. Therefore,
         // we create a mutable object out of it before adding it as
         // a property.
         properties.put(attributeKey, new ArrayList<String>(Arrays.asList(attributeValues)));
       }
     }
     wsdlResource.setProperties(properties);
   }
   wsdlResource.setUUID(wsdl.getId());
 }