Java Code Examples for org.apache.commons.digester3.Digester

The following examples show how to use org.apache.commons.digester3.Digester. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: warnings-ng-plugin   Source File: CheckStyleRules.java    License: MIT License 6 votes vote down vote up
/**
 * Initializes the rules.
 */
public void initialize() {
    String[] ruleFiles = {"annotation", "blocks", "coding", "design", "filters", "header",
            "imports", "javadoc", "metrics", "misc", "modifier", "naming", "regexp",
            "reporting", "sizes", "whitespace"};
    for (String ruleFile : ruleFiles) {
        try (InputStream inputStream = CheckStyleRules.class.getResourceAsStream("config_" + ruleFile + ".xml")) {
            Digester digester = createDigester();
            List<Rule> rules = new ArrayList<>();
            digester.push(rules);
            digester.parse(inputStream);
            for (Rule rule : rules) {
                if (StringUtils.isNotBlank(rule.getDescription())) {
                    rulesByName.put(rule.getName(), rule);
                }
            }
        }
        catch (ParserConfigurationException | IOException | SAXException exception) {
            log(exception);
        }
    }
}
 
Example 2
Source Project: warnings-ng-plugin   Source File: CheckStyleRules.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a new digester.
 *
 * @return the new digester.
 * @throws ParserConfigurationException
 *         if digester is not configured properly
 */
private Digester createDigester() throws ParserConfigurationException {
    SecureDigester digester = new SecureDigester(CheckStyleRules.class);

    String section = "*/section";
    digester.addObjectCreate(section, Rule.class);
    digester.addSetProperties(section);
    digester.addSetNext(section, "add");

    String subSection = "*/section/subsection";
    digester.addObjectCreate(subSection, Topic.class);
    digester.addSetProperties(subSection);
    digester.addSetNext(subSection, "setDescription");
    digester.addRule(subSection, new TopicRule());
    return digester;
}
 
Example 3
Source Project: tagme   Source File: TagmeConfig.java    License: Apache License 2.0 6 votes vote down vote up
protected static void setRules(Digester d)
{
	d.addObjectCreate("tagme", Config.class);

	d.addCallMethod("tagme/logConfiguration", "setLoggingFilePath", 0);
	d.addCallMethod("tagme/stopword", "setStopwordDir", 0);
	d.addCallMethod("tagme/repository", "setRepositoryDir", 0);

	d.addCallMethod("tagme/inits/class", "addInit", 0);
	d.addCallMethod("tagme/langs/lang", "addLang", 0);

	d.addObjectCreate("tagme/setting", ParamSetting.class);
	d.addSetNext("tagme/setting", "addSetting", ParamSetting.class.getName());
	d.addCallMethod("tagme/setting", "setName", 1);
	d.addCallParam("tagme/setting", 0, "name");

	d.addCallMethod("tagme/setting/param", "addParam", 2);
	d.addCallParam("tagme/setting/param", 0, "name");
	d.addCallParam("tagme/setting/param", 1, "value");

}
 
Example 4
Source Project: formatter-maven-plugin   Source File: ConfigReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read from the <code>input</code> and return it's configuration settings as a {@link Map}.
 *
 * @param input
 *            the input
 * 
 * @return return {@link Map} with all the configurations read from the config file, or throws an exception if
 *         there's a problem reading the input, e.g.: invalid XML.
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the SAX exception
 * @throws ConfigReadException
 *             the config read exception
 */
public Map<String, String> read(InputStream input) throws IOException, SAXException, ConfigReadException {
    Digester digester = new Digester();
    digester.addRuleSet(new RuleSet());

    Object result = digester.parse(input);
    if (result == null || !(result instanceof Profiles)) {
        throw new ConfigReadException("No profiles found in config file");
    }

    Profiles profiles = (Profiles) result;
    List<Map<String, String>> list = profiles.getProfiles();
    if (list.isEmpty()) {
        throw new ConfigReadException("No profile in config file of kind: " + Profiles.PROFILE_KIND);
    }

    return list.get(0);
}
 
Example 5
Source Project: tankbattle   Source File: MapParser.java    License: MIT License 6 votes vote down vote up
public static XmlMap getMapFromXml(String name) {
    try {

        DigesterLoader loader = DigesterLoader.newLoader(new FromAnnotationsRuleModule() {
            @Override
            protected void configureRules() {
                bindRulesFrom(XmlMap.class);
            }

        });

        Digester digester = loader.newDigester();
        return digester.parse(new FileInputStream(new File(System.getProperty("user" +
                ".home") + File
                .separator +
                ".tankBattle" + File.separator + "custom" + File.separator + name + ".xml")));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 6
Source Project: analysis-model   Source File: FindBugsParser.java    License: MIT License 6 votes vote down vote up
/**
 * Pre-parses a file for some information not available from the FindBugs parser. Creates a mapping of FindBugs
 * warnings to messages. A bug is represented by its unique hash code. Also obtains original categories for bug
 * types.
 *
 * @param file
 *         the FindBugs XML file
 *
 * @return the map of warning messages
 * @throws SAXException
 *         if the file contains no valid XML
 * @throws IOException
 *         signals that an I/O exception has occurred.
 */
@VisibleForTesting
List<XmlBugInstance> preParse(final Reader file) throws SAXException, IOException {
    Digester digester = new SecureDigester(FindBugsParser.class);

    String rootXPath = "BugCollection/BugInstance";
    digester.addObjectCreate(rootXPath, XmlBugInstance.class);
    digester.addSetProperties(rootXPath);

    String fileXPath = rootXPath + "/LongMessage";
    digester.addCallMethod(fileXPath, "setMessage", 0);

    digester.addSetNext(rootXPath, "add", Object.class.getName());
    ArrayList<XmlBugInstance> bugs = new ArrayList<>();
    digester.push(bugs);
    digester.parse(file);

    return bugs;
}
 
Example 7
Source Project: analysis-model   Source File: DupFinderParser.java    License: MIT License 6 votes vote down vote up
@Override
protected void configureParser(final Digester digester) {
    String duplicationXPath = "*/DuplicatesReport/Duplicates/Duplicate";
    digester.addObjectCreate(duplicationXPath, Duplicate.class);
    digester.addSetProperties(duplicationXPath, "Cost", "cost");
    digester.addSetNext(duplicationXPath, "add");

    String fragmentXPath = duplicationXPath + "/Fragment";
    digester.addObjectCreate(fragmentXPath, Fragment.class);
    digester.addBeanPropertySetter(fragmentXPath + "/FileName", "fileName");
    digester.addBeanPropertySetter(fragmentXPath + "/Text", "text");
    digester.addSetNext(fragmentXPath, "addFragment", Fragment.class.getName());

    String lineRangeXPath = fragmentXPath + "/LineRange";
    digester.addObjectCreate(lineRangeXPath, Range.class);
    digester.addSetProperties(lineRangeXPath, "Start", "start");
    digester.addSetProperties(lineRangeXPath, "End", "end");
    digester.addSetNext(lineRangeXPath, "setLineRange", Range.class.getName());

    String offsetRangeXPath = fragmentXPath + "/OffsetRange";
    digester.addObjectCreate(offsetRangeXPath, Range.class);
    digester.addSetProperties(offsetRangeXPath, "Start", "start");
    digester.addSetProperties(offsetRangeXPath, "End", "end");
    digester.addSetNext(offsetRangeXPath, "setOffsetRange", Range.class.getName());
}
 
Example 8
Source Project: analysis-model   Source File: AbstractDryParser.java    License: MIT License 6 votes vote down vote up
@Override
public Report parse(final ReaderFactory readerFactory) throws ParsingCanceledException, ParsingException {
    Digester digester = new SecureDigester(AbstractDryParser.class);

    configureParser(digester);

    List<T> duplications = new ArrayList<>();
    digester.push(duplications);

    try (Reader reader = readerFactory.create()) {
        Object result = digester.parse(reader);
        if (result != duplications) { // NOPMD
            throw new ParsingException("Input stream is not a valid duplications file.");
        }

        return convertDuplicationsToIssues(duplications, new IssueBuilder().setMessage("Found duplicated code."));
    }
    catch (IOException | SAXException exception) {
        throw new ParsingException(exception);
    }
}
 
Example 9
Source Project: knox   Source File: TopologyRulesModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseTopologyWithApplication() throws IOException, SAXException {
  Digester digester = loader.newDigester();
  String name = "topology-with-application.xml";
  URL url = TestUtils.getResourceUrl( TopologyRulesModuleTest.class, name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  File file = new File( url.getFile() );
  TopologyBuilder topologyBuilder = digester.parse( url );
  Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  Application app = topology.getApplications().iterator().next();
  assertThat( "Failed to find application", app, notNullValue() );
  assertThat( app.getName(), is("test-app-name") );
  assertThat( app.getUrl(), is("test-app-path") );
  assertThat( app.getUrls().get( 0 ), is("test-app-path") );
  assertThat( app.getParams().get( "test-param-name" ), is( "test-param-value" ) );
}
 
Example 10
Source Project: knox   Source File: TopologyRulesModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseTopologyWithDispatch() throws IOException, SAXException {
  final Digester digester = loader.newDigester();
  final String name = "topology-with-dispatch.xml";
  final URL url = TestUtils.getResourceUrl( TopologyRulesModuleTest.class, name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  final File file = new File( url.getFile() );
  final TopologyBuilder topologyBuilder = digester.parse( url );
  final Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  final Collection<Service> services =  topology.getServices();
  final CustomDispatch dispatch = services.iterator().next().getDispatch();

  assertThat( "Failed to find dispatch", dispatch, notNullValue() );
  assertThat( dispatch.getContributorName(), is("testContributor") );
  assertThat( dispatch.getHaContributorName(), is("testHAContributor") );
  assertThat( dispatch.getClassName(), is("org.apache.hadoop.gateway.hbase.HBaseDispatch") );
  assertThat( dispatch.getHaClassName(), is("testHAClassName") );
  assertThat( dispatch.getHttpClientFactory(), is("testHttpClientFactory") );
  assertThat( dispatch.getUseTwoWaySsl(), is(true) );
  assertThat( dispatch.getParams().size(), is(0) );
}
 
Example 11
Source Project: knox   Source File: TopologyRulesModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseTopologyWithDispatchParameters() throws IOException, SAXException {
  final Digester digester = loader.newDigester();
  final String name = "topology-with-dispatch-parameters.xml";
  final URL url = TestUtils.getResourceUrl( TopologyRulesModuleTest.class, name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  final File file = new File( url.getFile() );
  final TopologyBuilder topologyBuilder = digester.parse( url );
  final Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  final Collection<Service> services =  topology.getServices();
  final CustomDispatch dispatch = services.iterator().next().getDispatch();

  assertThat( "Failed to find dispatch", dispatch, notNullValue() );
  assertThat( dispatch.getContributorName(), is("testContributor") );
  assertThat( dispatch.getHaContributorName(), is("testHAContributor") );
  assertThat( dispatch.getClassName(), is("org.apache.hadoop.gateway.hbase.HBaseDispatch") );
  assertThat( dispatch.getHaClassName(), is("testHAClassName") );
  assertThat( dispatch.getHttpClientFactory(), is("testHttpClientFactory") );
  assertThat( dispatch.getUseTwoWaySsl(), is(true) );
  assertThat( dispatch.getParams().size(), is(2) );
  assertThat( dispatch.getParams().get("abc"), is("def") );
  assertThat( dispatch.getParams().get("ghi"), is("123") );
}
 
Example 12
private static void setupSingleEntryParser(Digester digester){
	digester.addObjectCreate("*/entry", NotificationHubDescription.class);
	digester.addCallMethod("*/entry/title","setPath",1);
	digester.addCallParam("*/entry/title",0);
	digester.addObjectCreate("*/ApnsCredential", ApnsCredential.class);
	digester.addObjectCreate("*/AdmCredential", AdmCredential.class);
	digester.addObjectCreate("*/WnsCredential", WindowsCredential.class);
	digester.addObjectCreate("*/MpnsCredential", MpnsCredential.class);
	digester.addObjectCreate("*/GcmCredential", GcmCredential.class);
	digester.addObjectCreate("*/FcmCredential", FcmCredential.class);
	digester.addObjectCreate("*/BaiduCredential", BaiduCredential.class);
	PnsCredential.setupDigister(digester);
	digester.addSetNext("*/ApnsCredential", "setApnsCredential", ApnsCredential.class.getName());
	digester.addSetNext("*/AdmCredential", "setAdmCredential", AdmCredential.class.getName());
	digester.addSetNext("*/WnsCredential", "setWindowsCredential", WindowsCredential.class.getName());
	digester.addSetNext("*/MpnsCredential", "setMpnsCredential", MpnsCredential.class.getName());
	digester.addSetNext("*/GcmCredential", "setGcmCredential", GcmCredential.class.getName());
	digester.addSetNext("*/FcmCredential", "setFcmCredential", FcmCredential.class.getName());
	digester.addSetNext("*/BaiduCredential", "setBaiduCredential", BaiduCredential.class.getName());
}
 
Example 13
private static void addCollectionRules(Digester digester) {
	digester.addObjectCreate("feed", CollectionResult.class);
	digester.addSetNext("*/RegistrationDescription", "addRegistration");
	digester.addSetNext("*/WindowsRegistrationDescription", "addRegistration");
	digester.addSetNext("*/WindowsTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/AppleRegistrationDescription", "addRegistration");
	digester.addSetNext("*/AppleTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/GcmRegistrationDescription", "addRegistration");
	digester.addSetNext("*/GcmTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/FcmRegistrationDescription", "addRegistration");
	digester.addSetNext("*/FcmTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/MpnsRegistrationDescription", "addRegistration");
	digester.addSetNext("*/MpnsTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/AdmRegistrationDescription", "addRegistration");
	digester.addSetNext("*/AdmTemplateRegistrationDescription", "addRegistration");
	digester.addSetNext("*/BaiduRegistrationDescription", "addRegistration");
	digester.addSetNext("*/BaiduTemplateRegistrationDescription", "addRegistration");
}
 
Example 14
private static void setupSingleEntryParser(Digester digester){
	digester.addObjectCreate("*/entry", NotificationHubJob.class);
	digester.addCallMethod("*/JobId", "setJobId",1);
	digester.addCallParam("*/JobId", 0);
	digester.addCallMethod("*/Progress", "setProgressFromString",1);
	digester.addCallParam("*/Progress", 0);
	digester.addCallMethod("*/Type", "setJobTypeFromString",1);
	digester.addCallParam("*/Type", 0);
	digester.addCallMethod("*/Status", "setJobStatusFromString",1);
	digester.addCallParam("*/Status", 0);
	digester.addCallMethod("*/OutputContainerUri", "setOutputContainerUri",1);
	digester.addCallParam("*/OutputContainerUri", 0);
	digester.addCallMethod("*/ImportFileUri", "setImportFileUri",1);
	digester.addCallParam("*/ImportFileUri", 0);
	digester.addCallMethod("*/Failure", "setFailure",1);
	digester.addCallParam("*/Failure", 0);
	digester.addCallMethod("*/CreatedAt", "setCreatedAtFromString",1);
	digester.addCallParam("*/CreatedAt", 0);
	digester.addCallMethod("*/UpdatedAt", "setUpdatedAtFromString",1);
	digester.addCallParam("*/UpdatedAt", 0);		
	digester.addObjectCreate("*/OutputProperties", HashMap.class);
	digester.addCallMethod("*/d3p1:KeyValueOfstringstring", "put",2);
	digester.addCallParam("*/d3p1:Key", 0);
	digester.addCallParam("*/d3p1:Value", 1);
	digester.addSetNext("*/OutputProperties", "setOutputProperties", Map.class.getName());
}
 
Example 15
Source Project: velocity-tools   Source File: XmlFactoryConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Reads an XML document from an {@link URL}
 * and uses it to configure this {@link FactoryConfiguration}.</p>
 * 
 * @param url the URL to read from
 */
protected void readImpl(URL url) throws IOException
{
    // since beanutils 1.9.4, we need to relax access to the 'class' method
    BeanUtilsBean.getInstance().getPropertyUtils().removeBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);

    Digester digester = new Digester();
    digester.setNamespaceAware(true);
    digester.setXIncludeAware(true);
    digester.setValidating(false);
    digester.setUseContextClassLoader(true);
    digester.push(this);
    digester.addRuleSet(getRuleSet());
    try
    {
        digester.parse(url);
    }
    catch (SAXException saxe)
    {
        throw new RuntimeException("There was an error while parsing the InputStream", saxe);
    }
    finally
    {
        BeanUtilsBean.getInstance().getPropertyUtils().resetBeanIntrospectors();
    }
}
 
Example 16
Source Project: formatter-maven-plugin   Source File: RuleSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds the rule instances.
 *
 * @param digester
 *            the digester
 * 
 * @see org.apache.commons.digester3.RuleSetBase#addRuleInstances(org.apache.commons.digester3.Digester)
 */
@Override
public void addRuleInstances(Digester digester) {
    digester.addObjectCreate("profiles", Profiles.class);
    digester.addObjectCreate(PROFILES_PROFILE, Profile.class);
    digester.addObjectCreate(PROFILES_PROFILE_SETTING, Setting.class);

    digester.addSetNext(PROFILES_PROFILE, "addProfile");
    digester.addSetNext(PROFILES_PROFILE_SETTING, "addSetting");

    digester.addSetProperties(PROFILES_PROFILE, "kind", "kind");
    digester.addSetProperties(PROFILES_PROFILE_SETTING, "id", "id");
    digester.addSetProperties(PROFILES_PROFILE_SETTING, "value", "value");
}
 
Example 17
Source Project: analysis-model   Source File: CheckStyleParser.java    License: MIT License 5 votes vote down vote up
@Override
public Report parse(final ReaderFactory readerFactory) throws ParsingException {
    Digester digester = new SecureDigester(CheckStyleParser.class);

    String rootXPath = "checkstyle";
    digester.addObjectCreate(rootXPath, CheckStyle.class);
    digester.addSetProperties(rootXPath);

    String fileXPath = "checkstyle/file";
    digester.addObjectCreate(fileXPath, File.class);
    digester.addSetProperties(fileXPath);
    digester.addSetNext(fileXPath, "addFile", File.class.getName());

    String bugXPath = "checkstyle/file/error";
    digester.addObjectCreate(bugXPath, Error.class);
    digester.addSetProperties(bugXPath);
    digester.addSetNext(bugXPath, "addError", Error.class.getName());

    try (Reader reader = readerFactory.create()) {
        CheckStyle checkStyle = digester.parse(reader);
        if (checkStyle == null) {
            throw new ParsingException("Input stream is not a Checkstyle file.");
        }

        return convert(checkStyle);
    }
    catch (IOException | SAXException exception) {
        throw new ParsingException(exception);
    }
}
 
Example 18
Source Project: analysis-model   Source File: SimianParser.java    License: MIT License 5 votes vote down vote up
@Override
protected void configureParser(final Digester digester) {
    String duplicationXPath = "*/simian/check/set";
    digester.addObjectCreate(duplicationXPath, Set.class);
    digester.addSetProperties(duplicationXPath);
    digester.addSetNext(duplicationXPath, "add");

    String fileXPath = duplicationXPath + "/block";
    digester.addObjectCreate(fileXPath, Block.class);
    digester.addSetProperties(fileXPath);
    digester.addSetNext(fileXPath, "addBlock", Block.class.getName());
}
 
Example 19
Source Project: analysis-model   Source File: CpdParser.java    License: MIT License 5 votes vote down vote up
@Override
protected void configureParser(final Digester digester) {
    String duplicationXPath = "*/pmd-cpd/duplication";
    digester.addObjectCreate(duplicationXPath, Duplication.class);
    digester.addSetProperties(duplicationXPath);
    digester.addCallMethod(duplicationXPath + "/codefragment", "setCodeFragment", 0);
    digester.addSetNext(duplicationXPath, "add");

    String fileXPath = duplicationXPath + "/file";
    digester.addObjectCreate(fileXPath, SourceFile.class);
    digester.addSetProperties(fileXPath);
    digester.addSetNext(fileXPath, "addFile", SourceFile.class.getName());
}
 
Example 20
Source Project: knox   Source File: XmlGatewayDescriptorImporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GatewayDescriptor load( Reader reader ) throws IOException {
  Digester digester = loader.newDigester( new ExtendedBaseRules() );
  digester.setValidating( false );
  try {
    return digester.parse( reader );
  } catch( SAXException e ) {
    throw new IOException( e );
  }
}
 
Example 21
Source Project: knox   Source File: TopologyRulesModuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testParseServiceParamsInKnoxFormat() throws IOException, SAXException {
  Digester digester = loader.newDigester();
  String name = "org/apache/knox/gateway/topology/xml/service-param-topology-knox-format.xml";
  URL url = ClassLoader.getSystemResource( name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  File file = new File( url.getFile() );
  TopologyBuilder topologyBuilder = digester.parse( url );
  Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  assertThat( topology.getName(), is( "test-topology-name" ) );
  assertThat( topology.getTimestamp(), is( file.lastModified() ) );
  assertThat( topology.getServices().size(), is( 1 ) );

  Provider provider = topology.getProviders().iterator().next();
  assertThat( provider, notNullValue() );
  assertThat( provider.getRole(), is( "test-provider-role" ) );
  assertThat( provider.getName(), is( "test-provider-name" ) );
  assertThat( provider.getParams(), hasEntry( is( "test-provider-param-name-1" ), is( "test-provider-param-value-1" ) ) );
  assertThat( provider.getParams(), hasEntry( is( "test-provider-param-name-2" ), is( "test-provider-param-value-2" ) ) );

  Service service = topology.getServices().iterator().next();
  assertThat( service, notNullValue() );
  assertThat( service.getRole(), is( "test-service-role" ) );
  assertThat( service.getUrls().size(), is( 2 ) );
  assertThat( service.getUrls(), hasItem( "test-service-scheme://test-service-host1:42/test-service-path" ) );
  assertThat( service.getUrls(), hasItem( "test-service-scheme://test-service-host2:42/test-service-path" ) );
  assertThat( service.getName(), is( "test-service-name" ) );
  assertThat( service.getParams(), hasEntry( is( "test-service-param-name-1" ), is( "test-service-param-value-1" ) ) );
  assertThat( service.getParams(), hasEntry( is( "test-service-param-name-2" ), is( "test-service-param-value-2" ) ) );
  assertThat( service.getVersion(), is( new Version(1,0,0)));
}
 
Example 22
Source Project: knox   Source File: TopologyRulesModuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testParseServiceParamsInAmbariFormat() throws IOException, SAXException {
  Digester digester = loader.newDigester();
  String name = "org/apache/knox/gateway/topology/xml/service-param-topology-ambari-format.conf";
  URL url = ClassLoader.getSystemResource( name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  File file = new File( url.getFile() );
  TopologyBuilder topologyBuilder = digester.parse( url );
  Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  assertThat( topology.getName(), is( "test-topology-name" ) );
  assertThat( topology.getTimestamp(), is( file.lastModified() ) );

  assertThat( topology.getProviders().size(), is( 1 ) );
  Provider provider = topology.getProviders().iterator().next();
  assertThat( provider, notNullValue() );
  assertThat( provider.getRole(), is( "test-provider-role" ) );
  assertThat( provider.getName(), is( "test-provider-name" ) );
  assertThat( provider.isEnabled(), is( true ) );
  assertThat( provider.getParams(), hasEntry( is( "test-provider-param-name-1" ), is( "test-provider-param-value-1" ) ) );
  assertThat( provider.getParams(), hasEntry( is( "test-provider-param-name-2" ), is( "test-provider-param-value-2" ) ) );

  assertThat( topology.getServices().size(), is( 1 ) );
  Service service = topology.getServices().iterator().next();
  assertThat( service, notNullValue() );
  assertThat( service.getRole(), is( "test-service-role" ) );
  assertThat( service.getUrls().size(), is( 2 ) );
  assertThat( service.getUrls(), hasItem( "test-service-scheme://test-service-host1:42/test-service-path" ) );
  assertThat( service.getUrls(), hasItem( "test-service-scheme://test-service-host2:42/test-service-path" ) );
  assertThat( service.getName(), is( "test-service-name" ) );
  assertThat( service.getParams(), hasEntry( is( "test-service-param-name-1" ), is( "test-service-param-value-1" ) ) );
  assertThat( service.getParams(), hasEntry( is( "test-service-param-name-2" ), is( "test-service-param-value-2" ) ) );
}
 
Example 23
Source Project: knox   Source File: XmlRewriteRulesDigester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void begin( String namespace, String name, Attributes attributes ) throws Exception {
  Digester digester = getDigester();
  UrlRewriteRulesDescriptor rules = digester.peek();
  UrlRewriteRuleDescriptor rule = rules.newRule();
  getDigester().push( rule );
}
 
Example 24
Source Project: knox   Source File: XmlRewriteRulesDigester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void end( String namespace, String name ) throws Exception {
  Digester digester = getDigester();
  UrlRewriteRuleDescriptor rule = digester.pop();
  UrlRewriteRulesDescriptor rules = digester.peek();
  rules.addRule( rule );
}
 
Example 25
/**
 * Load plugin data from the XML file using Jakarta Commons Digester
 * 
 * @param strFilename
 *            The XML plugin filename
 * @throws fr.paris.lutece.portal.service.init.LuteceInitException
 *             If a problem occured during the loading
 */
public void load( String strFilename ) throws LuteceInitException
{
    // Configure Digester from XML ruleset
    DigesterLoader digesterLoader = DigesterLoader.newLoader( new FromXmlRulesModule( )
    {
        @Override
        protected void loadRules( )
        {
            loadXMLRules( getClass( ).getResource( FILE_RULES ) );
        }
    } );

    Digester digester = digesterLoader.newDigester( );

    // Allow variables in plugin files
    MultiVariableExpander expander = new MultiVariableExpander( );
    expander.addSource( "$", ( (Map) AppPropertiesService.getPropertiesAsMap( ) ) );

    Substitutor substitutor = new VariableSubstitutor( expander );
    digester.setSubstitutor( substitutor );

    // Push empty List onto Digester's Stack
    digester.push( this );
    digester.setValidating( false );

    try
    {
        InputStream input = new FileInputStream( strFilename );
        digester.parse( input );
    }
    catch( IOException | IllegalArgumentException | SAXException e )
    {
        throw new LuteceInitException( "Error loading plugin file : " + strFilename, e );
    }
}
 
Example 26
Source Project: gocd   Source File: GoPluginBundleDescriptorParser.java    License: Apache License 2.0 5 votes vote down vote up
static GoPluginBundleDescriptor parseXML(InputStream pluginXML,
                                         String pluginJarFileLocation,
                                         File pluginBundleLocation,
                                         boolean isBundledPlugin) throws IOException, SAXException {
    Digester digester = initDigester();

    GoPluginBundleDescriptorParser parserForThisXML = new GoPluginBundleDescriptorParser(pluginJarFileLocation, pluginBundleLocation, isBundledPlugin);
    digester.push(parserForThisXML);

    digester.addCallMethod("gocd-bundle", "createBundle", 1);
    digester.addCallParam("gocd-bundle", 0, "version");

    digester.addCallMethod("gocd-bundle/plugins/plugin", "createPlugin", 1);
    digester.addCallParam("gocd-bundle/plugins/plugin", 0, "id");

    digester.addCallMethod("gocd-bundle/plugins/plugin/about", "createAbout", 4);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/name", 0);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/version", 1);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/target-go-version", 2);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/description", 3);

    digester.addCallMethod("gocd-bundle/plugins/plugin/about/vendor", "createVendor", 2);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/vendor/name", 0);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/vendor/url", 1);

    digester.addCallMethod("gocd-bundle/plugins/plugin/about/target-os/value", "addTargetOS", 1);
    digester.addCallParam("gocd-bundle/plugins/plugin/about/target-os/value", 0);

    digester.addCallMethod("gocd-bundle/plugins/plugin/extensions/extension", "addExtension", 1);
    digester.addCallParam("gocd-bundle/plugins/plugin/extensions/extension", 0, "class");

    digester.parse(pluginXML);

    return parserForThisXML.descriptor;
}
 
Example 27
Source Project: gocd   Source File: GoPluginDescriptorParser.java    License: Apache License 2.0 5 votes vote down vote up
static GoPluginBundleDescriptor parseXML(InputStream pluginXML,
                                         String pluginJarFileLocation,
                                         File pluginBundleLocation,
                                         boolean isBundledPlugin) throws IOException, SAXException {
    Digester digester = initDigester();
    GoPluginDescriptorParser parserForThisXML = new GoPluginDescriptorParser(pluginJarFileLocation, pluginBundleLocation, isBundledPlugin);
    digester.push(parserForThisXML);

    digester.addCallMethod("go-plugin", "createPlugin", 2);
    digester.addCallParam("go-plugin", 0, "id");
    digester.addCallParam("go-plugin", 1, "version");

    digester.addCallMethod("go-plugin/about", "createAbout", 4);
    digester.addCallParam("go-plugin/about/name", 0);
    digester.addCallParam("go-plugin/about/version", 1);
    digester.addCallParam("go-plugin/about/target-go-version", 2);
    digester.addCallParam("go-plugin/about/description", 3);

    digester.addCallMethod("go-plugin/about/vendor", "createVendor", 2);
    digester.addCallParam("go-plugin/about/vendor/name", 0);
    digester.addCallParam("go-plugin/about/vendor/url", 1);

    digester.addCallMethod("go-plugin/about/target-os/value", "addTargetOS", 1);
    digester.addCallParam("go-plugin/about/target-os/value", 0);

    digester.parse(pluginXML);

    return parserForThisXML.descriptor;
}
 
Example 28
/**
 * <p>Add the set of Rule instances defined in this RuleSet to the
 * specified <code>Digester</code> instance, associating them with
 * our namespace URI (if any).  This method should only be called
 * by a Digester instance.  These rules assume that an instance of
 * <code>org.apache.velocity.tools.view.ToolboxManager</code> is pushed
 * onto the evaluation stack before parsing begins.</p>
 *
 * @param digester Digester instance to which the new Rule instances
 *        should be added.
 */
public void addRuleInstances(Digester digester)
{
    // create the config objects
    digester.addObjectCreate("tools/property", propertyClass);
    digester.addObjectCreate("tools/*/property", propertyClass);
    digester.addObjectCreate("tools/data", dataClass);
    digester.addObjectCreate("tools/toolbox", toolboxConfigurationClass);
    digester.addObjectCreate("tools/toolbox/tool", toolConfigurationClass);

    // to apply matching attributes to specific setters of config objects
    digester.addSetProperties("tools/property");
    digester.addSetProperties("tools/*/property");
    digester.addSetProperties("tools");
    digester.addSetProperties("tools/data");
    digester.addSetProperties("tools/toolbox");
    digester.addSetProperties("tools/toolbox/tool", "class", "classname");

    // to add all attributes to config via setProperty(name,value)
    digester.addRule("tools", new PropertyAttributeRule());
    digester.addRule("tools/toolbox", new PropertyAttributeRule());
    digester.addRule("tools/toolbox/tool", new PropertyAttributeRule());

    // for config data & properties whose values are in the body of the tag
    digester.addRule("tools/data", new DataValueInBodyRule());
    digester.addRule("tools/*/property", new DataValueInBodyRule());

    // to finish a config and move on to the next
    digester.addSetNext("tools/property", "addProperty");
    digester.addSetNext("tools/*/property", "addProperty");
    digester.addSetNext("tools/data", "addData");
    digester.addSetNext("tools/toolbox", "addToolbox");
    digester.addSetNext("tools/toolbox/tool", "addTool");
}
 
Example 29
Source Project: velocity-tools   Source File: UiDependencyTool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads group info out of the specified file and into this instance.
 * If the file cannot be found and required is true, then this will throw
 * an IllegalArgumentException.  Otherwise, it will simply do nothing. Any
 * checked exceptions during the actual reading of the file are caught and
 * wrapped as {@link RuntimeException}s.
 * @param file file
 * @param required whether this file is required
 */
protected void read(String file, boolean required) {
    getLog().debug("UiDependencyTool: Reading file from {}", file);
    URL url = toURL(file);
    if (url == null) {
        String msg = "UiDependencyTool: Could not read file from '"+file+"'";
        if (required) {
            getLog().error(msg);
            throw new IllegalArgumentException(msg);
        } else {
            getLog().debug(msg);
        }
    } else {
        Digester digester = createDigester();
        try
        {
            digester.parse(url.openStream());
        }
        catch (SAXException saxe)
        {
            getLog().error("UiDependencyTool: Failed to parse '{}'", file, saxe);
            throw new RuntimeException("While parsing the InputStream", saxe);
        }
        catch (IOException ioe)
        {
            getLog().error("UiDependencyTool: Failed to read '{}'", file, ioe);
            throw new RuntimeException("While handling the InputStream", ioe);
        }
    }
}
 
Example 30
Source Project: velocity-tools   Source File: UiDependencyTool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the {@link Digester} used by {@link #read} to create
 * the group info for this instance out of the specified XML file.
 * @return new digester
 */
protected Digester createDigester() {
    Digester digester = new Digester();
    digester.setValidating(false);
    digester.setUseContextClassLoader(true);
    digester.addRule("ui/type", new TypeRule());
    digester.addRule("ui/group", new GroupRule());
    digester.addRule("ui/group/file", new FileRule());
    digester.addRule("ui/group/needs", new NeedsRule());
    digester.push(this);
    return digester;
}