Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

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

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:musite.io.xml.ProteinResidueAnnotationReader.java

License:Open Source License

public Map<String, MultiMap<Integer, Map<String, Object>>> read(InputStream is) throws IOException {
    if (is == null)
        return null;

    final Map<String, MultiMap<Integer, Map<String, Object>>> result = new HashMap();

    SAXReader saxReader = new SAXReader();
    BufferedInputStream bis = new BufferedInputStream(is);

    Document document;//from ww w.  j  av a  2 s .  c om
    try {
        document = saxReader.read(bis);
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }

    Element root = document.getRootElement();

    // iterate through child elements of root
    for (Iterator i = root.elementIterator(); i.hasNext();) {
        Element annTypeElm = (Element) i.next();
        String annType = annTypeElm.getQualifiedName();
        MultiMap<Integer, Map<String, Object>> sites = result.get(annType);
        if (sites == null) {
            sites = new MultiTreeMap();
            result.put(annType, sites);
        }

        Iterator<Element> itSite = annTypeElm.elementIterator(SITE);
        while (itSite.hasNext()) {
            Element siteElm = (Element) itSite.next();
            String pos = siteElm.attributeValue(POSITION);
            if (pos == null) {
                System.err.println("No site info");
                continue;
            }
            int site = Integer.parseInt(pos) - 1;
            Map<String, Object> annotations = new HashMap();
            sites.add(site, annotations);

            Iterator<Element> itAnn = siteElm.elementIterator();
            while (itAnn.hasNext()) {
                Element annElm = (Element) itAnn.next();
                String name = annElm.getQualifiedName();

                Object obj = null;
                if (annElm.hasContent()) {
                    Reader fieldReader = annotationFieldReaders.get(name);
                    if (fieldReader != null) {
                        try {
                            String text = ProteinsXMLReader.nodeContentToString(annElm);
                            InputStream bais = StringUtil.toStream(text);
                            obj = fieldReader.read(bais);
                            bais.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            continue;
                        }
                    } else {
                        obj = StringEscapeUtils.unescapeXml(annElm.getTextTrim());
                    }
                }

                annotations.put(name, obj);
            }
        }
    }

    return result;
}

From source file:musite.io.xml.ProteinsXMLReader.java

License:Open Source License

public ProteinsXMLReader(Proteins proteins) {
    this.data = proteins;
    nullData = proteins == null;// w w  w.j  a v  a  2s. c  o  m
    proteinFieldReaders = new HashMap();
    fieldFilter = null;
    saxReaderHandler = new HashMap();
    String path = "/protein-list/protein";
    if (root != null)
        path = "/" + root + path;
    addSaxReaderHandler(path, new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            ProteinImpl protein = new ProteinImpl();

            Element elem = path.getCurrent();
            Iterator<Element> itr = elem.elementIterator();
            while (itr.hasNext()) {
                Element field = (Element) itr.next();
                String name = field.getQualifiedName();
                if (fieldFilter != null && fieldFilterInclude != fieldFilter.contains(name))
                    continue;

                Object obj;

                Reader fieldReader = proteinFieldReaders.get(name);
                if (fieldReader != null) {
                    try {
                        String text = nodeContentToString(field);//field.getTextTrim();
                        InputStream bais = StringUtil.toStream(text);
                        obj = fieldReader.read(bais);
                        bais.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        continue;
                    }
                } else {
                    obj = StringEscapeUtils.unescapeXml(field.getTextTrim());
                }

                protein.putInfo(name, obj);
            }

            //System.out.println(protein.getAccession());

            if (proteinFilter == null || proteinFilter.filter(protein))
                data.addProtein(protein);

            int count = data.proteinCount();
            if (count % 1000 == 0)
                System.out.println(count);

            // prune the tree
            elem.detach();
        }
    });
}

From source file:musite.io.xml.UniProtXMLReader.java

License:Open Source License

public Proteins read(InputStream is) throws IOException {
    if (is == null) {
        throw new IllegalArgumentException();
    }//from w  ww.  ja  v  a  2  s . com

    final Proteins result = data == null ? new ProteinsImpl() : data;

    SAXReader saxReader = new SAXReader();

    final StringBuilder acc = new StringBuilder(30);
    final StringBuilder name = new StringBuilder(30);
    final StringBuilder fullName = new StringBuilder(200);
    final StringBuilder org = new StringBuilder(30);
    final StringBuilder seq = new StringBuilder(2000);
    final List<List> sites = new ArrayList(4); // location, ptm, enzyme, annotation
    final Set<String> accs = new HashSet();

    // entry
    saxReader.addHandler("/uniprot/entry", new ElementHandler() {
        public void onStart(ElementPath path) {
            acc.setLength(0);
            fullName.setLength(0);
            seq.setLength(0);
            org.setLength(0);
            name.setLength(0);
            sites.clear();
            accs.clear();
        }

        public void onEnd(ElementPath path) {
            // process a element
            if (org.length() > 0 && (organismFilter == null || organismFilter.contains(org.toString()))
                    && acc.length() > 0 && seq.length() > 0) {
                String accession = acc.toString();
                String sequence = seq.toString();

                ProteinImpl protein = new ProteinImpl(acc.toString(), sequence,
                        name.length() == 0 ? null : name.toString(),
                        fullName.length() == 0 ? null : fullName.toString(),
                        org.length() == 0 ? null : org.toString());
                result.addProtein(protein);

                for (List l : sites) {
                    Integer site = (Integer) l.get(0);
                    PTM ptm = (PTM) l.get(1);
                    String enzyme = (String) l.get(2);
                    if (enzyme != null && enzyme.equalsIgnoreCase("autocatalysis")) {
                        enzyme = name.toString();
                    }

                    Map ann = (Map) l.get(3);
                    try {
                        PTMAnnotationUtil.annotate(protein, site, ptm, enzyme, ann);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (keepAllIds) {
                    for (String ac : accs) {
                        mapIdMainId.put(ac, accession);
                    }
                    if (!accs.isEmpty())
                        protein.putInfo("other-accessions", new HashSet(accs));
                }

                //System.out.println(accession);
            }

            // prune the tree
            Element row = path.getCurrent();
            row.detach();
        }
    });

    // accession
    saxReader.addHandler("/uniprot/entry/accession", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            if (acc.length() == 0) {
                Element el = path.getCurrent();
                acc.append(el.getText());
                //                    if (keepAllIds) {
                //                        accs.add(acc.toString());
                //                    }
            } else {
                if (keepAllIds) {
                    accs.add(path.getCurrent().getText());
                }
            }

        }
    });

    // name
    saxReader.addHandler("/uniprot/entry/name", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            if (name.length() > 0)
                return;

            Element el = path.getCurrent();
            name.append(el.getText());
        }
    });

    // full name
    saxReader.addHandler("/uniprot/entry/protein/recommendedName/fullName", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            if (fullName.length() > 0)
                return;

            Element el = path.getCurrent();
            fullName.append(el.getTextTrim());
        }
    });

    saxReader.addHandler("/uniprot/entry/organism/name", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            if (org.length() > 0)
                return;

            Element el = path.getCurrent();
            String attr = el.attributeValue("type");
            if (attr == null || !attr.equalsIgnoreCase("scientific")) {
                return;
            }

            org.append(el.getText());
        }
    });

    saxReader.addHandler("/uniprot/entry/sequence", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            if (seq.length() > 0)
                return;

            Element el = path.getCurrent();
            seq.append(el.getText().replaceAll("\\p{Space}", ""));
        }
    });

    saxReader.addHandler("/uniprot/entry/feature", new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing
        }

        public void onEnd(ElementPath path) {
            Element el = path.getCurrent();
            String type = el.attributeValue("type");
            if (type == null)
                return;

            PTM ptm = null;
            String enzyme = null;
            String description = null;
            String keyword = null;

            if (UNIPROT_TYPES.contains(type.toLowerCase())) {
                description = el.attributeValue("description");
                if (description == null)
                    return;

                String[] descs = description.split("; ");
                for (String desc : descs) {
                    PTM tmp = PTM.ofKeyword(desc);
                    if (tmp != null) {
                        ptm = tmp;
                        keyword = desc;
                    } else if (desc.startsWith("by ")) {
                        enzyme = desc.substring(3);
                    }
                }
            }
            //                else if (type.equalsIgnoreCase("glycosylation site")) {
            //                    description = el.attributeValue("description");
            //                    ptm = PTM.GLYCOSYLATION;
            //                }
            //                else if (type.equalsIgnoreCase()) {
            //                    description = el.attributeValue("description");
            //                    String[] descs = description.split("; ");
            //                    for (String desc : descs) {
            //                        PTM tmp = PTM.ofKeyword(desc);
            //                        if (tmp != null) {
            //                            ptm = tmp;
            //                            keyword = desc;
            //                        } else if (desc.startsWith("by ")) {
            //                            enzyme = desc.substring(3);
            //                        }
            //                    }
            //                }

            if (ptm == null || (ptmFilter != null && !ptmFilter.contains(ptm)))
                return;

            String status = el.attributeValue("status");
            if (status != null) {
                if (!includeBySimilarity && status.equalsIgnoreCase("By similarity"))
                    return;
                if (!includeProbable && status.equalsIgnoreCase("Probable"))
                    return;
                if (!includePotential && status.equalsIgnoreCase("Potential"))
                    return;
            }

            int site = -1;

            List<Element> locs = el.elements("location");
            for (Element loc : locs) {
                List<Element> poss = loc.elements("position");
                for (Element pos : poss) {
                    String str = pos.attributeValue("position");
                    if (str == null)
                        continue;

                    try {
                        site = Integer.parseInt(str) - 1; //start from 0
                    } catch (NumberFormatException e) {
                        continue;
                    }
                }
            }

            if (site != -1) {
                List l = new ArrayList();
                l.add(site);
                l.add(ptm);
                l.add(enzyme);
                Map<String, Object> m = new HashMap();
                if (keyword != null)
                    m.put("keyword", keyword);
                if (description != null)
                    m.put("description", description);
                if (status != null)
                    m.put("status", status);
                l.add(m);
                sites.add(l);
            }
        }
    });

    BufferedInputStream bis = new BufferedInputStream(is);

    try {
        saxReader.read(bis);
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }

    return result;
}

From source file:net.sf.jguard.jee.provisioning.HttpServletProvisioningServicePoint.java

License:Open Source License

/**
 * load configuration from an XML file.//w  w w .  j  a  v  a  2  s .  com
 *
 * @param configurationLocation
 * @return Map containing filter configuration
 */
private Map<String, String> loadFilterConfiguration(URL configurationLocation) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(J_GUARD_FILTER_2_0_0_XSD);
    Document doc = XMLUtils.read(configurationLocation, url);

    Element authentication = doc.getRootElement();
    Map<String, String> filterSettings = new HashMap<String, String>();
    if (authentication.element(HttpConstants.REGISTER_PROCESS_URI) != null) {
        filterSettings.put(HttpConstants.REGISTER_PROCESS_URI,
                authentication.element(HttpConstants.REGISTER_PROCESS_URI).getTextTrim());
    }
    if (authentication.element(HttpConstants.REGISTER_URI) != null) {
        filterSettings.put(HttpConstants.REGISTER_URI,
                authentication.element(HttpConstants.REGISTER_URI).getTextTrim());
    }

    filterSettings.put(HttpConstants.AUTH_SCHEME,
            authentication.element(HttpConstants.AUTH_SCHEME).getTextTrim());
    Element loginElement = authentication.element(HttpConstants.LOGIN_FIELD);
    if (loginElement != null) {
        filterSettings.put(HttpConstants.LOGIN_FIELD, loginElement.getTextTrim());
    }
    Element passwordElement = authentication.element(HttpConstants.PASSWORD_FIELD);
    if (passwordElement != null) {
        filterSettings.put(HttpConstants.PASSWORD_FIELD, passwordElement.getTextTrim());
    }

    return filterSettings;
}

From source file:net.sf.kraken.BaseTransport.java

License:Open Source License

/**
 * Handle gateway translation service request.
 *
 * @param packet An IQ packet in the iq gateway namespace.
 * @return A list of IQ packets to be returned to the user.
 *///from  w w w  .  j  a  v  a  2s .  c o m
private List<Packet> handleIQGateway(IQ packet) {
    List<Packet> reply = new ArrayList<Packet>();

    if (packet.getType() == IQ.Type.get) {
        IQ result = IQ.createResultIQ(packet);
        Element query = DocumentHelper.createElement(QName.get("query", NameSpace.IQ_GATEWAY));
        query.addElement("desc").addText(LocaleUtils.getLocalizedString("gateway.base.enterusername", "kraken",
                Arrays.asList(transportType.toString().toUpperCase())));
        query.addElement("prompt");
        result.setChildElement(query);
        reply.add(result);
    } else if (packet.getType() == IQ.Type.set) {
        IQ result = IQ.createResultIQ(packet);
        String prompt = null;
        Element promptEl = packet.getChildElement().element("prompt");
        if (promptEl != null) {
            prompt = promptEl.getTextTrim();
        }
        if (prompt == null) {
            result.setError(Condition.bad_request);
        } else {
            JID jid = this.convertIDToJID(prompt);
            Element query = DocumentHelper.createElement(QName.get("query", NameSpace.IQ_GATEWAY));
            // This is what Psi expects
            query.addElement("prompt").addText(jid.toString());
            // This is JEP complient
            query.addElement("jid").addText(jid.toString());
            result.setChildElement(query);
        }
        reply.add(result);
    }

    return reply;
}

From source file:net.sf.kraken.registration.RegistrationHandler.java

License:Open Source License

/**
 * Handles a IQ-register 'set' request, which is to be interpreted as a
 * request to create a new registration.
 *
 * @param packet the IQ-register 'set' stanza.
 * @throws UnauthorizedException if the user isn't allowed to register.
 *//*from  w  w  w . j a va  2s  .co m*/
private void setRegistrationForm(IQ packet) throws UnauthorizedException {
    final JID from = packet.getFrom();

    final boolean registered;
    Collection<Registration> registrations = RegistrationManager.getInstance().getRegistrations(from,
            parent.transportType);
    if (registrations.iterator().hasNext()) {
        registered = true;
    } else {
        registered = false;
    }

    if (!registered && !parent.permissionManager.hasAccess(from)) {
        // User does not have permission to register with transport.
        // We want to allow them to change settings if they are already
        // registered.
        throw new UnauthorizedException(
                LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyacls", "kraken"));
    }

    // Parse the input variables
    String username = null;
    String password = null;
    String nickname = null;
    try {
        if (packet.getChildElement().element("x") != null) {
            final DataForm form = new DataForm(packet.getChildElement().element("x"));
            final List<FormField> fields = form.getFields();
            for (final FormField field : fields) {
                final String var = field.getVariable();
                if (var.equals("username")) {
                    username = field.getValues().get(0);
                } else if (var.equals("password")) {
                    password = field.getValues().get(0);
                } else if (var.equals("nick")) {
                    nickname = field.getValues().get(0);
                }
            }
        }
    }
    // TODO: This shouldn't be done by catching an Exception - check for the
    // existence of elements instead. If we insist doing this with an
    // exception handler, prevent catching a generic Exception (catch more
    // specific subclasses instead).
    catch (Exception ex) {
        // No with data form apparently
        Log.info("Most likely, no dataform was present " + "in the IQ-register request.", ex);
    }

    // input variables could also exist in the non-extended elements
    final Element userEl = packet.getChildElement().element("username");
    final Element passEl = packet.getChildElement().element("password");
    final Element nickEl = packet.getChildElement().element("nick");
    if (userEl != null) {
        username = userEl.getTextTrim();
    }
    if (passEl != null) {
        password = passEl.getTextTrim();
    }
    if (nickEl != null) {
        nickname = nickEl.getTextTrim();
    }

    username = (username == null || username.equals("")) ? null : username;
    password = (password == null || password.equals("")) ? null : password;
    nickname = (nickname == null || nickname.equals("")) ? null : nickname;

    // verify that we've got wat we need.
    if (username == null || (parent.isPasswordRequired() && password == null)
            || (parent.isNicknameRequired() && nickname == null)) {
        // Invalid information from stanza, lets yell.
        Log.info("Cannot process IQ register request, as it " + "fails to provide all data that's required: "
                + packet.toXML());
        final IQ result = IQ.createResultIQ(packet);
        result.setError(Condition.bad_request);
        parent.sendPacket(result);
        return;
    }

    // Check if the client supports our proprietary 'rosterless' mode.
    final boolean rosterlessMode;
    final Element x = packet.getChildElement().element("x");
    if (x != null && x.getNamespaceURI() != null && x.getNamespaceURI().equals(NameSpace.IQ_GATEWAY_REGISTER)) {
        rosterlessMode = true;
        Log.info("Registering " + packet.getFrom() + " as " + username + " in rosterless mode.");
    } else {
        rosterlessMode = false;
        Log.info("Registering " + packet.getFrom() + " as " + username
                + " (without making use of rosterless mode).");
    }

    // Here's where the true magic lies: create the registration!
    try {
        addNewRegistration(from, username, password, nickname, rosterlessMode);

        registrations = RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
        Registration registration = registrations.iterator().next();
        TransportSession session = parent.registrationLoggedIn(registration, from, PresenceType.available, "",
                -1);
        session.setRegistrationPacket(packet);
        session.detachSession();
        parent.getSessionManager().storeSession(from, session);

        //final IQ result = IQ.createResultIQ(packet);
        // I believe this shouldn't be included. Leaving it around just in
        // case.
        // Element response =
        // DocumentHelper.createElement(QName.get("query", IQ_REGISTER));
        // result.setChildElement(response);
        //parent.sendPacket(result);
    } catch (UserNotFoundException e) {
        Log.warn("Someone attempted to register with the gateway " + "who is not registered with the server: "
                + from);
        final IQ eresult = IQ.createResultIQ(packet);
        eresult.setError(Condition.forbidden);
        parent.sendPacket(eresult);
        final Message em = new Message();
        em.setType(Message.Type.error);
        em.setTo(packet.getFrom());
        em.setFrom(packet.getTo());
        em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniednoacct", "kraken"));
        parent.sendPacket(em);
    } catch (IllegalAccessException e) {
        Log.warn("Someone who is not a user of this server " + "tried to register with the transport: " + from);
        final IQ eresult = IQ.createResultIQ(packet);
        eresult.setError(Condition.forbidden);
        parent.sendPacket(eresult);
        final Message em = new Message();
        em.setType(Message.Type.error);
        em.setTo(packet.getFrom());
        em.setFrom(packet.getTo());
        em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyhost", "kraken"));
        parent.sendPacket(em);
    } catch (IllegalArgumentException e) {
        Log.warn("Someone attempted to register with the " + "gateway with an invalid username: " + from);
        final IQ eresult = IQ.createResultIQ(packet);
        eresult.setError(Condition.bad_request);
        parent.sendPacket(eresult);
        final Message em = new Message();
        em.setType(Message.Type.error);
        em.setTo(packet.getFrom());
        em.setFrom(packet.getTo());
        em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbadusername", "kraken"));
        parent.sendPacket(em);
    }
}

From source file:net.techest.railgun.action.FilterActionNode.java

License:Apache License

@Override
public Shell execute(Element node, Shell shell) throws Exception {
    // ?// w  ww.  ja va  2 s  . com
    if (node.getData() == null) {
        throw new ActionException("Filter???filters");
    }
    String[] classP = node.getTextTrim().split("/");
    String className = classP[0];
    String methodName = "process";
    if (classP.length == 2) {
        methodName = classP[1];
    }
    new FiltersInvoker().invoke(shell, className, methodName);
    return shell;
}

From source file:net.unicon.academus.apps.messaging.ImportExportHelper.java

License:Open Source License

/**
 * Parse an XML fragment containing a message.
 * @param e Element object representing the <code>&lt;message&gt;</code>
 *          element.//from   w  w w . j  a  va 2s  .  co m
 * @param facs Civis factories used to validate users and groups
 * @param gexpand Flag to indicate whether groups should be expanded into
 *                their users, or left as groups.
 * @return IMessage representing the given XML element
 */
public static DraftMessage parse(Element e, ICivisFactory[] facs) throws MercuryException {
    // Assertions.
    if (e == null) {
        throw new IllegalArgumentException("Argument 'e [Element]' cannot be null.");
    }
    if (!e.getName().equals("message")) {
        throw new XmlFormatException("Argument 'e [Element]' must be a <message> element.");
    }

    DraftMessage msg = new DraftMessage();
    String buf = null;
    Attribute recipType = null;
    Element e2 = null;
    List list = null;

    // Priority.
    e2 = (Element) e.selectSingleNode("priority");
    if (e2 != null) {
        String tmp = e2.getText();
        Priority p = null;
        try {
            p = Priority.getInstance(tmp);
        } catch (IllegalArgumentException ex) {
            try {
                p = Priority.getInstance(Integer.parseInt(tmp));
            } catch (Exception ex2) {
                p = null;
            }
        }

        if (p == null) {
            throw new XmlFormatException("Illegal priority specified: " + tmp);
        }

        msg.setPriority(p);
    }

    // Recipient.
    list = e.elements("recipient");
    Element recipElement = null;
    Element eType = null;
    Element recipId = null;
    for (Iterator it = list.iterator(); it.hasNext();) {
        recipElement = (Element) it.next();
        recipType = recipElement.attribute("type");

        // get the id 
        recipId = (Element) recipElement.selectSingleNode("id");
        if (recipId == null) {
            throw new XmlFormatException("Missing Element <id> under <recipient>");
        }

        // get the entityType
        eType = (Element) recipElement.selectSingleNode("entity-type");
        if (eType == null) {
            throw new XmlFormatException(
                    "Missing Element <entity-type> under <recipient> for entity " + recipId.getText());
        }

        // entity type is a group
        if (eType.getTextTrim().equalsIgnoreCase(EntityType.GROUP.toString())) {
            // If we have factories to check with, make sure they are valid
            // groups.
            if (facs != null && facs.length > 0) {
                IGroup group = findGroup(facs, recipId.getText());
                if (group == null) {
                    throw new RuntimeException("Could not find the specified group: " + recipId.getText());
                }
            }

            // Don't expand groups -- it is handled by the message factory.
            msg.addRecipient(recipType.getValue(), recipId.getText(), recipId.getText(), EntityType.GROUP);

        } else if (eType.getTextTrim().equalsIgnoreCase(EntityType.USER.toString())) {
            Element eLabel = (Element) recipElement.selectSingleNode("label");
            String uid = recipId.getText();
            String name = uid;

            if (eLabel != null)
                name = eLabel.getText();

            name = validateUsername(facs, uid, name);

            msg.addRecipient(recipType.getValue(), name, uid, EntityType.USER);
        } else {
            throw new XmlFormatException("Illegal value for <entity-type> element: " + eType.getText());
        }
    }

    // Subject.
    e2 = (Element) e.selectSingleNode("subject");
    if (e2 != null)
        msg.setSubject(e2.getText());
    else
        throw new XmlFormatException("Missing element <subject>: Message subject required.");

    // Body.
    e2 = (Element) e.selectSingleNode("body");
    if (e2 != null) {
        Element e3 = (Element) e2.selectSingleNode("html");
        if (e3 != null)
            msg.setBody(e3.asXML());
        else
            msg.setBody(e2.getText());
    } else
        throw new XmlFormatException("Missing element <body>: Message body required.");

    //e2 = (Element)e.selectSingleNode("expires");

    return msg;
}

From source file:no.ntnu.idi.freerider.backend.DBConfigurator.java

License:Apache License

private static void reloadFields() {
    try {// w  w  w .j  a va 2 s .c  om
        Document document = null;
        document = new SAXReader().read(configFile);
        lastRead = new GregorianCalendar();
        Element root = document.getRootElement();
        Element dbUrlElement = root.element("DATABASE_URL");
        DB_URL = dbUrlElement.getTextTrim();
        Element dbUserNameElement = root.element("DATABASE_USERNAME");
        DB_USERNAME = dbUserNameElement.getTextTrim();
        Element dbPasswordElement = root.element("DATABASE_PASSWORD");
        DB_PASSWORD = dbPasswordElement.getTextTrim();
    } catch (Exception e) {
        throw new RuntimeException("Error reading configuration file.", e);
    }
}

From source file:no.ntnu.idi.freerider.xml.RequestParser.java

License:Apache License

/** Read and parse XML from this InputStream, returning a Request if found. */
public static Request parse(InputStream stream) {
    //Create and use reader to make Document.
    SAXReader reader = new SAXReader(false);
    Document document = null;//from w w  w .j a  v  a2  s .co m
    try {
        document = reader.read(stream);
        if (logger.isDebugEnabled()) {
            logger.debug("Parsing request:\n{}", document.asXML());
        }
    } catch (Exception e) {
        logger.warn("Error parsing Request.", e);
    }
    if (!RequestValidator.validate(document)) {
        return null;
    }

    //Find the major elements of the Request.
    Element root = document.getRootElement();
    Element header = (Element) root.elements().get(0);
    Element Data = (Element) root.elements().get(1);
    String typestr = header.attributeValue(ProtocolConstants.REQUEST_TYPE_ATTRIBUTE);
    RequestType type = RequestType.valueOf(typestr);
    User user = new User("", header.attributeValue(ProtocolConstants.USER_ATTRIBUTE));

    //Parse out data unique to different request types.
    if (type.getRequestClass() == UserRequest.class.asSubclass(Request.class)) {
        user = ParserUtils.parseUser(Data.element(ProtocolConstants.USER_ELEMENT));
        return new UserRequest(type, user);
    } else if (type.getRequestClass() == RouteRequest.class.asSubclass(Request.class)) {
        Route route = ParserUtils.parseRoute(Data.element(ProtocolConstants.ROUTE));
        user = route.getOwner();
        return new RouteRequest(type, user, route);
    } else if (type.getRequestClass() == JourneyRequest.class.asSubclass(Request.class)) {
        Journey journey = ParserUtils.parseJourney(Data.element(ProtocolConstants.JOURNEY));
        return new JourneyRequest(type, user, journey);
    } else if (type.getRequestClass() == SingleJourneyRequest.class.asSubclass(Request.class)) {
        return new SingleJourneyRequest(type, user,
                Integer.parseInt(Data.attributeValue(ProtocolConstants.SINGLE_JOURNEY_ID)));
    } else if (type.getRequestClass() == SearchRequest.class.asSubclass(Request.class)) {
        Element searchElement = Data.element(ProtocolConstants.SEARCH);
        Calendar starttime = null;
        try {
            Date startDate = new SimpleDateFormat(ProtocolConstants.XML_DATE_FORMAT)
                    .parse(searchElement.attributeValue(ProtocolConstants.STARTTIME));
            starttime = new GregorianCalendar();
            starttime.setTime(startDate);
        } catch (ParseException e) {
            logger.error("Error parsing time in SEARCH.", e);
        }
        Location startPoint = ParserUtils
                .parseLocation(searchElement.element(ProtocolConstants.START_LOCATION));
        Location endPoint = ParserUtils.parseLocation(searchElement.element(ProtocolConstants.END_LOCATION));
        return new SearchRequest(user, startPoint, endPoint, starttime,
                Integer.parseInt(searchElement.attributeValue(ProtocolConstants.NUMBER_OF_DAYS)));
    } else if (type.getRequestClass() == NotificationRequest.class.asSubclass(Request.class)) {
        Notification note = ParserUtils.parseNotification(Data.element(ProtocolConstants.NOTIFICATION_ELEMENT));
        return new NotificationRequest(type, user, note);
    } else if (type.getRequestClass() == LoginRequest.class.asSubclass(Request.class)) {
        Element tokenElement = Data.element(ProtocolConstants.ACCESS_TOKEN_ELEMENT);
        String accessToken = tokenElement.getTextTrim();
        return new LoginRequest(user, accessToken);
    } else if (type.getRequestClass() == PreferenceRequest.class.asSubclass(Request.class)) {
        TripPreferences preference = ParserUtils.parsePreference(Data.element(ProtocolConstants.PREFERENCE));
        return new PreferenceRequest(type, user, preference);
    } else if (type.getRequestClass() == CarRequest.class.asSubclass(Request.class)) {
        Car car = ParserUtils.parseCar(Data.element(ProtocolConstants.CAR));
        return new CarRequest(type, user, car);
    } else
        return null;
}