Example usage for org.dom4j DocumentException DocumentException

List of usage examples for org.dom4j DocumentException DocumentException

Introduction

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

Prototype

public DocumentException(Throwable cause) 

Source Link

Usage

From source file:at.jabberwocky.impl.core.io.PacketReader.java

private Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = docFactory;//from   w  w w .j av a2  s  .  c  om
    Document document = df.createDocument();
    Element parent = null;
    XmlPullParser pp = parser;
    int count = 0;
    while (true) {
        int type = -1;
        type = pp.nextToken();
        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");
            if (loc >= 0) {
                document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1));
            } else {
                document.addProcessingInstruction(text, "");
            }
            break;
        }
        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }
            break;
        }
        case XmlPullParser.CDSECT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addCDATA(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;

        }
        case XmlPullParser.ENTITY_REF: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have an entityref outside of the root document");
                }
            }
            break;
        }
        case XmlPullParser.END_DOCUMENT: {
            return document;
        }
        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = null;
            // Do not include the namespace if this is the start tag of a new packet
            // This avoids including "jabber:client", "jabber:server" or
            // "jabber:component:accept"
            if ("jabber:client".equals(qname.getNamespaceURI())
                    || "jabber:server".equals(qname.getNamespaceURI())
                    || "jabber:component:accept".equals(qname.getNamespaceURI())
                    || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) {
                newElement = df.createElement(pp.getName());
            } else {
                newElement = df.createElement(qname);
            }
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());
            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }
            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }
            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }
            parent = newElement;
            count++;
            break;
        }
        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }
            count--;
            if (count < 1) {
                return document;
            }
            break;
        }
        case XmlPullParser.TEXT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;
        }
        default:
        }
    }
}

From source file:au.gov.ansto.bragg.process.parse.Parse.java

License:Open Source License

public static Document readFile(File fileName) throws DocumentException {
    SAXReader fileHandle = new SAXReader();
    Document documentHandle = null;
    try {/*w  ww  . ja  v a2  s . co  m*/
        documentHandle = fileHandle.read(fileName);
    } catch (DocumentException e) {
        // TODO: handle exception
        try {
            documentHandle = fileHandle.read(fileName.toURL());
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            throw new DocumentException(e1);
        }
    }
    return documentHandle;
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private Map<String, CompartmentMetabolite> parseMetabolites(Element elMetas,
        Map<Annotateable, Map<String, String>> annotations) throws DocumentException {
    Map<String, CompartmentMetabolite> metas = new LinkedHashMap<String, CompartmentMetabolite>();
    Iterator it = elMetas.elementIterator(ELEMENT_METABOLITE);
    while (it.hasNext()) {
        Element el = (Element) it.next();
        String metaId = el.attributeValue(ATTRIBUTE_ID);
        String metaName = el.attributeValue(ATTRIBUTE_NAME);
        String compartment = el.attributeValue(ATTRIBUTE_COMPARTMENT);
        CompartmentMetabolite meta = metaName == null ? new CompartmentMetabolite(metaId, compartment)
                : new CompartmentMetabolite(metaId, metaName, compartment);

        if (metas.put(metaId, meta) != null) {
            throw new DocumentException("duplicate metabolite: " + metaId);
        }/*from   w w  w. ja  v  a  2  s .  c o m*/
        parseAnnotations(el, meta, annotations);
    }
    return metas;
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private static Set<CompartmentReaction> parseReactions(Element elReacts,
        Map<String, CompartmentMetabolite> metas, Map<Annotateable, Map<String, String>> annotations)
        throws DocumentException {
    final Set<CompartmentReaction> reacts = new LinkedHashSet<CompartmentReaction>();
    final Iterator<Element> it = elementIterator(elReacts, ELEMENT_REACTION);
    while (it.hasNext()) {
        boolean any = false;
        final Element el = it.next();
        String reactId = el.attributeValue(ATTRIBUTE_ID);
        String reactName = el.attributeValue(ATTRIBUTE_NAME);
        boolean reversible = !Boolean.FALSE.toString()
                .equalsIgnoreCase(el.attributeValue(ATTRIBUTE_REVERSIBLE));//default is true
        final List<CompartmentMetaboliteRatio> ratios = new ArrayList<CompartmentMetaboliteRatio>();
        final Iterator<Element> eduIt = elementIterator(el.element(ELEMENT_EDUCTS), ELEMENT_EDUCT);
        any |= eduIt.hasNext();//  w ww . j  a va2  s .c o  m
        while (eduIt.hasNext()) {
            Element edu = (Element) eduIt.next();
            CompartmentMetaboliteRatio ratio = parseMetaboliteRatio(el, edu, metas, true /*educt*/);
            ratios.add(ratio);
        }
        final Iterator<Element> proIt = elementIterator(el.element(ELEMENT_PRODUCTS), ELEMENT_PRODUCT);
        any |= proIt.hasNext();
        while (proIt.hasNext()) {
            final Element pro = proIt.next();
            CompartmentMetaboliteRatio ratio = parseMetaboliteRatio(el, pro, metas, false /*educt*/);
            ratios.add(ratio);
        }
        if (!any) {
            throw new DocumentException(
                    "reaction has neither educts nor products: " + reactId + "/" + reactName);
        }
        final CompartmentReaction reac = new CompartmentReaction(reactId, reactName, ratios, reversible);
        if (!reacts.add(reac)) {
            throw new DocumentException("duplicate reaction: " + reactId);
        }
        parseAnnotations(el, reac, annotations);
    }
    return reacts;
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private static CompartmentMetaboliteRatio parseMetaboliteRatio(Element elReact, Element elRatio,
        Map<String, CompartmentMetabolite> metas, boolean educt) throws DocumentException {
    String metaId = elRatio.attributeValue(ATTRIBUTE_SPECIES);
    String sStoich = elRatio.attributeValue(ATTRIBUTE_STOICHIOMETRY);
    double stoich = sStoich == null ? 1d : Double.parseDouble(sStoich);
    CompartmentMetabolite meta = metas.get(metaId);
    if (meta == null) {
        throw new DocumentException(
                "metabolite '" + metaId + "' not found for reaction: " + elReact.attributeValue(ATTRIBUTE_ID));
    }// w ww .j a  va 2s .co m
    return new CompartmentMetaboliteRatio(meta, educt ? -stoich : stoich);
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private static void parseAnnotations(Element element, Annotateable annotateable,
        Map<Annotateable, Map<String, String>> annotations) throws DocumentException {
    Iterator noteIt = element.elementIterator(ELEMENT_NOTES);
    while (noteIt.hasNext()) {
        Element notes = (Element) noteIt.next();
        Iterator htmlpIt = notes.elementIterator(ELEMENT_HTML_P);
        while (htmlpIt.hasNext()) {
            Element note = (Element) htmlpIt.next();
            String txt = note.getText();
            String[] keyVal = txt.trim().split(":");
            if (keyVal.length != 2) {
                throw new DocumentException("invalid annotation format: " + txt);
            }/*from  w w w .  j  av a  2s.  c  o m*/
            String key = keyVal[0].trim();
            String val = keyVal[1].trim();
            getAnnotationMap(annotations, annotateable, true).put(key, val);
        }
    }
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

@SuppressWarnings("unchecked")
private CompartmentMetabolicNetwork createNetwork(Element model, Map<String, CompartmentMetabolite> metas,
        Set<CompartmentReaction> reactions, Map<Annotateable, Map<String, String>> annotations)
        throws DocumentException {
    final CompartmentMetabolicNetwork net;
    if (compartmentOnly) {
        //only a network for the desired compartment, everything else is external
        Set<CompartmentMetabolite> cMetas = new LinkedHashSet<CompartmentMetabolite>();
        Set<CompartmentReaction> cReacts = new LinkedHashSet<CompartmentReaction>();
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                if (!cMetas.add(meta)) {
                    throw new DocumentException("duplicate metabolite: " + meta.getName());
                }/*from   www.  j a  v a 2s .c o  m*/
            }
        }
        for (CompartmentReaction react : reactions) {
            ArrayIterable<? extends CompartmentMetaboliteRatio> ratios = react
                    .getMetabolieRatiosForCompartment(compartmentName);
            if (!ratios.isEmpty()) {
                List<CompartmentMetaboliteRatio> newRatios = new ArrayList<CompartmentMetaboliteRatio>(
                        ratios.toGenericArray(false));
                if (!react.getEductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    //we have also educts from other compartments, which makes this
                    //reaction being an external one                  
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, false /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, -1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, true /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                if (!react.getProductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, true /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, +1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, false /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                CompartmentReaction cReact = new CompartmentReaction(react.getName(), react.getFullName(),
                        newRatios, react.getConstraints().isReversible());
                if (!cReacts.add(cReact)) {
                    throw new DocumentException("duplicate reaction: " + cReact.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(cMetas, cReacts);
    } else {
        //add the exchange reactions for the external compartment metabolites
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                CompartmentReaction react = createExchangeReaction(meta, false /*uptake*/, true /*reversible*/);
                if (!reactions.add(react)) {
                    throw new DocumentException("duplicate reaction: " + react.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(metas.values(), reactions);
    }

    //set compartment full names
    final Element elCmps = model.element(ELEMENT_COMPARTMENTS);
    for (Element elCmp : (List<Element>) elCmps.elements(ELEMENT_COMPARTMENT)) {
        final String cmpName = elCmp.attributeValue(ATTRIBUTE_ID);
        final String cmpFullName = elCmp.attributeValue(ATTRIBUTE_NAME);
        if (cmpFullName != null && !cmpFullName.equals(cmpName)) {
            net.setCompartmentFullName(cmpName, cmpFullName);
        }
    }

    //add the annotations
    //a) for the network
    parseAnnotations(model, net, annotations);
    //b) for the elements
    for (Annotateable elem : annotations.keySet()) {
        for (Map.Entry<String, String> annot : annotations.get(elem).entrySet()) {
            net.addAnnotation(elem, annot.getKey(), annot.getValue());
        }
    }
    return net;
}

From source file:cn.myloveqian.utils.XmlUtils.java

License:Open Source License

/**
 * @param elements/*w  w w . j a v a  2  s .c  om*/
 * @return
 * @throws DocumentException
 */
public static List<Map<String, String>> getEachElement(List elements) throws DocumentException {
    List<Map<String, String>> resultList = new ArrayList<>();
    if (elements.size() > 0) {
        for (Iterator it = elements.iterator(); it.hasNext();) {
            Map<String, String> resultMap = new HashMap<>();
            Element subElement = (Element) it.next();
            List subElements = subElement.elements();
            for (Iterator subIt = subElements.iterator(); subIt.hasNext();) {
                Element son = (Element) subIt.next();
                String name = son.getName();
                String text = son.getText();
                resultMap.put(name, text);
            }
            resultList.add(resultMap);
        }
    } else {
        throw new DocumentException("this element is disappeared");
    }
    return resultList;
}

From source file:com.arc.cdt.debug.seecode.core.launch.CMPDInfoFromVDKConfigReader.java

License:Open Source License

/**
 * Given a VDK configuration file, extract CMPD information suitable for creating a launch configuration.
 * @param vdkConfig the XML file to read from.
 * @return cmpd description/* w  w  w .  ja va2  s .c  o  m*/
 * @throws VDKConfigException if an error occurs in reading the config file.
 */
@SuppressWarnings("unchecked")
public static ICMPDInfo extractCMPDInfo(File vdkConfig, IProject project) throws VDKConfigException {
    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(vdkConfig);
        Element root = doc.getRootElement();
        if (root == null || !root.getName().equalsIgnoreCase("CMPD")) {
            throw new DocumentException("Root element is not \"CMPD\" node");
        }
        if (!"1".equals(root.attributeValue("version"))) {
            throw new DocumentException("VDK config file has unknown version: " + root.attribute("version"));
        }

        List<Element> processes = root.elements("PROCESS");

        final List<ICMPDInfo.IProcess> pList = new ArrayList<ICMPDInfo.IProcess>(processes.size());
        File workingDir = vdkConfig.getParentFile();
        for (Element p : processes) {
            pList.add(formProcess(p, workingDir, project));
        }

        List<Element> launches = root.elements("LAUNCH"); // should be just one
        final List<String> launchSwitches = new ArrayList<String>();
        final List<String> startupCommands = new ArrayList<String>();
        if (launches != null) {
            for (Element e : launches) {
                appendLaunchSwitches(launchSwitches, startupCommands, e);
            }
        }

        return new ICMPDInfo() {

            @Override
            public String[] getLaunchArgs() {
                return launchSwitches.toArray(new String[launchSwitches.size()]);
            }

            @Override
            public IProcess[] getProcesses() {
                return pList.toArray(new IProcess[pList.size()]);
            }

            @Override
            public String[] getStartupCommands() {
                return startupCommands.toArray(new String[startupCommands.size()]);
            }
        };
    } catch (MalformedURLException e) {
        throw new VDKConfigException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new VDKConfigException(e.getMessage(), e);
    }
}

From source file:com.arc.cdt.debug.seecode.core.launch.CMPDInfoFromVDKConfigReader.java

License:Open Source License

@SuppressWarnings("unchecked")
private static ICMPDInfo.IProcess formProcess(Element e, File workingDir, final IProject project)
        throws DocumentException {
    List<Element> switches = e.elements("SWITCH");
    final String name = e.attributeValue("name");
    final List<String> args = new ArrayList<String>(switches.size());
    ProcessIdList plist = null;//from  www  . j  a  va2s  . co  m
    boolean exeArgsPending = false;
    final List<String> exeCommand = new ArrayList<String>();
    for (Element s : switches) {
        String arg = s.getTextTrim();
        if (arg.startsWith("-pset=")) {
            try {
                plist = ProcessIdList.create(arg.substring(6));
            } catch (NumberFormatException x) {
                throw new DocumentException("Bogus -pset value: " + arg.substring(6) + ": " + x.getMessage());
            }
        } else if (arg.startsWith("-psetname=")) {
            // Do nothing; process name already known
        } else if (arg.equals("--") && exeCommand.size() == 1) {
            exeArgsPending = true;
        } else if (arg.startsWith("-") && !exeArgsPending) {
            args.add(arg);
        } else if (exeCommand.size() > 0 && !exeArgsPending) {
            throw new DocumentException("Multiple exe path specified: " + exeCommand.get(0) + " and " + arg);
        } else
            exeCommand.add(arg);
    }
    if (exeCommand.size() == 0) {
        throw new DocumentException("exe path missing for process " + name);
    }
    if (!new File(exeCommand.get(0)).isAbsolute() && workingDir != null) {
        String file = new File(workingDir, exeCommand.get(0)).toString();
        exeCommand.set(0, file.replaceAll("\\\\", "/"));
    }

    if (new File(exeCommand.get(0)).isAbsolute() && project != null) {
        // Make absolute paths relative to project if possible.
        IPath exePath = new Path(exeCommand.get(0));
        IPath projectPath = project.getLocation();
        if (projectPath.isPrefixOf(exePath)) {
            exePath = exePath.setDevice(null).removeFirstSegments(projectPath.segmentCount());
            exeCommand.set(0, exePath.toString());
        }
    }

    List<Element> props = e.elements("property");
    final Map<String, String> properties = new HashMap<String, String>();
    if (props != null) {
        for (Element p : props) {
            String key = p.attributeValue("name");
            String value = p.attributeValue("value");
            if (key != null && value != null && key.length() > 0) {
                properties.put(key, value);
            }
        }
    }
    final ProcessIdList plistCopy = plist;
    return new ICMPDInfo.IProcess() {

        @Override
        public String[] getCommand() {
            return exeCommand.toArray(new String[exeCommand.size()]);
        }

        @Override
        public int getInstanceCount() {
            return plistCopy.getCount();
        }

        @Override
        public ProcessIdList getIDList() {
            return plistCopy;
        }

        @Override
        public String getProcessName() {
            return name;
        }

        @Override
        public IProject getProject() {
            return project;
        }

        @Override
        public String[] getSwahiliArgs() {
            return args.toArray(new String[args.size()]);
        }

        @Override
        public Map<String, String> getGuihiliProperties() {
            return properties;
        }
    };
}