예제 #1
0
 private static void elementToSecurityConstraints(Element element, RetsConfig config) {
   if (element == null) {
     config.setSecurityConstraints(new ArrayList());
     return;
   }
   List securityConstraints = new ArrayList();
   List children = element.getChildren(GROUP_RULES);
   for (int i = 0; i < children.size(); i++) {
     Element child = (Element) children.get(i);
     String groupName = child.getAttributeValue(GROUP);
     GroupRules groupRules = new GroupRules(groupName);
     List grandChildren = child.getChildren();
     for (int j = 0; j < grandChildren.size(); j++) {
       Element grandChild = (Element) grandChildren.get(j);
       RuleDescription ruleDescription = new RuleDescription();
       if (grandChild.getName().equals(INCLUDE_RULE)) {
         ruleDescription.setType(RuleDescription.INCLUDE);
       } else if (grandChild.getName().equals(EXCLUDE_RULE)) {
         ruleDescription.setType(RuleDescription.EXCLUDE);
       } else {
         LOG.warn("Unknown rule" + grandChild.toString());
         continue;
       }
       ruleDescription.setResource(grandChild.getAttributeValue(RESOURCE));
       ruleDescription.setRetsClass(grandChild.getAttributeValue(CLASS));
       String systemNamesText = grandChild.getChildTextNormalize(SYSTEM_NAMES);
       String[] systemNamesArray = StringUtils.split(systemNamesText, " ");
       ruleDescription.setSystemNames(Arrays.asList(systemNamesArray));
       groupRules.addRule(ruleDescription);
     }
     securityConstraints.add(groupRules);
   }
   config.setSecurityConstraints(securityConstraints);
 }
 /**
  * Make the contents of an external resource mentioned in an <code>mdRef</code> element
  * available as an <code>InputStream</code>. See the <code>METSManifest.MdRef</code> interface
  * for details.
  *
  * @param mdref the METS mdRef element to locate the input for.
  * @return the input stream of its content.
  */
 public InputStream getInputStream(Element mdref)
     throws MetadataValidationException, IOException, SQLException, AuthorizeException {
   Bitstream mdbs = getBitstreamForMdRef(mdref);
   if (mdbs == null)
     throw new MetadataValidationException(
         "Failed dereferencing bitstream for mdRef element=" + mdref.toString());
   return mdbs.retrieve();
 }
  // apply metadata values returned in DIM to the target item.
  private void applyDim(List dimList, Item item) throws MetadataValidationException {
    Iterator di = dimList.iterator();
    while (di.hasNext()) {
      Element elt = (Element) di.next();
      if (elt.getName().equals("field") && elt.getNamespace().equals(DIM_NS))
        applyDimField(elt, item);

      // if it's a <dim> container, apply its guts
      else if (elt.getName().equals("dim") && elt.getNamespace().equals(DIM_NS))
        applyDim(elt.getChildren(), item);
      else {
        log.error("Got unexpected element in DIM list: " + elt.toString());
        throw new MetadataValidationException(
            "Got unexpected element in DIM list: " + elt.toString());
      }
    }
  }
예제 #4
0
파일: TestUuid.java 프로젝트: Geocent/CTPOS
  public static final void main(final String[] args) throws Exception {

    // This simulates the method:
    // public YParameter[] describeRequiredParams()

    // NOTE: with the addition of Ehcache, RabbitMQ use is required for end
    // of life cycle tasks; e.g., writing data to Gate, to a Neo4J Db, or
    // to a file, etc.
    // The YAWL engine startup and a YawlGatewayObserver class MessagingLoader
    // will load this when in a Yawl server environment, we load here, for
    // testing. BUT, a RabbitMQ server SHALL be running someplace as referenced in the
    // RabbitMqConnection.properties config file.
    LOGGER.info("------------------------------ STARTUP ---------------------------------");
    LOGGER.info("------------------------------------------------------------------------");
    LOGGER.info(
        "Like sands through the hourglass, so are the days of our lives: {}",
        StringUtil.dateAsRfc822(false));
    LOGGER.info("------------------------------------------------------------------------");

    LOGGER.info("----------------------------  EHCACHE   --------------------------------");
    // This gives the system a chance to load the Ehcache properties file
    // and to set up the BootstrapPropertiesFetcher and BootstrapConfigFinder
    // classes, again to bootstrap - individual web apps will
    // need to create their own instances.
    //		BootstrapPropertiesFetcher bspf = new BootstrapPropertiesFetcher();
    //		LOGGER.info("BootstrapPropertiesFetcher: using this server: {}",
    //				bspf.getProperties().getProperty("ehcache.client.serviceurl"));

    LOGGER.info("------------------------------  GATE   ---------------------------------");

    if (null == GateDataStore.getInstance()) {
      LOGGER.info("Gate: Failure on GateDataStore.getInstance(): Gate not available.");
    }

    LOGGER.info("------------------------------  NEO4J  ---------------------------------");

    LOGGER.info("----------------  Using the server instance of Neo4J.  -----------------");

    // Using the Neo4J server instead of embedded due to issues with single instance
    // within this environment.
    // See the PersistenceConnection.properties file.

    LOGGER.info("-------------------------  CAMEL FILEMOVER  ----------------------------");

    FileMover fm = new FileMover("FileMover.properties");
    fm.prepareCamelContext();

    LOGGER.info("----------------------  CAMEL FILEPROCESSOR  ---------------------------");

    FileProcessor fp = new FileProcessor("FileProcessor.properties");
    fp.prepareCamelContext();

    LOGGER.info("----------------------  CAMEL IMAPPROCESSOR  ---------------------------");

    ImapProcessor imp = new ImapProcessor("ImapProcessor.properties");
    imp.prepareCamelContext();

    LOGGER.info("----------------------  CAMEL GATEPROCESSOR  ---------------------------");

    GateProcessor gp = new GateProcessor("GateFileProcessor.properties");
    gp.prepareCamelContext();

    LOGGER.info("--------------------  CAMEL TIKAFILEPROCESSOR  -------------------------");

    TikaFileProcessor tfp = new TikaFileProcessor("TikaFileProcessor.properties");
    tfp.prepareCamelContext();

    LOGGER.info("----------------------  CAMEL TIKAPROCESSOR  ---------------------------");

    // TikaProcessor is currently using a singleton due to issues writing to
    // Lucene index - one writer per index - always ...
    if (null == TikaLuceneProcessor.getInstance()) {
      LOGGER.info(
          "TikaProcessor: Failure on TikaProcessor.getInstance(): TikaProcessor not available.");
    }

    LOGGER.info("----------------------  CAMEL CMISPROCESSOR  ---------------------------");

    CmisProcessor cp = new CmisProcessor("CmisFileProcessor.properties");
    cp.prepareCamelContext();

    LOGGER.info("------------------------------ RabbitMq --------------------------------");
    LOGGER.info("MessagingLoader: announceEngineInitialised: IS using RabbitMQ listener.");

    if (ProcessKonstants.YDS_MESSAGE_QUEUE_AVAILABLE.equalsIgnoreCase("true")) {
      LOGGER.info("MessagingLoader: announceEngineInitialised: Starting YDS message listener.");
      // Spin off the Receiver instance.
      new Thread(
              new Runnable() {
                public void run() {
                  Receiver.getInstance().receiver(null);
                }
              })
          .start();
    }

    LOGGER.info("------------  PAUSING TO ALLOW ABOVE INSTANCES TO SPIN UP  -------------\n");
    try {
      LOGGER.info("I'm so sleepy, I'll take a quick nap ... {}\n", StringUtil.dateAsRfc822(false));
      Thread.sleep(20000);

    } catch (InterruptedException e) {
      LOGGER.error("Startup Pause: Error in Thread.sleep(20000): ", e.getLocalizedMessage());
    }
    LOGGER.info(
        "Wow, great nap - you've been busy already - let's play! {}\n",
        StringUtil.dateAsRfc822(false));
    LOGGER.info("---------------------------- END STARTUP -------------------------------\n");

    // SNIPPET START: Replace form here down to the last SNIPPET END ...
    LOGGER.info("----------------------------- START TEST -------------------------------");
    LOGGER.info(
        SERVICE_NAME + " TEST: describeRequiredParams: {}", SERVICE_NAME + ProcessKonstants.AVRO);
    LOGGER.info("------------------------------------------------------------------------\n");

    final YParameter[] params =
        SchemaToInputElement.loadRequiredYawlParams(
            SERVICE_NAME + ProcessKonstants.AVRO, ProcessKonstants.RETURN_DATA_SCHEMA);

    // Use the first params element to store documentation
    if (null != params) {
      params[0].setDocumentation("Add a documentation string here.");
    }

    // ----------------------------------------------------------------------
    // This simulates the method:
    // prepareToExecuteCommand()

    String result = SERVICE_NAME + " TEST: Cannot instantiate service: " + CoreKonstants.YDS_FAILED;

    UuidServiceWrapper uuid = new UuidServiceWrapper();

    if (null != uuid) {

      result =
          uuid.updateStatus(
              uuid.getRdm().getResultId(),
              CoreKonstants.YDS_UNKNOWN,
              "Initializing with parameters.",
              SERVICE_NAME);

      //			 {
      //			      "namespace": "org.imsys.naiche.yds.avro",
      //			      "name": "UuidService",
      //			      "type": "record",
      //			      "fields": [
      //			          {"name": "Guid", "type": "string" }
      //			          ]
      //			}

      // Manually create a data element based on corresponding Avro schema.
      Element data = new Element("data");
      Element guid = new Element("Guid");
      guid.setText("yes");
      data.addContent(guid);

      LOGGER.info(SERVICE_NAME + " TEST: data element: {}", data.toString());
      LOGGER.info("---------------------------------------------------------\n");

      Reflection.yawlElementToObject(SERVICE_NAME, data, uuid);

      // Need to build a YawlWorkitemModel object
      WorkItemRecord wir = new WorkItemRecord();

      wir.setCaseID("CaseId50");
      wir.setTaskID(SERVICE_NAME + "-taskId");
      wir.setTaskName(SERVICE_NAME + "-taskName");
      wir.setDataList(data);

      // SNIPPET START
      // Get a json formatted text of the service object.
      ObjectMapper mapper = new ObjectMapper();
      String yawlInputEleAsJson = null;
      try {

        yawlInputEleAsJson = mapper.writeValueAsString(uuid);

        LOGGER.info(SERVICE_NAME + ": prepareToExecuteCommand: Json: {}", yawlInputEleAsJson);

      } catch (JsonParseException e) {
        LOGGER.error(
            SERVICE_NAME
                + ": prepareToExecuteCommand: JsonParseException: {} "
                + e.getLocalizedMessage());
      } catch (JsonMappingException e) {
        LOGGER.error(
            SERVICE_NAME
                + ": prepareToExecuteCommand: JsonMappingException: {} "
                + e.getLocalizedMessage());
      } catch (IOException e) {
        LOGGER.error(
            SERVICE_NAME + ": prepareToExecuteCommand: IOException: {} " + e.getLocalizedMessage());
      }

      // This creates and inputs a YawlWorkitemModel object into a map for later
      // retrieval.
      YawlWorkitemModel ywim =
          new YawlWorkitemModel(
              "serviceRequestId",
              "dataXmlString",
              "serviceName",
              ENGINEUSER,
              ENGINEPASSWORD,
              "wkitemId",
              // inputData will be created when the service object is instantiated
              null,
              // outputData will be created when the service object is instantiated
              null,
              "wkitemTaskName",
              "wkitemTaskId",
              "wkitemCaseId",
              "wkitemSpecUri",
              "wkitemSpecVersion",
              "wkitemSpecIdentifier",
              SERVICE_NAME + ProcessKonstants.AVRO,
              ProcessKonstants.RETURN_DATA_SCHEMA);

      // Optional, will use in graphDB.
      ywim.setTaskId(wir.getTaskID());
      ywim.setCaseId(wir.getCaseID());
      ywim.setSpecUri(SERVICE_NAME + "SPECIFICATION-NAME");
      ywim.setSpecVersion(SERVICE_NAME + "SPECIFCATION-VERSION");
      ywim.setSpecId(SERVICE_NAME + "SPECIFICATION-GUID");

      ywim.setInputSchemaName(SERVICE_NAME + ProcessKonstants.AVRO);
      ywim.setOutputSchemaName(ProcessKonstants.RETURN_DATA_SCHEMA);

      // ywim.putWorkitemToMap(uuid.getRdm().getResultId() , ywim);
      // SNIPPET END.

      // This realizes the goal of the service.
      result = uuid.performService();

      LOGGER.info(SERVICE_NAME + " TEST: result: {}", result);
      LOGGER.info("-----------------------END OF TEST--------------------------\n");

      // SNIPPET END: To here with a service class to test. Leave the other external
      // services running to better test some level of integration prior to doing a
      // full build and running in the container.

      LOGGER.info("CAMEL PROCCESES MAY CONTINUE TO RUN - WATCH FOLDERS AND EMAIL FOR OUTPUT");
      LOGGER.info("-------------------------------- END -----------------------------------\n");
    }

    // Give the running services some time to catch up ...
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      LOGGER.error("Test: Error in Thread.sleep(10000): ", e.getLocalizedMessage());
    }

    BufferedReader ir = new BufferedReader(new InputStreamReader(System.in));
    String s = null;
    System.out.print("\nshutdown prompt:>>> ");
    while ((s = ir.readLine()).length() > 0) {
      if (s.equals("shutdown")) {
        System.out.println("\nSending shutdown request ...");

        System.out.println("Shutdown successful. Quitting console.\n");

        System.exit(0);
      }
      System.out.print("\nshutdown prompt:>>> ");
    }
  }
예제 #5
0
 /**
  * toString converts an (TMX) element to a string)<br>
  *
  * <pre>
  * &lt;seg&gt;hallo&lt;ph&gt;xxx&lt;/ph&gt; ist...&lt;/seg&gt;
  * </pre>
  *
  * @param element to create astring from
  * @return a string representing the element
  */
 public String toString(Element element) {
   return element.toString();
 }
예제 #6
0
 /**
  * segToString returns the string representation of an element
  *
  * @param seg the seg to convert
  * @return a string representation of a seg
  */
 public String segToString(Element seg) {
   String elst = seg.toString();
   return elst.replaceAll(seg.getName(), "");
 }
  /**
   * Simple command-line rig for testing the DIM output of a stylesheet. Usage: java
   * XSLTIngestionCrosswalk <crosswalk-name> <input-file>
   */
  public static void main(String[] argv) throws Exception {
    if (argv.length < 2) {
      System.err.println("Usage:  java XSLTIngestionCrosswalk [-l] <crosswalk-name> <input-file>");
      System.exit(1);
    }

    int i = 0;
    boolean list = false;
    // skip first arg if it's the list option
    if (argv.length > 2 && argv[0].equals("-l")) {
      ++i;
      list = true;
    }
    IngestionCrosswalk xwalk =
        (IngestionCrosswalk) PluginManager.getNamedPlugin(IngestionCrosswalk.class, argv[i]);
    if (xwalk == null) {
      System.err.println(
          "Error, cannot find an IngestionCrosswalk plugin for: \"" + argv[i] + "\"");
      System.exit(1);
    }

    XSLTransformer xform = ((XSLTIngestionCrosswalk) xwalk).getTransformer(DIRECTION);
    if (xform == null)
      throw new CrosswalkInternalException(
          "Failed to initialize transformer, probably error loading stylesheet.");

    SAXBuilder builder = new SAXBuilder();
    Document inDoc = builder.build(new FileInputStream(argv[i + 1]));
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    Document dimDoc = null;
    List dimList = null;
    if (list) {
      dimList = xform.transform(inDoc.getRootElement().getChildren());
      outputter.output(dimList, System.out);
    } else {
      dimDoc = xform.transform(inDoc);
      outputter.output(dimDoc, System.out);
      dimList = dimDoc.getRootElement().getChildren();
    }

    // Sanity-check the generated DIM, make sure it would load.
    Context context = new Context();
    Iterator di = dimList.iterator();
    while (di.hasNext()) {
      // skip over comment, text and other trash some XSLs generate..
      Object o = di.next();
      if (!(o instanceof Element)) continue;

      Element elt = (Element) o;
      if (elt.getName().equals("field") && elt.getNamespace().equals(DIM_NS)) {
        String schema = elt.getAttributeValue("mdschema");
        String element = elt.getAttributeValue("element");
        String qualifier = elt.getAttributeValue("qualifier");
        MetadataSchema ms = MetadataSchema.find(context, schema);
        if (ms == null) {
          System.err.println(
              "DIM Error, Cannot find metadata schema for: schema=\""
                  + schema
                  + "\" (... element=\""
                  + element
                  + "\", qualifier=\""
                  + qualifier
                  + "\")");
        } else {
          if (qualifier != null && qualifier.equals("")) {
            System.err.println(
                "DIM Warning, qualifier is empty string: "
                    + " schema=\""
                    + schema
                    + "\", element=\""
                    + element
                    + "\", qualifier=\""
                    + qualifier
                    + "\"");
            qualifier = null;
          }
          MetadataField mf =
              MetadataField.findByElement(context, ms.getSchemaID(), element, qualifier);
          if (mf == null)
            System.err.println(
                "DIM Error, Cannot find metadata field for: schema=\""
                    + schema
                    + "\", element=\""
                    + element
                    + "\", qualifier=\""
                    + qualifier
                    + "\"");
        }
      } else {
        // ("Got unexpected element in DIM list: "+elt.toString());
        throw new MetadataValidationException(
            "Got unexpected element in DIM list: " + elt.toString());
      }
    }
  }