Example usage for org.jdom2 Content getValue

List of usage examples for org.jdom2 Content getValue

Introduction

In this page you can find the example usage for org.jdom2 Content getValue.

Prototype

public abstract String getValue();

Source Link

Document

Returns the XPath 1.0 string value of this child.

Usage

From source file:com.eds.Model.XMLProcessor.java

License:Apache License

public AuthToken ProcessUIDAuthResponse(ServiceResponse response) {

    BufferedReader reader = response.getReader();
    String authTokenXML = "";
    AuthToken authToken = new AuthToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        authToken.setErrorMessage(ProcessAuthError(response.getErrorNumber(), response.getErrorStream()));
        return authToken;
    }/*from   w  ww  .  jav a2 s .c  o  m*/
    if (null != reader) {
        try {
            String line = "";
            while ((line = reader.readLine()) != null) {
                authTokenXML += line;
            }
            StringReader stringReader = new StringReader(authTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);
            Content timeout = root.getContent().get(1);

            if (content.getValue() != null) {
                authToken.setAuthToken(content.getValue());
                authToken.setAuthTimeout(timeout.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing UID auth response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            authToken.setErrorMessage(errorMessage);
        }
    }
    return authToken;
}

From source file:com.eds.Model.XMLProcessor.java

License:Apache License

public SessionToken ProcessCreateSessionResponse(ServiceResponse response) {
    BufferedReader reader = response.getReader();
    String line = "";
    String sessionTokenXML = "";
    // Check for errors
    SessionToken sessionToken = new SessionToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        sessionToken.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {/*from  w  w  w  .j  a va  2s .com*/
        if (null != reader) {
            try {
                while ((line = reader.readLine()) != null) {
                    sessionTokenXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing create session response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                sessionToken.setApiErrorMessage(errorMessage);
            }
        }
        /*
         * Parse String to XML and the get the value
         */
        try {
            StringReader stringReader = new StringReader(sessionTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);

            if (content.getValue() != null) {
                sessionToken.setSessionToken(content.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            sessionToken.setApiErrorMessage(errorMessage);
        }
    }
    return sessionToken;

}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a session token object from an EDS API Response
 *//*from  w  w w. j  a  v a2 s .  c  om*/
public SessionToken buildSessionToken(Response response) {
    BufferedReader reader = response.getRead();
    String sessionTokenXML = "";
    // Check for errors
    SessionToken sessionToken = new SessionToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        sessionToken.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        if (null != reader) {
            try {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sessionTokenXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing create session response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                sessionToken.setApiErrorMessage(errorMessage);
            }
        }
        /*
         * Parse String to XML and the get the value
         */
        try {
            StringReader stringReader = new StringReader(sessionTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);

            if (content.getValue() != null) {
                sessionToken.setSessionToken(content.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            sessionToken.setApiErrorMessage(errorMessage);
        }
    }
    return sessionToken;

}

From source file:com.rometools.rome.io.impl.RSS092Parser.java

License:Open Source License

@Override
protected Description parseItemDescription(final Element rssRoot, final Element eDesc) {
    final Description desc = new Description();
    final StringBuilder sb = new StringBuilder();
    final XMLOutputter xmlOut = new XMLOutputter();
    for (final Content c : eDesc.getContent()) {
        switch (c.getCType()) {
        case Text:
        case CDATA:
            sb.append(c.getValue());
            break;
        case EntityRef:
            LOG.debug("Entity: {}", c.getValue());
            sb.append(c.getValue());/*w  w  w  .j a va2s  .c  om*/
            break;
        case Element:
            sb.append(xmlOut.outputString((Element) c));
            break;
        default:
            // ignore
            break;
        }
    }
    desc.setValue(sb.toString());
    String att = eDesc.getAttributeValue("type");
    if (att == null) {
        att = "text/html";
    }
    desc.setType(att);
    return desc;
}

From source file:com.sun.syndication.io.impl.Atom03Generator.java

License:Open Source License

protected Element generateTagLineElement(Content tagline) {
    Element taglineElement = new Element("tagline", getFeedNamespace());

    if (tagline.getType() != null) {
        Attribute typeAttribute = new Attribute("type", tagline.getType());
        taglineElement.setAttribute(typeAttribute);
    }// w  w w .ja  v a2 s.c  o  m

    if (tagline.getValue() != null) {
        taglineElement.addContent(tagline.getValue());
    }
    return taglineElement;
}

From source file:com.sun.syndication.io.impl.Atom03Generator.java

License:Open Source License

protected void fillContentElement(Element contentElement, Content content) throws FeedException {

    if (content.getType() != null) {
        Attribute typeAttribute = new Attribute("type", content.getType());
        contentElement.setAttribute(typeAttribute);
    }/*from w  w  w.j a  v a 2 s. c o  m*/

    String mode = content.getMode();
    if (mode != null) {
        Attribute modeAttribute = new Attribute("mode", content.getMode().toString());
        contentElement.setAttribute(modeAttribute);
    }

    if (content.getValue() != null) {

        if (mode == null || mode.equals(Content.ESCAPED)) {
            contentElement.addContent(content.getValue());
        } else if (mode.equals(Content.BASE64)) {
            contentElement.addContent(Base64.encode(content.getValue()));
        } else if (mode.equals(Content.XML)) {

            StringBuffer tmpDocString = new StringBuffer("<tmpdoc>");
            tmpDocString.append(content.getValue());
            tmpDocString.append("</tmpdoc>");
            StringReader tmpDocReader = new StringReader(tmpDocString.toString());
            Document tmpDoc;

            try {
                SAXBuilder saxBuilder = new SAXBuilder();
                tmpDoc = saxBuilder.build(tmpDocReader);
            } catch (Exception ex) {
                throw new FeedException("Invalid XML", ex);
            }

            List children = tmpDoc.getRootElement().removeContent();
            contentElement.addContent(children);
        }
    }
}

From source file:org.openconcerto.xml.JDOM2Utils.java

License:Open Source License

static String getDiff(Element elem1, Element elem2, final boolean normalizeText) {
    if (elem1 == elem2)
        return null;
    if (!equals(elem1, elem2))
        return "element name or namespace";

    // ignore attributes order
    final List<Attribute> attr1 = elem1.getAttributes();
    final List<Attribute> attr2 = elem2.getAttributes();
    if (attr1.size() != attr2.size())
        return "attributes count";
    for (final Attribute attr : attr1) {
        if (!attr.getValue().equals(elem2.getAttributeValue(attr.getName(), attr.getNamespace())))
            return "attribute value";
    }/*  w w w .j a  v a2 s.c o m*/

    // use content order
    final IPredicate<Content> filter = new IPredicate<Content>() {
        @Override
        public boolean evaluateChecked(Content input) {
            return input instanceof Text || input instanceof Element;
        }
    };
    // only check Element and Text (also merge them)
    final Iterator<Content> contents1 = getContent(elem1, filter, true);
    final Iterator<Content> contents2 = getContent(elem2, filter, true);
    while (contents1.hasNext() && contents2.hasNext()) {
        final Content content1 = contents1.next();
        final Content content2 = contents2.next();
        if (content1.getClass() != content2.getClass())
            return "content";
        if (content1 instanceof Text) {
            final String s1 = normalizeText ? ((Text) content1).getTextNormalize() : content1.getValue();
            final String s2 = normalizeText ? ((Text) content2).getTextNormalize() : content2.getValue();
            if (!s1.equals(s2))
                return "text";
        } else {
            final String rec = getDiff((Element) content1, (Element) content2, normalizeText);
            if (rec != null)
                return rec;
        }
    }
    if (contents1.hasNext() || contents2.hasNext())
        return "content size";

    return null;
}

From source file:org.openconcerto.xml.JDOM2Utils.java

License:Open Source License

/**
 * Get the filtered content of an element, optionnaly merging adjacent {@link Text}. Adjacent
 * text can only happen programmatically.
 * /*  www.  j  a v a2  s . c o  m*/
 * @param elem the parent.
 * @param pred which content to return.
 * @param mergeText <code>true</code> if adjacent Text should be merged into one,
 *        <code>false</code> to leave the list as it is.
 * @return the filtered content (not supportting {@link Iterator#remove()}).
 */
public static Iterator<Content> getContent(final Element elem, final IPredicate<? super Content> pred,
        final boolean mergeText) {
    final Iterator<Content> iter = (Iterator<Content>) elem.getContent(new AbstractFilter<Content>() {
        @Override
        public Content filter(Object obj) {
            final Content c = (Content) obj;
            return pred.evaluateChecked(c) ? c : null;
        }
    }).iterator();
    if (!mergeText)
        return iter;

    return new Iterator<Content>() {

        private Content next = null;

        @Override
        public boolean hasNext() {
            return this.next != null || iter.hasNext();
        }

        @Override
        public Content next() {
            if (this.next != null) {
                final Content res = this.next;
                this.next = null;
                return res;
            }

            Content res = iter.next();
            assert res != null;
            if (res instanceof Text && iter.hasNext()) {
                this.next = iter.next();
                Text concatText = null;
                while (this.next instanceof Text) {
                    if (concatText == null) {
                        concatText = new Text(res.getValue());
                    }
                    concatText.append((Text) this.next);
                    this.next = iter.hasNext() ? iter.next() : null;
                }
                assert this.next != null;
                if (concatText != null)
                    res = concatText;
            }

            return res;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:recparser.idmef.IdmefParser.java

License:Open Source License

public List<IntrusionAlert> parser(String input) {

    long initParser = System.currentTimeMillis();
    System.out.println("*** INIT PARSER IDMEF at " + initParser + " *** ");

    //Primero verificar si vienen una o mas alertas
    String[] mensajes = splitIDMEF(input);
    for (int i = 0; i < mensajes.length; i++) {
        IntrusionAlert intrusionAlert = new IntrusionAlert();
        try {//w  w  w  .  j  av  a  2 s  .  c o m
            DateToXsdDatetimeFormatter xdf = new DateToXsdDatetimeFormatter();
            String currentDate = xdf.format(new Date());
            String intrusionCount = currentDate.replace(":", "").replace("-", "");
            intrusionAlert.setIntCount(intrusionCount);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        String messageID = null;
        SAXBuilder builder = new SAXBuilder();
        StringReader inputReader = new StringReader(mensajes[i]);
        try {

            //XML parser SAX
            Document doc = builder.build(inputReader);
            Element root = doc.getRootElement();
            Namespace ns = root.getNamespace();
            root = root.getChild("Alert", ns);

            //Es una alerta
            if (root != null) {

                //Cogemos los valores relevantes
                Content content;
                // 0. ID de la alerta
                Attribute attribute = root.getAttribute("messageid");
                if (attribute != null) {
                    intrusionAlert.setIntID(attribute.getValue());
                    intrusionAlert.setMessageID(attribute.getValue());
                    messageID = attribute.getValue();
                }
                //1. Datos del analizador
                Element e = root.getChild("Analyzer", ns);
                if (e != null) {
                    attribute = e.getAttribute("analyzerid");
                    if (attribute != null) {
                        intrusionAlert.setAnalyzerID(attribute.getValue());
                        messageID = attribute.getValue() + messageID;
                        intrusionAlert.setIntID(messageID); //MOdificamos el valor de IntID = analyzerID+messageID
                    }
                }

                //2. Tiempo de creacin
                e = root.getChild("CreateTime", ns);
                if (e != null) {
                    for (int j = 0; j < e.getContentSize(); j++) {
                        content = e.getContent(j);
                        intrusionAlert.setIntAlertCreateTime(content.getValue());
                    }
                }

                //3. Severidad 
                e = root.getChild("Assessment", ns);
                if (e != null) {
                    attribute = e.getAttribute("completion");
                    if (attribute != null)
                        intrusionAlert.setIntCompletion(attribute.getValue());
                    e = e.getChild("Impact", ns);
                    if (e != null) {
                        attribute = e.getAttribute("severity");
                        if (attribute != null) {
                            String attributeValue = attribute.getValue();
                            for (int j = 0; j < 4; j++) {
                                if (attributeValue.equals(severidad[j])) {
                                    intrusionAlert.setIntSeverity(j + 1);
                                }
                            }
                        }
                    }
                }

                Namespace reclamo = Namespace.getNamespace("http://reclamo.inf.um.es/idmef");
                Element additional = null;
                additional = root.getChild("AdditionalData", ns);
                if (additional != null) {
                    //4. Porcentaje de ataque
                    additional = additional.getChild("xml", ns);
                    if (additional != null) {

                        additional = additional.getChild("IntrusionTrust", reclamo);

                        if (additional != null) {
                            e = additional.getChild("AttackPercentage", reclamo);
                            if (e != null) {
                                for (int j = 0; j < e.getContentSize(); j++)
                                    content = e.getContent(j);
                            }
                            //5. Certeza
                            additional = additional.getChild("AssessmentTrust", reclamo);
                            if (additional != null) {
                                additional = additional.getChild("Assessment", reclamo);
                                if (additional != null) {
                                    e = additional.getChild("Trust", reclamo);
                                    if (e != null) {
                                        for (int j = 0; j < e.getContentSize(); j++) {
                                            content = e.getContent(j);
                                            intrusionAlert.setAnalyzerConfidence(
                                                    Double.parseDouble(content.getValue()));
                                        }
                                    }
                                }
                            }
                        }
                    }

                }

                //6. Tiempo de deteccin
                e = root.getChild("DetectTime", ns);
                if (e != null) {
                    content = e.getContent(0);
                    intrusionAlert.setIntDetectionTime(content.getValue());

                } else if (additional != null) {//No aparece esta rama, hay que cogerlo del additionaldata
                    e = additional.getChild("Timestamp", reclamo);
                    if (e != null) {
                        for (int j = 0; j < e.getContentSize(); j++) {
                            content = e.getContent(j);
                            intrusionAlert.setIntDetectionTime(content.getValue());
                        }
                    }
                }

                //7. Recursividad en la rama Target
                List targets = root.getChildren("Target", ns);
                Iterator it = targets.iterator();
                while (it.hasNext()) {
                    IntrusionTarget intrusionTarget = new IntrusionTarget();
                    listChildren((Element) it.next(), intrusionTarget, null);
                    intrusionAlert.setIntrusionTarget(intrusionTarget);

                }

                //8. Recursividad en la rama Source
                List sources = root.getChildren("Source", ns);
                it = sources.iterator();
                while (it.hasNext()) {
                    IntrusionSource intrusionSource = new IntrusionSource();
                    listChildren((Element) it.next(), intrusionSource, null);
                    intrusionAlert.setIntrusionSource(intrusionSource);
                }

                //9. Classification

                e = root.getChild("Classification", ns);
                String tipo_alert = null;
                if (e != null) {
                    attribute = e.getAttribute("text");
                    if (attribute != null) {
                        tipo_alert = attribute.getValue();
                        intrusionAlert.setIntName(tipo_alert);
                        String path = "/"
                                + getClass().getProtectionDomain().getCodeSource().getLocation().toString();
                        String path2 = path.substring(6, path.length() - 13);
                        String classtype = this.obtainParameter(
                                path2 + props.getIdmefIntrusionClassificationFile(), tipo_alert);

                        intrusionAlert.setIntType(classtype);
                    }
                }

                //10. En caso de no tener el tipo de alerta antes:
                if (tipo_alert != null && tipo_alert.equals("unknown")) {
                    e = root.getChild("CorrelationAlert", ns);
                    if (e != null) {
                        e = e.getChild("name", ns);
                        if (e != null) {
                            for (int j = 0; j < e.getContentSize(); j++) {
                                content = e.getContent(j);
                                intrusionAlert.setIntType(content.getValue());
                            }
                        }

                    }
                }

                if (intrusionAlert.getIntSeverity() < 0) {
                    intrusionAlert.setIntSeverity(0); //Asignamos 0 al valor de la severidad en caso de que sea -1
                }
                //Insertamos la alerta leida
                intrusionAlerts.add(intrusionAlert);
            }
        }
        // indicates a well-formedness error
        catch (JDOMException e) {
            System.out.println(" is not well-formed.");
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println(e + "2");
        }

        long endParser = System.currentTimeMillis();
        System.out.println("*** END PARSER IDMEF *** Parsing time : " + (endParser - initParser) + " (ms)*** ");
    }

    return intrusionAlerts;

}

From source file:ru.iteco.xmldoc.Config.java

License:Open Source License

/**
 *    ? element./* www  . j  ava 2 s .co  m*/
 * ? ? ,  null.
 *
 * @param element
 * @return
 */
protected static String getPreviousComment(Element element) {
    //? ?    
    Element parent = element.getParentElement();
    //?  ?  
    int index = parent.indexOf(element);

    // ""   ?,   ?-
    for (int i = index - 1; i > 0; i--) {
        //? 
        Content prev = parent.getContent(i);
        //? ?  ? - ?, , ? /??
        if (prev.getCType().equals(Content.CType.Text))
            continue;
        //? ?  -  ,  ?,  
        else if (prev.getCType().equals(Content.CType.Comment))
            return prev.getValue();
        // ?,  ?  ,   ?  ? ?. .
        else
            return "";
    }
    //   ?    .
    return "";
}