Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

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

Prototype

public List<Element> getChildren(final String cname) 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to no namespace, returned as Element objects.

Usage

From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java

License:Creative Commons License

/**
 * Update member contents with resolved data
 * //from w w w.  ja v a 2  s. co  m
 * @param node
 * @param memberReference
 * @param memberDocument
 * @return
 * @throws Exception
 */
private static Element updateMember(Element node, EReference memberReference, int id, EObject memberObject,
        Document memberDocument) throws Exception {
    Namespace namespace = node.getNamespace(modelMetaData.getNamespace(memberReference));

    List<Element> children = null;
    if (namespace == null) {
        children = node.getChildren(modelMetaData.getName(memberReference));
    } else
        throw new IllegalArgumentException();
    if (id < children.size()) {
        // Inserting resolved contents to the member
        Element element = children.get(id);
        Element clone = memberDocument.getRootElement().clone();
        clone.setName(memberReference.getName());
        node.setContent(node.indexOf(element), clone);
        // Setting xsi:type
        clone.setAttribute("type",
                memberObject.eClass().getEPackage().getName() + ":" + memberObject.eClass().getName(),
                node.getNamespace("xsi"));
    }

    return node;
}

From source file:de.knewcleus.openradar.gui.flightplan.FpXml_1_0.java

License:Open Source License

public static List<FpAtc> parseAtcs(Element eAtcsInRange) {
    List<FpAtc> result = new ArrayList<FpAtc>();
    for (Element eAtc : eAtcsInRange.getChildren("atc")) {
        String callsign = eAtc.getChildText("callsign");
        String username = eAtc.getChildText("username");
        String frequency = eAtc.getChildText("frequency");
        double lon = Double.parseDouble(eAtc.getChildText("lon"));
        double lat = Double.parseDouble(eAtc.getChildText("lat"));
        double distance = Double.parseDouble(eAtc.getChildText("dist"));
        result.add(new FpAtc(callsign, username, frequency, new Point2D.Double(lon, lat), distance));
    }//w  w  w.  j a  va 2  s  .  c om

    return result;
}

From source file:de.knewcleus.openradar.view.stdroutes.StdRouteReader.java

License:Open Source License

private void readRouteXml() {

    SAXBuilder builder = new SAXBuilder();
    InputStream xmlInputStream = null;

    File dir = new File("data/routes/" + data.getAirportCode());
    if (!dir.exists() || !dir.isDirectory()) {
        return;//w w  w.jav  a 2 s. c  o  m
    }

    List<File> files = new ArrayList<File>(Arrays.asList(dir.listFiles()));

    data.getNavaidDB().clearAddPoints();

    while (files.size() > 0) {
        File file = files.remove(0);
        try {
            if (!file.getName().endsWith(".xml"))
                continue;
            // todo read all files
            xmlInputStream = new FileInputStream(file);

            Document document = (Document) builder.build(xmlInputStream);
            Element rootNode = document.getRootElement();

            //                String orFilename = "data/routes/" + data.getAirportCode() + "/" + file.getName().substring(0, file.getName().indexOf(".xml")) + ".or.xml";
            if ("ProceduresDB".equalsIgnoreCase(rootNode.getName())) {// && !(new File(orFilename).exists())) {
                // if converted file does not exist, convert it now.
                // deactivated for now convertProcedureDbFile(orFilename, rootNode);
            } else {
                // read or file
                List<Element> list = rootNode.getChildren("addPoint");
                for (Element eAddPoint : list) {
                    String code = eAddPoint.getAttributeValue("code");
                    String sPoint = eAddPoint.getAttributeValue("point");
                    try {
                        Point2D point = StdRoute.getPoint(data, mapViewAdapter, sPoint, null);
                        data.getNavaidDB().addPoint(code, point);
                    } catch (Exception e) {
                        log.error("Problem to parse file " + file.getAbsolutePath() + ", addPoint: " + code
                                + ": " + sPoint + ", Error:" + e.getMessage());
                    }
                }
                List<Element> includeList = rootNode.getChildren("include");
                for (Element eInclude : includeList) {
                    String fileName = eInclude.getAttributeValue("file");
                    files.add(new File(file.getAbsolutePath().substring(0,
                            file.getAbsolutePath().lastIndexOf(File.separator) + 1) + fileName));
                }
                // routes
                list = rootNode.getChildren("route");
                for (Element eRoute : list) {
                    String name = eRoute.getAttributeValue("name");
                    String displayMode = eRoute.getAttributeValue("displayMode");
                    String zoomMin = eRoute.getAttributeValue("zoomMin");
                    String zoomMax = eRoute.getAttributeValue("zoomMax");
                    String stroke = eRoute.getAttributeValue("stroke");
                    String lineWidth = eRoute.getAttributeValue("lineWidth");
                    String color = eRoute.getAttributeValue("color");
                    List<Element> sublist = eRoute.getChildren();
                    AStdRouteElement previous = null;
                    StdRoute route = new StdRoute(data, mapViewAdapter, name, displayMode, zoomMin, zoomMax,
                            stroke, lineWidth, color);
                    for (Element element : sublist) {
                        try {
                            if (element.getName().equalsIgnoreCase("activeLandingRunways")) {
                                route.setActiveLandingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("activeStartRunways")) {
                                route.setActiveStartingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("navaids")) {
                                color = element.getAttributeValue("color");
                                route.setNavaids(element.getText(), color);
                            } else if (element.getName().equalsIgnoreCase("include")) {
                                String routeName = element.getAttributeValue("routeName");
                                route.includeRoute(stdRoutes, routeName);
                            } else if (element.getName().equalsIgnoreCase("line")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String angle = element.getAttributeValue("angle");
                                String length = element.getAttributeValue("length");
                                String startOffset = element.getAttributeValue("startOffset");
                                String endOffset = element.getAttributeValue("endOffset");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteLine line = new StdRouteLine(route, mapViewAdapter, previous, start,
                                        end, angle, length, startOffset, endOffset, stroke, lineWidth, arrows,
                                        color, text);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("bow")) {
                                String center = element.getAttributeValue("center");
                                String radius = element.getAttributeValue("radius");
                                String startAngle = element.getAttributeValue("startAngle");
                                String extentAngle = element.getAttributeValue("extentAngle");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteBow bow = new StdRouteBow(route, mapViewAdapter, previous, center,
                                        radius, startAngle, extentAngle, stroke, lineWidth, color, arrows,
                                        text);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("curve")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String controlPoint = element.getAttributeValue("controlPoint");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteCurve bow = new StdRouteCurve(route, mapViewAdapter, previous, start,
                                        end, controlPoint, stroke, lineWidth, color, arrows);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("intercept")) {
                                String start = element.getAttributeValue("start");
                                String startOffset = element.getAttributeValue("startOffset");
                                String startHeading = element.getAttributeValue("startHeading");
                                String startTurn = element.getAttributeValue("startTurn");
                                String radius = element.getAttributeValue("radius");
                                String speed = element.getAttributeValue("speed");
                                String end = element.getAttributeValue("end");
                                String radial = element.getAttributeValue("radial");
                                String endHeading = element.getAttributeValue("endHeading");
                                String direction = element.getAttributeValue("direction");
                                String endOffset = element.getAttributeValue("endOffset");
                                String text = element.getAttributeValue("text");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteIntercept intercept = new StdRouteIntercept(route, mapViewAdapter,
                                        previous, start, startOffset, startHeading, startTurn, radius, speed,
                                        end, radial, endHeading, direction, endOffset, stroke, lineWidth,
                                        arrows, color, text);
                                previous = intercept;
                                route.addElement(intercept);
                            } else if (element.getName().equalsIgnoreCase("loop")) {
                                String navpoint = element.getAttributeValue("navpoint");
                                String inboundHeading = element.getAttributeValue("inboundHeading");
                                String length = element.getAttributeValue("length");
                                String width = element.getAttributeValue("width");
                                String right = element.getAttributeValue("right");
                                String arrows = element.getAttributeValue("arrows");
                                String minHeight = element.getAttributeValue("minHeight");
                                String maxHeight = element.getAttributeValue("maxHeight");
                                String misapHeight = element.getAttributeValue("misapHeight");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                StdRouteLoop ellipse = new StdRouteLoop(route, mapViewAdapter, previous,
                                        navpoint, inboundHeading, length, width, right, arrows, minHeight,
                                        maxHeight, misapHeight, stroke, lineWidth, color);
                                previous = ellipse;
                                route.addElement(ellipse);
                            } else if (element.getName().equalsIgnoreCase("multiPointLine")) {
                                String close = element.getAttributeValue("close");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                List<String> points = new ArrayList<String>();
                                List<Element> pointList = element.getChildren("point");
                                for (Element ePoint : pointList) {
                                    points.add(ePoint.getTextTrim());
                                }
                                StdRouteMultipointLine line = new StdRouteMultipointLine(route, mapViewAdapter,
                                        previous, points, close, stroke, lineWidth, color);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("text")) {
                                String position = element.getAttributeValue("position");
                                String angle = element.getAttributeValue("angle");
                                String alignHeading = element.getAttributeValue("alignHeading");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                boolean clickable = "true".equals(element.getAttributeValue("clickable"));
                                String sText = element.getAttributeValue("text");
                                StdRouteText text = new StdRouteText(route, mapViewAdapter, previous, position,
                                        angle, alignHeading, font, fontSize, color, clickable, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("screenText")) {
                                String position = element.getAttributeValue("screenPos");
                                String angle = element.getAttributeValue("angle");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                String sText = element.getAttributeValue("text");
                                StdRouteScreenText text = new StdRouteScreenText(route, mapViewAdapter,
                                        previous, position, angle, font, fontSize, color, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("minAlt")) {
                                String position = element.getAttributeValue("position");
                                String value = element.getAttributeValue("value");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                StdRouteMinAltitude minAlt = new StdRouteMinAltitude(route, mapViewAdapter,
                                        previous, position, value, font, fontSize, color);
                                previous = minAlt;
                                route.addElement(minAlt);
                            }

                        } catch (Exception e) {
                            log.error("Problem to parse file " + file.getAbsolutePath() + ", Route: "
                                    + route.getName() + ", Error:" + e.getMessage(), e);
                            break;
                        }
                    }
                    stdRoutes.add(route);
                }
            }

        } catch (Exception e) {
            log.error("Problem to parse file " + file.getAbsolutePath() + ", Error:" + e.getMessage());

        } finally {
            if (xmlInputStream != null) {
                try {
                    xmlInputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
    data.getNavaidDB().setStdRoutes(stdRoutes);
}

From source file:de.nava.informa.parsers.OPML_1_1_Parser.java

License:Open Source License

static Collection<FeedIF> parse(Element root) {

    Collection<FeedIF> feedColl = new ArrayList<>();

    Date dateParsed = new Date();
    logger.debug("start parsing.");

    // Lower the case of these tags to simulate case-insensitive parsing
    ParserUtils.matchCaseOfChildren(root, "body");

    // Get the head element (only one should occur)
    //    Element headElem = root.getChild("head");
    //    String title = headElem.getChildTextTrim("title");

    // Get the body element (only one occurs)
    Element bodyElem = root.getChild("body");

    // 1..n outline elements
    ParserUtils.matchCaseOfChildren(bodyElem, "outline");
    List feeds = bodyElem.getChildren("outline");
    for (Object feed1 : feeds) {
        Element feedElem = (Element) feed1;
        // get title attribute
        Attribute attrTitle = feedElem.getAttribute("title");
        String strTitle = "[No Title]";
        if (attrTitle != null) {
            strTitle = attrTitle.getValue();
        }// w w w.  j  ava 2s. c o m
        FeedIF feed = new Feed(strTitle);
        if (logger.isDebugEnabled()) {
            logger.debug("Feed element found (" + strTitle + ").");
        }
        // get text attribute
        Attribute attrText = feedElem.getAttribute("text");
        String strText = "[No Text]";
        if (attrText != null) {
            strText = attrText.getValue();
        }
        feed.setText(strText);
        // get attribute type (for example: 'rss')
        Attribute attrType = feedElem.getAttribute("type");
        String strType = "text/xml";
        if (attrType != null) {
            strType = attrType.getValue();
        }
        feed.setContentType(strType);

        // TODO: handle attribute version (for example: 'RSS')

        // get attribute xmlUrl
        Attribute attrXmlUrl = feedElem.getAttribute("xmlUrl");
        if (attrXmlUrl != null && attrXmlUrl.getValue() != null) {
            feed.setLocation(ParserUtils.getURL(attrXmlUrl.getValue()));
        }
        // get attribute htmllUrl
        Attribute attrHtmlUrl = feedElem.getAttribute("htmlUrl");
        if (attrHtmlUrl != null && attrHtmlUrl.getValue() != null) {
            feed.setSite(ParserUtils.getURL(attrHtmlUrl.getValue()));
        }
        // set current date
        feed.setDateFound(dateParsed);
        // add feed to collection
        feedColl.add(feed);
    }

    return feedColl;
}

From source file:de.nava.informa.parsers.RSS_0_91_Parser.java

License:Open Source License

/**
 * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element)
 *///from  ww  w  .j  a  v a 2  s .  c o  m
public ChannelIF parse(ChannelBuilderIF cBuilder, Element root) throws ParseException {
    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }
    Date dateParsed = new Date();
    logger.debug("start parsing.");

    // Get the channel element (only one occurs)
    ParserUtils.matchCaseOfChildren(root, "channel");
    Element channel = root.getChild("channel");
    if (channel == null) {
        logger.warn("Channel element could not be retrieved from feed.");
        throw new ParseException("No channel element found in feed.");
    }

    // --- read in channel information

    ParserUtils.matchCaseOfChildren(channel,
            new String[] { "title", "description", "link", "language", "item", "image", "textinput",
                    "copyright", "rating", "pubDate", "lastBuildDate", "docs", "managingEditor", "webMaster",
                    "cloud" });

    // 1 title element
    ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title"));

    chnl.setFormat(ChannelFormat.RSS_0_91);

    // 1 description element
    chnl.setDescription(channel.getChildTextTrim("description"));

    // 1 link element
    chnl.setSite(ParserUtils.getURL(channel.getChildTextTrim("link")));

    // 1 language element
    chnl.setLanguage(channel.getChildTextTrim("language"));

    // 1..n item elements
    List items = channel.getChildren("item");
    Iterator i = items.iterator();
    while (i.hasNext()) {
        Element item = (Element) i.next();

        ParserUtils.matchCaseOfChildren(item,
                new String[] { "title", "link", "description", "source", "enclosure" });

        // get title element
        Element elTitle = item.getChild("title");
        String strTitle = "<No Title>";
        if (elTitle != null) {
            strTitle = elTitle.getTextTrim();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Item element found (" + strTitle + ").");
        }

        // get link element
        Element elLink = item.getChild("link");
        String strLink = "";
        if (elLink != null) {
            strLink = elLink.getTextTrim();
        }

        // get description element
        Element elDesc = item.getChild("description");
        String strDesc = "";
        if (elDesc != null) {
            strDesc = elDesc.getTextTrim();
        }

        // generate new RSS item (link to article)
        ItemIF rssItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink));
        rssItem.setFound(dateParsed);

        // get source element (an RSS 0.92 element)
        Element source = item.getChild("source");
        if (source != null) {
            String sourceName = source.getTextTrim();
            Attribute sourceAttribute = source.getAttribute("url");
            if (sourceAttribute != null) {
                String location = sourceAttribute.getValue().trim();
                ItemSourceIF itemSource = cBuilder.createItemSource(rssItem, sourceName, location, null);
                rssItem.setSource(itemSource);
            }
        }

        // get enclosure element (an RSS 0.92 element)
        Element enclosure = item.getChild("enclosure");
        if (enclosure != null) {
            URL location = null;
            String type = null;
            int length = -1;
            Attribute urlAttribute = enclosure.getAttribute("url");
            if (urlAttribute != null) {
                location = ParserUtils.getURL(urlAttribute.getValue().trim());
            }
            Attribute typeAttribute = enclosure.getAttribute("type");
            if (typeAttribute != null) {
                type = typeAttribute.getValue().trim();
            }
            Attribute lengthAttribute = enclosure.getAttribute("length");
            if (lengthAttribute != null) {
                try {
                    length = Integer.parseInt(lengthAttribute.getValue().trim());
                } catch (NumberFormatException e) {
                    logger.warn(e);
                }
            }
            ItemEnclosureIF itemEnclosure = cBuilder.createItemEnclosure(rssItem, location, type, length);
            rssItem.setEnclosure(itemEnclosure);
        }
    }

    // 0..1 image element
    Element image = channel.getChild("image");
    if (image != null) {

        ParserUtils.matchCaseOfChildren(image,
                new String[] { "title", "url", "link", "width", "height", "description" });

        ImageIF rssImage = cBuilder.createImage(image.getChildTextTrim("title"),
                ParserUtils.getURL(image.getChildTextTrim("url")),
                ParserUtils.getURL(image.getChildTextTrim("link")));
        Element imgWidth = image.getChild("width");
        if (imgWidth != null) {
            try {
                rssImage.setWidth(Integer.parseInt(imgWidth.getTextTrim()));
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        Element imgHeight = image.getChild("height");
        if (imgHeight != null) {
            try {
                rssImage.setHeight(Integer.parseInt(imgHeight.getTextTrim()));
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        Element imgDescr = image.getChild("description");
        if (imgDescr != null) {
            rssImage.setDescription(imgDescr.getTextTrim());
        }
        chnl.setImage(rssImage);
    }

    // 0..1 textinput element
    Element txtinp = channel.getChild("textinput");
    if (txtinp != null) {

        ParserUtils.matchCaseOfChildren(txtinp, new String[] { "title", "description", "name", "link" });

        TextInputIF rssTextInput = cBuilder.createTextInput(txtinp.getChild("title").getTextTrim(),
                txtinp.getChild("description").getTextTrim(), txtinp.getChild("name").getTextTrim(),
                ParserUtils.getURL(txtinp.getChild("link").getTextTrim()));
        chnl.setTextInput(rssTextInput);
    }

    // 0..1 copyright element
    Element copyright = channel.getChild("copyright");
    if (copyright != null) {
        chnl.setCopyright(copyright.getTextTrim());
    }

    // 0..1 rating element
    Element rating = channel.getChild("rating");
    if (rating != null) {
        chnl.setRating(rating.getTextTrim());
    }

    // 0..1 pubDate element
    Element pubDate = channel.getChild("pubDate");
    if (pubDate != null) {
        chnl.setPubDate(ParserUtils.getDate(pubDate.getTextTrim()));
    }

    // 0..1 lastBuildDate element
    Element lastBuildDate = channel.getChild("lastBuildDate");
    if (lastBuildDate != null) {
        chnl.setLastBuildDate(ParserUtils.getDate(lastBuildDate.getTextTrim()));
    }

    // 0..1 docs element
    Element docs = channel.getChild("docs");
    if (docs != null) {
        chnl.setDocs(docs.getTextTrim());
    }

    // 0..1 managingEditor element
    Element managingEditor = channel.getChild("managingEditor");
    if (managingEditor != null) {
        chnl.setCreator(managingEditor.getTextTrim());
    }

    // 0..1 webMaster element
    Element webMaster = channel.getChild("webMaster");
    if (webMaster != null) {
        chnl.setPublisher(webMaster.getTextTrim());
    }

    // 0..1 cloud element
    Element cloud = channel.getChild("cloud");
    if (cloud != null) {
        String _port = cloud.getAttributeValue("port");
        int port = -1;
        if (_port != null) {
            try {
                port = Integer.parseInt(_port);
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        chnl.setCloud(
                cBuilder.createCloud(cloud.getAttributeValue("domain"), port, cloud.getAttributeValue("path"),
                        cloud.getAttributeValue("registerProcedure"), cloud.getAttributeValue("protocol")));
    }

    chnl.setLastUpdated(dateParsed);
    // 0..1 skipHours element
    // 0..1 skipDays element

    return chnl;
}

From source file:de.openVJJ.basic.Module.java

License:Open Source License

/**
 * @see de.openVJJ.basic.Plugable#setConfig(org.jdom2.Element)
 *///w w w.  ja  v  a2  s .  co  m
@Override
public void setConfig(Element element) {
    super.setConfig(element);

    Map<Integer, Plugable> plugabelNrMap = new HashMap<Integer, Plugable>();
    Element plugablesElement = element.getChild(ELEMENT_NAME_PLUGABLES);
    if (plugablesElement != null) {
        for (Element plugableElement : plugablesElement.getChildren(ELEMENT_NAME_PLUGABLE)) {
            String plugableClass = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_CLASS);
            Plugable plugable = null;
            if (plugableClass != null) {
                try {
                    Class<?> c = Class.forName(plugableClass);
                    Object classInstance = c.newInstance();
                    plugable = (Plugable) classInstance;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if (plugable == null) {
                System.err.println("Was not abel to create instance of Plugabe");
                continue;
            }
            String plugableNr = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_NR);
            if (plugableNr != null) {
                plugabelNrMap.put(Integer.parseInt(plugableNr), plugable);
            }
            addPlugable(plugable);

            Element plugableElementConfig = plugableElement.getChild(ELEMENT_NAME_PLUGABLE_CONFIG);
            if (plugableElementConfig != null) {
                plugable.setConfig(plugableElementConfig);
            }
        }
    }

    Element connectionsElement = element.getChild(ELEMENT_NAME_CONNECTIONS);
    if (connectionsElement != null) {
        for (Element connectionElement : connectionsElement.getChildren(ELEMENT_NAME_CONNECTION)) {
            String inNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_PLUGABLE_NR);
            Plugable inPlugable = null;
            if (inNRString != null) {
                inPlugable = plugabelNrMap.get(Integer.parseInt(inNRString));
            }
            String outNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_PLUGABLE_NR);
            Plugable outPlugable = null;
            if (outNRString != null) {
                outPlugable = plugabelNrMap.get(Integer.parseInt(outNRString));
            }
            String inName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_NAME);
            String outName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_NAME);

            if (inPlugable == null || outPlugable == null || inName == null || outName == null) {
                System.err.println("Connection not fully defined: " + inNRString + ":" + inName + " -> "
                        + outNRString + ":" + outName);
                continue;
            }

            Connection outCon = outPlugable.getConnection(outName);
            inPlugable.setInput(inName, outCon);
        }
    }
}

From source file:de.openVJJ.InputComponents.java

License:Open Source License

public static void load(String fileName) {
    try {//from w  w w  .  j av  a 2s  .c  o m
        Document document = new SAXBuilder().build(fileName);
        Element rootElement = document.getRootElement();
        if (rootElement.getName() != ROOT_ELEMET_NAME) {
            System.err.println("is notan Open-VJJ Project");
            return;
        }
        Element gpuElement = rootElement.getChild(GPU_ELEMENT_NAME);
        if (gpuElement != null) {
            Attribute gpuActiv = gpuElement.getAttribute(GPU_ACTIV_ATTRIBUTE_NAME);
            if (gpuActiv != null) {
                useGPU = gpuActiv.getBooleanValue();
            }
        }
        removeAll();
        Element components = rootElement.getChild(COMPONENTS_ELEMENT_NAME);
        List<Element> elements = components.getChildren(COMPONENT_ELEMENT_NAME);
        for (Element rootComponente : elements) {
            addComponent((ImagePublisher) loadComponent(rootComponente));
        }
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.openVJJ.InputComponents.java

License:Open Source License

private static VJJComponent loadComponent(Element element) {
    String className = element.getAttribute(CLASS_NAME_ATTRIBUTE_NAME).getValue();
    try {/* ww  w .  j  av  a 2  s. c  o m*/
        Class<?> c = Class.forName(className);
        Object classInstance = c.newInstance();
        if (VJJComponent.class.isInstance(classInstance)) {
            VJJComponent vjjComponent = (VJJComponent) classInstance;
            Element componentSetup = element.getChild(COMPONENT_SETUP_ELEMENT_NAME);
            if (componentSetup != null) {
                vjjComponent.setConfig(componentSetup);
            }
            if (ImagePublisher.class.isInstance(vjjComponent)) {
                ImagePublisher imagePublisher = (ImagePublisher) classInstance;
                Element components = element.getChild(COMPONENTS_ELEMENT_NAME);
                if (components != null) {
                    List<Element> elements = components.getChildren(COMPONENT_ELEMENT_NAME);
                    for (Element subComponentElement : elements) {
                        ImageListener imageListener = (ImageListener) loadComponent(subComponentElement);
                        if (imageListener == null) {
                            continue;
                        }
                        addComponent(imageListener, imagePublisher);
                    }
                }
            }
            return vjjComponent;
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:de.sub.goobi.helper.tasks.ProcessSwapInTask.java

License:Open Source License

/**
 * Aufruf als Thread ================================================================
 *//*www  .  j  a  v a2s  .c om*/
@SuppressWarnings("deprecation")
@Override
public void run() {
    setStatusProgress(5);
    String swapPath = null;
    //      ProzessDAO dao = new ProzessDAO();
    String processDirectory = "";

    if (ConfigurationHelper.getInstance().isUseSwapping()) {
        swapPath = ConfigurationHelper.getInstance().getSwapPath();
    } else {
        setStatusMessage("swapping not activated");
        setStatusProgress(-1);
        return;
    }
    if (swapPath == null || swapPath.length() == 0) {
        setStatusMessage("no swappingPath defined");
        setStatusProgress(-1);
        return;
    }
    Path swapFile = Paths.get(swapPath);
    if (!StorageProvider.getInstance().isFileExists(swapFile)) {
        setStatusMessage("Swap folder does not exist or is not mounted");
        setStatusProgress(-1);
        return;
    }
    try {
        processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping();
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(
                "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    Path fileIn = Paths.get(processDirectory);
    Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator());

    if (!StorageProvider.getInstance().isFileExists(fileOut)) {
        setStatusMessage(getProzess().getTitel() + ": swappingOutTarget does not exist");
        setStatusProgress(-1);
        return;
    }
    if (!StorageProvider.getInstance().isFileExists(fileIn)) {
        setStatusMessage(getProzess().getTitel() + ": process data folder does not exist");
        setStatusProgress(-1);
        return;
    }

    SAXBuilder builder = new SAXBuilder();
    Document docOld;
    try {
        Path swapLogFile = Paths.get(processDirectory, "swapped.xml");
        docOld = builder.build(swapLogFile.toFile());
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage("Error while reading swapped.xml in process data folder: " + e.getClass().getName()
                + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    /*
     * --------------------- alte Checksummen in HashMap schreiben -------------------
     */
    setStatusMessage("reading checksums");
    Element rootOld = docOld.getRootElement();

    HashMap<String, String> crcMap = new HashMap<String, String>();

    // TODO: Don't use Iterators
    for (Iterator<Element> it = rootOld.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        crcMap.put(el.getAttribute("path").getValue(), el.getAttribute("crc32").getValue());
    }
    StorageProvider.getInstance().deleteDataInDir(fileIn);

    /*
     * --------------------- Dateien kopieren und Checksummen ermitteln -------------------
     */
    Document doc = new Document();
    Element root = new Element("goobiArchive");
    doc.setRootElement(root);

    /*
     * --------------------- Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren -------------------
     */
    setStatusProgress(50);
    try {
        setStatusMessage("copying process files");
        Helper.copyDirectoryWithCrc32Check(fileOut, fileIn, swapPath.length(), root);
    } catch (IOException e) {
        logger.warn("IOException:", e);
        setStatusMessage("IOException in copyDirectory: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(80);

    /*
     * --------------------- Checksummen vergleichen -------------------
     */
    setStatusMessage("checking checksums");
    // TODO: Don't use Iterators
    for (Iterator<Element> it = root.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        String newPath = el.getAttribute("path").getValue();
        String newCrc = el.getAttribute("crc32").getValue();
        if (crcMap.containsKey(newPath)) {
            if (!crcMap.get(newPath).equals(newCrc)) {
                setLongMessage(getLongMessage() + "File " + newPath + " has different checksum<br/>");
            }
            crcMap.remove(newPath);
        }
    }

    setStatusProgress(85);
    /*
     * --------------------- prfen, ob noch Dateien fehlen -------------------
     */
    setStatusMessage("checking missing files");
    if (crcMap.size() > 0) {
        for (String myFile : crcMap.keySet()) {
            setLongMessage(getLongMessage() + "File " + myFile + " is missing<br/>");
        }
    }

    setStatusProgress(90);

    /* in Prozess speichern */
    StorageProvider.getInstance().deleteDir(fileOut);
    try {
        setStatusMessage("saving process");
        Process myProzess = ProcessManager.getProcessById(getProzess().getId());
        myProzess.setSwappedOutGui(false);
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        setStatusMessage("DAOException while saving process: " + e.getMessage());
        logger.warn("DAOException:", e);
        setStatusProgress(-1);
        return;
    }
    setStatusMessage("done");

    setStatusProgress(100);
}

From source file:de.tor.tribes.util.report.ReportRule.java

License:Apache License

public ReportRule(Element pElm) throws IllegalArgumentException {
    try {//  w ww .j a va  2s .co  m
        type = RuleType.valueOf(pElm.getChildText("type"));
        targetSet = pElm.getChildText("targetSet");
        Element settings = pElm.getChild("settings");

        //check arguments and throw Exception if illigal
        switch (type) {
        case AGE:
            Long maxAge = Long.parseLong(settings.getText());
            filterComponent = maxAge;
            break;
        case ATTACKER_ALLY:
            List<Ally> attAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                attAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = attAllyList;
            break;
        case ATTACKER_TRIBE:
            List<Tribe> attTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                attTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = attTribeList;
            break;
        case COLOR:
            Integer color = Integer.parseInt(settings.getText());
            filterComponent = color;
            break;
        case DATE:
            String dates[] = settings.getText().split("-");
            Long start = Long.parseLong(dates[0]);
            Long end = Long.parseLong(dates[1]);
            Range<Long> dateSpan = Range.between(start, end);
            filterComponent = dateSpan;
            break;
        case DEFENDER_ALLY:
            List<Ally> defAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                defAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = defAllyList;
            break;
        case DEFENDER_TRIBE:
            List<Tribe> defTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                defTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = defTribeList;
            break;
        case CATA:
        case CONQUERED:
        case FAKE:
        case FARM:
        case OFF:
        case WALL:
            filterComponent = null;
            break;
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}