Example usage for org.dom4j Attribute getValue

List of usage examples for org.dom4j Attribute getValue

Introduction

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

Prototype

String getValue();

Source Link

Document

Returns the value of the attribute.

Usage

From source file:org.opensha.commons.data.TimeSpan.java

License:Apache License

public static TimeSpan fromXMLMetadata(Element el) {
    String precision = el.attribute("startTimePrecision").getValue();
    String units = el.attribute("durationUnits").getValue();
    double duration = Double.parseDouble(el.attribute("duration").getValue());

    TimeSpan span = new TimeSpan(precision, units);
    span.setDuration(duration, units);/*from w  w w . ja va 2  s.  co  m*/
    Element startTimes = el.element("startTimes");

    int count = startTimes.attributeCount();

    int num = 0;
    int year = -1;
    int month = -1;
    int day = -1;
    int hour = -1;
    int minute = -1;
    int second = -1;
    int millisecond = -1;

    for (int i = 0; i < count; i++) {
        Attribute att = startTimes.attribute(i);
        if (att.getName().equals(TimeSpan.START_DAY.replaceAll(" ", ""))) {
            day = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_HOUR.replaceAll(" ", ""))) {
            hour = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_MILLISECOND.replaceAll(" ", ""))) {
            millisecond = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_MINUTE.replaceAll(" ", ""))) {
            minute = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_MONTH.replaceAll(" ", ""))) {
            month = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_SECOND.replaceAll(" ", ""))) {
            second = Integer.parseInt(att.getValue());
            num++;
        } else if (att.getName().equals(TimeSpan.START_YEAR.replaceAll(" ", ""))) {
            year = Integer.parseInt(att.getValue());
            num++;
        }
    }

    if (num == 1)
        span.setStartTime(year);
    else if (num == 2)
        span.setStartTime(year, month);
    else if (num == 3)
        span.setStartTime(year, month, day);
    else if (num == 4)
        span.setStartTime(year, month, day, hour);
    else if (num == 5)
        span.setStartTime(year, month, day, hour, minute);
    else if (num == 6)
        span.setStartTime(year, month, day, hour, minute, second);
    else if (num == 7)
        span.setStartTime(year, month, day, hour, minute, second, millisecond);

    return span;
}

From source file:org.opensha.commons.geo.Region.java

License:Apache License

/**
 * Initializes a new {@code Region} from stored metadata.
 * @param e metadata element/*w w  w.  j  a  v a  2  s. com*/
 * @return a {@code Region}
 */
public static Region fromXMLMetadata(Element e) {
    LocationList list = LocationList.fromXMLMetadata(e.element(LocationList.XML_METADATA_NAME));
    Region region = new Region(list, BorderType.MERCATOR_LINEAR);
    Attribute nameAtt = e.attribute("name");
    if (nameAtt != null) {
        String name = nameAtt.getValue();
        if (name.length() > 0)
            region.setName(name);
    }
    return region;
}

From source file:org.opensha.refFaultParamDb.vo.Contributor.java

License:Apache License

public static Contributor fromXMLMetadata(Element el) {
    Contributor cont = new Contributor();

    Attribute idAtt = el.attribute("id");
    if (idAtt != null) {
        int id = Integer.parseInt(idAtt.getValue());
        cont.setId(id);//from  w  w  w .  j av  a 2 s .co m
    }
    Attribute nameAtt = el.attribute("name");
    if (nameAtt != null) {
        cont.setName(nameAtt.getValue());
    }
    Attribute emailAtt = el.attribute("email");
    if (emailAtt != null) {
        cont.setEmail(emailAtt.getValue());
    }
    Attribute firstNameAtt = el.attribute("firstName");
    if (firstNameAtt != null) {
        cont.setFirstName(firstNameAtt.getValue());
    }
    Attribute lastNameAtt = el.attribute("lastName");
    if (lastNameAtt != null) {
        cont.setLastName(lastNameAtt.getValue());
    }

    return cont;
}

From source file:org.opensha.refFaultParamDb.vo.FaultModelSummary.java

License:Apache License

public static FaultModelSummary fromXMLMetadata(Element el) {
    Attribute idAtt = el.attribute("faultModelId");
    String name = el.attributeValue("faultModelName");

    Contributor cont = Contributor.fromXMLMetadata(el.element(Contributor.XML_METADATA_NAME));

    if (idAtt != null) {
        int id = Integer.parseInt(idAtt.getValue());

        return new FaultModelSummary(id, name, cont);
    }/* ww w .j ava 2s  .  com*/

    return new FaultModelSummary(name, cont);
}

From source file:org.opensha.sha.earthquake.AbstractEpistemicListERF.java

License:Apache License

public static BaseERF fromXMLMetadata(Element el) throws InvocationTargetException {
    BaseERF erf = AbstractERF.baseERF_FromXML(el);

    Attribute indexAtt = el.attribute("index");
    if (indexAtt != null) {
        int index = Integer.parseInt(indexAtt.getValue());
        return ((EpistemicListERF) erf).getERF(index);
    }/* w  w  w  . ja v a2s  . c  o  m*/

    return erf;
}

From source file:org.opentides.service.impl.ReportServiceImpl.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
@Transactional(readOnly = true)//  w ww  .  ja  va2s. c om
public Map<String, Object> getParameterValues(Map<String, String[]> requestParams, InputStream reportFile) {
    Map<String, Object> ret = new HashMap<String, Object>();
    try {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(reportFile);
        List<Element> list = document.getRootElement().elements("parameter");
        for (String param : requestParams.keySet()) {
            // skip parameter - "report_format" and "report_file"
            if (DynamicReport.REPORT_FILE.equals(param) || DynamicReport.REPORT_FORMAT.equals(param))
                continue;
            for (Element elem : list) {
                Attribute attrib = elem.attribute("name");
                if (attrib.getValue().equals(param)) {
                    Attribute attrClass = elem.attribute("class");
                    String className = "java.lang.String";
                    String[] valueArr = requestParams.get(param);
                    String value = StringUtil.explode(',', valueArr);
                    //ignore empty parameters
                    if (StringUtil.isEmpty(value))
                        continue;
                    if (attrClass != null)
                        className = attrClass.getValue();
                    try {
                        if ("java.io.InputStream".equals(className)) {
                            File image = new File(jasperPath + value);
                            InputStream stream = new FileInputStream(image);
                            if (stream == null)
                                _log.warn("Unable to find file [" + jasperPath + value + "]");
                            else
                                ret.put(param, stream);
                        } else if ("java.util.List".equals(className)) {
                            if (value != null) {
                                String[] values = value.split(",");
                                List<String> temp = Arrays.asList(values);
                                ret.put(param, temp);
                            }
                        } else {
                            Class classDefinition = Class.forName(className);
                            Object objectValue = classDefinition.getConstructor(String.class)
                                    .newInstance(value);
                            ret.put(param, objectValue);
                        }
                    } catch (Exception e) {
                        _log.error("Failed to parse parameter [" + param + "] with value [" + value + "].", e);
                    }
                }
            }

        }
    } catch (DocumentException e) {
        _log.error(e, e);
    }
    return ret;
}

From source file:org.opentides.service.impl.ReportServiceImpl.java

License:Apache License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//  ww  w . j  ava  2  s . co  m
public List<ReportDefinition> getMissingParameters(Map<String, String[]> requestParams,
        InputStream reportFile) {
    List<ReportDefinition> missing = new ArrayList<ReportDefinition>();
    try {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(reportFile);
        List<Element> list = document.getRootElement().elements("parameter");
        for (Element elem : list) {
            Attribute name = elem.attribute("name");
            boolean found = false;
            for (String param : requestParams.keySet()) {
                if (name.getValue().equals(param)) {
                    found = true;
                    continue;
                }
            }
            if (!found) {
                /* Sample entry
                 *    <parameter name="office" class="java.lang.String">
                 *      <property name="prompt.type" value="dropdown"/>
                 *      <property name="prompt.query" value="select key as key_, value as value_ from system_codes
                 *         where category_ = :category"/>
                 *   </parameter>
                 *
                 *  :[paramName] - where paramName will be replaced by the value passed as parameter to the jasper 
                 *     report with the same name as [paramName]
                 */
                // add to missingParameter
                ReportDefinition missed = new ReportDefinition();
                // set the name
                missed.setName(name.getValue());
                // set the class
                Attribute clazz = elem.attribute("class");
                missed.setClazz(clazz.getValue());
                List<Element> props = elem.elements("property");
                Properties property = new SortedProperties();
                for (Element prop : props) {
                    String propName = prop.attributeValue("name");
                    String propValue = prop.attributeValue("value");
                    if ("prompt.type".equals(propName)) {
                        missed.setType(propValue);
                    } else if ("prompt.query".equals(propName)) {
                        // extract the native query to database                     
                        String queryName = propValue;
                        if (!StringUtil.isEmpty(queryName)) {
                            //try to match :[paramName]
                            Matcher matcher = Pattern.compile(":(\\w+)").matcher(queryName);
                            while (matcher.find()) {
                                String paramName = matcher.group(0).substring(1);
                                if (!StringUtil.isEmpty(paramName) && requestParams.get(paramName) != null) {
                                    String[] paramValueArr = requestParams.get(paramName);
                                    String paramValue = StringUtil.explode(',', paramValueArr);
                                    queryName = queryName.replaceAll(":" + paramName, paramValue);
                                }
                            }
                        }

                        List<Object[]> rs = ((ReportDAO) getDao()).getParamOptionResults(queryName);
                        for (Object[] option : rs) {
                            property.put(Long.valueOf(option[1].toString()), option[0].toString());
                        }
                    } else if ("prompt.command".equals(propName)) {
                        missed.setType(propName);
                        property.put(propValue, dynamicParameters.get(propValue));
                    } else
                        property.put(propName, propValue);
                }
                missed.setProperties(property);
                missing.add(missed);
            }
        }
        if (!requestParams.containsKey(DynamicReport.REPORT_FORMAT)) {
            ReportDefinition missed = new ReportDefinition();
            missed.setName("reportFormat");
            missed.setClazz("java.lang.String");
            missed.setType("dropdown");
            Properties props = new Properties();
            props.put(DynamicReport.FORMAT_EXCEL, "Excel");
            props.put(DynamicReport.FORMAT_HTML, "Html");
            props.put(DynamicReport.FORMAT_IMAGE, "Graph Image");
            props.put(DynamicReport.FORMAT_PDF, "PDF");
            missed.setProperties(props);
            missing.add(missed);
        }
    } catch (DocumentException e) {
        _log.error(e, e);
    }
    return missing;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

/**
 * Check the element for the following OPC compliance rules:
 * /*from  w  ww  .j a  va2 s  . c o m*/
 * Rule M4.2: A format consumer shall consider the use of the Markup
 * Compatibility namespace to be an error.
 * 
 * Rule M4.3: Producers shall not create a document element that contains
 * refinements to the Dublin Core elements, except for the two specified in
 * the schema: <dcterms:created> and <dcterms:modified> Consumers shall
 * consider a document element that violates this constraint to be an error.
 * 
 * Rule M4.4: Producers shall not create a document element that contains
 * the xml:lang attribute. Consumers shall consider a document element that
 * violates this constraint to be an error.
 * 
 * Rule M4.5: Producers shall not create a document element that contains
 * the xsi:type attribute, except for a <dcterms:created> or
 * <dcterms:modified> element where the xsi:type attribute shall be present
 * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace
 * prefix of the Dublin Core namespace. Consumers shall consider a document
 * element that violates this constraint to be an error.
 */
public void checkElementForOPCCompliance(Element el) throws InvalidFormatException {
    // Check the current element
    List declaredNamespaces = el.declaredNamespaces();
    Iterator itNS = declaredNamespaces.iterator();
    while (itNS.hasNext()) {
        Namespace ns = (Namespace) itNS.next();

        // Rule M4.2
        if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
            throw new InvalidFormatException(
                    "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
    }

    // Rule M4.3
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)
            && !(el.getName().equals(KEYWORD_CREATED) || el.getName().equals(KEYWORD_MODIFIED)))
        throw new InvalidFormatException(
                "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.4
    if (el.attribute(new QName("lang", namespaceXML)) != null)
        throw new InvalidFormatException(
                "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.5
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)) {
        // DCTerms namespace only use with 'created' and 'modified' elements
        String elName = el.getName();
        if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
            throw new InvalidFormatException("Namespace error : " + elName
                    + " shouldn't have the following naemspace -> " + PackageProperties.NAMESPACE_DCTERMS);

        // Check for the 'xsi:type' attribute
        Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
        if (typeAtt == null)
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute present !");

        // Check for the attribute value => 'dcterms:W3CDTF'
        if (!typeAtt.getValue().equals("dcterms:W3CDTF"))
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute with the value 'dcterms:W3CDTF' !");
    }

    // Check its children
    Iterator itChildren = el.elementIterator();
    while (itChildren.hasNext())
        checkElementForOPCCompliance((Element) itChildren.next());
}

From source file:org.openxml4j.opc.PackageRelationshipCollection.java

License:Apache License

/**
 * Parse the relationship part and add all relationship in this collection.
 * //from   ww w.java2  s  .  c o m
 * @param relPart
 *            The package part to parse.
 * @throws InvalidFormatException
 *             Throws if the relationship part is invalid.
 */
private void parseRelationshipsPart(PackagePart relPart) throws InvalidFormatException {
    try {
        SAXReader reader = new SAXReader();
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

        logger.debug("Parsing relationship: " + relPart.getPartName());
        Document xmlRelationshipsDoc = reader.read(relPart.getInputStream());

        // Browse default types
        Element root = xmlRelationshipsDoc.getRootElement();

        // Check OPC compliance M4.1 rule
        boolean fCorePropertiesRelationship = false;

        for (Iterator i = root.elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME); i.hasNext();) {
            Element element = (Element) i.next();
            // Relationship ID
            String id = element.attribute(PackageRelationship.ID_ATTRIBUTE_NAME).getValue();
            // Relationship type
            String type = element.attribute(PackageRelationship.TYPE_ATTRIBUTE_NAME).getValue();

            /* Check OPC Compliance */
            // Check Rule M4.1
            if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES))
                if (!fCorePropertiesRelationship)
                    fCorePropertiesRelationship = true;
                else
                    throw new InvalidFormatException(
                            "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");

            /* End OPC Compliance */

            // TargetMode (default value "Internal")
            Attribute targetModeAttr = element.attribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
            TargetMode targetMode = TargetMode.INTERNAL;
            if (targetModeAttr != null) {
                targetMode = targetModeAttr.getValue().toLowerCase().equals("internal") ? TargetMode.INTERNAL
                        : TargetMode.EXTERNAL;
            }

            // Target converted in URI
            URI target;
            String value = "";
            try {
                value = element.attribute(PackageRelationship.TARGET_ATTRIBUTE_NAME).getValue();

                if (value.indexOf("\\") != -1) {
                    logger.info("target contains \\ therefore not a valid URI" + value + " replaced by /");
                    value = value.replaceAll("\\\\", "/");
                    // word can save external relationship with a \ instead
                    // of /
                }

                target = new URI(value);
            } catch (URISyntaxException e) {
                logger.error("Cannot convert " + value + " in a valid relationship URI-> ignored", e);
                continue;
            }
            addRelationship(target, targetMode, type, id);
        }
    } catch (Exception e) {
        logger.error(e);
        throw new InvalidFormatException(e.getMessage());
    }
}