Example usage for org.dom4j Attribute setValue

List of usage examples for org.dom4j Attribute setValue

Introduction

In this page you can find the example usage for org.dom4j Attribute setValue.

Prototype

void setValue(String value);

Source Link

Document

Sets the value of this attribute or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

protected void resolveAttributeValue(Attribute att, String path) throws XmlConfigException {
    int start;/*from   w  w  w . j a  v a 2 s.  c  o m*/
    int end = -1;

    String value = att.getValue();
    String resValue = "";
    while ((start = value.indexOf("${", end + 1)) != -1) {
        resValue += value.substring(end + 1, start);
        end = value.indexOf('}', start + 2);
        if (end == -1) {
            throw new XmlConfigException(
                    "closing } missing for attribute \"" + att.getName() + "=" + value + "\"", path);
        }
        resValue += getResolvedAttributeValue(att, path, value.substring(start + 2, end));
    }
    resValue += value.substring(end + 1, value.length());
    att.setValue(resValue);
}

From source file:cn.mario256.blog.util.SystemUtils.java

License:Open Source License

/**
 * /*  www .  j av a2s. c o  m*/
 * 
 * @param setting
 *            
 */
@SuppressWarnings("unchecked")
public static void setSetting(Setting setting) {
    Assert.notNull(setting);

    try {
        File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile();
        Document document = new SAXReader().read(turingXmlFile);
        List<org.dom4j.Element> elements = document.selectNodes("/turing/setting");
        for (org.dom4j.Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = BEAN_UTILS.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            xmlWriter = new XMLWriter(new FileOutputStream(turingXmlFile), outputFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            try {
                if (xmlWriter != null) {
                    xmlWriter.close();
                }
            } catch (IOException e) {
            }
        }
        Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME);
        String cacheKey = "setting";
        cache.put(new Element(cacheKey, setting));
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.app.util.SettingUtils.java

License:Open Source License

/**
 * // www . j  ava  2  s.c o  m
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File appXmlFile = new ClassPathResource(CommonAttributes.APP_XML_PATH).getFile();
        Document document = new SAXReader().read(appXmlFile);
        List<Element> elements = document.selectNodes("/app/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(appXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cc.framework.util.SettingUtils.java

License:Open Source License

/**
 * /*www  . j a va2 s.  c  o  m*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/shopxx/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(shopxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

/**
* Sets the Schema Location attribute on the root element
*
* @param document The Exchanger document
* @param schemaType The schema type (either schemaLocation or noNamespaceSchemaLocation)
* @param namespace The namespace/*from w w w . j  a va2s .c o m*/
* @param schemaURL The URL or the schema
* 
*/
public static void setSchemaLocation(ExchangerDocument document, String schemaType, String namespace,
        String schemaURL) {
    schemaURL = URLUtilities.encodeURL(schemaURL);

    XDocument xdoc = document.getDocument();
    Element root = xdoc.getRootElement();

    if (schemaType.equals(SCHEMALOCATION)) {
        Attribute attrNoNS = root.attribute(NOSCHEMALOCATION);
        if (attrNoNS != null) {
            root.remove(attrNoNS);
        }

        // need to set both namspace and url
        Attribute attr = root.attribute(SCHEMALOCATION);
        if (attr == null) {
            // does the schema instance already exist
            Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE);
            if (ns != null) {
                String schemaInstancePrefix = ns.getPrefix();
                StringBuffer name = new StringBuffer();
                name.append(schemaInstancePrefix);
                name.append(":");
                name.append(SCHEMALOCATION);

                StringBuffer value = new StringBuffer();
                value.append(namespace);
                value.append(" ");
                value.append(schemaURL);

                root.addAttribute(name.toString(), value.toString());
            } else {
                root.addNamespace("xsi", SCHEMAINSTANCE);

                StringBuffer name = new StringBuffer();
                name.append("xsi");
                name.append(":");
                name.append(SCHEMALOCATION);

                StringBuffer value = new StringBuffer();
                value.append(namespace);
                value.append(" ");
                value.append(schemaURL);

                root.addAttribute(name.toString(), value.toString());
            }
        } else {
            String attrValue = attr.getValue();

            // break up all the namespace and url pairs
            ArrayList stringValues = new ArrayList();

            StringTokenizer st = new StringTokenizer(attrValue);
            while (st.hasMoreTokens()) {
                stringValues.add(st.nextToken());
            }

            // update existing attribute, Note: it may have multiple attribute pairs
            StringBuffer value = new StringBuffer();
            value.append(namespace);
            value.append(" ");
            value.append(schemaURL);

            //need to start at the third value (i.e we only replace the first namespace-url pair)
            for (int i = 2; i < stringValues.size(); i++) {
                value.append(" ");
                value.append((String) stringValues.get(i));
            }

            attr.setValue(value.toString());
        }
    } else {
        // is of type "no schema location"
        Attribute attrSchema = root.attribute(SCHEMALOCATION);
        if (attrSchema != null) {
            root.remove(attrSchema);
        }

        // just need to set the url
        Attribute attr = root.attribute(NOSCHEMALOCATION);
        if (attr == null) {
            // does the schema instance already exist
            Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE);
            if (ns != null) {
                String schemaInstancePrefix = ns.getPrefix();
                StringBuffer name = new StringBuffer();
                name.append(schemaInstancePrefix);
                name.append(":");
                name.append(NOSCHEMALOCATION);

                root.addAttribute(name.toString(), schemaURL);
            } else {
                root.addNamespace("xsi", SCHEMAINSTANCE);

                StringBuffer name = new StringBuffer();
                name.append("xsi");
                name.append(":");
                name.append(NOSCHEMALOCATION);

                root.addAttribute(name.toString(), schemaURL);
            }
        } else {
            // update existing attribute
            attr.setValue(schemaURL);
        }
    }
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementAVPParser.java

License:Open Source License

public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception {
    List<Element> result;

    if (element.getName().equalsIgnoreCase("header") || element.getName().startsWith("send")) {
        result = xmlElementDefaultParser.replace(element, parameterPool);
    } else // <avp .../>
    {/*  ww  w.j av  a2  s .co m*/
        LinkedList list = new LinkedList<Element>();

        List<Attribute> attributes;
        attributes = element.attributes();

        int allowedParameterLength = -1;
        boolean hasParameter = false;

        for (Attribute attribute : attributes) {
            String value = attribute.getValue();
            Matcher matcher = Parameter.pattern.matcher(value);

            while (matcher.find()) {
                String variableStr = matcher.group();

                if (false == parameterPool.isConstant(variableStr)) {
                    Parameter variable = parameterPool.get(variableStr);
                    hasParameter = true;
                    if (variable != null) {
                        if (allowedParameterLength == -1 || allowedParameterLength == 1) {
                            allowedParameterLength = variable.length();
                        } else if (variable.length() != 1 && allowedParameterLength != variable.length()) {
                            throw new ExecutionException("Invalid length of variables : a variable of length "
                                    + allowedParameterLength + " has been found but " + variableStr
                                    + " has a length of " + variable.length());
                        }
                    }
                }
            }
        }

        if (!hasParameter) {
            allowedParameterLength = 1;
        }

        for (int i = 0; i < allowedParameterLength; i++) {
            Element newElement = element.createCopy();

            List<Attribute> newElementAttributes;
            newElementAttributes = newElement.attributes();

            for (Attribute newAttribute : newElementAttributes) {
                String value = newAttribute.getValue();

                Pattern pattern = Pattern.compile(Parameter.EXPRESSION);
                Matcher matcher = pattern.matcher(value);
                int offset = 0;
                while (matcher.find()) {
                    String before = value.substring(0, matcher.end() + offset - 1);
                    String after = value.substring(matcher.end() + offset - 1);

                    if (parameterPool.exists(matcher.group())) {
                        int index = i;
                        if (parameterPool.get(matcher.group()).length() == 1) {
                            index = 0;
                        }

                        value = before + "(" + index + ")" + after;
                        offset += ((String) "(" + index + ")").length();
                    }

                }
                newAttribute.setValue(value);
            }

            List<Element> tempList = xmlElementDefaultParser.replace(newElement, parameterPool);
            try {
                for (Element e : tempList) {
                    // MsgDiameterParser.getInstance().doDictionnary(e, "0", false);

                    list.addAll(xmlElementTextOnlyParser.replace(e, parameterPool));
                }
            } catch (Exception e) {
                throw new ExecutionException("Error while checking parsed variables against dictionary", e);
            }

        }
        result = list;
    }

    return result;
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementDefaultParser.java

License:Open Source License

public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception {
    List<Element> list = new LinkedList<Element>();

    Element newElement = element.createCopy();
    list.add(newElement);/* w  w  w . j av  a 2  s.  c om*/
    List<Attribute> attributes = newElement.attributes();

    for (Attribute attribute : attributes) {
        String value = attribute.getValue();

        LinkedList<String> parsedValue = parameterPool.parse(value);

        if (parsedValue.size() != 1) {
            throw new ExecutionException("Invalid size of variables in attribute " + value);
        }

        attribute.setValue(parsedValue.getFirst());
    }
    return list;
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementRTPFLOWParser.java

License:Open Source License

public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception {
    List<Element> result = new LinkedList();

    //do classic replacement of attribute and save it in result
    Element newElement = element.createCopy();
    result.add(newElement);//www  .j  a  va 2  s.c  o  m
    List<Attribute> attributes = newElement.attributes();

    for (Attribute attribute : attributes) {
        if (!attribute.getName().equalsIgnoreCase("timestamp")
                && !attribute.getName().equalsIgnoreCase("seqnum")
                && !attribute.getName().equalsIgnoreCase("deltaTime")
                && !attribute.getName().equalsIgnoreCase("mark")) {
            String value = attribute.getValue();

            LinkedList<String> parsedValue = parameterPool.parse(value);

            if (parsedValue.size() != 1) {
                throw new ExecutionException("Invalid size of variables in attribute " + value);
            }

            attribute.setValue(parsedValue.getFirst());
        }
    }

    return result;
}

From source file:com.dp2345.util.SettingUtils.java

License:Open Source License

/**
 * //w ww. java  2 s.co m
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File dp2345XmlFile = new ClassPathResource(CommonAttributes.DP2345_XML_PATH).getFile();
        Document document = new SAXReader().read(dp2345XmlFile);
        List<Element> elements = document.selectNodes("/dp2345/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(dp2345XmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.eurelis.opencms.workflows.workflows.A_OSWorkflowManager.java

License:Open Source License

/**
 * Get the OpenCMS RFS OSWorkflow configuration file and update it with the given filepath.
 * /*  w ww.  j  a va2 s. com*/
 * @param listOfWorkflowsFilepath
 *            the path of the file containing the list of available workflow descriptions
 * @return the path in RFS of the updated file
 * @throws DocumentException
 *             this exception is thrown if an error occurs during the parsing of the document
 * @throws IOException
 *             this exception is thrown if a problem occurs during overwriting of the config file
 */
private String updateOSWorkflowConfigFile(String listOfWorkflowsFilepath)
        throws CmsException, DocumentException, IOException {

    // get file path
    String configFilePath = this.getWebINFPath() + ModuleSharedVariables.SYSTEM_FILE_SEPARATOR
            + OSWORKFLOWCONFIGFILE_RFSFILEPATH;

    File listOfWorkflowsFile = new File(listOfWorkflowsFilepath);
    // Load Jdom parser
    SAXReader reader = new SAXReader();
    Document document = reader.read(configFilePath);
    Node propertyNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH);
    if (propertyNode != null) {
        if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
            // convert Node into element
            Element propertyElement = (Element) propertyNode;

            // update the Attribute
            Attribute valueAttribute = propertyElement
                    .attribute(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_ATTRIBUTNAME);

            valueAttribute.setValue(listOfWorkflowsFile.toURI().toString());

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH + " in the file "
                    + configFilePath + " doesn't correspond to an element");
        }

    } else {
        Node parentNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH);
        if (parentNode != null) {

            if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
                // convert Node into element
                Element parentElement = (Element) parentNode;

                // add new property
                Element propertyElement = parentElement.addElement("property");

                // add attributs
                propertyElement.addAttribute("key", "resource");
                propertyElement.addAttribute("value", listOfWorkflowsFile.toURI().toString());

            } else {
                LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH
                        + " in the file " + configFilePath + " doesn't correspond to an element");
            }

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH
                    + " in the file " + configFilePath + " has not been found.");
        }
    }

    /*
     * Get a string of the resulting file
     */

    // creating of a buffer that will collect result
    ByteArrayOutputStream xmlContent = new ByteArrayOutputStream();

    // Pretty print the document to xmlContent
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(xmlContent, format);
    writer.write(document);
    writer.flush();
    writer.close();

    // get the config file content as a String
    String documentContent = new String(xmlContent.toByteArray());

    /*
     * Overwrite the config file
     */
    FileWriter.writeFile(configFilePath, documentContent);

    return configFilePath;
}