Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.espertech.esper.client.TestConfigurationParser.java

protected static void assertFileConfig(Configuration config) throws Exception {
    // assert name for class
    assertEquals(2, config.getEventTypeAutoNamePackages().size());
    assertEquals("com.mycompany.eventsone", config.getEventTypeAutoNamePackages().toArray()[0]);
    assertEquals("com.mycompany.eventstwo", config.getEventTypeAutoNamePackages().toArray()[1]);

    // assert name for class
    assertEquals(3, config.getEventTypeNames().size());
    assertEquals("com.mycompany.myapp.MySampleEventOne", config.getEventTypeNames().get("MySampleEventOne"));
    assertEquals("com.mycompany.myapp.MySampleEventTwo", config.getEventTypeNames().get("MySampleEventTwo"));
    assertEquals("com.mycompany.package.MyLegacyTypeEvent",
            config.getEventTypeNames().get("MyLegacyTypeEvent"));

    // assert auto imports
    assertEquals(8, config.getImports().size());
    assertEquals("java.lang.*", config.getImports().get(0));
    assertEquals("java.math.*", config.getImports().get(1));
    assertEquals("java.text.*", config.getImports().get(2));
    assertEquals("java.util.*", config.getImports().get(3));
    assertEquals("com.espertech.esper.client.annotation.*", config.getImports().get(4));
    assertEquals("com.espertech.esper.dataflow.ops.*", config.getImports().get(5));
    assertEquals("com.mycompany.myapp.*", config.getImports().get(6));
    assertEquals("com.mycompany.myapp.ClassOne", config.getImports().get(7));

    // assert XML DOM - no schema
    assertEquals(2, config.getEventTypesXMLDOM().size());
    ConfigurationEventTypeXMLDOM noSchemaDesc = config.getEventTypesXMLDOM().get("MyNoSchemaXMLEventName");
    assertEquals("MyNoSchemaEvent", noSchemaDesc.getRootElementName());
    assertEquals("/myevent/element1", noSchemaDesc.getXPathProperties().get("element1").getXpath());
    assertEquals(XPathConstants.NUMBER, noSchemaDesc.getXPathProperties().get("element1").getType());
    assertEquals(null, noSchemaDesc.getXPathProperties().get("element1").getOptionalCastToType());
    assertNull(noSchemaDesc.getXPathFunctionResolver());
    assertNull(noSchemaDesc.getXPathVariableResolver());
    assertFalse(noSchemaDesc.isXPathPropertyExpr());

    // assert XML DOM - with schema
    ConfigurationEventTypeXMLDOM schemaDesc = config.getEventTypesXMLDOM().get("MySchemaXMLEventName");
    assertEquals("MySchemaEvent", schemaDesc.getRootElementName());
    assertEquals("MySchemaXMLEvent.xsd", schemaDesc.getSchemaResource());
    assertEquals("actual-xsd-text-here", schemaDesc.getSchemaText());
    assertEquals("samples:schemas:simpleSchema", schemaDesc.getRootElementNamespace());
    assertEquals("default-name-space", schemaDesc.getDefaultNamespace());
    assertEquals("/myevent/element2", schemaDesc.getXPathProperties().get("element2").getXpath());
    assertEquals(XPathConstants.STRING, schemaDesc.getXPathProperties().get("element2").getType());
    assertEquals(Long.class, schemaDesc.getXPathProperties().get("element2").getOptionalCastToType());
    assertEquals("/bookstore/book", schemaDesc.getXPathProperties().get("element3").getXpath());
    assertEquals(XPathConstants.NODESET, schemaDesc.getXPathProperties().get("element3").getType());
    assertEquals(null, schemaDesc.getXPathProperties().get("element3").getOptionalCastToType());
    assertEquals("MyOtherXMLNodeEvent",
            schemaDesc.getXPathProperties().get("element3").getOptionaleventTypeName());
    assertEquals(1, schemaDesc.getNamespacePrefixes().size());
    assertEquals("samples:schemas:simpleSchema", schemaDesc.getNamespacePrefixes().get("ss"));
    assertFalse(schemaDesc.isXPathResolvePropertiesAbsolute());
    assertEquals("com.mycompany.OptionalFunctionResolver", schemaDesc.getXPathFunctionResolver());
    assertEquals("com.mycompany.OptionalVariableResolver", schemaDesc.getXPathVariableResolver());
    assertTrue(schemaDesc.isXPathPropertyExpr());
    assertFalse(schemaDesc.isEventSenderValidatesRoot());
    assertFalse(schemaDesc.isAutoFragment());
    assertEquals("startts", schemaDesc.getStartTimestampPropertyName());
    assertEquals("endts", schemaDesc.getEndTimestampPropertyName());

    // assert mapped events
    assertEquals(1, config.getEventTypesMapEvents().size());
    assertTrue(config.getEventTypesMapEvents().keySet().contains("MyMapEvent"));
    Map<String, String> expectedProps = new HashMap<String, String>();
    expectedProps.put("myInt", "int");
    expectedProps.put("myString", "string");
    assertEquals(expectedProps, config.getEventTypesMapEvents().get("MyMapEvent"));
    assertEquals(1, config.getMapTypeConfigurations().size());
    Set<String> superTypes = config.getMapTypeConfigurations().get("MyMapEvent").getSuperTypes();
    EPAssertionUtil.assertEqualsExactOrder(new Object[] { "MyMapSuperType1", "MyMapSuperType2" },
            superTypes.toArray());/*from   ww w  .  j a va2s  .  c om*/
    assertEquals("startts",
            config.getMapTypeConfigurations().get("MyMapEvent").getStartTimestampPropertyName());
    assertEquals("endts", config.getMapTypeConfigurations().get("MyMapEvent").getEndTimestampPropertyName());

    // assert objectarray events
    assertEquals(1, config.getEventTypesNestableObjectArrayEvents().size());
    assertTrue(config.getEventTypesNestableObjectArrayEvents().containsKey("MyObjectArrayEvent"));
    Map<String, String> expectedPropsObjectArray = new HashMap<String, String>();
    expectedPropsObjectArray.put("myInt", "int");
    expectedPropsObjectArray.put("myString", "string");
    assertEquals(expectedPropsObjectArray,
            config.getEventTypesNestableObjectArrayEvents().get("MyObjectArrayEvent"));
    assertEquals(1, config.getObjectArrayTypeConfigurations().size());
    Set<String> superTypesOA = config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent")
            .getSuperTypes();
    EPAssertionUtil.assertEqualsExactOrder(
            new Object[] { "MyObjectArraySuperType1", "MyObjectArraySuperType2" }, superTypesOA.toArray());
    assertEquals("startts", config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent")
            .getStartTimestampPropertyName());
    assertEquals("endts",
            config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent").getEndTimestampPropertyName());

    // assert legacy type declaration
    assertEquals(1, config.getEventTypesLegacy().size());
    ConfigurationEventTypeLegacy legacy = config.getEventTypesLegacy().get("MyLegacyTypeEvent");
    assertEquals(ConfigurationEventTypeLegacy.CodeGeneration.ENABLED, legacy.getCodeGeneration());
    assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC, legacy.getAccessorStyle());
    assertEquals(1, legacy.getFieldProperties().size());
    assertEquals("myFieldName", legacy.getFieldProperties().get(0).getAccessorFieldName());
    assertEquals("myfieldprop", legacy.getFieldProperties().get(0).getName());
    assertEquals(1, legacy.getMethodProperties().size());
    assertEquals("myAccessorMethod", legacy.getMethodProperties().get(0).getAccessorMethodName());
    assertEquals("mymethodprop", legacy.getMethodProperties().get(0).getName());
    assertEquals(Configuration.PropertyResolutionStyle.CASE_INSENSITIVE, legacy.getPropertyResolutionStyle());
    assertEquals("com.mycompany.myapp.MySampleEventFactory.createMyLegacyTypeEvent", legacy.getFactoryMethod());
    assertEquals("myCopyMethod", legacy.getCopyMethod());
    assertEquals("startts", legacy.getStartTimestampPropertyName());
    assertEquals("endts", legacy.getEndTimestampPropertyName());

    // assert database reference - data source config
    assertEquals(3, config.getDatabaseReferences().size());
    ConfigurationDBRef configDBRef = config.getDatabaseReferences().get("mydb1");
    ConfigurationDBRef.DataSourceConnection dsDef = (ConfigurationDBRef.DataSourceConnection) configDBRef
            .getConnectionFactoryDesc();
    assertEquals("java:comp/env/jdbc/mydb", dsDef.getContextLookupName());
    assertEquals(
            "{java.naming.provider.url=iiop://localhost:1050, java.naming.factory.initial=com.myclass.CtxFactory}",
            dsDef.getEnvProperties().toString());
    assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.POOLED, configDBRef.getConnectionLifecycleEnum());
    assertNull(configDBRef.getConnectionSettings().getAutoCommit());
    assertNull(configDBRef.getConnectionSettings().getCatalog());
    assertNull(configDBRef.getConnectionSettings().getReadOnly());
    assertNull(configDBRef.getConnectionSettings().getTransactionIsolation());
    ConfigurationLRUCache lruCache = (ConfigurationLRUCache) configDBRef.getDataCacheDesc();
    assertEquals(10, lruCache.getSize());
    assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.LOWERCASE, configDBRef.getColumnChangeCase());
    assertEquals(ConfigurationDBRef.MetadataOriginEnum.SAMPLE, configDBRef.getMetadataRetrievalEnum());
    assertEquals(2, configDBRef.getSqlTypesMapping().size());
    assertEquals("int", configDBRef.getSqlTypesMapping().get(2));
    assertEquals("float", configDBRef.getSqlTypesMapping().get(6));

    // assert database reference - driver manager config
    configDBRef = config.getDatabaseReferences().get("mydb2");
    ConfigurationDBRef.DriverManagerConnection dmDef = (ConfigurationDBRef.DriverManagerConnection) configDBRef
            .getConnectionFactoryDesc();
    assertEquals("my.sql.Driver", dmDef.getClassName());
    assertEquals("jdbc:mysql://localhost", dmDef.getUrl());
    assertEquals("myuser1", dmDef.getOptionalUserName());
    assertEquals("mypassword1", dmDef.getOptionalPassword());
    assertEquals("{user=myuser2, password=mypassword2, somearg=someargvalue}",
            dmDef.getOptionalProperties().toString());
    assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.RETAIN, configDBRef.getConnectionLifecycleEnum());
    assertEquals((Boolean) false, configDBRef.getConnectionSettings().getAutoCommit());
    assertEquals("test", configDBRef.getConnectionSettings().getCatalog());
    assertEquals(Boolean.TRUE, configDBRef.getConnectionSettings().getReadOnly());
    assertEquals(new Integer(3), configDBRef.getConnectionSettings().getTransactionIsolation());
    ConfigurationExpiryTimeCache expCache = (ConfigurationExpiryTimeCache) configDBRef.getDataCacheDesc();
    assertEquals(60.5, expCache.getMaxAgeSeconds());
    assertEquals(120.1, expCache.getPurgeIntervalSeconds());
    assertEquals(ConfigurationCacheReferenceType.HARD, expCache.getCacheReferenceType());
    assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.UPPERCASE, configDBRef.getColumnChangeCase());
    assertEquals(ConfigurationDBRef.MetadataOriginEnum.METADATA, configDBRef.getMetadataRetrievalEnum());
    assertEquals(1, configDBRef.getSqlTypesMapping().size());
    assertEquals("java.lang.String", configDBRef.getSqlTypesMapping().get(99));

    // assert database reference - data source factory and DBCP config
    configDBRef = config.getDatabaseReferences().get("mydb3");
    ConfigurationDBRef.DataSourceFactory dsFactory = (ConfigurationDBRef.DataSourceFactory) configDBRef
            .getConnectionFactoryDesc();
    assertEquals("org.apache.commons.dbcp.BasicDataSourceFactory", dsFactory.getFactoryClassname());
    assertEquals("jdbc:mysql://localhost/test", dsFactory.getProperties().getProperty("url"));
    assertEquals("myusername", dsFactory.getProperties().getProperty("username"));
    assertEquals("mypassword", dsFactory.getProperties().getProperty("password"));
    assertEquals("com.mysql.jdbc.Driver", dsFactory.getProperties().getProperty("driverClassName"));
    assertEquals("2", dsFactory.getProperties().getProperty("initialSize"));

    // assert custom view implementations
    List<ConfigurationPlugInView> configViews = config.getPlugInViews();
    assertEquals(2, configViews.size());
    for (int i = 0; i < configViews.size(); i++) {
        ConfigurationPlugInView entry = configViews.get(i);
        assertEquals("ext" + i, entry.getNamespace());
        assertEquals("myview" + i, entry.getName());
        assertEquals("com.mycompany.MyViewFactory" + i, entry.getFactoryClassName());
    }

    // assert custom virtual data window implementations
    List<ConfigurationPlugInVirtualDataWindow> configVDW = config.getPlugInVirtualDataWindows();
    assertEquals(2, configVDW.size());
    for (int i = 0; i < configVDW.size(); i++) {
        ConfigurationPlugInVirtualDataWindow entry = configVDW.get(i);
        assertEquals("vdw" + i, entry.getNamespace());
        assertEquals("myvdw" + i, entry.getName());
        assertEquals("com.mycompany.MyVdwFactory" + i, entry.getFactoryClassName());
        if (i == 1) {
            assertEquals("abc", entry.getConfig());
        }
    }

    // assert adapter loaders parsed
    List<ConfigurationPluginLoader> plugins = config.getPluginLoaders();
    assertEquals(2, plugins.size());
    ConfigurationPluginLoader pluginOne = plugins.get(0);
    assertEquals("Loader1", pluginOne.getLoaderName());
    assertEquals("com.espertech.esper.support.plugin.SupportLoaderOne", pluginOne.getClassName());
    assertEquals(2, pluginOne.getConfigProperties().size());
    assertEquals("val1", pluginOne.getConfigProperties().get("name1"));
    assertEquals("val2", pluginOne.getConfigProperties().get("name2"));
    assertEquals(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sample-initializer><some-any-xml-can-be-here>This section for use by a plugin loader.</some-any-xml-can-be-here></sample-initializer>",
            pluginOne.getConfigurationXML());

    ConfigurationPluginLoader pluginTwo = plugins.get(1);
    assertEquals("Loader2", pluginTwo.getLoaderName());
    assertEquals("com.espertech.esper.support.plugin.SupportLoaderTwo", pluginTwo.getClassName());
    assertEquals(0, pluginTwo.getConfigProperties().size());

    // assert plug-in aggregation function loaded
    assertEquals(4, config.getPlugInAggregationFunctions().size());
    ConfigurationPlugInAggregationFunction pluginAgg = config.getPlugInAggregationFunctions().get(0);
    assertEquals("com.mycompany.MyMatrixAggregationMethod0DEPRECATED", pluginAgg.getFunctionClassName());
    assertEquals("func1", pluginAgg.getName());
    assertEquals(null, pluginAgg.getFactoryClassName());
    pluginAgg = config.getPlugInAggregationFunctions().get(1);
    assertEquals("com.mycompany.MyMatrixAggregationMethod1DEPRECATED", pluginAgg.getFunctionClassName());
    assertEquals("func2", pluginAgg.getName());
    assertEquals(null, pluginAgg.getFactoryClassName());
    pluginAgg = config.getPlugInAggregationFunctions().get(2);
    assertEquals(null, pluginAgg.getFunctionClassName());
    assertEquals("func1a", pluginAgg.getName());
    assertEquals("com.mycompany.MyMatrixAggregationMethod0Factory", pluginAgg.getFactoryClassName());
    pluginAgg = config.getPlugInAggregationFunctions().get(3);
    assertEquals(null, pluginAgg.getFunctionClassName());
    assertEquals("func2a", pluginAgg.getName());
    assertEquals("com.mycompany.MyMatrixAggregationMethod1Factory", pluginAgg.getFactoryClassName());

    // assert plug-in aggregation multi-function loaded
    assertEquals(1, config.getPlugInAggregationMultiFunctions().size());
    ConfigurationPlugInAggregationMultiFunction pluginMultiAgg = config.getPlugInAggregationMultiFunctions()
            .get(0);
    EPAssertionUtil.assertEqualsExactOrder(new String[] { "func1", "func2" },
            pluginMultiAgg.getFunctionNames());
    assertEquals("com.mycompany.MyAggregationMultiFunctionFactory",
            pluginMultiAgg.getMultiFunctionFactoryClassName());
    assertEquals(1, pluginMultiAgg.getAdditionalConfiguredProperties().size());
    assertEquals("value1", pluginMultiAgg.getAdditionalConfiguredProperties().get("prop1"));

    // assert plug-in singlerow function loaded
    assertEquals(2, config.getPlugInSingleRowFunctions().size());
    ConfigurationPlugInSingleRowFunction pluginSingleRow = config.getPlugInSingleRowFunctions().get(0);
    assertEquals("com.mycompany.MyMatrixSingleRowMethod0", pluginSingleRow.getFunctionClassName());
    assertEquals("method1", pluginSingleRow.getFunctionMethodName());
    assertEquals("func3", pluginSingleRow.getName());
    assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.DISABLED, pluginSingleRow.getValueCache());
    assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.ENABLED,
            pluginSingleRow.getFilterOptimizable());
    assertFalse(pluginSingleRow.isRethrowExceptions());
    pluginSingleRow = config.getPlugInSingleRowFunctions().get(1);
    assertEquals("com.mycompany.MyMatrixSingleRowMethod1", pluginSingleRow.getFunctionClassName());
    assertEquals("func4", pluginSingleRow.getName());
    assertEquals("method2", pluginSingleRow.getFunctionMethodName());
    assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.ENABLED, pluginSingleRow.getValueCache());
    assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.DISABLED,
            pluginSingleRow.getFilterOptimizable());
    assertTrue(pluginSingleRow.isRethrowExceptions());

    // assert plug-in guard objects loaded
    assertEquals(4, config.getPlugInPatternObjects().size());
    ConfigurationPlugInPatternObject pluginPattern = config.getPlugInPatternObjects().get(0);
    assertEquals("com.mycompany.MyGuardFactory0", pluginPattern.getFactoryClassName());
    assertEquals("ext0", pluginPattern.getNamespace());
    assertEquals("guard1", pluginPattern.getName());
    assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD,
            pluginPattern.getPatternObjectType());
    pluginPattern = config.getPlugInPatternObjects().get(1);
    assertEquals("com.mycompany.MyGuardFactory1", pluginPattern.getFactoryClassName());
    assertEquals("ext1", pluginPattern.getNamespace());
    assertEquals("guard2", pluginPattern.getName());
    assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD,
            pluginPattern.getPatternObjectType());
    pluginPattern = config.getPlugInPatternObjects().get(2);
    assertEquals("com.mycompany.MyObserverFactory0", pluginPattern.getFactoryClassName());
    assertEquals("ext0", pluginPattern.getNamespace());
    assertEquals("observer1", pluginPattern.getName());
    assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER,
            pluginPattern.getPatternObjectType());
    pluginPattern = config.getPlugInPatternObjects().get(3);
    assertEquals("com.mycompany.MyObserverFactory1", pluginPattern.getFactoryClassName());
    assertEquals("ext1", pluginPattern.getNamespace());
    assertEquals("observer2", pluginPattern.getName());
    assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER,
            pluginPattern.getPatternObjectType());

    // assert engine defaults
    assertFalse(config.getEngineDefaults().getThreading().isInsertIntoDispatchPreserveOrder());
    assertEquals(3000, config.getEngineDefaults().getThreading().getInsertIntoDispatchTimeout());
    assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND,
            config.getEngineDefaults().getThreading().getInsertIntoDispatchLocking());

    assertFalse(config.getEngineDefaults().getThreading().isListenerDispatchPreserveOrder());
    assertEquals(2000, config.getEngineDefaults().getThreading().getListenerDispatchTimeout());
    assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND,
            config.getEngineDefaults().getThreading().getListenerDispatchLocking());
    assertTrue(config.getEngineDefaults().getThreading().isThreadPoolInbound());
    assertTrue(config.getEngineDefaults().getThreading().isThreadPoolOutbound());
    assertTrue(config.getEngineDefaults().getThreading().isThreadPoolRouteExec());
    assertTrue(config.getEngineDefaults().getThreading().isThreadPoolTimerExec());
    assertEquals(1, config.getEngineDefaults().getThreading().getThreadPoolInboundNumThreads());
    assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolOutboundNumThreads());
    assertEquals(3, config.getEngineDefaults().getThreading().getThreadPoolTimerExecNumThreads());
    assertEquals(4, config.getEngineDefaults().getThreading().getThreadPoolRouteExecNumThreads());
    assertEquals(1000, (int) config.getEngineDefaults().getThreading().getThreadPoolInboundCapacity());
    assertEquals(1500, (int) config.getEngineDefaults().getThreading().getThreadPoolOutboundCapacity());
    assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolTimerExecCapacity());
    assertEquals(2000, (int) config.getEngineDefaults().getThreading().getThreadPoolRouteExecCapacity());

    assertFalse(config.getEngineDefaults().getThreading().isInternalTimerEnabled());
    assertEquals(1234567, config.getEngineDefaults().getThreading().getInternalTimerMsecResolution());
    assertFalse(config.getEngineDefaults().getViewResources().isShareViews());
    assertTrue(config.getEngineDefaults().getViewResources().isAllowMultipleExpiryPolicies());
    assertEquals(Configuration.PropertyResolutionStyle.DISTINCT_CASE_INSENSITIVE,
            config.getEngineDefaults().getEventMeta().getClassPropertyResolutionStyle());
    assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC,
            config.getEngineDefaults().getEventMeta().getDefaultAccessorStyle());
    assertEquals(Configuration.EventRepresentation.MAP,
            config.getEngineDefaults().getEventMeta().getDefaultEventRepresentation());
    assertEquals(100, config.getEngineDefaults().getEventMeta().getAnonymousCacheSize());
    assertTrue(config.getEngineDefaults().getLogging().isEnableExecutionDebug());
    assertFalse(config.getEngineDefaults().getLogging().isEnableTimerDebug());
    assertTrue(config.getEngineDefaults().getLogging().isEnableQueryPlan());
    assertTrue(config.getEngineDefaults().getLogging().isEnableJDBC());
    assertEquals("[%u] %m", config.getEngineDefaults().getLogging().getAuditPattern());
    assertEquals(30000, config.getEngineDefaults().getVariables().getMsecVersionRelease());
    assertEquals(3L, (long) config.getEngineDefaults().getPatterns().getMaxSubexpressions());
    assertEquals(false, config.getEngineDefaults().getPatterns().isMaxSubexpressionPreventStart());
    assertEquals(StreamSelector.RSTREAM_ISTREAM_BOTH,
            config.getEngineDefaults().getStreamSelection().getDefaultStreamSelector());

    assertEquals(ConfigurationEngineDefaults.TimeSourceType.NANO,
            config.getEngineDefaults().getTimeSource().getTimeSourceType());
    assertTrue(config.getEngineDefaults().getExecution().isPrioritized());
    assertTrue(config.getEngineDefaults().getExecution().isFairlock());
    assertTrue(config.getEngineDefaults().getExecution().isDisableLocking());
    assertEquals(ConfigurationEngineDefaults.ThreadingProfile.LARGE,
            config.getEngineDefaults().getExecution().getThreadingProfile());

    ConfigurationMetricsReporting metrics = config.getEngineDefaults().getMetricsReporting();
    assertTrue(metrics.isEnableMetricsReporting());
    assertEquals(4000L, metrics.getEngineInterval());
    assertEquals(500L, metrics.getStatementInterval());
    assertFalse(metrics.isThreading());
    assertEquals(2, metrics.getStatementGroups().size());
    assertTrue(metrics.isJmxEngineMetrics());
    ConfigurationMetricsReporting.StmtGroupMetrics def = metrics.getStatementGroups().get("MyStmtGroup");
    assertEquals(5000, def.getInterval());
    assertTrue(def.isDefaultInclude());
    assertEquals(50, def.getNumStatements());
    assertTrue(def.isReportInactive());
    assertEquals(5, def.getPatterns().size());
    assertEquals(def.getPatterns().get(0),
            new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*"), true));
    assertEquals(def.getPatterns().get(1),
            new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*test.*"), false));
    assertEquals(def.getPatterns().get(2),
            new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyMetricsStatement%"), false));
    assertEquals(def.getPatterns().get(3),
            new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyFraudAnalysisStatement%"), true));
    assertEquals(def.getPatterns().get(4),
            new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%SomerOtherStatement%"), true));
    def = metrics.getStatementGroups().get("MyStmtGroupTwo");
    assertEquals(200, def.getInterval());
    assertFalse(def.isDefaultInclude());
    assertEquals(100, def.getNumStatements());
    assertFalse(def.isReportInactive());
    assertEquals(0, def.getPatterns().size());
    assertTrue(config.getEngineDefaults().getLanguage().isSortUsingCollator());
    assertTrue(config.getEngineDefaults().getExpression().isIntegerDivision());
    assertTrue(config.getEngineDefaults().getExpression().isDivisionByZeroReturnsNull());
    assertFalse(config.getEngineDefaults().getExpression().isSelfSubselectPreeval());
    assertFalse(config.getEngineDefaults().getExpression().isUdfCache());
    assertFalse(config.getEngineDefaults().getExpression().isExtendedAggregation());
    assertTrue(config.getEngineDefaults().getExpression().isDuckTyping());
    assertEquals(2, config.getEngineDefaults().getExpression().getMathContext().getPrecision());
    assertEquals(RoundingMode.CEILING,
            config.getEngineDefaults().getExpression().getMathContext().getRoundingMode());
    assertEquals(2, config.getEngineDefaults().getExceptionHandling().getHandlerFactories().size());
    assertEquals("my.company.cep.LoggingExceptionHandlerFactory",
            config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(0));
    assertEquals("my.company.cep.AlertExceptionHandlerFactory",
            config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(1));
    assertEquals(2, config.getEngineDefaults().getConditionHandling().getHandlerFactories().size());
    assertEquals("my.company.cep.LoggingConditionHandlerFactory",
            config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(0));
    assertEquals("my.company.cep.AlertConditionHandlerFactory",
            config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(1));
    assertEquals("abc", config.getEngineDefaults().getScripts().getDefaultDialect());

    // variables
    assertEquals(3, config.getVariables().size());
    ConfigurationVariable variable = config.getVariables().get("var1");
    assertEquals(Integer.class.getName(), variable.getType());
    assertEquals("1", variable.getInitializationValue());
    assertFalse(variable.isConstant());
    variable = config.getVariables().get("var2");
    assertEquals(String.class.getName(), variable.getType());
    assertEquals(null, variable.getInitializationValue());
    assertFalse(variable.isConstant());
    variable = config.getVariables().get("var3");
    assertTrue(variable.isConstant());

    // method references
    assertEquals(2, config.getMethodInvocationReferences().size());
    ConfigurationMethodRef methodRef = config.getMethodInvocationReferences().get("abc");
    expCache = (ConfigurationExpiryTimeCache) methodRef.getDataCacheDesc();
    assertEquals(91.0, expCache.getMaxAgeSeconds());
    assertEquals(92.2, expCache.getPurgeIntervalSeconds());
    assertEquals(ConfigurationCacheReferenceType.WEAK, expCache.getCacheReferenceType());

    methodRef = config.getMethodInvocationReferences().get("def");
    lruCache = (ConfigurationLRUCache) methodRef.getDataCacheDesc();
    assertEquals(20, lruCache.getSize());

    // plug-in event representations
    assertEquals(2, config.getPlugInEventRepresentation().size());
    ConfigurationPlugInEventRepresentation rep = config.getPlugInEventRepresentation()
            .get(new URI("type://format/rep/name"));
    assertEquals("com.mycompany.MyPlugInEventRepresentation", rep.getEventRepresentationClassName());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event rep init</anyxml>",
            rep.getInitializer());
    rep = config.getPlugInEventRepresentation().get(new URI("type://format/rep/name2"));
    assertEquals("com.mycompany.MyPlugInEventRepresentation2", rep.getEventRepresentationClassName());
    assertEquals(null, rep.getInitializer());

    // plug-in event types
    assertEquals(2, config.getPlugInEventTypes().size());
    ConfigurationPlugInEventType type = config.getPlugInEventTypes().get("MyEvent");
    assertEquals(2, type.getEventRepresentationResolutionURIs().length);
    assertEquals("type://format/rep", type.getEventRepresentationResolutionURIs()[0].toString());
    assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[1].toString());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event type init</anyxml>",
            type.getInitializer());
    type = config.getPlugInEventTypes().get("MyEvent2");
    assertEquals(1, type.getEventRepresentationResolutionURIs().length);
    assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[0].toString());
    assertEquals(null, type.getInitializer());

    // plug-in event representation resolution URIs when using a new name in a statement
    assertEquals(2, config.getPlugInEventTypeResolutionURIs().length);
    assertEquals("type://format/rep", config.getPlugInEventTypeResolutionURIs()[0].toString());
    assertEquals("type://format/rep2", config.getPlugInEventTypeResolutionURIs()[1].toString());

    // revision types
    assertEquals(1, config.getRevisionEventTypes().size());
    ConfigurationRevisionEventType configRev = config.getRevisionEventTypes().get("MyRevisionEvent");
    assertEquals(1, configRev.getNameBaseEventTypes().size());
    assertTrue(configRev.getNameBaseEventTypes().contains("MyBaseEventName"));
    assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameOne"));
    assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameTwo"));
    EPAssertionUtil.assertEqualsAnyOrder(new String[] { "id", "id2" }, configRev.getKeyPropertyNames());
    assertEquals(ConfigurationRevisionEventType.PropertyRevision.MERGE_NON_NULL,
            configRev.getPropertyRevision());

    // variance types
    assertEquals(1, config.getVariantStreams().size());
    ConfigurationVariantStream configVStream = config.getVariantStreams().get("MyVariantStream");
    assertEquals(2, configVStream.getVariantTypeNames().size());
    assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameOne"));
    assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameTwo"));
    assertEquals(ConfigurationVariantStream.TypeVariance.ANY, configVStream.getTypeVariance());
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * @param responseString/*from w  w w . j  a  v a2 s.c o  m*/
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
public static HashMap<String, HashMap<String, String>> responseFactory(String responseString)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    HashMap<String, HashMap<String, String>> returnMap = new HashMap<String, HashMap<String, String>>();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(new InputSource(new StringReader(responseString)));

    //String messageName = document.getFirstChild().getNodeName();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(new SugarCRMNamespaceContext());
    XPathExpression expr = xpath.compile("//ns1:get_entry_listResponse/return/entry_list/item");

    Object result = expr.evaluate(document, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {

        NodeList innerNodes = nodes.item(i).getChildNodes();

        String id = innerNodes.item(0).getTextContent();

        HashMap<String, String> elementData = new HashMap<String, String>();

        NodeList infoNodes = innerNodes.item(2).getChildNodes();

        for (int z = 0; z < infoNodes.getLength(); z++) {
            String name = infoNodes.item(z).getFirstChild().getTextContent();
            String value = infoNodes.item(z).getLastChild().getTextContent();

            elementData.put(name, value);
        }
        returnMap.put(id, elementData);
    }
    return returnMap;
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * Returns the error codes//from  w w  w  .j av  a  2s  .c o m
 * @param rootNode
 * @param xpath
 * @return
 * @throws TSClientExecutionException
 */
protected List<Long> parseErrorCodes(Node rootNode, XPath xpath) throws TSClientExecutionException {

    NodeList errorCodeNodes = null;
    try {
        errorCodeNodes = (NodeList) xpath.evaluate(TEST_EXEC_ERROR_CODES, rootNode, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException(
                "Failed to parse out error codes from document received from " + httpHost.getHostName());
    }

    List<Long> result = new ArrayList<Long>();
    if (errorCodeNodes != null && errorCodeNodes.getLength() > 0) {
        for (int i = 0; i < errorCodeNodes.getLength(); i++) {
            if (errorCodeNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                try {
                    // TODO refactor to xpath
                    String errorCodeStr = errorCodeNodes.item(i).getTextContent();//;(String)xpath.evaluate(TEST_EXEC_SINGLE_ERROR_CODE, errorCodeNodes.item(i), XPathConstants.STRING);                  
                    result.add(Long.parseLong(errorCodeStr.trim()));
                } catch (NumberFormatException e) {
                    throw new TSClientExecutionException(
                            "Failed to parse error code from document received from " + httpHost.getHostName()
                                    + ". Error: " + e.getMessage());
                    //               } catch(XPathExpressionException e) {
                    //                  throw new TSClientExecutionException("Failed to parse error code from document received from " + httpHost.getHostName() + ". Error: " + e.getMessage());
                }
            }
        }
    }
    return result;
}

From source file:com.searchbox.collection.oppfin.IdealISTCollection.java

private void addField(String uid, Document document, FieldMap fields, Class<?> clazz, String key,
        String fieldName) {//from   w w w . j  a va  2  s .co  m
    XPath xPath = XPathFactory.newInstance().newXPath();
    String metaDataExpression = "//metadata[@key='" + key + "']|" + "//content[@cid='" + key + "']";

    // read a nodelist using xpath
    NodeList nodeList;
    try {
        nodeList = (NodeList) xPath.compile(metaDataExpression).evaluate(document, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {

            StringBuilder textBuilder = new StringBuilder();
            for (int j = 0; j < nodeList.item(i).getChildNodes().getLength(); j++) {
                Node textNode = nodeList.item(i).getChildNodes().item(j);
                if (textNode.getNodeType() == Node.TEXT_NODE
                        || textNode.getNodeType() == Node.CDATA_SECTION_NODE) {
                    textBuilder.append(textNode.getNodeValue());
                }
            }
            String value = textBuilder.toString();

            LOGGER.debug("value for key {} is {}", key, value);
            if (value.isEmpty()) {
                continue;
            }
            if (String.class.isAssignableFrom(clazz)) {
                String content = new HtmlToPlainText().getPlainText(Jsoup.parse(value));
                fields.put(fieldName, content);
                fields.put(fieldName + "Html", value);
            } else if (Date.class.isAssignableFrom(clazz)) {
                Date date;
                try {
                    date = dfmt.parse(value);
                    fields.put(fieldName, date);
                } catch (ParseException e) {
                    LOGGER.warn("Could not parse date({}) for for key {} in document {}", value, key, uid);
                }
            }
        }
    } catch (XPathExpressionException e) {
        LOGGER.warn("Could not execute XPATH for key {} in document {}", key, uid);
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void execute0(Document document, MessageContext msgCtxt) throws Exception {
    String xpath = getXpath(msgCtxt);
    XPathEvaluator xpe = getXpe(msgCtxt);
    NodeList nodes = (NodeList) xpe.evaluate(xpath, document, XPathConstants.NODESET);
    validate(nodes);//  www . j  av  a  2 s  .c  om
    EditAction action = getAction(msgCtxt);
    if (action == EditAction.Remove) {
        remove(nodes);
        return;
    }

    short newNodeType = getNewNodeType(msgCtxt);
    String text = getNewNodeText(msgCtxt);
    Node newNode = null;
    switch (newNodeType) {
    case Node.ELEMENT_NODE:
        // Create a duplicate node and transfer ownership of the
        // new node into the destination document.
        Document temp = XmlUtils.parseXml(text);
        newNode = document.importNode(temp.getDocumentElement(), true);
        break;
    case Node.ATTRIBUTE_NODE:
        if (text.indexOf("=") < 1) {
            throw new IllegalStateException("attribute spec must be name=value");
        }
        String[] parts = text.split("=", 2);
        if (parts.length != 2)
            throw new IllegalStateException("attribute spec must be name=value");
        Attr attr = document.createAttribute(parts[0]);
        attr.setValue(parts[1]);
        newNode = attr;
        break;
    case Node.TEXT_NODE:
        newNode = document.createTextNode(text);
        break;
    }
    switch (action) {
    case InsertBefore:
        insertBefore(nodes, newNode, newNodeType);
        break;
    case Append:
        append(nodes, newNode, newNodeType);
        break;
    case Replace:
        replace(nodes, newNode, newNodeType);
        break;
    }
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

XPathExpression evaluateXPaths(XPathIterator iterator, Document doc) throws Exception {
    while (iterator.hasNext()) {
        XPathExpression exp = iterator.next();
        NodeList result = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        boolean negativeTest = exp.toString().startsWith("-");
        int solutions = result.getLength();
        // a positive test should return exactly one solution
        boolean failure = ((solutions < 1 && !negativeTest)
                // a negative test should return no solutions
                || (solutions > 0 && negativeTest));
        if (failure)
            return exp; // fail
    }/*  w  w w .ja va  2s.  c o  m*/
    return null;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneStatus() throws XPathExpressionException {
    NodeList statuses = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:status", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), statuses.getLength() <= 1);
}

From source file:org.bedework.notifier.outbound.email.EmailAdaptor.java

private List<TemplateResult> applyTemplates(final Action action) throws NoteException {
    final Note note = action.getNote();
    final NotificationType nt = note.getNotification();
    final EmailSubscription sub = EmailSubscription.rewrap(action.getSub());

    List<TemplateResult> results = new ArrayList<TemplateResult>();
    try {/*  w  ww  . jav  a  2s  .c om*/
        String prefix = nt.getParsed().getDocumentElement().getPrefix();

        if (prefix == null) {
            prefix = "default";
        }

        final String abstractPath = Util.buildPath(false, Note.DeliveryMethod.email.toString(), "/", prefix,
                "/", nt.getNotification().getElementName().getLocalPart());

        File templateDir = new File(Util.buildPath(false, globalConfig.getTemplatesPath(), "/", abstractPath));
        if (templateDir.isDirectory()) {

            Map<String, Object> root = new HashMap<String, Object>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(nt.toXml(true))));
            Element el = doc.getDocumentElement();
            NodeModel.simplify(el);
            NodeModel.useJaxenXPathSupport();
            root.put("notification", el);

            HashSet<String> recipients = new HashSet<String>();
            for (String email : sub.getEmails()) {
                recipients.add(MAILTO + email);
            }
            root.put("recipients", recipients);

            if (globalConfig.getCardDAVHost() != null && globalConfig.getCardDAVPort() != 0
                    && globalConfig.getCardDAVContextPath() != null) {
                HashMap<String, Object> vcards = new HashMap<String, Object>();
                BasicHttpClient client;
                try {
                    ArrayList<Header> hdrs = new ArrayList<Header>();
                    BasicHeader h = new BasicHeader(HEADER_ACCEPT, globalConfig.getVCardContentType());
                    hdrs.add(h);

                    client = new BasicHttpClient(globalConfig.getCardDAVHost(), globalConfig.getCardDAVPort(),
                            null, 15 * 1000);

                    XPathExpression exp = xPath.compile("//*[local-name() = 'href']");
                    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    HashSet<String> vcardLookups = new HashSet<String>();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        String text = n.getTextContent();

                        text = pMailto.matcher(text).replaceFirst(MAILTO);
                        if (text.startsWith(MAILTO)
                                || text.startsWith(globalConfig.getCardDAVPrincipalsPath())) {
                            vcardLookups.add(text);
                        }
                    }

                    // Get vCards for recipients too. They may not be referenced in the notification.
                    vcardLookups.addAll(recipients);

                    for (String lookup : vcardLookups) {
                        String path = Util.buildPath(false,
                                globalConfig.getCardDAVContextPath() + "/" + lookup.replace(':', '/'));

                        final InputStream is = client.get(path + VCARD_SUFFIX, "application/text", hdrs);
                        if (is != null) {
                            ObjectMapper om = new ObjectMapper();
                            @SuppressWarnings("unchecked")
                            ArrayList<Object> hm = om.readValue(is, ArrayList.class);
                            vcards.put(lookup, hm);
                        }
                    }
                    root.put("vcards", vcards);
                } catch (final Throwable t) {
                    error(t);
                }
            }

            if (nt.getNotification() instanceof ResourceChangeType) {
                ResourceChangeType chg = (ResourceChangeType) nt.getNotification();
                BedeworkConnectorConfig cfg = ((BedeworkConnector) action.getConn()).getConnectorConfig();
                BasicHttpClient cl = getClient(cfg);
                List<Header> hdrs = getHeaders(cfg, new BedeworkSubscription(action.getSub()));

                String href = null;
                if (chg.getCreated() != null) {
                    href = chg.getCreated().getHref();
                } else if (chg.getDeleted() != null) {
                    href = chg.getDeleted().getHref();
                } else if (chg.getUpdated() != null && chg.getUpdated().size() > 0) {
                    href = chg.getUpdated().get(0).getHref();
                }

                if (href != null) {
                    if (chg.getDeleted() == null) {
                        // We only have an event for the templates on a create or update, not on delete.
                        ObjectMapper om = new ObjectMapper();
                        final InputStream is = cl.get(cfg.getSystemUrl() + href, null, hdrs);
                        JsonNode a = om.readValue(is, JsonNode.class);

                        // Check for a recurrence ID on this notification.
                        XPathExpression exp = xPath.compile("//*[local-name() = 'recurrenceid']/text()");
                        String rid = exp.evaluate(doc);
                        if (rid != null && !rid.isEmpty()) {
                            Calendar rcal = Calendar.getInstance();
                            recurIdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                            rcal.setTime(recurIdFormat.parse(rid));

                            // Find the matching recurrence ID in the JSON, and make that the only vevent object.
                            Calendar c = Calendar.getInstance();
                            ArrayNode vevents = (ArrayNode) a.get(2);
                            for (JsonNode vevent : vevents) {
                                if (vevent.size() > 1 && vevent.get(1).size() > 1) {
                                    JsonNode n = vevent.get(1).get(0);
                                    if (n.get(0).asText().equals("recurrence-id")) {
                                        if (n.get(1).size() > 0 && n.get(1).get("tzid") != null) {
                                            jsonIdFormatTZ.setTimeZone(
                                                    TimeZone.getTimeZone(n.get(1).get("tzid").asText()));
                                            c.setTime(jsonIdFormatTZ.parse(n.get(3).asText()));
                                        } else {
                                            jsonIdFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            c.setTime(jsonIdFormatUTC.parse(n.get(3).asText()));
                                        }
                                        if (rcal.compareTo(c) == 0) {
                                            vevents.removeAll();
                                            vevents.add(vevent);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        root.put("vevent", (ArrayList<Object>) om.convertValue(a, ArrayList.class));
                    }

                    // TODO: Provide some calendar information to the templates. This is currently the publisher's
                    // calendar, but needs to be fixed to be the subscriber's calendar.
                    String chref = href.substring(0, href.lastIndexOf("/"));
                    hdrs.add(new BasicHeader(HEADER_DEPTH, "0"));
                    int rc = cl.sendRequest("PROPFIND", cfg.getSystemUrl() + chref, hdrs, "text/xml",
                            CALENDAR_PROPFIND.length(), CALENDAR_PROPFIND.getBytes());
                    if (rc == HttpServletResponse.SC_OK || rc == SC_MULTISTATUS) {
                        Document d = builder.parse(new InputSource(cl.getResponseBodyAsStream()));
                        HashMap<String, String> hm = new HashMap<String, String>();
                        XPathExpression exp = xPath.compile("//*[local-name() = 'href']/text()");
                        hm.put("href", exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'displayname']/text()");
                        hm.put("name", (String) exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'calendar-description']/text()");
                        hm.put("description", (String) exp.evaluate(d));
                        root.put("calendar", hm);
                    }
                }
            }

            if (note.getExtraValues() != null) {
                root.putAll(note.getExtraValues());
            }

            DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(
                    Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            root.put("timezone", (TemplateHashModel) wrapper.getStaticModels().get("java.util.TimeZone"));

            // Sort files so the user can control the order of content types/body parts of the email by template file name.
            File[] templates = templateDir.listFiles(templateFilter);
            Arrays.sort(templates);
            for (File f : templates) {
                Template template = fmConfig.getTemplate(Util.buildPath(false, abstractPath, "/", f.getName()));
                Writer out = new StringWriter();
                Environment env = template.createProcessingEnvironment(root, out);
                env.process();

                TemplateResult r = new TemplateResult(f.getName(), out.toString(), env);
                if (!r.getBooleanVariable("skip")) {
                    results.add(new TemplateResult(f.getName(), out.toString(), env));
                }
            }
        }
    } catch (final Throwable t) {
        throw new NoteException(t);
    }
    return results;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

public List<List<String>> getResults(String token, String queryId) throws UniverseException {
    HttpGet httpGet = new HttpGet(
            String.format("%s%s%s%s", apiUrl, "/sl/v1/queries/", queryId, "/data.svc/Flows0"));
    setHeaders(httpGet, token);// w  ww. j av  a  2  s. co  m
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new UniverseException(
                    String.format(errorMessageTemplate, "UniverseClient " + "(get results): Request failed\n",
                            EntityUtils.toString(response.getEntity())));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Request failed", ExceptionUtils.getStackTrace(e)));
    }

    try (InputStream xmlStream = response.getEntity().getContent()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//feed/entry/content/properties");
        NodeList resultsNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        if (resultsNodes != null) {
            return parseResults(resultsNodes);
        } else {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get results): Response processing failed"));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Request failed", ExceptionUtils.getStackTrace(e)));
    } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Response processing failed",
                ExceptionUtils.getStackTrace(e)));
    }
}

From source file:org.ala.harvester.FlickrHarvester.java

/**
 * Retrieves a map of licences./*from w  ww .  j  a va 2s . c om*/
 * 
 * @return
 */
private Map<String, Licence> getLicencesMap() throws Exception {

    final String flickrMethodUri = "flickr.photos.licenses.getInfo";
    String urlToSearch = this.flickrRestBaseUrl + "/" + "?method=" + flickrMethodUri + "&api_key="
            + this.flickrApiKey;

    logger.info(urlToSearch);
    logger.debug("URL to search is: " + "`" + urlToSearch + "`" + "\n");

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(urlToSearch);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    method.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "UTF-8");
    method.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8");

    try {
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            String errMsg = "HTTP GET to " + "`" + urlToSearch + "`"
                    + " returned non HTTP OK code.  Returned code " + statusCode + " and message "
                    + method.getStatusLine() + "\n";
            method.releaseConnection();
            throw new Exception(errMsg);
        }

        //parse the response
        InputStream responseStream = method.getResponseBodyAsStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(responseStream);
        XPathFactory xfactory = XPathFactory.newInstance();
        XPath xpath = xfactory.newXPath();

        XPathExpression xe = xpath.compile("/rsp/licenses/license");
        NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET);

        Map<String, Licence> licencesMap = new HashMap<String, Licence>();

        for (int i = 0; i < nodeSet.getLength(); i++) {
            NamedNodeMap map = nodeSet.item(i).getAttributes();
            String id = map.getNamedItem("id").getNodeValue();
            Licence licence = new Licence();
            licence.setName(map.getNamedItem("name").getNodeValue());
            licence.setUrl(map.getNamedItem("url").getNodeValue());
            licencesMap.put(id, licence);
        }
        return licencesMap;

    } catch (Exception httpErr) {
        String errMsg = "HTTP GET to `" + urlToSearch + "` returned HTTP error.";
        throw new Exception(errMsg, httpErr);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}