Example usage for org.apache.commons.digester3 Digester addCallMethod

List of usage examples for org.apache.commons.digester3 Digester addCallMethod

Introduction

In this page you can find the example usage for org.apache.commons.digester3 Digester addCallMethod.

Prototype

public void addCallMethod(String pattern, String methodName, int paramCount) 

Source Link

Document

Add an "call method" rule for the specified parameters.

Usage

From source file:org.apache.commons.digester3.examples.api.catalog.Main.java

private static void addRules(Digester d) {

    // --------------------------------------------------

    // when we encounter the root "catalog" tag, create an
    // instance of the Catalog class.
    ///*  ww w  . j  a va 2 s. c  o  m*/
    // Note that this approach is different from the approach taken in
    // the AddressBook example, where an initial "root" object was
    // explicitly created and pushed onto the digester stack before
    // parsing started instead
    //
    // Either approach is fine.

    d.addObjectCreate("catalog", Catalog.class);

    // --------------------------------------------------

    // when we encounter a book tag, we want to create a Book
    // instance. However the Book class doesn't have a default
    // constructor (one with no arguments), so we can't use
    // the ObjectCreateRule. Instead, we use the FactoryCreateRule.

    BookFactory factory = new BookFactory();
    d.addFactoryCreate("catalog/book", factory);

    // and add the book to the parent catalog object (which is
    // the next-to-top object on the digester object stack).
    d.addSetNext("catalog/book", "addItem");

    // we want each subtag of book to map the text contents of
    // the tag into a bean property with the same name as the tag.
    // eg <title>foo</title> --> setTitle("foo")
    d.addSetNestedProperties("catalog/book");

    // -----------------------------------------------

    // We are using the "AudioVisual" class to represent both
    // dvds and videos, so when the "dvd" tag is encountered,
    // create an AudioVisual object.

    d.addObjectCreate("catalog/dvd", AudioVisual.class);

    // add this dvd to the parent catalog object

    d.addSetNext("catalog/dvd", "addItem");

    // We want to map every xml attribute onto a corresponding
    // property-setter method on the Dvd class instance. However
    // this doesn't work with the xml attribute "year-made", because
    // of the internal hyphen. We could use explicit CallMethodRule
    // rules instead, or use a version of the SetPropertiesRule that
    // allows us to override any troublesome mappings...
    //
    // If there was more than one troublesome mapping, we could
    // use the method variant that takes arrays of xml-attribute-names
    // and bean-property-names to override multiple mappings.
    //
    // For any attributes not explicitly mapped here, the default
    // processing is applied, so xml attribute "category" --> setCategory.

    d.addSetProperties("catalog/dvd", "year-made", "yearMade");

    // We also need to tell this AudioVisual object that it is actually
    // a dvd; we can use the ObjectParamRule to pass a string to any
    // method. This usage is a little artificial - normally in this
    // situation there would be separate Dvd and Video classes.
    // Note also that equivalent behaviour could be implemented by
    // using factory objects to create & initialise the AudioVisual
    // objects with their type rather than using ObjectCreateRule.

    d.addCallMethod("catalog/dvd", "setType", 1);
    d.addObjectParam("catalog/dvd", 0, "dvd"); // pass literal "dvd" string

    // Each tag of form "<attr id="foo" value="bar"/> needs to map
    // to a call to setFoo("bar").
    //
    // This is an alternative to the syntax used for books above (see
    // method addSetNestedProperties), where the name of the subtag
    // indicated which property to set. Using this syntax in the xml has
    // advantages and disadvantages both for the user and the application
    // developer. It is commonly used with the FactoryCreateRule variant
    // which allows the target class to be created to be specified in an
    // xml attribute; this feature of FactoryCreateRule is not demonstrated
    // in this example, but see the Apache Tomcat configuration files for
    // an example of this usage.
    //
    // Note that despite the name similarity, there is no link
    // between SetPropertyRule and SetPropertiesRule.

    d.addSetProperty("catalog/dvd/attr", "id", "value");

    // -----------------------------------------------

    // and here we repeat the dvd rules, but for the video tag.
    d.addObjectCreate("catalog/video", AudioVisual.class);
    d.addSetNext("catalog/video", "addItem");
    d.addSetProperties("catalog/video", "year-made", "yearMade");
    d.addCallMethod("catalog/video", "setType", 1);
    d.addObjectParam("catalog/video", 0, "video");
    d.addSetProperty("catalog/video/attr", "id", "value");
}

From source file:org.apache.commons.digester3.examples.api.dbinsert.Main.java

private static void addRules(Digester d, java.sql.Connection conn) {

    // --------------------------------------------------
    // when we encounter a "table" tag, do the following:

    // Create a new instance of class Table, and push that
    // object onto the digester stack of objects. We only need
    // this so that when a row is inserted, it can find out what
    // the enclosing tablename was.
    ///* w w w.j  a  v a  2s  .com*/
    // Note that the object is popped off the stack at the end of the
    // "table" tag (normal behaviour for ObjectCreateRule). Because we
    // never added the table object to some parent object, when it is
    // popped off the digester stack it becomes garbage-collected. That
    // is fine in this situation; we've done all the necessary work and
    // don't need the table object any more.
    d.addObjectCreate("database/table", Table.class);

    // Map *any* attributes on the table tag to appropriate
    // setter-methods on the top object on the stack (the Table
    // instance created by the preceeding rule). We only expect one
    // attribute, though: a 'name' attribute specifying what table
    // we are inserting rows into.
    d.addSetProperties("database/table");

    // --------------------------------------------------
    // When we encounter a "row" tag, invoke methods on the provided
    // RowInserterRule instance.
    //
    // This rule creates a Row instance and pushes it on the digester
    // object stack, rather like ObjectCreateRule, so that the column
    // tags have somewhere to store their information. And when the
    // </row> end tag is found, the rule will trigger to remove this
    // object from the stack, and also do an actual database insert.
    //
    // Note that the rule instance we are passing to the digester has
    // been initialised with some useful data (the SQL connection).
    //
    // Note also that in this case we are not using the digester's
    // factory methods to create the rule instance; that's just a
    // convenience - and obviously not an option for Rule classes
    // that are not part of the digester core implementation.
    RowInserterRule rowInserterRule = new RowInserterRule(conn);
    d.addRule("database/table/row", rowInserterRule);

    // --------------------------------------------------
    // when we encounter a "column" tag, call setColumn on the top
    // object on the stack, passing two parameters: the "name"
    // attribute, and the text within the tag body.
    d.addCallMethod("database/table/row/column", "addColumn", 2);
    d.addCallParam("database/table/row/column", 0, "name");
    d.addCallParam("database/table/row/column", 1);
}

From source file:org.apache.commons.digester3.examples.plugins.pipeline.Pipeline.java

public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("usage: pipeline config-file");
        System.exit(-1);/*from w ww  . j a  v a  2  s .c  o m*/
    }
    String configFile = args[0];

    Digester digester = new Digester();
    PluginRules rc = new PluginRules();
    digester.setRules(rc);

    digester.addObjectCreate("pipeline", Pipeline.class);

    digester.addCallMethod("pipeline/source", "setSource", 1);
    digester.addCallParam("pipeline/source", 0, "file");

    PluginCreateRule pcr = new PluginCreateRule(Transform.class);
    digester.addRule("pipeline/transform", pcr);
    digester.addSetNext("pipeline/transform", "setTransform");

    digester.addCallMethod("pipeline/destination", "setDest", 1);
    digester.addCallParam("pipeline/destination", 0, "file");

    Pipeline pipeline = null;
    try {
        pipeline = digester.parse(configFile);
    } catch (Exception e) {
        System.err.println("oops exception occurred during parse.");
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        pipeline.execute();
    } catch (Exception e) {
        System.err.println("oops exception occurred during pipeline execution.");
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:org.apache.commons.digester3.examples.plugins.pipeline.SubstituteTransform.java

public static void addRules(Digester d, String patternPrefix) {
    d.addCallMethod(patternPrefix + "/from", "setFrom", 0);
    d.addCallMethod(patternPrefix + "/to", "setTo", 0);
}

From source file:org.esupportail.monitor.web.tools.Config.java

/**
 * Lit le fichier de configuration/* ww w. j a va2 s  . c o  m*/
 */
private void parseConfigFile() {
    Digester dig = new Digester();
    dig.push(this);

    dig.addCallMethod("config/server", "addServer", 2);
    dig.addCallParam("config/server", 0, "name");
    dig.addCallParam("config/server", 1, "url");

    URL resourceURL = Config.class.getResource(configFile);
    if (resourceURL != null) {
        try {
            // On parse le fichier dont le chemin est pass en paramtre
            dig.parse(new InputSource(resourceURL.toExternalForm()));
        } catch (IOException e) {
            logger.error("Config::parseConfig() : Impossible d'ouvrir le fichier de config \n" + e);
        } catch (SAXException e) {
            logger.error("Config::parseConfig() : SAXException :\n" + e);
        } catch (Exception e) {
            logger.error("Config::parseConfig() : Exception :\n" + e);
        }
    } else {
        logger.error("Config::parseConfig() : Le fichier de configuration est introuvable");
    }
}

From source file:org.esupportail.monitor.web.tools.InfosCollector.java

/**
 * Rcupre les informations d'un serveur distant
 * @param s L'objet  remplit/*from w  w  w .jav a 2 s  .  com*/
 * @return status vrai si tout se passe bien, faux sinon
 */
public static boolean fetch(ServerInfo s, boolean users) {

    Digester dig = new Digester();
    dig.push(s);

    dig.addObjectCreate("runtimeinfo/memory", MemoryInfo.class);
    dig.addSetProperties("runtimeinfo/memory");
    dig.addSetNext("runtimeinfo/memory", "setMemory");

    dig.addObjectCreate("runtimeinfo/sessions", SessionInfo.class);
    dig.addSetProperties("runtimeinfo/sessions");
    dig.addSetNext("runtimeinfo/sessions", "setSession");

    dig.addCallMethod("runtimeinfo/users/user", "addUser", 1);
    dig.addCallParam("runtimeinfo/users/user", 0, "uid");

    URL ressourceUrl = null;
    try {
        if (users) {
            ressourceUrl = new URL(s.getUrl() + "?xml=full");
        } else {
            ressourceUrl = new URL(s.getUrl() + "?xml");
        }
    } catch (MalformedURLException e) {
        //  logger.error(e);
        System.out.print(e + "\n");
        return false;
    }
    if (ressourceUrl != null) {
        try {
            // On parse le fichier dont le chemin est pass en paramtre
            dig.parse(new InputSource(ressourceUrl.toExternalForm()));

        } catch (IOException e) {
            //logger.error("InfosCollector::fetch() : Impossible d'ouvrir l'URL \n" + e);
            System.out.print("InfosCollector::fetch() : Impossible d'ouvrir l'URL \n" + e);
            return false;
        } catch (SAXException e) {
            //logger.error("InfosCollector::fetch() : SAXException :\n" + e);
            System.out.print("InfosCollector::fetch() : SAXException :\n" + e);
            return false;
        } catch (Exception e) {
            //logger.error("InfosCollector::fetch() : Exception :\n" + e);
            System.out.print("InfosCollector::fetch() : Exception :\n" + e);
            return false;
        }
    } else {
        //logger.error("InfosCollector::fetch() : L'URL est introuvable");
        System.out.print("InfosCollector::fetch() : L'URL est introuvable");
        return false;
    }
    return true;
}

From source file:org.gbif.metadata.eml.EmlFactory.java

/**
 * Uses rule based parsing to read the EML XML and build the EML model.
 * Note the following: - Metadata provider rules are omitted on the assumption that the provider is the same as the
 * creator - Contact rules are omitted on the assumption that contacts are covered by the creator and associated
 * parties - Publisher rules are omitted on the assumption the publisher is covered by the creator and associated
 * parties/*from  w ww.  ja v a2s . c  o m*/
 *
 * @param xml To read. Note this will be closed before returning
 *
 * @return The EML populated
 *
 * @throws IOException  If the Stream cannot be read from
 * @throws SAXException If the XML is not well formed
 */
public static Eml build(InputStream xml) throws IOException, SAXException, ParserConfigurationException {
    Digester digester = new Digester();
    digester.setNamespaceAware(true);

    // push the EML object onto the stack
    Eml eml = new Eml();
    digester.push(eml);

    // add the rules

    // language as xml:lang attribute
    digester.addCallMethod("eml", "setMetadataLanguage", 1);
    digester.addCallParam("eml", 0, "xml:lang");
    // guid as packageId attribute
    digester.addCallMethod("eml", "setPackageId", 1);
    digester.addCallParam("eml", 0, "packageId");

    // alternative ids
    digester.addCallMethod("eml/dataset/alternateIdentifier", "addAlternateIdentifier", 1);
    digester.addCallParam("eml/dataset/alternateIdentifier", 0);

    // title together with language
    digester.addCallMethod("eml/dataset/title", "setTitle", 2);
    digester.addCallParam("eml/dataset/title", 0);
    digester.addCallParam("eml/dataset/title", 1, "xml:lang");

    digester.addBeanPropertySetter("eml/dataset/language", "language");

    // descriptions, broken into multiple paragraphs
    digester.addCallMethod("eml/dataset/abstract/para", "addDescriptionPara", 1);
    digester.addCallParam("eml/dataset/abstract/para", 0);

    digester.addBeanPropertySetter("eml/dataset/additionalInfo/para", "additionalInfo");
    digester.addRule("eml/dataset/intellectualRights/para", new NodeCreateRule(Node.ELEMENT_NODE));
    digester.addSetNext("eml/dataset/intellectualRights/para", "parseIntellectualRights");
    digester.addCallMethod("eml/dataset/methods/methodStep/description/para", "addMethodStep", 1);
    digester.addCallParam("eml/dataset/methods/methodStep/description/para", 0);
    digester.addBeanPropertySetter("eml/dataset/methods/sampling/studyExtent/description/para", "studyExtent");
    digester.addBeanPropertySetter("eml/dataset/methods/sampling/samplingDescription/para",
            "sampleDescription");
    digester.addBeanPropertySetter("eml/dataset/methods/qualityControl/description/para", "qualityControl");
    digester.addBeanPropertySetter("eml/dataset/distribution/online/url", "distributionUrl");
    digester.addBeanPropertySetter("eml/dataset/purpose/para", "purpose");
    digester.addBeanPropertySetter("eml/dataset/maintenance/description/para", "updateFrequencyDescription");
    digester.addCallMethod("eml/dataset/maintenance/maintenanceUpdateFrequency", "setUpdateFrequency", 1);
    digester.addCallParam("eml/dataset/maintenance/maintenanceUpdateFrequency", 0);
    digester.addCallMethod("eml/additionalMetadata/metadata/gbif/citation", "setCitation", 2);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/citation", 0);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/citation", 1, "identifier");
    digester.addCallMethod("eml/additionalMetadata/metadata/gbif/specimenPreservationMethod",
            "addSpecimenPreservationMethod", 1);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/specimenPreservationMethod", 0);
    digester.addBeanPropertySetter("eml/additionalMetadata/metadata/gbif/resourceLogoUrl", "logoUrl");
    digester.addBeanPropertySetter("eml/additionalMetadata/metadata/gbif/hierarchyLevel", "hierarchyLevel");
    digester.addCallMethod("eml/dataset/pubDate", "setPubDateAsString", 1);
    digester.addCallParam("eml/dataset/pubDate", 0);

    digester.addCallMethod("eml/additionalMetadata/metadata/gbif/dateStamp", "setDateStamp", 1);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/dateStamp", 0);

    addAgentRules(digester, "eml/dataset/creator", "addCreator");
    addAgentRules(digester, "eml/dataset/metadataProvider", "addMetadataProvider");
    addAgentRules(digester, "eml/dataset/contact", "addContact");
    addAgentRules(digester, "eml/dataset/associatedParty", "addAssociatedParty");
    addKeywordRules(digester);
    addBibliographicCitations(digester);
    addGeographicCoverageRules(digester);
    addTemporalCoverageRules(digester);
    addLivingTimePeriodRules(digester);
    addFormationPeriodRules(digester);
    addTaxonomicCoverageRules(digester);
    addProjectRules(digester);
    addCollectionRules(digester);
    addPhysicalDataRules(digester);
    addJGTICuratorialIUnit(digester);

    // now parse and return the EML
    try {
        digester.parse(xml);
    } finally {
        xml.close();
    }

    return eml;
}

From source file:org.gbif.metadata.eml.EmlFactory.java

/**
 * This is a reusable set of rules to build Agents and their Addresses, and add the Agent to the predecessor object
 * on the Stack Note that we are ignoring the userId as there have been no requests for the IPT to support this.
 *
 * @param digester     to add the rules to
 * @param prefix       The XPath prefix to prepend for extracting the Agent information
 * @param parentMethod Of the previous stack object to call and add the Agent to
 *///  w  ww. j  a  v a 2  s. co m
private static void addAgentRules(Digester digester, String prefix, String parentMethod) {
    digester.addObjectCreate(prefix, Agent.class);
    digester.addBeanPropertySetter(prefix + "/individualName/givenName", "firstName");
    digester.addBeanPropertySetter(prefix + "/individualName/surName", "lastName");
    digester.addBeanPropertySetter(prefix + "/organizationName", "organisation");
    digester.addBeanPropertySetter(prefix + "/positionName", "position");
    digester.addBeanPropertySetter(prefix + "/phone", "phone");
    digester.addBeanPropertySetter(prefix + "/electronicMailAddress", "email");
    digester.addBeanPropertySetter(prefix + "/onlineUrl", "homepage");

    digester.addBeanPropertySetter(prefix + "/role", "role");

    digester.addObjectCreate(prefix + "/address", Address.class);
    digester.addBeanPropertySetter(prefix + "/address/city", "city");
    digester.addBeanPropertySetter(prefix + "/address/administrativeArea", "province");
    digester.addBeanPropertySetter(prefix + "/address/postalCode", "postalCode");
    digester.addBeanPropertySetter(prefix + "/address/country", "country");
    digester.addBeanPropertySetter(prefix + "/address/deliveryPoint", "address");
    digester.addSetNext(prefix + "/address", "setAddress"); // called on </address> to set on parent Agent

    digester.addObjectCreate(prefix + "/userId", UserId.class);
    digester.addCallMethod(prefix + "/userId", "setDirectory", 1);
    digester.addCallParam(prefix + "/userId", 0, "directory");
    digester.addBeanPropertySetter(prefix + "/userId", "identifier");
    digester.addSetNext(prefix + "/userId", "addUserId"); // called on </userId> to set on parent Agent

    digester.addSetNext(prefix, parentMethod); // method called on parent object which is the previous stack object
}

From source file:org.gbif.metadata.eml.EmlFactory.java

/**
 * Add rules to extract the keywords./*  w ww  .j av a  2 s. c  om*/
 *
 * @param digester to add the rules to
 */
private static void addKeywordRules(Digester digester) {
    digester.addObjectCreate("eml/dataset/keywordSet", KeywordSet.class);
    digester.addCallMethod("eml/dataset/keywordSet/keyword", "add", 1);
    digester.addCallParam("eml/dataset/keywordSet/keyword", 0);
    digester.addBeanPropertySetter("eml/dataset/keywordSet/keywordThesaurus", "keywordThesaurus");
    digester.addSetNext("eml/dataset/keywordSet", "addKeywordSet"); // add the
    // KeywordSet
    // to the
    // list in
    // EML
}

From source file:org.gbif.metadata.eml.EmlFactory.java

/**
 * Add rules to extract the bibliographic citations.
 *
 * @param digester to add the rules to//w  w  w  .  ja v  a  2  s  . c  om
 */
private static void addBibliographicCitations(Digester digester) {
    digester.addObjectCreate("eml/additionalMetadata/metadata/gbif/bibliography",
            BibliographicCitationSet.class);
    digester.addCallMethod("eml/additionalMetadata/metadata/gbif/bibliography/citation", "add", 2);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/bibliography/citation", 0);
    digester.addCallParam("eml/additionalMetadata/metadata/gbif/bibliography/citation", 1, "identifier");
    // add the BibliographicCitations to the list in EML
    digester.addSetNext("eml/additionalMetadata/metadata/gbif/bibliography", "setBibliographicCitationSet");
}