public void test_phase_selection() throws IOException, SAXException {
    Smooks smooks = new Smooks();
    ExecutionContext execContext;
    DOMContentDeliveryConfig config;

    smooks.addConfigurations("config1.xml", getClass().getResourceAsStream("config1.xml"));
    execContext = smooks.createExecutionContext();
    config = (DOMContentDeliveryConfig) execContext.getDeliveryConfig();

    // Check the assembly units...
    List<ContentHandlerConfigMap<DOMVisitBefore>> assemblyVBs =
        config.getAssemblyVisitBefores().getMappings("a");
    List<ContentHandlerConfigMap<DOMVisitAfter>> assemblyVAs =
        config.getAssemblyVisitAfters().getMappings("a");
    assertEquals(2, assemblyVBs.size());
    assertTrue(assemblyVBs.get(0).getContentHandler() instanceof AssemblyVisitor1);
    assertTrue(assemblyVBs.get(1).getContentHandler() instanceof ConfigurableVisitor);
    assertEquals(2, assemblyVAs.size());
    assertTrue(assemblyVAs.get(0).getContentHandler() instanceof ConfigurableVisitor);
    assertTrue(assemblyVAs.get(1).getContentHandler() instanceof AssemblyVisitor1);

    List<ContentHandlerConfigMap<DOMVisitBefore>> processingVBs =
        config.getProcessingVisitBefores().getMappings("a");
    List<ContentHandlerConfigMap<DOMVisitAfter>> processingVAs =
        config.getProcessingVisitAfters().getMappings("a");
    assertEquals(2, processingVBs.size());
    assertTrue(processingVBs.get(0).getContentHandler() instanceof ProcessorVisitor1);
    assertTrue(processingVBs.get(1).getContentHandler() instanceof ConfigurableVisitor);
    assertEquals(2, processingVAs.size());
    assertTrue(processingVAs.get(0).getContentHandler() instanceof ConfigurableVisitor);
    assertTrue(processingVAs.get(1).getContentHandler() instanceof ProcessorVisitor1);
  }
  public void test_filtering() throws IOException, SAXException {
    Smooks smooks = new Smooks();
    BasicExecutionEventListener eventListener = new BasicExecutionEventListener();

    smooks.addConfigurations("config2.xml", getClass().getResourceAsStream("config2.xml"));
    // Create an exec context - no profiles....
    ExecutionContext executionContext = smooks.createExecutionContext();
    CharArrayWriter outputWriter = new CharArrayWriter();

    // Filter the input message to the outputWriter, using the execution context...
    executionContext.setEventListener(eventListener);
    smooks.filterSource(
        executionContext,
        new StreamSource(getClass().getResourceAsStream("testxml1.xml")),
        new StreamResult(outputWriter));

    log.debug(outputWriter.toString());
    byte[] expected =
        StreamUtils.readStream(getClass().getResourceAsStream("testxml1-expected.xml"));
    assertTrue(
        StreamUtils.compareCharStreams(
            new ByteArrayInputStream(expected),
            new ByteArrayInputStream(outputWriter.toString().getBytes())));
    assertEquals(32, eventListener.getEvents().size());
  }
  @SuppressWarnings("unchecked")
  protected static List runSmooksTransform() throws IOException, SAXException, SmooksException {

    Smooks smooks = new Smooks();

    try {
      // ****
      // And here's the configuration... configuring the CSV reader and
      // the direct
      // binding config to create a List of Person objects
      // (List<Person>)...
      // ****
      smooks.setReaderConfig(
          new CSVReaderConfigurator("firstName,lastName,gender,age,country")
              .setBinding(new CSVBinding("customerList", Customer.class, CSVBindingType.LIST)));

      // Configure the execution context to generate a report...
      ExecutionContext executionContext = smooks.createExecutionContext();
      executionContext.setEventListener(new HtmlReportGenerator("target/report/report.html"));

      JavaResult javaResult = new JavaResult();
      smooks.filterSource(executionContext, new StringSource(messageIn), javaResult);

      return (List) javaResult.getBean("customerList");
    } finally {
      smooks.close();
    }
  }
  public void test_simple_smooks_config() throws Exception {
    test_config_file("simple_smooks_config");

    // Programmatic config....
    Smooks smooks = new Smooks();
    smooks.setReaderConfig(new JSONReaderConfigurator());
    test_config_file("simple_smooks_config", smooks);
  }
  public void test_configured_different_node_names() throws Exception {
    test_config_file("configured_different_node_names");

    // Programmatic config....
    Smooks smooks = new Smooks();

    smooks.setReaderConfig(
        new JSONReaderConfigurator().setRootName("root").setArrayElementName("e"));
    test_config_file("configured_different_node_names", smooks);
  }
  public void test_CDATA(String config) throws IOException, SAXException {
    Smooks smooks = new Smooks(getClass().getResourceAsStream(config));
    StringResult result = new StringResult();

    smooks.filterSource(new StreamSource(getClass().getResourceAsStream("in-message.xml")), result);
    assertTrue(
        StreamUtils.compareCharStreams(
            new InputStreamReader(getClass().getResourceAsStream("in-message.xml")),
            new StringReader(result.getResult())));
  }
  private Smooks getExtenededConfigDigester(String configNamespace) {
    Smooks smooks = extendedConfigDigesters.get(configNamespace);

    if (smooks == null) {
      URI namespaceURI;

      try {
        namespaceURI = new URI(configNamespace);
      } catch (URISyntaxException e) {
        throw new SmooksConfigurationException(
            "Unable to parse extended config namespace URI '" + configNamespace + "'.", e);
      }

      String resourcePath = "/META-INF" + namespaceURI.getPath() + "-smooks.xml";
      File resourceFile = new File(resourcePath);
      String baseURI = resourceFile.getParent().replace('\\', '/');

      // Validate the extended config...
      assertExtendedConfigOK(configNamespace, resourcePath);

      // Construct the Smooks instance for processing this config namespace...
      smooks = new Smooks(StandaloneApplicationContext.createNewInstance(false));
      setExtentionDigestOn();
      try {
        SmooksResourceConfigurationStore configStore = smooks.getApplicationContext().getStore();
        SmooksResourceConfigurationList extConfigList =
            new SmooksResourceConfigurationList(baseURI);

        XMLConfigDigester configDigester = new XMLConfigDigester(extConfigList);

        configDigester.extendedConfigDigesters = extendedConfigDigesters;
        configDigester.digestConfigRecursively(
            new InputStreamReader(ClassUtil.getResourceAsStream(resourcePath, classLoader)),
            baseURI);
        configStore.addSmooksResourceConfigurationList(extConfigList);
      } catch (Exception e) {
        throw new SmooksConfigurationException(
            "Failed to construct Smooks instance for processing extended configuration resource '"
                + resourcePath
                + "'.",
            e);
      } finally {
        setExtentionDigestOff();
      }

      // And add it to the Map of extension digesters...
      extendedConfigDigesters.put(configNamespace, smooks);
    }

    if (classLoader != null) {
      smooks.setClassLoader(classLoader);
    }

    return smooks;
  }
  public void test_indent() throws IOException, SAXException {
    Smooks smooks = new Smooks(getClass().getResourceAsStream("indent-config.xml"));
    StringResult result = new StringResult();

    smooks.filterSource(
        new StreamSource(getClass().getResourceAsStream("input-message.jsn")), result);

    assertTrue(
        XMLUnit.compareXML(
                StreamUtils.readStreamAsString(
                    getClass().getResourceAsStream("indent-expected.xml")),
                result.toString())
            .identical());
  }
  public void test_key_replacement() throws Exception {
    test_config_file("key_replacement");

    // Programmatic config....
    Smooks smooks = new Smooks();

    Map<String, String> keyMap = new HashMap<String, String>();

    keyMap.put("some key", "someKey");
    keyMap.put("some&key", "someAndKey");

    smooks.setReaderConfig(new JSONReaderConfigurator().setKeyMap(keyMap));
    test_config_file("key_replacement", smooks);
  }
  public void test_several_replacements() throws Exception {
    test_config_file("several_replacements");

    // Programmatic config....
    Smooks smooks = new Smooks();

    smooks.setReaderConfig(
        new JSONReaderConfigurator()
            .setKeyWhitspaceReplacement("_")
            .setKeyPrefixOnNumeric("n")
            .setIllegalElementNameCharReplacement(".")
            .setNullValueReplacement("##NULL##"));

    test_config_file("several_replacements", smooks);
  }
  private void digestExtendedResourceConfig(
      Element configElement,
      String defaultSelector,
      String defaultNamespace,
      String defaultProfile,
      String defaultConditionRef) {
    String configNamespace = configElement.getNamespaceURI();
    Smooks configDigester = getExtenededConfigDigester(configNamespace);
    ExecutionContext executionContext = configDigester.createExecutionContext();
    ExtensionContext extentionContext;
    Element conditionElement = DomUtils.getElement(configElement, "condition", 1);

    // Create the ExtenstionContext and set it on the ExecutionContext...
    if (conditionElement != null
        && (conditionElement.getNamespaceURI().equals(XSD_V10)
            || conditionElement.getNamespaceURI().equals(XSD_V11))) {
      extentionContext =
          new ExtensionContext(
              this,
              defaultSelector,
              defaultNamespace,
              defaultProfile,
              digestCondition(conditionElement));
    } else if (defaultConditionRef != null) {
      extentionContext =
          new ExtensionContext(
              this,
              defaultSelector,
              defaultNamespace,
              defaultProfile,
              getConditionEvaluator(defaultConditionRef));
    } else {
      extentionContext =
          new ExtensionContext(this, defaultSelector, defaultNamespace, defaultProfile, null);
    }
    ExtensionContext.setExtensionContext(extentionContext, executionContext);

    // Filter the extension element through Smooks...
    configDigester.filterSource(executionContext, new DOMSource(configElement), null);

    // Copy the created resources from the ExtensionContext and onto the
    // SmooksResourceConfigurationList...
    List<SmooksResourceConfiguration> resources = extentionContext.getResources();
    for (SmooksResourceConfiguration resource : resources) {
      resourcelist.add(resource);
    }
  }
  public void test_SAX() throws IOException, SAXException {
    Smooks smooks;
    ExecutionContext execContext;

    SAXAndDOMVisitor.visited = false;
    smooks = new Smooks(getClass().getResourceAsStream("test-config-SAX-01.xml"));
    execContext = smooks.createExecutionContext();
    smooks.filterSource(execContext, new StreamSource(new StringReader("<a/>")), null);
    assertEquals(execContext, TestExecutionContextExpressionEvaluator.context);
    assertTrue(SAXAndDOMVisitor.visited);

    SAXAndDOMVisitor.visited = false;
    smooks = new Smooks(getClass().getResourceAsStream("test-config-SAX-02.xml"));
    execContext = smooks.createExecutionContext();
    smooks.filterSource(execContext, new StreamSource(new StringReader("<a/>")), null);
    assertEquals(execContext, TestExecutionContextExpressionEvaluator.context);
    assertFalse(SAXAndDOMVisitor.visited);
  }
  private void test_config_file(String testName, Smooks smooks) throws IOException {
    ExecutionContext context = smooks.createExecutionContext();
    String result =
        SmooksUtil.filterAndSerialize(
            context,
            getClass().getResourceAsStream("/test/" + testName + "/input-message.jsn"),
            smooks);

    if (logger.isDebugEnabled()) {
      logger.debug("Result: " + result);
    }

    assertEquals("/test/" + testName + "/expected.xml", result.getBytes());
  }
Exemple #14
0
  /**
   * Run the transform for the request or response.
   *
   * @param inputJavaObject The input Java Object.
   * @return The transformed Java Object XML.
   */
  public String runSmooksTransform(Object inputJavaObject, String configFile)
      throws IOException, SAXException {
    Smooks smooks = new Smooks(configFile);
    String resultString = new String();
    try {
      ExecutionContext executionContext = smooks.createExecutionContext();
      StringWriter writer = new StringWriter();

      // Configure the execution context to generate a report...
      // executionContext.setEventListener(new HtmlReportGenerator("target/report/report.html"));

      // Filter the message to the result writer, using the execution context...
      smooks.filterSource(
          executionContext, new JavaSource(inputJavaObject), new StreamResult(writer));
      resultString = writer.toString();
      /*            resultString = this.replace(resultString, "list", "ResultSet");
                  resultString = this.replace(resultString, "<id>", "<GeneID type='entrez'>");
                  resultString = this.replace(resultString, "</id>", "</GeneID>");
                  resultString = this.replace(resultString, "<symbol>", "<GeneSymbol>");
                  resultString = this.replace(resultString, "</symbol>", "</GeneSymbol>");
                  resultString = this.replace(resultString, "org.ncibi.mimiweb.data.ResultGeneMolecule", "Result");
                  resultString = this.replace(resultString, "<taxid>", "<TaxonomyID>");
                  resultString = this.replace(resultString, "</taxid>", "</TaxonomyID>");
                  resultString = this.replace(resultString, "<description>", "<GeneDescription>");
                  resultString = this.replace(resultString, "</description>", "</GeneDescription>");
                  resultString = this.replace(resultString, "interactionGeneIds", "InteractingGeneIDSet");
                  resultString = this.replace(resultString, "<int>", "<GeneID type='entrez'>");
                  resultString = this.replace(resultString, "</int>", "</GeneID>");
                  resultString = this.replace(resultString, "interactionGeneSymbols", "InteractingGeneSymbolSet");
      */
      return resultString;

    } finally {
      smooks.close();
    }
  }
  public Map insertFilter(Source source) {
    JavaResult result = new JavaResult();

    // preserve the previous classloader, While we make Smooks aware of the Drools classloader
    ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread()
        .setContextClassLoader(
            ((InternalRuleBase) this.session.getRuleBase()).getRootClassLoader());

    ExecutionContext executionContext = this.smooks.createExecutionContext();

    // Filter the input message to extract, using the execution context...
    smooks.filter(source, result, executionContext);

    Thread.currentThread().setContextClassLoader(previousClassLoader);

    Map handles = new HashMap<FactHandle, Object>();

    Object object = result.getBean(this.configuration.getRoodId());
    if (object == null) {
      return handles;
    }

    if (this.getterExpr != null) {
      Iterable it = (Iterable) MVEL.executeExpression(this.getterExpr, object);
      if (it != null) {
        for (Object item : it) {
          FactHandle handle = this.session.insert(item);
          handles.put(handle, object);
        }
      }
    } else {
      FactHandle handle = this.session.insert(object);
      handles.put(handle, object);
    }

    return handles;
  }