Example usage for org.jdom2 Element getAttributeValue

List of usage examples for org.jdom2 Element getAttributeValue

Introduction

In this page you can find the example usage for org.jdom2 Element getAttributeValue.

Prototype

public String getAttributeValue(final String attname) 

Source Link

Document

This returns the attribute value for the attribute with the given name and within no namespace, null if there is no such attribute, and the empty string if the attribute value is empty.

Usage

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static void udpateMarkerStructuredLogOverrideMap() {

    InputStream messageFormatIS = AbstractFoundationLoggingMarker.class
            .getResourceAsStream("/messageFormat.xml");
    if (messageFormatIS == null) {
        LOGGER.debug("file messageformat.xml not found in classpath");
    } else {/*  w  ww.  ja va  2s.com*/
        try {
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(messageFormatIS);

            messageFormatIS.close();

            Element rootElement = document.getRootElement();
            List<Element> markers = rootElement.getChildren("marker");
            for (Element marker : markers) {
                AbstractFoundationLoggingMarker.markersXmlMap.put(marker.getAttributeValue("id"), marker);
            }

        } catch (Exception e) {
            LOGGER.error("cannot load the structured log override file. error is: " + e, e);
            throw new IllegalArgumentException("Problem parsing messageformat.xml", e);
        }
    }

}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static boolean buildFromXml(Element markerElement, StringBuilder builder) {

    Element defaultAppender = markerElement.getChild("defaultAppender");

    List<Element> appenders = markerElement.getChildren("appender");
    String markerId = markerElement.getAttributeValue("id");

    if (appenders != null) {
        for (Element appender : appenders) {
            String appenderId = appender.getAttributeValue("id");
            if (appenderId == null) {
                LOGGER.error("the appender element must have an id poiting to a valid appender name");
            } else {
                buildFromAppenderElement(markerId, appenderId, appender, builder, false, appenderId);
            }// w  w w . j  a v  a 2  s . co m
        }
    }

    if (defaultAppender == null) {

        LOGGER.error("The marker element: '{}' must contain a 'defaultAppender' element", markerId);
        builder.append("return null;");

    } else {

        buildFromAppenderElement(markerId, "defaultAppender", defaultAppender, builder, true, "DEFAULT");
    }

    return true;
}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static void buildFromAppenderElement(String markerId, String appenderId, Element appenderElement,
        StringBuilder builder, boolean isDefault, String appenderName) {

    if (!isDefault) {
        builder.append("if (\"").append(appenderName).append("\".equals(").append("appenderName)){\n");
    }/*w  w w .  j ava  2  s  . c  o m*/

    Element criteriaElement = appenderElement.getChild("criteria");

    if (criteriaElement != null) {

        List<Element> criterionList = criteriaElement.getChildren("criterion");

        if (criterionList != null) {

            for (Element criterionElement : criterionList) {

                String result = criterionElement.getAttributeValue("format");
                List<Element> fieldList = criterionElement.getChildren("field");

                if (fieldList != null) {

                    for (int i = 0; i < fieldList.size(); i++) {
                        Element fieldElement = fieldList.get(i);

                        String key = fieldElement.getAttributeValue("name");
                        String value = fieldElement.getAttributeValue("equals");

                        String getterField = "marker.get" + WordUtils.capitalize(key) + "()";

                        if (i == 0) {
                            builder.append("if (").append(getterField).append(" != null && \"").append(value)
                                    .append("\".equals(").append(getterField).append(".toString())");
                        } else {
                            builder.append(" && ").append(getterField).append(" != null && \"").append(value)
                                    .append("\".equals(").append(getterField).append(".toString())");
                        }

                    }

                    builder.append(")\n\treturn \"").append(result).append("\";\n");
                }

            }
        }
    } else {
        LOGGER.info("The marker element '{}' does not contain a 'criteria' element for appender: '{}'",
                markerId, appenderId);
    }

    String defaultFormat = appenderElement.getAttributeValue("defaultFormat");
    if (defaultFormat == null) {
        LOGGER.error("The marker element: '{}' must contain a 'defaultFormat' element", markerId);
    }
    builder.append("return \"" + defaultFormat + "\";");

    if (!isDefault) {
        builder.append("\n}\n");
    }
}

From source file:com.compomics.pladipus.core.control.updates.ProcessingBeanUpdater.java

/**
 * Adds a new class to the bean definition
 * @param fullyDefinedClassName the fully defined class name
 * @throws IllegalArgumentException/*from w ww. java 2s .  c om*/
 * @throws IOException
 * @throws JDOMException
 */
public void addNewProcessingStep(String fullyDefinedClassName)
        throws IllegalArgumentException, IOException, JDOMException {
    String className = fullyDefinedClassName.substring(fullyDefinedClassName.lastIndexOf(".") + 1);

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(beanXMLDefinitionFile);

    //check if the class is not already in there
    for (Element aBean : document.getRootElement().getChildren()) {
        if (aBean.getAttribute("class").getValue().equals(fullyDefinedClassName)) {
            throw new IllegalArgumentException(
                    "Class is already defined in the bean configuration for " + aBean.getAttributeValue("id"));
        } else if (aBean.getAttribute("id").getValue().equals(className)) {
            throw new IllegalArgumentException("Classname is already in use");
        }
    }

    Element newClassElement = new Element("bean").setAttribute("id", className)
            .setAttribute("class", fullyDefinedClassName).setAttribute("lazy-init", "true");
    document.getRootElement().addContent(newClassElement);
    XMLOutputter outputter = new XMLOutputter();
    try (StringWriter stringWriter = new StringWriter();
            FileWriter writer = new FileWriter(beanXMLDefinitionFile);) {
        outputter.output(document, stringWriter);
        String output = stringWriter.getBuffer().toString();
        //remove empty namespaces
        output = output.replace(" xmlns=\"\"", "");
        writer.append(output);
    }
}

From source file:com.dexterapps.android.translator.TranslateTextForAndroid.java

License:Apache License

private void parseXMLAndGenerateDom(String sourceFile) {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(sourceFile);
    //System.out.println(xmlFile.getAbsolutePath());
    try {//  w  w w.  j  ava  2 s  . c  o  m

        /*Navigate the XML DOM and populate the string array for translation
          We also map the XML in java object so we can use to navigate it again for generating the xml back
         */
        Document document = (Document) builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren();
        for (int i = 0; i < list.size(); i++) {

            AndroidStringMapping stringElement = new AndroidStringMapping();

            Element stringNode = (Element) list.get(i);
            if (stringNode.getName().equalsIgnoreCase("string")) {
                stringElement.setType("string");
                stringElement.setAttributeName(stringNode.getAttributeValue("name"));
                stringElement.setAttributeValue(stringNode.getText());

                baseLanguageStringForTranslation.add(stringNode.getText());
                baseStringResourcesMapping.put(stringNode.getText(), i);
            } else if (stringNode.getName().equalsIgnoreCase("string-array")) {
                List stringArrayNodeList = stringNode.getChildren();
                ArrayList<String> stringArrayItems = new ArrayList<String>();

                for (int j = 0; j < stringArrayNodeList.size(); j++) {
                    Element stringArrayNode = (Element) stringArrayNodeList.get(j);

                    baseLanguageStringForTranslation.add(stringArrayNode.getText());
                    baseStringResourcesMapping.put(stringArrayNode.getText(), i + j);

                    stringArrayItems.add(stringArrayNode.getText());
                }

                stringElement.setType("string-array");
                stringElement.setAttributeName(stringNode.getAttributeValue("name"));
                stringElement.setAttributeValue(stringArrayItems);

            } else {
                List stringPluralNodeList = stringNode.getChildren();
                ArrayList<AndroidStringPlurals> stringPluralsItems = new ArrayList<AndroidStringPlurals>();

                for (int j = 0; j < stringPluralNodeList.size(); j++) {
                    Element stringPluralNode = (Element) stringPluralNodeList.get(j);

                    baseLanguageStringForTranslation.add(stringPluralNode.getText());
                    baseStringResourcesMapping.put(stringPluralNode.getText(), i + j);

                    AndroidStringPlurals pluralItem = new AndroidStringPlurals();

                    pluralItem.setAttributeName(stringPluralNode.getAttributeValue("quantity"));
                    pluralItem.setAttributeValue(stringPluralNode.getText());

                    stringPluralsItems.add(pluralItem);
                }

                stringElement.setType("plurals");
                stringElement.setAttributeName(stringNode.getAttributeValue("name"));
                stringElement.setAttributeValue(stringPluralsItems);

            }

            stringXmlDOM.add(stringElement);

        }

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}

From source file:com.doubotis.sc2dd.util.FontStyleXMLAnalyzer.java

private void computeAnalyze(Document doc) {
    mRacine = doc.getRootElement();/* ww w . j  ava 2  s. com*/
    List<Element> els = mRacine.getChildren();
    for (Element el : els) {
        if (el.getName().equals("Constant")) {
            String constantName = el.getAttributeValue("name");
            String constantValue = el.getAttributeValue("val");
            SFontStyle.SFontStyleConstant constant = new SFontStyle.SFontStyleConstant(constantName,
                    constantValue);
            System.out.println(" -XML- Created Constant " + constant.toString());
            mConstants.put(constant.name, constant);
            continue;
        }

        if (el.getName().equals("Style")) {
            String styleName = el.getAttributeValue("name");
            SFontStyle fontStyle = new SFontStyle(styleName);

            // Reading Styles on XML.
            String template = el.getAttributeValue("template");
            String font = el.getAttributeValue("font");
            String height = el.getAttributeValue("height");
            String vjustify = el.getAttributeValue("vjustify");
            String hjustify = el.getAttributeValue("hjustify");
            String fontflags = el.getAttributeValue("fontflags");
            String styleflags = el.getAttributeValue("styleflags");
            String textcolor = el.getAttributeValue("textcolor");
            String disabledcolor = el.getAttributeValue("disabledcolor");
            String highlightcolor = el.getAttributeValue("highlightcolor");
            String hotkeycolor = el.getAttributeValue("hotkeycolor");
            String hyperlinkcolor = el.getAttributeValue("hyperlinkcolor");
            String glowcolor = el.getAttributeValue("glowcolor");
            String shadowoffset = el.getAttributeValue("shadowoffset");

            fontStyle.template = template;
            fontStyle.font = font;
            fontStyle.height = height;
            fontStyle.vJustify = vjustify;
            fontStyle.hJustify = hjustify;
            fontStyle.fontFlags = fontflags;
            fontStyle.styleFlags = styleflags;
            fontStyle.textColor = textcolor;
            fontStyle.disabledColor = disabledcolor;
            fontStyle.highlightColor = highlightcolor;
            fontStyle.hotkeyColor = hotkeycolor;
            fontStyle.hyperlinkColor = hyperlinkcolor;
            fontStyle.glowColor = glowcolor;
            fontStyle.shadowOffset = shadowoffset;

            if (template != null && !template.equals("")) {
                SFontStyle templateStyle = loadTemplate(template);
                if (templateStyle != null) {
                    SFontStyle foreignStyle = copy(templateStyle);
                    foreignStyle.name = styleName;
                    foreignStyle.template = template;
                    foreignStyle.font = (fontStyle.font != null) ? fontStyle.font : foreignStyle.font;
                    foreignStyle.height = (fontStyle.height != null) ? fontStyle.height : foreignStyle.height;
                    foreignStyle.vJustify = (fontStyle.vJustify != null) ? fontStyle.vJustify
                            : foreignStyle.vJustify;
                    foreignStyle.hJustify = (fontStyle.hJustify != null) ? fontStyle.hJustify
                            : foreignStyle.hJustify;
                    foreignStyle.fontFlags = (fontStyle.fontFlags != null) ? fontStyle.fontFlags
                            : foreignStyle.fontFlags;
                    foreignStyle.styleFlags = (fontStyle.styleFlags != null) ? fontStyle.styleFlags
                            : foreignStyle.styleFlags;
                    foreignStyle.textColor = (fontStyle.textColor != null) ? fontStyle.textColor
                            : foreignStyle.textColor;
                    foreignStyle.disabledColor = (fontStyle.disabledColor != null) ? fontStyle.disabledColor
                            : foreignStyle.disabledColor;
                    foreignStyle.highlightColor = (fontStyle.highlightColor != null) ? fontStyle.highlightColor
                            : foreignStyle.highlightColor;
                    foreignStyle.hotkeyColor = (fontStyle.hotkeyColor != null) ? fontStyle.hotkeyColor
                            : foreignStyle.hotkeyColor;
                    foreignStyle.hyperlinkColor = (fontStyle.hyperlinkColor != null) ? fontStyle.hyperlinkColor
                            : foreignStyle.hyperlinkColor;
                    foreignStyle.glowColor = (fontStyle.glowColor != null) ? fontStyle.glowColor
                            : foreignStyle.glowColor;
                    foreignStyle.shadowOffset = (fontStyle.shadowOffset != null) ? fontStyle.shadowOffset
                            : foreignStyle.shadowOffset;
                    // Transfer the values into fontStyle.
                    fontStyle = foreignStyle;
                }
            }

            // Now convert constants to true values.
            fontStyle.font = getConstantValueIfExists(fontStyle.font);
            fontStyle.height = getConstantValueIfExists(fontStyle.height);
            fontStyle.vJustify = getConstantValueIfExists(fontStyle.vJustify);
            fontStyle.hJustify = getConstantValueIfExists(fontStyle.hJustify);
            fontStyle.fontFlags = getConstantValueIfExists(fontStyle.fontFlags);
            fontStyle.styleFlags = getConstantValueIfExists(fontStyle.styleFlags);
            fontStyle.textColor = getConstantValueIfExists(fontStyle.textColor);
            fontStyle.disabledColor = getConstantValueIfExists(fontStyle.disabledColor);
            fontStyle.highlightColor = getConstantValueIfExists(fontStyle.highlightColor);
            fontStyle.hotkeyColor = getConstantValueIfExists(fontStyle.hotkeyColor);
            fontStyle.hyperlinkColor = getConstantValueIfExists(fontStyle.hyperlinkColor);
            fontStyle.glowColor = getConstantValueIfExists(fontStyle.glowColor);
            fontStyle.shadowOffset = getConstantValueIfExists(fontStyle.shadowOffset);

            // The Font Style is computed! Add it to the list of done styles!
            System.out.println(" -XML- Created Style " + fontStyle.toString());
            mStyles.put(fontStyle.name, fontStyle);
            continue;
        }
    }
}

From source file:com.forum.action.eder.PerfilACT.java

public String execute() throws Exception {
    int c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0, c10 = 0;
    Model modelo = ModelFactory.createDefaultModel();
    FileManager.get().readModel(modelo,// w  w  w.  jav a2  s  .  c  o  m
            ServletActionContext.getServletContext().getRealPath("/") + "/usuarios.rdf");
    Resource perfil = modelo.getResource("http://comunipn.multiaportes.com/rdf/" + nick);

    NodeIterator amigos = modelo.listObjectsOfProperty(
            modelo.getResource("http://comunipn.multiaportes.com/rdf/" + solicitante), FOAF.knows);

    while (amigos.hasNext()) {
        RDFNode amigo = amigos.next();
        Resource amigo1 = (Resource) amigo; // Resource es clase hija de RDFNode

        if (amigo1.getProperty(FOAF.nick).getObject().toString().equals(nick))
            es_conocido = "1";
        else
            es_conocido = "0";
    }

    ServletContext context = ServletActionContext.getServletContext();
    String url = context.getRealPath("/");

    Document document = getDocument(url + "/database.xml");
    Element root = document.getRootElement();
    Element temas = root.getChild("respuestas");
    List<Element> child = temas.getChildren();

    for (Element tema : child) {
        for (Element respuesta : tema.getChildren()) {
            if (respuesta.getAttributeValue("usuario").equals(nick)) {
                switch (Integer.parseInt(respuesta.getAttributeValue("calificacion"))) {
                case 0:
                    c0++;
                    break;
                case 1:
                    c1++;
                    break;
                case 2:
                    c2++;
                    break;
                case 3:
                    c3++;
                    break;
                case 4:
                    c4++;
                    break;
                case 5:
                    c5++;
                    break;
                case 6:
                    c6++;
                    break;
                case 7:
                    c7++;
                    break;
                case 8:
                    c8++;
                    break;
                case 9:
                    c9++;
                    break;
                case 10:
                    c10++;
                    break;
                }
            }
        }
    }

    detalles = new Perfil(perfil.getProperty(FOAF.givenname).getObject().toString(),
            perfil.getProperty(FOAF.family_name).getObject().toString(), "Alumno",
            perfil.getProperty(FOAF.schoolHomepage).getObject().toString());
    calificaciones = new EstadisticasIndiv(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10);
    return SUCCESS;
}

From source file:com.forum.action.eder.TemaACT.java

private ArrayList<Respuesta> respuestasTema(int id, String url) {
    ArrayList<Respuesta> arreglo = new ArrayList<>();
    Document document = getDocument(url);
    Element root = document.getRootElement();
    Element temas = root.getChild("respuestas");
    List<Element> child = temas.getChildren();
    for (Element e : child) {
        if (Integer.parseInt(e.getAttributeValue("id")) != id)
            continue;
        List<Element> child2 = e.getChildren();
        for (Element e2 : child2) {
            arreglo.add(new Respuesta(e2.getAttributeValue("usuario"), e2.getValue(),
                    Integer.parseInt(e2.getAttributeValue("id")),
                    Integer.parseInt(e2.getAttributeValue("calificacion"))));
        }/*from   w  w w. jav a2s  .c  om*/
    }
    return arreglo;
}

From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java

private ImagePanel drawTemplate(Element drawImageTemplateElement) throws Exception {
    // OutputImageSettings
    logger.info("reading ImageDrawTemlate attributes...");
    Element outputImageSettingsElement = drawImageTemplateElement.getChild(OUTPUT_IMAGE_SETTINGS);
    String colorDepth = outputImageSettingsElement.getAttributeValue("ColorDepth");
    String imageForat = outputImageSettingsElement.getAttributeValue("ImageFormat");
    String jpegCompressionLevel = outputImageSettingsElement.getAttributeValue("JpegCompressionLevel");
    String dpi = outputImageSettingsElement.getAttributeValue("Dpi");
    logger.info("Reading Canvas attributes...");
    // Canvas/*from w ww.j  ava2 s  .c o m*/
    Element canvasElement = drawImageTemplateElement.getChild(CANVAS);
    String autoSize = canvasElement.getAttributeValue("AutoSize");
    String centerElements = canvasElement.getAttributeValue("CenterElements");
    int height = Integer.valueOf(canvasElement.getAttributeValue("Height"));
    int width = Integer.valueOf(canvasElement.getAttributeValue("Width"));
    String fill = canvasElement.getAttributeValue("Fill");

    // create image of specified dimensions
    logger.info("Creating working image...");
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    // Elements
    logger.info("Processing elements...");
    Element elementsElement = drawImageTemplateElement.getChild("Elements");
    for (Element element : elementsElement.getChildren()) {
        switch (element.getName()) {
        case "ImageElement":
            image = processImageElement(image, element);
            break;
        case "TextElement":
            image = processTextElement(image, element);
            break;
        }
    }
    return new ImagePanel(image);
}

From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java

private BufferedImage processImageElement(BufferedImage image, Element imageElement) throws Exception {
    logger.info("Processing {}...", imageElement.getAttributeValue("Name"));
    int x = Integer.valueOf(imageElement.getAttributeValue("X"));
    int y = Integer.valueOf(imageElement.getAttributeValue("Y"));
    int width = Integer.valueOf(imageElement.getAttributeValue("Width"));
    int height = Integer.valueOf(imageElement.getAttributeValue("Height"));
    // File or Base64String
    String sourceType = imageElement.getAttributeValue("Source");
    String sourceData = imageElement.getAttributeValue("SourceData");
    String nullImageUrl = imageElement.getAttributeValue("NullImageUrl");
    //        String sourceDpi = imageElement.getAttributeValue("SourceDpi");
    //        boolean useSourceDpi = Boolean.valueOf(imageElement.getAttributeValue("UseSourceDpi"));
    // temporary image for this step
    BufferedImage tmpImage = null;
    switch (sourceType) {
    case "File":
        // load image from file
        if (StringUtils.isEmpty(sourceData)) {
            tmpImage = ImageIO.read(new File(nullImageUrl.replaceAll("\\\\", "/")));
        } else {//from  w w w  .jav a 2 s .c  o m
            tmpImage = ImageIO.read(new File(sourceData.replaceAll("\\\\", "/")));
        }
        break;
    case "Base64String":
        // use substitution to retrieve fileName
        // RATINGSTARS
        if (sourceData.equalsIgnoreCase("%RATINGSTARS%")) {
            //
            //                    BufferedImage stars = ImageIO.read(new FileInputStream(settings.getStarsRating().replaceAll("\\\\", "/")));
            //
            //                    // create stars
            //                    float starsNumber = Float.valueOf(tokenMap.get("%RATINGPERCENT%")) / 10F;
            //                    int fullStarsNumber = (int) Math.floor(starsNumber);
            //                    float starFraction = starsNumber - fullStarsNumber;
            //
            //                    // 1 star -> 24px, so 7.4 stars are 24x7.4 -> 178px
            //                    BufferedImage singleStar = stars.getSubimage(0, 0, 24, 24);
            //
            //                    //Initializing the final image  
            //                    tmpImage = new BufferedImage(width, height, singleStar.getType());
            //                    Graphics2D g2i = tmpImage.createGraphics();
            //                    for (int i = 0; i < fullStarsNumber; i++) {
            //                        g2i.drawImage(singleStar, 24 * i, 0, null);
            //                    }
            //                    // crop the last star
            //                    BufferedImage croppedStar = singleStar.getSubimage(0, 0, Math.round(24 * starFraction), 24);
            //                    g2i.drawImage(croppedStar, 24 * fullStarsNumber, 0, null);
        } else {
            String imageUrl = tokenMap.get(sourceData);
            if (imageUrl != null) {
                tmpImage = ImageIO.read(new File(imageUrl.replaceAll("\\\\", "/")));
            }
        }
        break;
    }
    if (tmpImage != null) {
        // process actions
        tmpImage = processActions(imageElement, tmpImage);
        // alway resize
        IMOperation cOp = new IMOperation();
        cOp.addImage();
        // use "!" to forget aspectratio
        cOp.resize(width, height, "!");
        cOp.addImage("png:-");
        Stream2BufferedImage s2b = new Stream2BufferedImage();
        convert.setOutputConsumer(s2b);
        convert.run(cOp, tmpImage);
        tmpImage = s2b.getImage();

        // compose over current image
        IMOperation op = new IMOperation();
        // the image is alrready resized, so we have to fill only x and y
        op.geometry(null, null, x, y);
        // compose putting source image over destination image
        op.compose("Src_Over");
        op.addImage(2);
        op.addImage("png:-");
        s2b = new Stream2BufferedImage();
        composite.setOutputConsumer(s2b);
        composite.run(op, tmpImage, image);

        // retrieve image
        image = s2b.getImage();

        //            logger.info("Saving image...");
        //            ScreenImage.writeImage(image, "/tmp/images/image" + imageElement.getAttributeValue("Name") + ".png");

    }
    logger.info("{} processed...", imageElement.getAttributeValue("Name"));
    // return processed image
    return image;
}