public static CQLQuery checkDefaultPredicates(CQLQuery original) throws Exception {
   LOG.debug("Checking query for Attributes with no predicate defined");
   StringWriter originalWriter = new StringWriter();
   Utils.serializeObject(original, DataServiceConstants.CQL_QUERY_QNAME, originalWriter);
   Element root =
       XMLUtilities.stringToDocument(originalWriter.getBuffer().toString()).getRootElement();
   Filter attributeNoPredicateFilter =
       new Filter() {
         public boolean matches(Object o) {
           if (o instanceof Element) {
             Element e = (Element) o;
             if (e.getName().equals("Attribute") && e.getAttribute("predicate") == null) {
               return true;
             }
           }
           return false;
         }
       };
   List<?> attributesWithNoPredicate = root.getContent(attributeNoPredicateFilter);
   Iterator<?> attribIter = attributesWithNoPredicate.iterator();
   while (attribIter.hasNext()) {
     LOG.debug("Adding default predicate to an attribute");
     Element elem = (Element) attribIter.next();
     elem.setAttribute("predicate", "EQUAL_TO");
   }
   String xml = XMLUtilities.elementToString(root);
   CQLQuery edited = Utils.deserializeObject(new StringReader(xml), CQLQuery.class);
   return edited;
 }
 @Override
 protected void storyTearDown() throws Throwable {
   super.storyTearDown();
   if (TEST_DIR.exists()) {
     Utils.deleteDir(TEST_DIR);
   }
 }
 protected void writeOutAuditorConfiguration(Data extData, ServiceInformation serviceInfo)
     throws CodegenExtensionException {
   if (CommonTools.servicePropertyExists(
       serviceInfo.getServiceDescriptor(),
       DataServiceConstants.DATA_SERVICE_AUDITORS_CONFIG_FILE_PROPERTY)) {
     try {
       // get the name of the auditor config file
       String filename =
           CommonTools.getServicePropertyValue(
               serviceInfo.getServiceDescriptor(),
               DataServiceConstants.DATA_SERVICE_AUDITORS_CONFIG_FILE_PROPERTY);
       if (extData.getDataServiceAuditors() != null) {
         File outFile =
             new File(
                 serviceInfo.getBaseDirectory().getAbsolutePath()
                     + File.separator
                     + "etc"
                     + File.separator
                     + filename);
         FileWriter writer = new FileWriter(outFile);
         Utils.serializeObject(
             extData.getDataServiceAuditors(),
             DataServiceConstants.DATA_SERVICE_AUDITORS_QNAME,
             writer);
         writer.flush();
         writer.close();
       }
     } catch (Exception ex) {
       ex.printStackTrace();
       throw new CodegenExtensionException(
           "Error writing auditor configuration: " + ex.getMessage(), ex);
     }
   }
 }
Exemplo n.º 4
0
  public void storyTearDown() throws Throwable {
    List<Throwable> errors = new LinkedList<Throwable>();
    try {
      new StopContainerStep(container).runStep();
    } catch (Throwable th) {
      errors.add(th);
    }
    try {
      new DestroyContainerStep(container).runStep();
    } catch (Throwable th) {
      errors.add(th);
    }
    try {
      // System.out.println("Data Service in " + testInfo.getDir());
      Utils.deleteDir(new File(testInfo.getDir()));
    } catch (Throwable th) {
      errors.add(th);
    }

    if (errors.size() != 0) {
      System.err.println("EXCEPTION(S) OCCURED DURING TEAR DOWN:");
      for (Throwable t : errors) {
        System.err.println("----------------");
        t.printStackTrace();
      }
      throw new Exception("EXCEPTION(S) OCCURED DURING TEAR DOWN.  SEE LOGS");
    }
  }
Exemplo n.º 5
0
  private void addUpdatePrivileges() {
    try {

      String id = Utils.clean(getIdentity().getText());
      if (id == null) {
        ErrorDialog.showError("Please enter a valid identity!!!");
      }
      boolean reload = false;
      StringBuffer sb = new StringBuffer();
      sb.append("Updating the privileges resulted in the following:\n");
      String s1 = addUpdateCreate();
      if (s1 != null) {
        reload = true;
        sb.append(s1 + "\n");
      }
      String s2 = addUpdateStem();
      if (s2 != null) {
        reload = true;
        sb.append(s2);
      }

      dispose();

      if (reload) {
        browser.loadPrivileges();
      }
      GridApplication.getContext().showMessage(sb.toString());
    } catch (Exception e) {
      ErrorDialog.showError(e);
      FaultUtil.logFault(log, e);
    }
  }
Exemplo n.º 6
0
 private void createGallery() {
   String name = this.getGalleryNane().getText();
   if (Utils.clean(name) == null) {
     ErrorDialog.showError("You must specify a gallery name.");
     return;
   }
   try {
     getProgress().showProgress("Creating gallery...");
     PhotoSharingHandle handle = this.root.getServiceHandle();
     handle.createGallery(name);
     this.root.refresh();
     getProgress().stopProgress();
     dispose();
   } catch (Exception e) {
     ErrorDialog.showError(Utils.getExceptionMessage(e), e);
   }
 }
 public void setAssertingCredentialsEncryptionPassword(
     String assertingCredentialsEncryptionPassword) throws DorianInternalFault {
   if (Utils.clean(assertingCredentialsEncryptionPassword) == null) {
     DorianInternalFault f = new DorianInternalFault();
     f.setFaultString("Invalid asserting credentials password specified.");
     throw f;
   }
   this.assertingCredentialsEncryptionPassword = assertingCredentialsEncryptionPassword;
 }
Exemplo n.º 8
0
 public void setAssertingCredentialsEncryptionPassword(
     String assertingCredentialsEncryptionPassword) throws DorianInternalException {
   if (Utils.clean(assertingCredentialsEncryptionPassword) == null) {
     DorianInternalException f =
         FaultHelper.createFaultException(
             DorianInternalException.class, "Invalid asserting credentials password specified.");
     throw f;
   }
   this.assertingCredentialsEncryptionPassword = assertingCredentialsEncryptionPassword;
 }
Exemplo n.º 9
0
  private void addInstanceCountResourceProperty() throws UpgradeException {
    // get the schemas dir so we can copy in the new XSD
    File dataSchemasDir = getDataSchemaDir();
    File instanceCountXsd = new File(dataSchemasDir, MetadataConstants.DATA_INSTANCE_XSD);

    // get the service's schema dir where the wsdl files live
    ServiceType baseService = getServiceInformation().getServices().getService(0);
    String serviceName = baseService.getName();
    File serviceSchemasDir = new File(getServicePath(), "schema" + File.separator + serviceName);

    // copy the schema
    File instanceCountXsdOut = new File(serviceSchemasDir, instanceCountXsd.getName());
    try {
      Utils.copyFile(instanceCountXsd, instanceCountXsdOut);
    } catch (Exception ex) {
      throw new UpgradeException(
          "Error copying data instance counts schema: " + ex.getMessage(), ex);
    }

    // add the schema to the service descriptor
    NamespaceType countNamespace = null;
    try {
      countNamespace =
          CommonTools.createNamespaceType(instanceCountXsdOut.getAbsolutePath(), serviceSchemasDir);
    } catch (Exception ex) {
      throw new UpgradeException(
          "Error creating data instance counts namespace: " + ex.getMessage(), ex);
    }
    countNamespace.setPackageName(MetadataConstants.DATA_INSTANCE_PACKAGE);
    countNamespace.setGenerateStubs(Boolean.FALSE);
    CommonTools.addNamespace(getServiceInformation().getServiceDescriptor(), countNamespace);

    if (CommonTools.getResourcePropertiesOfType(baseService, MetadataConstants.DATA_INSTANCE_QNAME)
            .length
        == 0) {
      // no resource property found, so we have to create and add it
      ResourcePropertyType countRp = new ResourcePropertyType();
      countRp.setRegister(true);
      countRp.setDescription(MetadataConstants.DATA_INSTANCE_DESCRIPTION);
      countRp.setQName(MetadataConstants.DATA_INSTANCE_QNAME);
      CommonTools.addResourcePropety(baseService, countRp);
    }

    // instance count frequency property
    if (!CommonTools.servicePropertyExists(
        getServiceInformation().getServiceDescriptor(),
        InstanceCountConstants.COUNT_UPDATE_FREQUENCY)) {
      CommonTools.setServiceProperty(
          getServiceInformation().getServiceDescriptor(),
          InstanceCountConstants.COUNT_UPDATE_FREQUENCY,
          InstanceCountConstants.COUNT_UPDATE_FREQUENCY_DEFAULT,
          false,
          InstanceCountConstants.COUNT_UPDATE_FREQUENCY_DESCRIPTION);
    }
  }
Exemplo n.º 10
0
 private void storeExtensionDataElement(Element elem) throws UpgradeException {
   MessageElement[] anys = getExtensionType().getExtensionData().get_any();
   for (int i = 0; (anys != null) && (i < anys.length); i++) {
     if (anys[i].getQName().equals(Data.getTypeDesc().getXmlType())) {
       // remove the old extension data
       anys = (MessageElement[]) Utils.removeFromArray(anys, anys[i]);
       break;
     }
   }
   // create a message element from the JDom element
   MessageElement data = null;
   try {
     data = AxisJdomUtils.fromElement(elem);
   } catch (JDOMException ex) {
     throw new UpgradeException(
         "Error converting extension data to Axis message element: " + ex.getMessage(), ex);
   }
   anys = (MessageElement[]) Utils.appendToArray(anys, data);
   getExtensionType().getExtensionData().set_any(anys);
 }
 private CQLQuery loadQuery(String queryFilename) {
   CQLQuery query = null;
   File queryFile = new File(TEST_QUERIES_DIR, queryFilename);
   try {
     FileReader reader = new FileReader(queryFile);
     query = (CQLQuery) Utils.deserializeObject(reader, CQLQuery.class);
   } catch (Exception ex) {
     ex.printStackTrace();
     fail("Error loading query " + queryFilename + ": " + ex.getMessage());
   }
   return query;
 }
Exemplo n.º 12
0
  /**
   * getRegistration reads the XML file and creates a registration object from it for testing
   *
   * <p>
   *
   * @return
   * @throws DeserializationException
   * @throws SAXException
   */
  private Registration getRegistration()
      throws DeserializationException, SAXException, IOException {
    // InputStream sampleIs = getClass().getResourceAsStream(sampleFile);
    InputStream sampleIs = new FileInputStream(sampleFile);
    InputStreamReader reader = new InputStreamReader(sampleIs);
    InputStream wsddIs =
        getClass().getResourceAsStream("/gov/nih/nci/ccts/grid/client/client-config.wsdd");

    Registration reg =
        (gov.nih.nci.cabig.ccts.domain.Registration)
            Utils.deserializeObject(
                reader, gov.nih.nci.cabig.ccts.domain.Registration.class, wsddIs);

    return reg;
  }
Exemplo n.º 13
0
 private void loadServiceMetadataFromFile() {
   try {
     File dataFile =
         new File(
             ContainerConfig.getBaseDirectory()
                 + File.separator
                 + getConfiguration().getServiceMetadataFile());
     this.serviceMetadataMD =
         (gov.nih.nci.cagrid.metadata.ServiceMetadata)
             Utils.deserializeDocument(
                 dataFile.getAbsolutePath(), gov.nih.nci.cagrid.metadata.ServiceMetadata.class);
   } catch (Exception e) {
     logger.error("ERROR: problem populating metadata from file: " + e.getMessage(), e);
   }
 }
  private void findCertificates() {
    try {
      showProgess("Searching...");
      getUserCertificates().clearTable();
      UserCertificateFilter f = new UserCertificateFilter();
      f.setGridIdentity(Utils.clean(getGridIdentity().getText()));
      if (Utils.clean(getUserCertificateSerialNumber().getText()) != null) {
        try {
          f.setSerialNumber(Long.valueOf(Utils.clean(getUserCertificateSerialNumber().getText())));
        } catch (NumberFormatException e) {
          stopProgess("Error");
          enableButtons();
          ErrorDialog.showError("The serial number must be an integer.");
          return;
        }
      }
      if ((searchStartDate != null) && (searchEndDate != null)) {
        if (searchStartDate.after(searchEndDate)) {
          stopProgess("Error");
          enableButtons();
          ErrorDialog.showError("The start date cannot be after the end date.");
          return;
        } else {
          DateRange r = new DateRange();
          r.setStartDate(searchStartDate);
          r.setEndDate(searchEndDate);
          f.setDateRange(r);
        }
      } else if ((searchStartDate == null) && (searchEndDate != null)) {
        stopProgess("Error");
        enableButtons();
        ErrorDialog.showError("You must specify a start date!!!");
        return;
      } else if ((searchStartDate != null) && (searchEndDate == null)) {
        stopProgess("Error");
        enableButtons();
        ErrorDialog.showError("You must specify an end date!!!");
        return;
      }

      f.setNotes(Utils.clean(getNotes().getText()));
      if (getStatus().getSelectedUserStatus() != null) {
        f.setStatus(getStatus().getSelectedUserStatus());
      }
      GridAdministrationClient client = this.session.getAdminClient();
      List<UserCertificateRecord> records = client.findUserCertificateRecords(f);
      getUserCertificates().addUserCertificates(records);
      stopProgess(records.size() + " user certificate(s) found.");
    } catch (Exception e) {
      stopProgess("Error");
      ErrorDialog.showError(Utils.getExceptionMessage(e), e);
      log.error(Utils.getExceptionMessage(e), e);
    }
    enableButtons();
  }
Exemplo n.º 15
0
 protected static String loadResource(String resourceName) throws IOException {
   String resource = null;
   synchronized (resourceMap) {
     if (resourceMap.containsKey(resourceName)) {
       resource = resourceMap.get(resourceName);
     } else {
       InputStream stream = ClassUtils.getResourceAsStream(SDK44EncodingUtils.class, resourceName);
       if (stream != null) {
         StringBuffer buffer = Utils.inputStreamToStringBuffer(stream);
         resource = buffer.toString();
         resourceMap.put(resourceName, resource);
         stream.close();
       }
     }
   }
   return resource;
 }
Exemplo n.º 16
0
  public static void main(String[] args) throws Exception {
    args =
        new String[] {
          "-gsh", "http://ccis1716.duhs.duke.edu/wsrf/services/cagrid/RPData",
          // "-gsh", "http://localhost:8080/wsrf/services/cagrid/RPData",
          // "-gsh", "http://140.254.80.99:8080/wsrf/services/cagrid/RPData",
          "-query", "queries\\scanFeatures_query3.xml",
          "-printXml"
        };

    Options options = getOptions();
    CommandLine cmd = null;
    try {
      cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
      System.out.println("Error parsing arguments: " + e.getMessage());
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("RPDataClient", options);
      System.exit(-1);
      return;
    }
    RPDataClient client = new RPDataClient(cmd.getOptionValue("gsh"));

    CQLQueryType query =
        (CQLQueryType) Utils.deserializeDocument(cmd.getOptionValue("query"), CQLQueryType.class);

    gov.nih.nci.cagrid.cql.CQLQueryResultsType results = client.query(query);
    gov.nih.nci.cagrid.cql.CQLQueryResultType[] resultsArray = results.getCQLQueryResult();
    if (resultsArray != null) {
      System.out.println("Got " + resultsArray.length + " result(s)");

      for (int i = 0; i < resultsArray.length; i++) {
        gov.nih.nci.cagrid.cql.CQLQueryResultType result = resultsArray[i];

        // Deserialize and print out each element........
        MessageElement[] msgs = result.get_any();
        for (int j = 0; j < msgs.length; j++) {
          StringWriter output = new StringWriter();
          TransformerFactory.newInstance()
              .newTransformer()
              .transform(new DOMSource(msgs[j]), new StreamResult(output));
          if (cmd.hasOption("printXml")) System.out.println(output.toString());
        }
      }
    }
  }
Exemplo n.º 17
0
  private void upgradeWsdls() throws UpgradeException {
    // get the service's schema dir where the wsdl files live
    String serviceName =
        getServiceInformation().getServiceDescriptor().getServices().getService(0).getName();
    File serviceSchemasDir = new File(getServicePath(), "schema" + File.separator + serviceName);

    // get the data service schemas dir
    File dataSchemasDir = getDataSchemaDir();

    // find data wsdls
    Map<String, File> dataWsdlsByName = new HashMap<String, File>();
    for (File file : dataSchemasDir.listFiles()) {
      String name = file.getName();
      if (name.endsWith(".wsdl")) {
        dataWsdlsByName.put(name, file);
      }
    }

    // list wsdls in service schemas dir.  If any match one from data, replace it with the new
    // version
    File[] serviceWsdls =
        serviceSchemasDir.listFiles(
            new FileFilter() {
              public boolean accept(File path) {
                return path.getName().endsWith(".wsdl");
              }
            });

    for (File serviceWsdl : serviceWsdls) {
      if (dataWsdlsByName.containsKey(serviceWsdl.getName())) {
        // overwrite the service wsdl with the new one
        try {
          Utils.copyFile(dataWsdlsByName.get(serviceWsdl.getName()), serviceWsdl);
          getStatus()
              .addDescriptionLine(
                  "Replaced WSDL "
                      + serviceWsdl.getName()
                      + " with new version "
                      + UpgraderConstants.DATA_CURRENT_VERSION);
        } catch (Exception ex) {
          throw new UpgradeException("Error replacing wsdl: " + ex.getMessage(), ex);
        }
      }
    }
  }
Exemplo n.º 18
0
 @Override
 public void runStep() throws Throwable {
   assertNotNull(this.credential);
   assertNotNull(this.credential.getGridCredential());
   assertNotNull(this.delegatedCredential);
   assertNotNull(this.delegatedCredential.getDelegatedCredentialReference());
   assertNotNull(this.expectedError);
   DelegatedCredentialUserClient client =
       new DelegatedCredentialUserClient(
           this.delegatedCredential.getDelegatedCredentialReference(),
           this.credential.getGridCredential());
   try {
     client.getDelegatedCredential();
     fail("Should not be able to get delegated credential.");
   } catch (Exception e) {
     String error = Utils.getExceptionMessage(e);
     if (error.indexOf(expectedError) == -1) {
       fail("Unexpected error encountered:\nEXPECTED:" + expectedError + "\n RECEIVED:" + error);
     }
   }
 }
Exemplo n.º 19
0
  private String addUpdatePrivilege(boolean wasSelected, boolean selectedNow, Privilege priv)
      throws Exception {
    String id = Utils.clean(getIdentity().getText());
    Subject subj = SubjectUtils.getSubject(id);
    if (update) {
      if (!wasSelected && selectedNow) {
        try {
          targetStem.grantPriv(subj, priv);
          return "GRANTED " + priv.getName() + " privilege.";
        } catch (Exception e) {
          FaultUtil.logFault(log, e);
          throw new Exception("ERROR granting " + priv.getName() + " privilege: " + e.getMessage());
        }

      } else if (wasSelected && !selectedNow) {
        try {
          targetStem.revokePriv(subj, priv);
          return "REVOKED " + priv.getName() + " privilege.";
        } catch (Exception e) {
          FaultUtil.logFault(log, e);
          throw new Exception("ERROR revoking " + priv.getName() + " privilege: " + e.getMessage());
        }
      }
    } else {
      if (selectedNow) {
        try {
          targetStem.grantPriv(subj, priv);
          return "GRANTED " + priv.getName() + " privilege.";
        } catch (Exception e) {
          FaultUtil.logFault(log, e);
          throw new Exception("ERROR granting " + priv.getName() + " privilege: " + e.getMessage());
        }
      }
    }
    return null;
  }
Exemplo n.º 20
0
  private void updateDataLibraries() throws UpgradeException {
    FileFilter oldDataLibFilter =
        new FileFilter() {
          public boolean accept(File pathname) {
            String name = pathname.getName();
            return name.endsWith(".jar")
                && (name.startsWith("caGrid-data-")
                    || name.startsWith("caGrid-core-")
                    || name.startsWith("caGrid-CQL-")
                    || name.startsWith("caGrid-caDSR-")
                    || name.startsWith("caGrid-metadata-"));
          }
        };
    FileFilter newDataLibFilter =
        new FileFilter() {
          public boolean accept(File pathname) {
            String name = pathname.getName();
            return name.endsWith(".jar")
                && (name.startsWith("caGrid-data-")
                    || name.startsWith("caGrid-core-")
                    || name.startsWith("caGrid-CQL-")
                    || name.startsWith("caGrid-caDSR-")
                    || name.startsWith("caGrid-metadata-")
                    || name.startsWith("caGrid-mms-")
                    || name.startsWith("castor-1.0.2"));
          }
        };
    // locate the old data service libs in the service
    File serviceLibDir = new File(getServicePath() + File.separator + "lib");
    File[] serviceDataLibs = serviceLibDir.listFiles(oldDataLibFilter);
    // delete the old libraries
    for (File oldLib : serviceDataLibs) {
      oldLib.delete();
      getStatus().addDescriptionLine("caGrid 1.5 library " + oldLib.getName() + " removed");
    }
    // copy new libraries in
    File extLibDir = new File(ExtensionsLoader.EXTENSIONS_DIRECTORY + File.separator + "lib");
    File[] dataLibs = extLibDir.listFiles(newDataLibFilter);
    List<File> outLibs = new ArrayList<File>(dataLibs.length);
    for (File newLib : dataLibs) {
      File out = new File(serviceLibDir.getAbsolutePath() + File.separator + newLib.getName());
      try {
        Utils.copyFile(newLib, out);
        getStatus()
            .addDescriptionLine(
                "caGrid "
                    + UpgraderConstants.DATA_CURRENT_VERSION
                    + " library "
                    + newLib.getName()
                    + " added");
      } catch (IOException ex) {
        throw new UpgradeException(
            "Error copying new data service library: " + ex.getMessage(), ex);
      }
      outLibs.add(out);
    }

    // update the Eclipse .classpath file
    File classpathFile = new File(getServicePath() + File.separator + ".classpath");
    File[] outLibArray = new File[dataLibs.length];
    outLibs.toArray(outLibArray);
    try {
      ExtensionUtilities.syncEclipseClasspath(classpathFile, outLibArray);
      getStatus().addDescriptionLine("Eclipse .classpath file updated");
    } catch (Exception ex) {
      throw new UpgradeException("Error updating Eclipse .classpath file: " + ex.getMessage(), ex);
    }
  }
  protected void generateClassToQnameMapping(Data extData, ServiceInformation info)
      throws CodegenExtensionException {
    try {
      Mappings mappings = new Mappings();
      List<ClassToQname> classMappings = new LinkedList<ClassToQname>();
      // the first place to look for mappings is in the model information, which
      // is derived from the data service Domain Model.  If no domain model is to be used,
      // the mappings are still required to do anything with caCORE SDK beans.
      ModelInformation modelInfo = extData.getModelInformation();
      if (modelInfo != null
          && !ModelSourceType.none.equals(modelInfo.getSource())
          && modelInfo.getModelPackage() != null) {
        logger.debug("Model information / domain model found in service model.");
        logger.debug("Generating class to qname mapping from the information");
        logger.debug("stored in the service model");
        // walk packages in the model
        for (ModelPackage pack : modelInfo.getModelPackage()) {
          // locate a NamsepaceType in the service model mapped to this package
          NamespaceType mappedNamespace = null;
          for (NamespaceType nsType : info.getServiceDescriptor().getNamespaces().getNamespace()) {
            if (pack.getPackageName().equals(nsType.getPackageName())) {
              mappedNamespace = nsType;
              break;
            }
          }
          if (mappedNamespace != null && pack.getModelClass() != null) {
            // walk classes in this package, if any exist
            for (ModelClass clazz : pack.getModelClass()) {
              if (clazz.isTargetable()) {
                // find a schema element type mapped to this class
                for (SchemaElementType element : mappedNamespace.getSchemaElement()) {
                  if (clazz.getShortClassName().equals(element.getClassName())) {
                    // found it!  Create a mapping
                    QName qname = new QName(mappedNamespace.getNamespace(), element.getType());
                    String fullClassname = pack.getPackageName() + "." + clazz.getShortClassName();
                    ClassToQname map = new ClassToQname(fullClassname, qname.toString());
                    classMappings.add(map);
                    break;
                  }
                }
              }
            }
          } else {
            logger.warn(
                "Model package " + pack.getPackageName() + " is not mapped to any namespace!");
          }
        }
        ClassToQname[] mapArray = new ClassToQname[classMappings.size()];
        classMappings.toArray(mapArray);
        mappings.setMapping(mapArray);
      } else {
        logger.warn("No model information / domain model found in service model.");
        logger.warn("Falling back to schema information for class to qname mapping.");
        NamespaceType[] namespaces = info.getNamespaces().getNamespace();
        // a set of namespaces to ignore
        Set<String> nsIgnores = new HashSet<String>();
        nsIgnores.add(IntroduceConstants.W3CNAMESPACE);
        nsIgnores.add(info.getServices().getService(0).getNamespace());
        nsIgnores.add(DataServiceConstants.ENUMERATION_DATA_SERVICE_NAMESPACE);
        nsIgnores.add(DataServiceConstants.DATA_SERVICE_NAMESPACE);
        nsIgnores.add(DataServiceConstants.CQL_QUERY_URI);
        nsIgnores.add(DataServiceConstants.CQL_RESULT_SET_URI);

        for (int nsIndex = 0; nsIndex < namespaces.length; nsIndex++) {
          NamespaceType currentNs = namespaces[nsIndex];
          // ignore any unneeded namespaces
          if (!nsIgnores.contains(currentNs.getNamespace())) {
            SchemaElementType[] schemaElements = currentNs.getSchemaElement();
            for (int elemIndex = 0;
                schemaElements != null && elemIndex < schemaElements.length;
                elemIndex++) {
              SchemaElementType currentElement = schemaElements[elemIndex];
              ClassToQname toQname = new ClassToQname();
              QName qname = new QName(currentNs.getNamespace(), currentElement.getType());
              String shortClassName = currentElement.getClassName();
              if (shortClassName == null) {
                shortClassName = currentElement.getType();
              }
              String fullClassName = currentNs.getPackageName() + "." + shortClassName;
              toQname.setQname(qname.toString());
              toQname.setClassName(fullClassName);
              classMappings.add(toQname);
            }
          }
        }
      }

      ClassToQname[] mapArray = new ClassToQname[classMappings.size()];
      classMappings.toArray(mapArray);
      mappings.setMapping(mapArray);
      // create the filename where the mapping will be stored
      String mappingFilename =
          new File(
                  info.getBaseDirectory(),
                  "etc" + File.separator + DataServiceConstants.CLASS_TO_QNAME_XML)
              .getAbsolutePath();
      // serialize the mapping to that file
      Utils.serializeDocument(mappingFilename, mappings, DataServiceConstants.MAPPING_QNAME);
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new CodegenExtensionException(
          "Error generating class to QName mapping: " + ex.getMessage(), ex);
    }
  }
 private Credential getBasicCredential(String userName, String password) {
   BasicAuthentication basicAuthentication = new BasicAuthentication();
   basicAuthentication.setUserId(Utils.clean(userName));
   basicAuthentication.setPassword(Utils.clean(password));
   return basicAuthentication;
 }
 private Credential getOnetimePasswordCredential(String userName, String onetimepassword) {
   OneTimePassword onetimePassword = new OneTimePassword();
   onetimePassword.setUserId(Utils.clean(userName));
   onetimePassword.setOneTimePassword(Utils.clean(onetimepassword));
   return onetimePassword;
 }
Exemplo n.º 24
0
  public void applyConfiguration() throws Exception {
    LOG.debug("Applying configuration");
    // just in case...
    validateSdkDirectory();

    // new data service's lib directory
    File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib");
    File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp");
    tempLibDir.mkdir();

    String projectName =
        getDeployPropertiesFromSdkDir()
            .getProperty(SDK41StyleConstants.DeployProperties.PROJECT_NAME);
    File remoteClientDir =
        new File(
            sdkDirectory,
            "output"
                + File.separator
                + projectName
                + File.separator
                + "package"
                + File.separator
                + "remote-client");
    File localClientDir =
        new File(
            sdkDirectory,
            "output"
                + File.separator
                + projectName
                + File.separator
                + "package"
                + File.separator
                + "local-client");
    // wrap up the remote-client config files as a jar file so it'll be on the classpath
    // local client stuff might be added by the API Type configuration step
    LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system");
    File remoteConfigDir = new File(remoteClientDir, "conf");
    String remoteConfigJarName = projectName + "-remote-config.jar";
    File remoteConfigJar = new File(tempLibDir, remoteConfigJarName);
    JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar);
    // also jar up the local-client config files
    LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system");
    File localConfigDir = new File(localClientDir, "conf");
    String localConfigJarName = projectName + "-local-config.jar";
    File localConfigJar = new File(tempLibDir, localConfigJarName);
    JarUtilities.jarDirectory(localConfigDir, localConfigJar);

    // set the config jar in the shared configuration
    SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar);
    SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar);

    // get a list of jars found in GLOBUS_LOCATION/lib
    File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV));
    File globusLib = new File(globusLocation, "lib");
    File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter());
    Set<String> globusJarNames = new HashSet<String>();
    for (File jar : globusJars) {
      globusJarNames.add(jar.getName());
    }
    Set<String> serviceJarNames = new HashSet<String>();
    for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) {
      serviceJarNames.add(jar.getName());
    }

    // get the application name
    final String applicationName =
        getDeployPropertiesFromSdkDir()
            .getProperty(SDK41StyleConstants.DeployProperties.PROJECT_NAME);

    // copy in libraries from the remote lib dir that DON'T collide with Globus's
    LOG.debug("Copying libraries from remote client directory");
    File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter());
    for (File lib : remoteLibs) {
      String libName = lib.getName();
      if (!globusJarNames.contains(libName) && !libName.startsWith("caGrid-CQL-cql.1.0-")) {
        File libOutput = new File(libOutDir, libName);
        Utils.copyFile(lib, libOutput);
        LOG.debug(libName + " copied to the service");
      }
    }
    LOG.debug("Copying libraries from the local client directory");
    File localLibDir = new File(localClientDir, "lib");
    File[] localLibs = localLibDir.listFiles();
    for (File lib : localLibs) {
      String name = lib.getName();
      boolean ok = true;
      // is the jar one that is known to conflict with caGrid or Globus?
      ok =
          !(name.equals("axis.jar")
              || name.startsWith("commons-collections")
              || name.startsWith("commons-logging")
              || name.startsWith("commons-discovery")
              || name.startsWith("log4j"));
      // is the jar already copied into the service
      if (ok && serviceJarNames.contains(name)) {
        ok = false;
      }
      // is the jar one of the caGrid 1.2 jars?
      if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) {
        if (!name.startsWith("caGrid-sdkQuery4-")) {
          ok = false;
        }
      }
      // is the jar in the globus lib dir?
      if (ok && !globusJarNames.contains(name)) {
        File libOutput = new File(libOutDir, name);
        Utils.copyFile(lib, libOutput);
        LOG.debug(name + " copied to the service");
      }
    }

    // set the application name service property
    setCql1ProcessorProperty(SDK41QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false);
    setCql2ProcessorProperty(
        SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME, applicationName, false);

    // grab the castor marshalling and unmarshalling xml mapping files
    // from the config dir and copy them into the service's package structure
    try {
      LOG.debug("Copying castor marshalling and unmarshalling files");
      File marshallingMappingFile =
          new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE);
      File unmarshallingMappingFile =
          new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE);
      // copy the mapping files to the service's source dir + base package name
      String marshallOut =
          CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation());
      String unmarshallOut =
          CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation());
      Utils.copyFile(marshallingMappingFile, new File(marshallOut));
      Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut));
    } catch (IOException ex) {
      ex.printStackTrace();
      CompositeErrorDialog.showErrorDialog(
          "Error copying castor mapping files", ex.getMessage(), ex);
    }

    // set up the shared configuration
    SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory());
    SharedConfiguration.getInstance().setServiceInfo(getServiceInformation());
    SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir());
  }
  private void editWsddForCastorMappings(ServiceInformation info) throws Exception {
    // change out the domain model validator class
    CommonTools.setServiceProperty(
        info.getServiceDescriptor(),
        DataServiceConstants.DOMAIN_MODEL_VALIDATOR_CLASS,
        ISODomainModelValidator.class.getName(),
        false);

    String mainServiceName =
        info.getIntroduceServiceProperties()
            .getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME);
    ServiceType mainService = CommonTools.getService(info.getServices(), mainServiceName);
    String servicePackageName = mainService.getPackageName();
    String packageDir = servicePackageName.replace('.', File.separatorChar);
    // find the client source directory, where the client-config will be located
    File clientConfigFile =
        new File(
            info.getBaseDirectory(),
            "src"
                + File.separator
                + packageDir
                + File.separator
                + "client"
                + File.separator
                + "client-config.wsdd");
    LOG.debug("Editing client config wsdd at " + clientConfigFile.getAbsolutePath());
    if (!clientConfigFile.exists()) {
      throw new CodegenExtensionException(
          "Client config file " + clientConfigFile.getAbsolutePath() + " not found!");
    }
    // find the server-config.wsdd, located in the service's root directory
    File serverConfigFile = new File(info.getBaseDirectory(), "server-config.wsdd");
    LOG.debug("Editing server config wsdd at " + serverConfigFile.getAbsolutePath());
    if (!serverConfigFile.exists()) {
      throw new CodegenExtensionException(
          "Server config file " + serverConfigFile.getAbsolutePath() + " not found!");
    }

    // edit the marshaling castor mapping to avoid serializing associations
    File castorMappingFile = new File(CastorMappingUtil.getMarshallingCastorMappingFileName(info));
    if (castorMappingFile.exists()) {
      String marshallingXmlText = Utils.fileToStringBuffer(castorMappingFile).toString();
      String editedMarshallingText =
          CastorMappingUtil.removeAssociationMappings(marshallingXmlText);
      String editedMarshallingFileName =
          CastorMappingUtil.getEditedMarshallingCastorMappingFileName(info);
      Utils.stringBufferToFile(new StringBuffer(editedMarshallingText), editedMarshallingFileName);

      // edit the unmarshaling castor mapping to avoid deserializing associations
      String unmarshallingXmlText =
          Utils.fileToStringBuffer(
                  new File(CastorMappingUtil.getUnmarshallingCastorMappingFileName(info)))
              .toString();
      String editedUnmarshallingText =
          CastorMappingUtil.removeAssociationMappings(unmarshallingXmlText);
      String editedUnmarshallingFileName =
          CastorMappingUtil.getEditedUnmarshallingCastorMappingFileName(info);
      Utils.stringBufferToFile(
          new StringBuffer(editedUnmarshallingText), editedUnmarshallingFileName);

      // set properties in the client to use the edited marshaler
      WsddUtil.setGlobalClientParameter(
          clientConfigFile.getAbsolutePath(),
          SDK43EncodingUtils.CASTOR_MARSHALLER_PROPERTY,
          CastorMappingUtil.getEditedMarshallingCastorMappingName(info));
      // and the edited unmarshaler
      WsddUtil.setGlobalClientParameter(
          clientConfigFile.getAbsolutePath(),
          SDK43EncodingUtils.CASTOR_UNMARSHALLER_PROPERTY,
          CastorMappingUtil.getEditedUnmarshallingCastorMappingName(info));

      // set properties in the server to use the edited marshaler
      WsddUtil.setServiceParameter(
          serverConfigFile.getAbsolutePath(),
          info.getServices().getService(0).getName(),
          SDK43EncodingUtils.CASTOR_MARSHALLER_PROPERTY,
          CastorMappingUtil.getEditedMarshallingCastorMappingName(info));
      // and the edited unmarshaler
      WsddUtil.setServiceParameter(
          serverConfigFile.getAbsolutePath(),
          info.getServices().getService(0).getName(),
          SDK43EncodingUtils.CASTOR_UNMARSHALLER_PROPERTY,
          CastorMappingUtil.getEditedUnmarshallingCastorMappingName(info));
    } else {
      LOG.debug(
          "Castor mapping file "
              + castorMappingFile.getAbsolutePath()
              + " not found... this is OK if you're using JaxB serialization");
    }
  }
  public static void main(String[] args) {
    System.out.println("Running the Grid Service Client");
    try {
      if (!(args.length < 2)) {
        if (args[0].equals("-url")) {
          IntroduceTestPersistentServiceClient client =
              new IntroduceTestPersistentServiceClient(args[1]);
          // place client calls here if you want to use this main as a
          // test....
          java.io.FileReader fr1 = new java.io.FileReader("persistenceTestEPR1.xml");
          org.apache.axis.message.addressing.EndpointReferenceType epr1 =
              (org.apache.axis.message.addressing.EndpointReferenceType)
                  gov.nih.nci.cagrid.common.Utils.deserializeObject(
                      fr1, org.apache.axis.message.addressing.EndpointReferenceType.class);
          org.test.persistent.resource.client.IntroduceTestPersistentResourceServiceClient
              resourceClient1 =
                  new org.test.persistent.resource.client
                      .IntroduceTestPersistentResourceServiceClient(epr1);
          projectmobius.org.BookType book1 = resourceClient1.getBook();
          if (book1 != null && book1.getAuthor().equals("Shannon Hastings")) {
            System.out.println("Got recovered persistence resource and is correct");
            new java.io.File("persistenceTestEPR1.xml").delete();
          } else {
            new java.io.File("persistenceTestEPR1.xml").delete();
            System.err.println("Could not retrieve the persistent resource");
            System.exit(1);
          }

          resourceClient1.destroy();
          book1 = null;
          try {
            book1 = resourceClient1.getBook();
          } catch (Exception e) {
            System.out.println("Destroy and remove of persistence file worked.");
          }
          if (book1 != null) {
            System.err.println("Destroy and remove of persistence file error.");
            System.exit(1);
          }

          java.io.FileReader fr2 = new java.io.FileReader("persistenceTestEPR2.xml");
          org.apache.axis.message.addressing.EndpointReferenceType epr2 =
              (org.apache.axis.message.addressing.EndpointReferenceType)
                  gov.nih.nci.cagrid.common.Utils.deserializeObject(
                      fr2, org.apache.axis.message.addressing.EndpointReferenceType.class);
          org.test.persistent.resource.client.IntroduceTestPersistentResourceServiceClient
              resourceClient2 =
                  new org.test.persistent.resource.client
                      .IntroduceTestPersistentResourceServiceClient(epr2);
          projectmobius.org.BookType book2 = resourceClient2.getBook();
          if (book2 != null && book2.getAuthor().equals("Bozo The Clown")) {
            System.out.println("Got recovered persistence resource and is correct");
            new java.io.File("persistenceTestEPR2.xml").delete();
          } else {
            new java.io.File("persistenceTestEPR2.xml").delete();
            System.err.println("Could not retrieve the persistent resource");
            System.exit(1);
          }
        } else {
          usage();
          System.exit(1);
        }
      } else {
        usage();
        System.exit(1);
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }