Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

In this page you can find the example usage for org.dom4j Element getText.

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:com.example.sample.pMainActivity.java

License:Apache License

public void listNodes(Element node) {
    System.out.println("" + node.getName());
    List<Attribute> list = node.attributes();
    for (Attribute attr : list) {
        Log.d(TAG, "listNodes: " + attr.getText() + "-----" + attr.getName() + "---" + attr.getValue());
    }//w ww . j  a  v a  2  s  .c  o  m

    if (!(node.getTextTrim().equals(""))) {
        Log.d(TAG, "getText: " + node.getText());
        node.setText("getText: ");
        saveDocument(document);
        Log.d(TAG, "saveDocument: " + node.getText());
    }
    Iterator<Element> it = node.elementIterator();
    while (it.hasNext()) {
        Element e = it.next();
        listNodes(e);
    }
}

From source file:com.feilong.tools.dom4j.Dom4jUtil.java

License:Apache License

/**
 * element.//from w  w w  . j  a  v  a  2s  .  co m
 * 
 * @param element
 *            element
 * @return null==element,null,?element.getText()
 */
public static String getElementText(Element element) {
    if (Validator.isNullOrEmpty(element)) {
        return null;
    }
    String text = element.getText();
    // log.debug("elementName:{}, text is :{}", element.getName(), text);
    return text;
}

From source file:com.fivepebbles.Backup.java

License:MIT License

public void processBackup() {

    //Retrieve Bucket Names and related files/folders from XML saved locally

    Document myDocument = null;/*from  www.  j a v  a  2 s .  com*/

    try {
        URL myURL = new File("target", "s3files.xml").toURI().toURL();
        SAXReader myReader = new SAXReader();
        myDocument = myReader.read(myURL);
    } catch (MalformedURLException | DocumentException e) {
        //***TODO*** log Msg
        e.printStackTrace();
    }

    Element root = myDocument.getRootElement();

    for (Iterator<Element> i1 = root.elementIterator(); i1.hasNext();) {
        Element bucketelem = i1.next();

        if (bucketelem.getName() == "bucket") {
            bucketnm = bucketelem.attributeValue("name");

            for (Iterator<Element> i2 = bucketelem.elementIterator(); i2.hasNext();) {
                Element fileelem = i2.next();

                if (fileelem.getName() == "file") {
                    bfile = fileelem.getText();

                    //Get list of files (bfile could be a folder name)
                    ProcessFiles p1 = new ProcessFiles();
                    filelist = p1.getFiles(bfile);

                    //Append files to arraylist
                    if (filelist != null) {
                        totalfilelist.addAll(filelist);
                    }
                }
            }

            //Make the data good for S3
            //Replace "\" with "/" for Windows

            for (int j = 0; j < totalfilelist.size(); j++) {

                if (totalfilelist.get(j).contains("\\")) {
                    newfilelist.add(totalfilelist.get(j).replace("\\", "/"));
                } else {
                    newfilelist.add(totalfilelist.get(j));
                }
            }

            //Remove Driveletter from files/object list if present (Windows)
            for (int k = 0; k < newfilelist.size(); k++) {
                if (newfilelist.get(k).contains("C:")) {
                    newfilelist2.add(newfilelist.get(k).replace("C:", ""));
                } else {
                    newfilelist2.add(newfilelist.get(k));
                }
            }

            //Get S3 key list corresponding to the files 
            //This is obtained by removing the "/" in index 0 from the file list since AWS key should not have a / at position 0

            for (int m = 0; m < newfilelist2.size(); m++) {
                keylist.add(newfilelist2.get(m).substring(1));
            }

            //Backup files in S3 (for this bucket)

            //Get AWS Credentials
            String[] awskeys = new S3Credentials().getCredentials();

            //Set AWS credentials
            ProcessAWS pr1 = new ProcessAWS(awskeys[0], awskeys[1]);

            //Check if Bucket exists in S3
            if (pr1.checkBucket(bucketnm)) {

                //Put Objects in S3
                //keylist contains S3 keys and newfilelist2 contains the files
                for (int l = 0; l < newfilelist2.size(); l++) {
                    boolean r1 = pr1.putAWSObject(keylist.get(l), new File(newfilelist2.get(l)), bucketnm);

                    if (!r1) {
                        //***TODO*** Log message
                    }
                }
            } else {
                //Create Bucket in S3
                boolean r2 = pr1.createBucket(bucketnm);

                if (r2) {
                    //Put Objects in S3
                    //keylist contains S3 keys and newfilelist2 contains the files
                    for (int m = 0; m < newfilelist2.size(); m++) {
                        boolean r3 = pr1.putAWSObject(keylist.get(m), new File(newfilelist2.get(m)), bucketnm);

                        if (!r3) {
                            //***TODO*** Log message
                        }
                    }

                } else {
                    //***TODO*** Log message
                }
            }

        }

        //Clear arrays for the next bucket
        totalfilelist.clear();
        newfilelist.clear();
        newfilelist2.clear();
        keylist.clear();

    }

}

From source file:com.flaptor.hounder.indexer.DocumentConverter.java

License:Apache License

/**
 * @todo refactor this method, is too long
 *//* w  w  w.j  av a2  s.c om*/
private org.apache.lucene.document.Document processAdd(final Element e) throws IllegalDocumentException {
    // TODO: This method is too long, refactor.
    logger.debug("Processing Add");

    float documentBoost;
    Node node = e.selectSingleNode("boost");
    if (null == node) {
        documentBoost = 1.0F;
    } else {
        documentBoost = Float.parseFloat(node.getText());
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Using non-default document boost of " + documentBoost);
        }
    }
    if (Float.isNaN(documentBoost) || Float.isInfinite(documentBoost) || documentBoost <= 0) {
        throw new IllegalDocumentException("Document with invalid boost (" + documentBoost + ") received.");
    }

    org.apache.lucene.document.Document ldoc = new org.apache.lucene.document.Document();
    ldoc.setBoost(documentBoost);

    // For comparison with the required fields we keep track of the added
    // fields.
    HashSet<String> providedFields = new HashSet<String>();

    //First, we add the documentId as a field under the name provided in the configuration (docIdName)
    node = e.selectSingleNode("documentId");
    if (null == node) {
        throw new IllegalDocumentException("Add document missing documentId.");
    }
    String docIdText = node.getText();
    //now we add the documentId as another field, using the name provided in the configuration (docIdName)
    Field lfield = new Field(docIdName, docIdText, Field.Store.YES, Field.Index.NOT_ANALYZED);
    ldoc.add(lfield);
    providedFields.add(docIdName);
    if (logger.isEnabledFor(Level.DEBUG)) {
        logger.debug("Writer - adding documentId field:" + docIdName
                + ", index: true, store: true, token: false, text: " + docIdText);
    }
    // Now we add the regular fields
    for (Iterator iter = e.elementIterator("field"); iter.hasNext();) {
        Element field = (Element) iter.next();
        String fieldName, storedS, indexedS, tokenizedS, boostS, fieldText;
        boolean stored, tokenized, indexed;
        float boost = 1;

        fieldName = field.valueOf("@name");
        if (fieldName.equals("")) {
            throw new IllegalDocumentException("Field without name.");
        }

        //There cannot be a field with the name used to store the documentId (docIdName)
        //as it would collide with the documentId per se when saved to the lucene index.
        fieldText = field.getText();
        if (fieldName.equals(docIdName)) {
            throw new IllegalDocumentException(
                    "This document contains a field with the same name as the configured name "
                            + "to save the documentId( " + docIdName + ").");
        }

        storedS = field.valueOf("@stored");
        if (storedS.equals("")) {
            throw new IllegalDocumentException("Field without stored attribute.");
        }
        stored = Boolean.valueOf(storedS);

        indexedS = field.valueOf("@indexed");
        if (indexedS.equals("")) {
            throw new IllegalDocumentException("Field without indexed attribute.");
        }
        indexed = Boolean.valueOf(indexedS);
        //Lucene complains of an unindexed unstored field with a runtime exception
        //and it makes no sense anyway
        if (!(indexed || stored)) {
            throw new IllegalDocumentException("processAdd: unindexed unstored field \"" + fieldName + "\".");
        }

        tokenizedS = field.valueOf("@tokenized");
        if (tokenizedS.equals("")) {
            throw new IllegalDocumentException("Field without tokenized attribute.");
        }
        tokenized = Boolean.valueOf(tokenizedS);

        boostS = field.valueOf("@boost");
        if (!boostS.equals("")) {
            try {
                boost = new Float(boostS).floatValue();
            } catch (NumberFormatException exception) {
                throw new IllegalDocumentException(
                        "Unparsable boost value (" + boostS + ") for field  \"" + fieldName + "\".");
            }
        }

        // Now we add the fields. Depending on the parameter stored, indexed
        // and tokenized we call a different field constructor.
        lfield = null;
        Field.Index indexType = (indexed ? (tokenized ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED)
                : Field.Index.NO);
        Field.Store storeType;
        if (!stored) {
            storeType = Field.Store.NO;
        } else {
            if (compressedFields.contains(fieldName)) {
                storeType = Field.Store.COMPRESS;
            } else {
                storeType = Field.Store.YES;
            }
        }
        lfield = new Field(fieldName, fieldText, storeType, indexType);

        lfield.setBoost(boost);
        providedFields.add(fieldName); // for later comparison with the required fields

        ldoc.add(lfield);
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Writer - adding field:" + fieldName + ", index:" + indexed + ", store:" + stored
                    + ", token:" + tokenized + " ,boost: " + boost + ", text: " + fieldText);
        }
    } // for  (field iterator)

    HashSet<String> providedPayloads = new HashSet<String>();
    // Now we add the payloads
    for (Iterator iter = e.elementIterator("payload"); iter.hasNext();) {
        Element payload = (Element) iter.next();

        String payloadName = payload.valueOf("@name");
        if (payloadName.equals("")) {
            throw new IllegalDocumentException("Payload without name.");
        }
        providedPayloads.add(payloadName);
        try {
            Long payloadValue = Long.parseLong(payload.getText());
            ldoc.add(new Field(payloadName, new FixedValueTokenStream(payloadName, payloadValue)));
            logger.debug("Adding payload \"" + payloadName + "\" to document \"" + docIdText + "\" with value "
                    + payloadValue);
        } catch (NumberFormatException nfe) {
            throw new IllegalDocumentException(
                    "Writer - while parsing Long payload \"" + payloadName + "\": " + nfe.getMessage());
        }
    }

    // no we test for the presence of the required fields
    if (!providedFields.containsAll(requiredFields) || !providedPayloads.containsAll(requiredPayloads)) {
        StringBuffer sb = new StringBuffer();
        sb.append("Document with missing required fields or payloads. Ignoring addition.\n");
        sb.append("Provided fields are: \n");
        for (String field : providedFields) {
            sb.append(field + "\n");
        }
        sb.append("The fields required are: \n");
        for (String field : requiredFields) {
            sb.append(field + "\n");
        }

        sb.append("Provided payloads are: \n");
        for (String payload : providedPayloads) {
            sb.append(payload + "\n");
        }
        sb.append("Required payloads are: \n");
        for (String payload : requiredPayloads) {
            sb.append(payload + "\n");
        }
        throw new IllegalDocumentException(sb.toString());
    }
    return ldoc;
}

From source file:com.flaptor.hounder.indexer.SanitizerModule.java

License:Apache License

/**
 * @param doc a non null document to process
 *///from ww  w .  j ava  2 s  . co m
public Document[] internalProcess(final Document doc) {
    Element root = doc.getRootElement();
    if (null != root) {
        for (String name : allFields) {
            Element elem = (Element) root.selectSingleNode(xpath.replace("$", name));
            if (null != elem) {
                try {
                    String text = elem.getText();

                    if (htmlFields.contains(name)) {
                        text = htmlParser.parse("internal document", text.getBytes("UTF-8"), "UTF-8").getText();
                    }

                    if (xmlFields.contains(name)) {
                        text = DomUtil.filterXml(text);
                    }

                    if (accentFields.contains(name)) {
                        text = filterAccents(text);
                    }

                    elem.setText(text);
                } catch (Exception e) {
                    logger.warn("Sanitizing field " + name, e);
                }
            }
        }
    }
    Document[] docs = { doc };
    return docs;
}

From source file:com.flaptor.hounder.util.HtmlParser.java

License:Apache License

@SuppressWarnings("unchecked")
private void extractLinks(Document htmlDoc, Output out) {
    List links = htmlDoc.selectNodes("//A");
    for (Iterator iter = links.iterator(); iter.hasNext();) {
        Element link = (Element) iter.next();
        Attribute href = link.attribute("href");
        if (null != href) {
            try {
                out.addLink(href.getValue(), link.getText());
            } catch (Exception e) {
                logger.warn("Exception occurred, ignoring link " + link.getText() + " at " + href.getValue(),
                        e);//w  w  w.j  a  v  a2 s  .  c  o  m
            }
        }
    }
}

From source file:com.flaptor.util.DomUtil.java

License:Apache License

/**
 * Returns the text of the first ocurrence of an element.
 * @param root the root element of the dom
 * @param elementName the name of the element
 * @return the value of the text of the first element, or null if not found.
 * The first matching element is considered only.
 */// ww w. j a  va2s.c  o  m
public static String getElementText(final Element root, final String elementName) {
    String value = null;
    Element element;
    Iterator elementIterator = root.elementIterator(elementName);
    while (elementIterator.hasNext()) {
        element = (Element) elementIterator.next();
        value = element.getText();
        if (value != null)
            break;
    }
    return value;
}

From source file:com.flaptor.util.parser.HtmlParser.java

License:Apache License

@SuppressWarnings("unchecked")
private void extractLinks(Document htmlDoc, ParseOutput out) {
    try {//w  w w .  j a  va 2s .  c o m
        Node baseNode = htmlDoc.selectSingleNode("//BASE|//Base|//base");
        if (null != baseNode) {
            Attribute href = ((Element) baseNode).attribute("href");
            if (null == href) {
                href = ((Element) baseNode).attribute("HREF");
                if (null == href) {
                    href = ((Element) baseNode).attribute("Href");
                }
            }
            if (null != href) {
                String base = href.getValue();
                if (null != base) {
                    out.setBaseUrl(base);
                }
            }
        }
        List links = htmlDoc.selectNodes("//A|//a");
        for (Iterator iter = links.iterator(); iter.hasNext();) {
            Element link = (Element) iter.next();
            Attribute href = link.attribute("href");
            if (null != href) {
                try {
                    out.addLink(href.getValue(), link.getText());
                } catch (URISyntaxException e) {
                    logger.debug(
                            "Exception occurred, ignoring link " + link.getText() + " at " + href.getValue(),
                            e);
                }
            }
        }
    } catch (URISyntaxException e) {
        logger.debug("Exception occurred, ignoring links in " + out.getUrl(), e);
    }
}

From source file:com.founder.fix.fixflow.core.impl.ProcessEngineConfigurationImpl.java

License:Apache License

private void initRulesConfig() {
    // this.rulesConfigs=new ArrayList<RulesConfig>();
    ruleMap.clear();/* w ww . j a  v  a 2 s  .  co  m*/

    RulesResourceConfig rulesResourceConfig = getFixFlowConfig().getRulesResourceConfig();
    List<RulesResource> rulesResources = rulesResourceConfig.getRulesResource();

    for (RulesResource rulesResource : rulesResources) {
        String classPath = rulesResource.getSrc();
        Document document = null;
        try {
            InputStream in = ReflectUtil.getResourceAsStream(classPath);
            document = XmlUtil.read(in);
        } catch (DocumentException e) {
            log.error("??:" + classPath + "", e);
            throw new FixFlowClassLoadingException(ExceptionCode.CLASSLOAD_EXCEPTION_DCUMENT, classPath, e);
        }

        for (Object ele : document.getRootElement().elements("dataBaseTable")) {
            Element element = (Element) ele;

            DataBaseTable dataBaseTable = SqlmappingconfigFactory.eINSTANCE.createDataBaseTable();
            dataBaseTable.setTableId(element.attributeValue("tableId"));
            dataBaseTable.setTableName(element.attributeValue("tableName"));
            dataBaseTable.setTableValue(element.attributeValue("tableValue"));
            dataBaseTable.setArchiveTable(element.attributeValue("archiveTable"));
            //dataBaseTable.setMappingType(element.attributeValue("mappingType"));

            for (Object eleNew : element.elements("column")) {
                Element columnElement = (Element) eleNew;
                Column column = SqlmappingconfigFactory.eINSTANCE.createColumn();
                column.setColumn(columnElement.attributeValue("column"));
                column.setName(columnElement.attributeValue("name"));
                column.setJdbcType(columnElement.attributeValue("jdbcType"));
                //column.setProperty(columnElement.attributeValue("property"));
                //column.setSimpleKey(columnElement.attributeValue("property"));

                dataBaseTable.getColumn().add(column);
                columnMap.put(dataBaseTable.getTableId() + "_" + column.getColumn(), column);
            }

            dataBaseTables.put(dataBaseTable.getTableId(), dataBaseTable);

        }

        for (Object ele : document.getRootElement().elements("resultMap")) {
            Element element = (Element) ele;

            ResultMap resultMap = SqlmappingconfigFactory.eINSTANCE.createResultMap();
            resultMap.setId(element.attributeValue("id"));
            resultMap.setName(element.attributeValue("name"));
            resultMap.setType(element.attributeValue("type"));

            for (Object eleNew : element.elements("result")) {
                Element resultMappingElement = (Element) eleNew;
                Result result = SqlmappingconfigFactory.eINSTANCE.createResult();
                result.setColumn(resultMappingElement.attributeValue("column"));
                result.setName(resultMappingElement.attributeValue("name"));
                result.setJdbcType(resultMappingElement.attributeValue("jdbcType"));
                result.setProperty(resultMappingElement.attributeValue("property"));
                //result.setSimpleKey(columnMappingElement.attributeValue("property"));

                resultMap.getResult().add(result);
                //columnMappingMap.put(dataBaseTable.getTableId()+"_"+columnMapping.getColumn(), columnMapping);
            }

            resultMaps.put(resultMap.getId(), resultMap);

        }

        for (Object ele : document.getRootElement().elements("insert")) {
            Element element = (Element) ele;

            Insert insertObj = SqlmappingconfigFactory.eINSTANCE.createInsert();
            insertObj.setId(element.attributeValue("id"));
            insertObj.setParameterType(element.attributeValue("parameterType"));
            insertObj.setRemark(element.attributeValue("remark"));
            insertObj.setSqlValue(element.getText());

            String classPathString = element.attributeValue("classPath");

            if (StringUtil.isNotEmpty(classPathString)) {
                Class<?> classObj = ReflectUtil.loadClass(classPathString);
                if (classObj != null) {
                    insertObj.setClassPath(classPathString);
                    ruleClassMap.put(element.attributeValue("id"), classObj);
                }
            }

            ruleMap.put(insertObj.getId(), insertObj);

        }

        for (Object ele : document.getRootElement().elements("delete")) {
            Element element = (Element) ele;

            Delete deleteObj = SqlmappingconfigFactory.eINSTANCE.createDelete();
            deleteObj.setId(element.attributeValue("id"));
            deleteObj.setParameterType(element.attributeValue("parameterType"));
            deleteObj.setRemark(element.attributeValue("remark"));
            deleteObj.setSqlValue(element.getText());

            String classPathString = element.attributeValue("classPath");

            if (StringUtil.isNotEmpty(classPathString)) {
                Class<?> classObj = ReflectUtil.loadClass(classPathString);
                if (classObj != null) {
                    deleteObj.setClassPath(classPathString);
                    ruleClassMap.put(element.attributeValue("id"), classObj);
                }
            }

            ruleMap.put(deleteObj.getId(), deleteObj);

        }

        for (Object ele : document.getRootElement().elements("update")) {
            Element element = (Element) ele;
            Update updateObj = SqlmappingconfigFactory.eINSTANCE.createUpdate();
            updateObj.setId(element.attributeValue("id"));
            updateObj.setParameterType(element.attributeValue("parameterType"));
            updateObj.setRemark(element.attributeValue("remark"));
            updateObj.setSqlValue(element.getText());
            String classPathString = element.attributeValue("classPath");

            if (StringUtil.isNotEmpty(classPathString)) {
                Class<?> classObj = ReflectUtil.loadClass(classPathString);
                if (classObj != null) {
                    updateObj.setClassPath(classPathString);
                    ruleClassMap.put(element.attributeValue("id"), classObj);
                }
            }
            ruleMap.put(updateObj.getId(), updateObj);
        }

        for (Object ele : document.getRootElement().elements("select")) {
            Element element = (Element) ele;
            Select selectObj = SqlmappingconfigFactory.eINSTANCE.createSelect();
            selectObj.setId(element.attributeValue("id"));
            selectObj.setParameterType(element.attributeValue("parameterType"));
            selectObj.setRemark(element.attributeValue("remark"));
            selectObj.setSqlValue(element.getText());
            selectObj.setResultMap(element.attributeValue("resultMap"));
            String classPathString = element.attributeValue("classPath");
            if (StringUtil.isNotEmpty(classPathString)) {
                Class<?> classObj = ReflectUtil.loadClass(classPathString);
                if (classObj != null) {
                    selectObj.setClassPath(classPathString);
                    ruleClassMap.put(element.attributeValue("id"), classObj);
                }
            }
            ruleMap.put(selectObj.getId(), selectObj);
        }

        for (Object ele : document.getRootElement().elements("businessRules")) {
            Element element = (Element) ele;
            BusinessRules businessRules = SqlmappingconfigFactory.eINSTANCE.createBusinessRules();
            businessRules.setId(element.attributeValue("id"));
            businessRules.setParameterType(element.attributeValue("parameterType"));
            businessRules.setRemark(element.attributeValue("remark"));
            businessRules.setSqlValue(element.getText());
            businessRules.setResultType(element.attributeValue("resultType"));
            String classPathString = element.attributeValue("classPath");
            if (StringUtil.isNotEmpty(classPathString)) {
                Class<?> classObj = ReflectUtil.loadClass(classPathString);
                if (classObj != null) {
                    businessRules.setClassPath(classPathString);
                    ruleClassMap.put(element.attributeValue("id"), classObj);
                }
            }
            ruleMap.put(businessRules.getId(), businessRules);
        }
    }
}

From source file:com.founder.fix.fixflow.core.impl.util.XmlUtil.java

License:Apache License

public static String getElementText(Element element) {
    String result = null;/*from www .  ja  v a2s  .  c  om*/
    if (element != null)
        result = element.getText();
    return result;
}