Example usage for org.jdom2 Element getTextTrim

List of usage examples for org.jdom2 Element getTextTrim

Introduction

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

Prototype

public String getTextTrim() 

Source Link

Document

Returns the textual content of this element with all surrounding whitespace removed.

Usage

From source file:neon.narrative.Resolver.java

License:Open Source License

private void addPerson(Element var, List<String> strings) {
    String[] npcs = var.getAttributeValue("id").split(",");
    String npc = npcs[Dice.roll(1, npcs.length, -1)];
    strings.add("$" + var.getTextTrim() + "$");
    strings.add(npc);//from w  w  w .  jav a 2s. com
    tracker.addObject(npc);
}

From source file:neon.narrative.Resolver.java

License:Open Source License

private void addCreature(Element var, List<String> strings) {
    List<RCreature> creatures = Engine.getResources().getResources(RCreature.class);
    String creature = creatures.get(Dice.roll(1, creatures.size(), -1)).toString();
    strings.add("$" + var.getTextTrim() + "$");
    strings.add(creature);/*www. ja  va 2 s.  c  om*/
    tracker.addObject(creature);
}

From source file:neon.resources.quest.RQuest.java

License:Open Source License

public RQuest(String id, Element properties, String... path) {
    super(id, path);
    name = properties.getAttributeValue("name");

    if (properties.getChild("stages") != null) {
        for (Element e : properties.getChild("stages").getChildren()) {
            Stage stage = new Stage(id, e);
            stages.put(stage.getIndex(), stage);
        }//from  ww  w  .ja v a  2  s  .  co  m
    }

    if (properties.getChild("pre") != null) {
        for (Element condition : properties.getChild("pre").getChildren()) {
            conditions.add(condition.getTextTrim());
        }
    }

    if (properties.getChild("objects") != null) {
        variables = properties.getChild("objects").detach();
    }

    repeat = properties.getName().equals("repeat");
    if (repeat) {
        frequency = Integer.parseInt(properties.getAttributeValue("f"));
    }

    initial = (properties.getAttribute("init") != null);
    journal = (properties.getAttribute("journal") != null);

    if (properties.getChild("dialog") != null) {
        initDialog(properties.getChild("dialog"));
    }
}

From source file:odml.core.Reader.java

License:Open Source License

/**
 * Parses value and creates the odMLValue representation of it.
 * //from   w  ww .j  a v  a2s .c  om
 * @param domValue
 *            - {@link Element}: the Element to parse. (should be a value element)
 * @return {@link Value} the {@link Value} representation of this domElement
 */
private Value parseValue(Element domValue) {
    Value value;

    String content;
    String unit;
    Object uncertainty;
    String type;
    String filename;
    String definition;
    String reference;
    String encoder;
    String checksum;
    content = domValue.getTextTrim();
    if (content == null) {
        content = "";
    }
    unit = domValue.getChildText("unit");
    uncertainty = domValue.getChildText("uncertainty");
    type = domValue.getChildText("type");
    filename = domValue.getChildText("filename");
    definition = domValue.getChildText("definition");
    reference = domValue.getChildText("reference");
    checksum = domValue.getChildText("checksum");
    encoder = domValue.getChildText("encoder");
    try {
        value = new Value(content, unit, uncertainty, type, filename, definition, reference, encoder, checksum);
    } catch (Exception e) {
        System.out.println("odml.core.Reader.parseValue: create Value failed. " + e.getMessage());
        return null;
    }
    return value;
}

From source file:org.apache.marmotta.ucuenca.wk.provider.scielo.ScieloRawProvider.java

License:Apache License

private List<String> getValuesXML(Element m, String key) {
    List<String> v = new ArrayList<>();
    List<Element> children = m.getChildren();
    for (Element aE : children) {
        if (aE.getAttributeValue("name").equals(key)) {
            if (aE.getName().equals("str")) {
                v.add(aE.getTextTrim());
            } else {
                List<Element> children1 = aE.getChildren();
                for (Element aE2 : children1) {
                    v.add(aE2.getText());
                }//from  w  ww .j av  a2s. c  om
            }

        }
    }
    return v;
}

From source file:org.dvlyyon.net.netconf.Client.java

License:Open Source License

/**
 * Called when the device sends <b>hello</b> message. This message comes with a list of device capabilities,
 * so we go process them.//from www.  j  a v  a2 s  .com
 *
 * @param response            XML node representing the RPC response.
 * @throws RuntimeException   if an error occurred processing the hello message.
 */
@Override
public synchronized void processHelloResponse(final Element response) throws RuntimeException {
    if (!m_helloResponseReceived) {
        Namespace xmlns = response.getNamespace();
        if (!"hello".equals(response.getName())) {
            s_logger.error("Unexpected message received, expected a hello response");
            s_logger.error("No capability information was processed!");
            return;
        }
        // This gives us the device capabilities - go get them
        Element capsRoot = response.getChild("capabilities", xmlns);
        if (capsRoot == null) {
            s_logger.error("Invalid hello response received; no capabilites sent by device.");
        } else {
            Element sessionIdElem = response.getChild("session-id", xmlns);
            if (sessionIdElem != null) {
                this.m_sessionID = sessionIdElem.getTextTrim();
                s_logger.debug("Got a session id of: " + sessionIdElem.getText());
            } else {
                String msg = "Error: No session ID received in hello message";
                s_logger.error(msg);
                throw new RuntimeException(msg);
            }
            m_deviceCaps.fromNetconfXml(capsRoot);
        }
        m_helloResponseReceived = true;
    }
}

From source file:org.esipfed.eskg.mapper.PODAACWebServiceObjectMapper.java

License:Apache License

private DIF mapGCMDXMLToPOJO(ByteArrayInputStream gcmdByteArrayInputStream) {
    //create DIF//  w w w .j av  a2s.co m
    DIF dif = new DIF();
    try {
        SAXBuilder jdomBuilder = new SAXBuilder();

        // jdomDocument is the JDOM2 Object
        Document jdomDocument = jdomBuilder.build(gcmdByteArrayInputStream);
        Element difElement = jdomDocument.getRootElement();
        Namespace ns = difElement.getNamespace();
        //populate immediate children
        dif.setEntryID(difElement.getChild("Entry_ID", ns).getTextTrim());
        dif.setEntryTitle(difElement.getChild("Entry_Title", ns).getTextTrim());
        dif.setAccessConstraints(difElement.getChild("Access_Constraints", ns).getTextTrim());
        dif.setUseConstraints(difElement.getChild("Use_Constraints", ns).getTextTrim());
        dif.getDataSetLanguage().add(difElement.getChild("Data_Set_Language", ns).getTextTrim());
        if (difElement.getChild("Originating_Center", ns).getTextTrim() != null) {
            dif.setOriginatingCenter(difElement.getChild("Originating_Center", ns).getTextTrim());
        }
        dif.setMetadataName(difElement.getChild("Metadata_Name", ns).getTextTrim());
        dif.setMetadataVersion(difElement.getChild("Metadata_Version", ns).getTextTrim());
        dif.setDIFCreationDate(difElement.getChild("DIF_Creation_Date", ns).getTextTrim());
        dif.setLastDIFRevisionDate(difElement.getChild("Last_DIF_Revision_Date", ns).getTextTrim());
        dif.setDIFRevisionHistory(difElement.getChild("DIF_Revision_History", ns).getTextTrim());

        //create ISO_Topic_Catgeory(s)
        List<Element> iSOTopicCategoryList = difElement.getChildren("ISO_Topic_Category", ns);
        for (Element iSOTopicCategory : iSOTopicCategoryList) {
            dif.getISOTopicCategory().add(iSOTopicCategory.getTextTrim());
        }

        //create Data_Set_Citation(s)
        List<Element> dataSetCitationList = difElement.getChildren("Data_Set_Citation", ns);
        for (Element dataSetCitationElement : dataSetCitationList) {
            List<Element> dataSetCitationElementChildren = dataSetCitationElement.getChildren();
            DataSetCitation dataSetCitation = new DataSetCitation();
            for (Element element : dataSetCitationElementChildren) {
                if ("Dataset_Creator".equals(element.getName())) {
                    dataSetCitation.setDatasetCreator(element.getTextTrim());
                } else if ("Dataset_Title".equals(element.getName())) {
                    dataSetCitation.setDatasetTitle(element.getTextTrim());
                } else if ("Dataset_Series_Name".equals(element.getName())) {
                    dataSetCitation.setDatasetSeriesName(element.getTextTrim());
                } else if ("Dataset_Release_Date".equals(element.getName())) {
                    dataSetCitation.setDatasetReleaseDate(element.getTextTrim());
                } else if ("Dataset_Release_Place".equals(element.getName())) {
                    dataSetCitation.setDatasetReleasePlace(element.getTextTrim());
                } else if ("Dataset_Publisher".equals(element.getName())) {
                    dataSetCitation.setDatasetPublisher(element.getTextTrim());
                } else if ("Version".equals(element.getName())) {
                    dataSetCitation.setVersion(element.getTextTrim());
                } else if ("Online_Resource".equals(element.getName())) {
                    dataSetCitation.setOnlineResource(element.getTextTrim());
                }
            }
            dif.getDataSetCitation().add(dataSetCitation);
        }

        //create Personnel(s)
        List<Element> personnelList = difElement.getChildren("Personnel", ns);
        for (Element personnelElement : personnelList) {
            List<Element> personnelElementChildren = personnelElement.getChildren();
            Personnel personnel = new Personnel();
            for (Element element : personnelElementChildren) {
                if ("Role".equals(element.getName())) {
                    personnel.getRole().add(element.getTextTrim());
                } else if ("First_Name".equals(element.getName())) {
                    personnel.setFirstName(element.getTextTrim());
                } else if ("Last_Name".equals(element.getName())) {
                    personnel.setLastName(element.getTextTrim());
                } else if ("Email".equals(element.getName())) {
                    personnel.getEmail().add(element.getTextTrim());
                }
            }
            dif.getPersonnel().add(personnel);
        }

        //create Parameters(s)
        List<Element> parameterList = difElement.getChildren("Parameters", ns);
        for (Element parameterElement : parameterList) {
            List<Element> parameterElementChildren = parameterElement.getChildren();
            Parameters parameters = new Parameters();
            for (Element element : parameterElementChildren) {
                if ("Category".equals(element.getName())) {
                    parameters.setCategory(element.getTextTrim());
                } else if ("Topic".equals(element.getName())) {
                    parameters.setTopic(element.getTextTrim());
                } else if ("Detailed_Variable".equals(element.getName())) {
                    parameters.setDetailedVariable(element.getTextTrim());
                } else if ("Term".equals(element.getName())) {
                    parameters.setTerm(element.getTextTrim());
                } else if ("Variable_Level_1".equals(element.getName())) {
                    parameters.setVariableLevel1(element.getTextTrim());
                } else if ("Variable_Level_2".equals(element.getName())) {
                    parameters.setVariableLevel2(element.getTextTrim());
                } else if ("Variable_Level_3".equals(element.getName())) {
                    parameters.setVariableLevel3(element.getTextTrim());
                }
            }
            dif.getParameters().add(parameters);
        }

        //create Sensor_Name(s)
        List<Element> sensorNameList = difElement.getChildren("Sensor_Name", ns);
        for (Element sensorNameElement : sensorNameList) {
            List<Element> sensorNameElementChildren = sensorNameElement.getChildren();
            SensorName sensorName = new SensorName();
            for (Element element : sensorNameElementChildren) {
                if ("Short_Name".equals(element.getName())) {
                    sensorName.setShortName(element.getTextTrim());
                } else if ("Long_Name".equals(element.getName())) {
                    sensorName.setLongName(element.getTextTrim());
                }
            }
            dif.getSensorName().add(sensorName);
        }

        //create Source_Name(s)
        List<Element> sourceNameList = difElement.getChildren("Source_Name", ns);
        for (Element sourceNameElement : sourceNameList) {
            List<Element> sourceNameElementChildren = sourceNameElement.getChildren();
            SourceName sourceName = new SourceName();
            for (Element element : sourceNameElementChildren) {
                if ("Short_Name".equals(element.getName())) {
                    sourceName.setShortName(element.getTextTrim());
                } else if ("Long_Name".equals(element.getName())) {
                    sourceName.setLongName(element.getTextTrim());
                }
            }
            dif.getSourceName().add(sourceName);
        }

        //create Temporal_Coverage(s)
        List<Element> temporalCoverageList = difElement.getChildren("Temporal_Coverage", ns);
        for (Element temporalCoverageElement : temporalCoverageList) {
            List<Element> temporalCoverageElementChildren = temporalCoverageElement.getChildren();
            TemporalCoverage temporalCoverage = new TemporalCoverage();
            for (Element element : temporalCoverageElementChildren) {
                if ("Start_Date".equals(element.getName())) {
                    temporalCoverage.setStartDate(element.getTextTrim());
                } else if ("Stop_Date".equals(element.getName())) {
                    temporalCoverage.setStopDate(element.getTextTrim());
                }
            }
            dif.getTemporalCoverage().add(temporalCoverage);
        }

        //create Spatial_Coverage(s)
        List<Element> spatialCoverageList = difElement.getChildren("Spatial_Coverage", ns);
        for (Element spatiaCoverageElement : spatialCoverageList) {
            List<Element> spatiallCoverageElementChildren = spatiaCoverageElement.getChildren();
            SpatialCoverage spatialCoverage = new SpatialCoverage();
            for (Element element : spatiallCoverageElementChildren) {
                if ("Easternmost_Longitude".equals(element.getName())) {
                    spatialCoverage.setEasternmostLongitude(element.getTextTrim());
                } else if ("Maximum_Altitude".equals(element.getName())) {
                    spatialCoverage.setMaximumAltitude(element.getTextTrim());
                } else if ("Maximum_Depth".equals(element.getName())) {
                    spatialCoverage.setMaximumDepth(element.getTextTrim());
                } else if ("Minimum_Altitude".equals(element.getName())) {
                    spatialCoverage.setMinimumAltitude(element.getTextTrim());
                } else if ("Minimum_Depth".equals(element.getName())) {
                    spatialCoverage.setMinimumDepth(element.getTextTrim());
                } else if ("Northernmost_Latitude".equals(element.getName())) {
                    spatialCoverage.setNorthernmostLatitude(element.getTextTrim());
                } else if ("Southernmost_Latitude".equals(element.getName())) {
                    spatialCoverage.setSouthernmostLatitude(element.getTextTrim());
                } else if ("Westernmost_Longitude".equals(element.getName())) {
                    spatialCoverage.setWesternmostLongitude(element.getTextTrim());
                }
            }
            dif.getSpatialCoverage().add(spatialCoverage);
        }

        //create Location(s)
        List<Element> locationList = difElement.getChildren("Location", ns);
        for (Element locationElement : locationList) {
            List<Element> locationElementChildren = locationElement.getChildren();
            Location location = new Location();
            for (Element element : locationElementChildren) {
                if ("Detailed_Location".equals(element.getName())) {
                    location.setDetailedLocation(element.getTextTrim());
                } else if ("Location_Category".equals(element.getName())) {
                    location.setLocationCategory(element.getTextTrim());
                } else if ("Location_Subregion_1".equals(element.getName())) {
                    location.setLocationSubregion1(element.getTextTrim());
                } else if ("Location_Subregion_2".equals(element.getName())) {
                    location.setLocationSubregion2(element.getTextTrim());
                } else if ("Location_Subregion_3".equals(element.getName())) {
                    location.setLocationSubregion3(element.getTextTrim());
                } else if ("Location_Type".equals(element.getName())) {
                    location.setLocationType(element.getTextTrim());
                }
            }
            dif.getLocation().add(location);
        }

        //create Data_Resolution(s)
        List<Element> dataResolutionList = difElement.getChildren("Data_Resolution", ns);
        for (Element dataResolutionElement : dataResolutionList) {
            List<Element> dataResolutionElementChildren = dataResolutionElement.getChildren();
            DataResolution dataResolution = new DataResolution();
            for (Element element : dataResolutionElementChildren) {
                if ("Horizontal_Resolution_Range".equals(element.getName())) {
                    dataResolution.setHorizontalResolutionRange(element.getTextTrim());
                } else if ("Latitude_Resolution".equals(element.getName())) {
                    dataResolution.setLatitudeResolution(element.getTextTrim());
                } else if ("Longitude_Resolution".equals(element.getName())) {
                    dataResolution.setLongitudeResolution(element.getTextTrim());
                } else if ("Temporal_Resolution".equals(element.getName())) {
                    dataResolution.setTemporalResolution(element.getTextTrim());
                } else if ("Temporal_Resolution_Range".equals(element.getName())) {
                    dataResolution.setTemporalResolutionRange(element.getTextTrim());
                } else if ("Vertical_Resolution".equals(element.getName())) {
                    dataResolution.setVerticalResolution(element.getTextTrim());
                } else if ("Vertical_Resolution_Range".equals(element.getName())) {
                    dataResolution.setVerticalResolutionRange(element.getTextTrim());
                }
            }
            dif.getDataResolution().add(dataResolution);
        }

        //create Project(s)
        List<Element> projectList = difElement.getChildren("Project", ns);
        for (Element projectElement : projectList) {
            List<Element> projectElementChildren = projectElement.getChildren();
            Project project = new Project();
            for (Element element : projectElementChildren) {
                if ("Long_Name".equals(element.getName())) {
                    project.setLongName(element.getTextTrim());
                } else if ("Short_Name".equals(element.getName())) {
                    project.setShortName(element.getTextTrim());
                }
            }
            dif.getProject().add(project);
        }

        //create Data_Center(s)
        List<Element> dataCenterList = difElement.getChildren("Data_Center", ns);
        for (Element dataCenterElement : dataCenterList) {
            List<Element> dataCenterElementChildren = dataCenterElement.getChildren();
            DataCenter dataCenter = new DataCenter();
            for (Element dataCenterElementChild : dataCenterElementChildren) {
                if ("Data_Center_Name".equals(dataCenterElementChild.getName())) {
                    //create Data_Center_Name
                    DataCenterName dataCenterName = new DataCenterName();
                    List<Element> dataCenterNameChildren = dataCenterElementChild.getChildren();
                    for (Element dataCenterNameChild : dataCenterNameChildren) {
                        if ("Long_Name".equals(dataCenterNameChild.getName())) {
                            dataCenterName.setLongName(dataCenterNameChild.getTextTrim());
                        } else if ("Short_Name".equals(dataCenterNameChild.getName())) {
                            dataCenterName.setShortName(dataCenterNameChild.getTextTrim());
                        }
                    }
                    dataCenter.setDataCenterName(dataCenterName);
                } else if ("Data_Center_URL".equals(dataCenterElementChild.getName())) {
                    dataCenter.setDataCenterURL(dataCenterElementChild.getTextTrim());
                } else if ("Personnel".equals(dataCenterElementChild.getName())) {
                    //create data center Personnel
                    Personnel personnel = new Personnel();
                    List<Element> dataCenterPersonnelChildren = dataCenterElementChild.getChildren();
                    for (Element element : dataCenterPersonnelChildren) {
                        if ("Role".equals(element.getName())) {
                            personnel.getRole().add(element.getTextTrim());
                        } else if ("First_Name".equals(element.getName())) {
                            personnel.setFirstName(element.getTextTrim());
                        } else if ("Last_Name".equals(element.getName())) {
                            personnel.setLastName(element.getTextTrim());
                        } else if ("Email".equals(element.getName())) {
                            personnel.getEmail().add(element.getTextTrim());
                        }
                    }
                    dataCenter.getPersonnel().add(personnel);
                }
            }
            dif.getDataCenter().add(dataCenter);
        }

        //create Summary(s)
        List<Element> summaryList = difElement.getChildren("Summary", ns);
        for (Element summaryListElement : summaryList) {
            Summary summary = new Summary();
            List<Element> summaryListElementChildren = summaryListElement.getChildren();
            for (Element summaryListElementChild : summaryListElementChildren) {
                if ("Abstract".equals(summaryListElementChild.getName())) {
                    ObjectFactory factory = new ObjectFactory();
                    summary.getContent().add(factory.createAbstract(summaryListElementChild.getTextTrim()));
                }
            }
            dif.setSummary(summary);
        }

        //create IDN_Node(s)
        List<Element> idnNodeList = difElement.getChildren("IDN_Node", ns);
        for (Element idnNodeListElement : idnNodeList) {
            IDNNode idnNode = new IDNNode();
            List<Element> idnNodeListElementChildren = idnNodeListElement.getChildren();
            for (Element element : idnNodeListElementChildren) {
                if ("Short_Name".equals(element.getName())) {
                    idnNode.setShortName(element.getTextTrim());
                } else if ("Long_Name".equals(element.getName())) {
                    idnNode.setLongName(element.getTextTrim());
                }
            }
            dif.getIDNNode().add(idnNode);
        }

    } catch (Exception e) {
        LOG.error("Error whilst parsing Atom XML response from Dataset Search: ", e);
    }
    return dif;

}

From source file:org.goobi.production.export.ExportXmlLog.java

License:Open Source License

/**
 * This method creates a new xml document with process metadata
 * /*from  w w w  .j  a v a 2s .co m*/
 * @param process the process to export
 * @return a new xml document
 * @throws ConfigurationException
 */
public Document createDocument(Process process, boolean addNamespace) {

    Element processElm = new Element("process");
    Document doc = new Document(processElm);

    processElm.setAttribute("processID", String.valueOf(process.getId()));

    Namespace xmlns = Namespace.getNamespace("http://www.goobi.io/logfile");
    processElm.setNamespace(xmlns);
    // namespace declaration
    if (addNamespace) {

        Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        processElm.addNamespaceDeclaration(xsi);
        Attribute attSchema = new Attribute("schemaLocation",
                "http://www.goobi.io/logfile" + " XML-logfile.xsd", xsi);
        processElm.setAttribute(attSchema);
    }
    // process information

    ArrayList<Element> processElements = new ArrayList<>();
    Element processTitle = new Element("title", xmlns);
    processTitle.setText(process.getTitel());
    processElements.add(processTitle);

    Element project = new Element("project", xmlns);
    project.setText(process.getProjekt().getTitel());
    processElements.add(project);

    Element date = new Element("time", xmlns);
    date.setAttribute("type", "creation date");
    date.setText(String.valueOf(process.getErstellungsdatum()));
    processElements.add(date);

    Element ruleset = new Element("ruleset", xmlns);
    ruleset.setText(process.getRegelsatz().getDatei());
    processElements.add(ruleset);

    Element comment = new Element("comments", xmlns);
    List<LogEntry> log = process.getProcessLog();
    for (LogEntry entry : log) {
        Element commentLine = new Element("comment", xmlns);
        commentLine.setAttribute("type", entry.getType().getTitle());
        commentLine.setAttribute("user", entry.getUserName());
        commentLine.setText(entry.getContent());
        if (StringUtils.isNotBlank(entry.getSecondContent())) {
            comment.setAttribute("secondField", entry.getSecondContent());
        }
        if (StringUtils.isNotBlank(entry.getThirdContent())) {
            comment.setAttribute("thirdField", entry.getThirdContent());
        }
        comment.addContent(commentLine);
    }

    processElements.add(comment);

    if (process.getBatch() != null) {
        Element batch = new Element("batch", xmlns);
        batch.setText(String.valueOf(process.getBatch().getBatchId()));
        if (StringUtils.isNotBlank(process.getBatch().getBatchName())) {
            batch.setAttribute("batchName", process.getBatch().getBatchName());
        }
        if (process.getBatch().getStartDate() != null) {
            batch.setAttribute("startDate", Helper.getDateAsFormattedString(process.getBatch().getStartDate()));
        }

        if (process.getBatch().getEndDate() != null) {
            batch.setAttribute("endDate", Helper.getDateAsFormattedString(process.getBatch().getEndDate()));
        }

        processElements.add(batch);
    }

    List<Element> processProperties = new ArrayList<>();
    List<ProcessProperty> propertyList = PropertyParser.getInstance().getPropertiesForProcess(process);
    for (ProcessProperty prop : propertyList) {
        Element property = new Element("property", xmlns);
        property.setAttribute("propertyIdentifier", prop.getName());
        if (prop.getValue() != null) {
            property.setAttribute("value", prop.getValue());
        } else {
            property.setAttribute("value", "");
        }

        Element label = new Element("label", xmlns);

        label.setText(prop.getName());
        property.addContent(label);
        processProperties.add(property);
    }
    if (processProperties.size() != 0) {
        Element properties = new Element("properties", xmlns);
        properties.addContent(processProperties);
        processElements.add(properties);
    }

    // step information
    Element steps = new Element("steps", xmlns);
    List<Element> stepElements = new ArrayList<>();
    for (Step s : process.getSchritteList()) {
        Element stepElement = new Element("step", xmlns);
        stepElement.setAttribute("stepID", String.valueOf(s.getId()));

        Element steptitle = new Element("title", xmlns);
        steptitle.setText(s.getTitel());
        stepElement.addContent(steptitle);

        Element state = new Element("processingstatus", xmlns);
        state.setText(s.getBearbeitungsstatusAsString());
        stepElement.addContent(state);

        Element begin = new Element("time", xmlns);
        begin.setAttribute("type", "start time");
        begin.setText(s.getBearbeitungsbeginnAsFormattedString());
        stepElement.addContent(begin);

        Element end = new Element("time", xmlns);
        end.setAttribute("type", "end time");
        end.setText(s.getBearbeitungsendeAsFormattedString());
        stepElement.addContent(end);

        if (s.getBearbeitungsbenutzer() != null && s.getBearbeitungsbenutzer().getNachVorname() != null) {
            Element user = new Element("user", xmlns);
            user.setText(s.getBearbeitungsbenutzer().getNachVorname());
            stepElement.addContent(user);
        }
        Element editType = new Element("edittype", xmlns);
        editType.setText(s.getEditTypeEnum().getTitle());
        stepElement.addContent(editType);

        stepElements.add(stepElement);
    }
    if (stepElements != null) {
        steps.addContent(stepElements);
        processElements.add(steps);
    }

    // template information
    Element templates = new Element("originals", xmlns);
    List<Element> templateElements = new ArrayList<>();
    for (Template v : process.getVorlagenList()) {
        Element template = new Element("original", xmlns);
        template.setAttribute("originalID", String.valueOf(v.getId()));

        List<Element> templateProperties = new ArrayList<>();
        for (Templateproperty prop : v.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);

            templateProperties.add(property);
            if (prop.getTitel().equals("Signatur")) {
                Element secondProperty = new Element("property", xmlns);
                secondProperty.setAttribute("propertyIdentifier", prop.getTitel() + "Encoded");
                if (prop.getWert() != null) {
                    secondProperty.setAttribute("value", "vorl:" + prop.getWert());
                    Element secondLabel = new Element("label", xmlns);
                    secondLabel.setText(prop.getTitel());
                    secondProperty.addContent(secondLabel);
                    templateProperties.add(secondProperty);
                }
            }
        }
        if (templateProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(templateProperties);
            template.addContent(properties);
        }
        templateElements.add(template);
    }
    if (templateElements != null) {
        templates.addContent(templateElements);
        processElements.add(templates);
    }

    // digital document information
    Element digdoc = new Element("digitalDocuments", xmlns);
    List<Element> docElements = new ArrayList<>();
    for (Masterpiece w : process.getWerkstueckeList()) {
        Element dd = new Element("digitalDocument", xmlns);
        dd.setAttribute("digitalDocumentID", String.valueOf(w.getId()));

        List<Element> docProperties = new ArrayList<>();
        for (Masterpieceproperty prop : w.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);
            docProperties.add(property);
        }
        if (docProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(docProperties);
            dd.addContent(properties);
        }
        docElements.add(dd);
    }
    if (docElements != null) {
        digdoc.addContent(docElements);
        processElements.add(digdoc);
    }
    // history
    List<HistoryEvent> eventList = HistoryManager.getHistoryEvents(process.getId());
    if (eventList != null && !eventList.isEmpty()) {
        List<Element> eventElementList = new ArrayList<>(eventList.size());

        for (HistoryEvent event : eventList) {
            Element element = new Element("historyEvent", xmlns);
            element.setAttribute("id", "" + event.getId());
            element.setAttribute("date", Helper.getDateAsFormattedString(event.getDate()));
            element.setAttribute("type", event.getHistoryType().getTitle());

            if (event.getNumericValue() != null) {
                element.setAttribute("numeric_value", "" + event.getNumericValue());
            }
            if (event.getStringValue() != null) {
                element.setText(event.getStringValue());
            }
            eventElementList.add(element);
        }

        if (!eventElementList.isEmpty()) {
            Element metadataElement = new Element("history", xmlns);
            metadataElement.addContent(eventElementList);
            processElements.add(metadataElement);
        }
    }

    // metadata
    List<StringPair> metadata = MetadataManager.getMetadata(process.getId());
    if (metadata != null && !metadata.isEmpty()) {
        List<Element> mdlist = new ArrayList<>();
        for (StringPair md : metadata) {
            String name = md.getOne();
            String value = md.getTwo();
            if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(name)) {
                Element element = new Element("metadata", xmlns);
                element.setAttribute("name", name);
                element.addContent(value);
                mdlist.add(element);
            }
        }
        if (!mdlist.isEmpty()) {
            Element metadataElement = new Element("metadatalist", xmlns);
            metadataElement.addContent(mdlist);
            processElements.add(metadataElement);
        }
    }
    // METS information
    Element metsElement = new Element("metsInformation", xmlns);
    List<Element> metadataElements = new ArrayList<>();

    try {
        String filename = process.getMetadataFilePath();
        Document metsDoc = new SAXBuilder().build(filename);
        Document anchorDoc = null;
        String anchorfilename = process.getMetadataFilePath().replace("meta.xml", "meta_anchor.xml");
        Path anchorFile = Paths.get(anchorfilename);
        if (StorageProvider.getInstance().isFileExists(anchorFile)
                && StorageProvider.getInstance().isReadable(anchorFile)) {
            anchorDoc = new SAXBuilder().build(anchorfilename);
        }

        List<Namespace> namespaces = getNamespacesFromConfig();

        HashMap<String, String> fields = getMetsFieldsFromConfig(false);
        for (String key : fields.keySet()) {
            List<Element> metsValues = getMetsValues(fields.get(key), metsDoc, namespaces);
            for (Element element : metsValues) {
                Element ele = new Element("property", xmlns);
                ele.setAttribute("name", key);
                ele.addContent(element.getTextTrim());
                metadataElements.add(ele);
            }
        }

        if (anchorDoc != null) {
            fields = getMetsFieldsFromConfig(true);
            for (String key : fields.keySet()) {
                List<Element> metsValues = getMetsValues(fields.get(key), anchorDoc, namespaces);
                for (Element element : metsValues) {
                    Element ele = new Element("property", xmlns);
                    ele.setAttribute("name", key);
                    ele.addContent(element.getTextTrim());
                    metadataElements.add(ele);
                }
            }
        }

        if (metadataElements != null) {
            metsElement.addContent(metadataElements);
            processElements.add(metsElement);
        }

    } catch (SwapException e) {
        logger.error(e);
    } catch (DAOException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } catch (InterruptedException e) {
        logger.error(e);
    } catch (JDOMException e) {
        logger.error(e);
    } catch (JaxenException e) {
        logger.error(e);
    }

    processElm.setContent(processElements);
    return doc;
}

From source file:org.graphwalker.io.GraphML.java

License:Open Source License

/**
 * Parses the graphml file, and returns the model as a edu.uci.ics.jung.graph.impl.Graph
 * //from  www .  j av a 2 s .com
 * @param fileName The graphml file
 * @return The graph
 */
private Graph parseFile(String fileName) {
    Graph graph = new Graph();
    graph.setFileKey(fileName);
    SAXBuilder parser = new SAXBuilder();

    try {
        logger.debug("Parsing file: " + fileName);
        Document doc = parser.build(Util.getFile(fileName));

        // Parse all vertices (nodes)
        Iterator<Element> iter_node = doc.getDescendants(new ElementFilter("node"));
        while (iter_node.hasNext()) {
            Object o = iter_node.next();
            if (o instanceof Element) {
                Element element = (Element) o;
                if (element.getAttributeValue("yfiles.foldertype") != null) {
                    logger.debug("  Excluded node: " + element.getAttributeValue("yfiles.foldertype"));
                    continue;
                }
                Iterator<Element> iterUMLNoteIter = element.getDescendants(new ElementFilter("UMLNoteNode"));
                if (iterUMLNoteIter.hasNext()) {
                    Iterator<Element> iter_label = element.getDescendants(new ElementFilter("NodeLabel"));
                    if (iter_label.hasNext()) {
                        Object o3 = iter_label.next();
                        Element nodeLabel = (Element) o3;
                        logger.debug("  Full name: '" + nodeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + nodeLabel.getTextTrim() + "'");
                        graph.setDescriptionKey(nodeLabel.getTextTrim());
                    }
                    continue;
                }
                logger.debug("  id: " + element.getAttributeValue("id"));

                // Used to remember which vertex to store the image location.
                Vertex currentVertex = null;

                Iterator<Element> iterNodeLabel = element.getDescendants(new ElementFilter("NodeLabel"));
                while (iterNodeLabel.hasNext()) {
                    Object o2 = iterNodeLabel.next();
                    if (o2 instanceof Element) {
                        Element nodeLabel = (Element) o2;
                        logger.debug("  Full name: '" + nodeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + nodeLabel.getTextTrim() + "'");
                        String str = nodeLabel.getTextTrim();

                        Vertex v = new Vertex();
                        graph.addVertex(v);
                        currentVertex = v;

                        // Parse description
                        Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data"));
                        while (iter_data.hasNext()) {
                            Object o3 = iter_data.next();
                            if (o instanceof Element) {
                                Element data = (Element) o3;
                                if (!data.getAttributeValue("key").equals("d5"))
                                    continue;
                                v.setDesctiptionKey(data.getText());
                                break;
                            }
                        }

                        v.setIdKey(element.getAttributeValue("id"));
                        v.setVisitedKey(0);
                        v.setFileKey(fileName);
                        v.setFullLabelKey(str);
                        v.setIndexKey(getNewVertexAndEdgeIndex());
                        v.setLabelKey(Vertex.getLabel(str));
                        v.setMergeKey(AbstractElement.isMerged(str));
                        v.setNoMergeKey(AbstractElement.isNoMerge(str));
                        v.setBlockedKey(AbstractElement.isBlocked(str));
                        v.setSwitchModelKey(Vertex.isSwitchModel(str));

                        Integer index = AbstractElement.getIndex(str);
                        if (index != 0) {
                            v.setIndexKey(index);
                        }

                        v.setReqTagKey(AbstractElement.getReqTags(str));
                    }
                }

                // Extract any manual test instructions
                Iterator<Element> iterData = element.getDescendants(new ElementFilter("data"));
                while (iterData.hasNext() && currentVertex != null) {
                    Object o2 = iterData.next();
                    if (o2 instanceof Element) {
                        Element data = (Element) o2;
                        if (!data.getContent().isEmpty() && data.getContent(0) != null) {
                            String text = data.getContent(0).getValue().trim();
                            if (!text.isEmpty()) {
                                logger.debug("  Data: '" + text + "'");
                                currentVertex.setManualInstructions(text);
                            }
                        }
                    }
                }

                // Using the yEd editor, an image can be used to depict the vertex.
                // When merging multiple
                // graphs into one, the code below, stores the image location, which
                // will be used when
                // writing that merged graphml file.
                Iterator<Element> iterImage = element.getDescendants(new ElementFilter("Image"));
                while (iterImage.hasNext() && currentVertex != null) {
                    Object o2 = iterImage.next();
                    if (o2 instanceof Element) {
                        Element image = (Element) o2;
                        if (image.getAttributeValue("href") != null) {
                            logger.debug("  Image: '" + image.getAttributeValue("href") + "'");
                            currentVertex.setImageKey(image.getAttributeValue("href"));
                        }
                    }
                }
                Iterator<Element> iterGeometry = element.getDescendants(new ElementFilter("Geometry"));
                while (iterGeometry.hasNext() && currentVertex != null) {
                    Object o2 = iterGeometry.next();
                    if (o2 instanceof Element) {
                        Element geometry = (Element) o2;
                        logger.debug("  width: '" + geometry.getAttributeValue("width") + "'");
                        logger.debug("  height: '" + geometry.getAttributeValue("height") + "'");
                        logger.debug("  x position: '" + geometry.getAttributeValue("x") + "'");
                        logger.debug("  y position: '" + geometry.getAttributeValue("y") + "'");
                        currentVertex.setWidth(Float.parseFloat(geometry.getAttributeValue("width")));
                        currentVertex.setHeight(Float.parseFloat(geometry.getAttributeValue("height")));
                        currentVertex.setLocation(
                                new Point2D.Float(Float.parseFloat(geometry.getAttributeValue("x")),
                                        Float.parseFloat(geometry.getAttributeValue("y"))));
                    }
                }
                Iterator<Element> iterFill = element.getDescendants(new ElementFilter("Fill"));
                while (iterFill.hasNext() && currentVertex != null) {
                    Object o2 = iterFill.next();
                    if (o2 instanceof Element) {
                        Element fill = (Element) o2;
                        logger.debug("  fill color: '" + fill.getAttributeValue("color") + "'");
                        currentVertex.setFillColor(new Color(
                                Integer.parseInt(fill.getAttributeValue("color").replace("#", ""), 16)));
                    }
                }
            }
        }

        Object[] vertices = graph.getVertices().toArray();

        // Parse all edges (arrows or transitions)
        Iterator<Element> iter_edge = doc.getDescendants(new ElementFilter("edge"));
        while (iter_edge.hasNext()) {
            Object o = iter_edge.next();
            if (o instanceof Element) {
                Element element = (Element) o;
                logger.debug("  id: " + element.getAttributeValue("id"));

                Edge e = new Edge();

                Iterator<Element> iter2 = element.getDescendants(new ElementFilter("EdgeLabel"));
                Element edgeLabel = null;
                if (iter2.hasNext()) {
                    Object o2 = iter2.next();
                    if (o2 instanceof Element) {
                        edgeLabel = (Element) o2;
                        logger.debug("  Full name: '" + edgeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + edgeLabel.getTextTrim() + "'");
                        logger.debug(" Edge label x: " + edgeLabel.getAttributeValue("x"));
                        logger.debug(" Edge label y: " + edgeLabel.getAttributeValue("y"));
                        logger.debug(" Edge label width: " + edgeLabel.getAttributeValue("width"));
                        logger.debug(" Edge label height: " + edgeLabel.getAttributeValue("height"));
                        e.setLabelHeight(Float.parseFloat(edgeLabel.getAttributeValue("height")));
                        e.setLabelWidth(Float.parseFloat(edgeLabel.getAttributeValue("width")));
                        e.setLabelLocation(new Point2D.Float(Float.parseFloat(edgeLabel.getAttributeValue("x")),
                                Float.parseFloat(edgeLabel.getAttributeValue("y"))));
                    }
                }
                Iterator<Element> iter3 = element.getDescendants(new ElementFilter("Path"));
                Element edgePath = null;
                if (iter3.hasNext()) {
                    Object o3 = iter3.next();
                    if (o3 instanceof Element) {
                        edgePath = (Element) o3;
                        logger.debug("  Path sx: '" + edgePath.getAttributeValue("sx"));
                        logger.debug("  Path sy: '" + edgePath.getAttributeValue("sy"));
                        logger.debug("  Path tx: '" + edgePath.getAttributeValue("tx"));
                        logger.debug("  Path ty: '" + edgePath.getAttributeValue("ty"));
                        e.setPathSourceLocation(
                                new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("sx")),
                                        Float.parseFloat(edgePath.getAttributeValue("sy"))));
                        e.setPathTargetLocation(
                                new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("tx")),
                                        Float.parseFloat(edgePath.getAttributeValue("ty"))));
                    }
                }

                // Add edge path points if there is any.
                Iterator<Element> iter4 = element.getDescendants(new ElementFilter("Point"));
                Element edgePathPoint = null;
                while (iter4.hasNext()) {
                    Object o4 = iter4.next();
                    if (o4 instanceof Element) {
                        edgePathPoint = (Element) o4;
                        logger.debug("  PathPoint x: '" + edgePathPoint.getAttributeValue("x"));
                        logger.debug("  PathPoint y: '" + edgePathPoint.getAttributeValue("y"));
                        e.setPathPoints(
                                new Point2D.Float(Float.parseFloat(edgePathPoint.getAttributeValue("x")),
                                        Float.parseFloat(edgePathPoint.getAttributeValue("y"))));
                    }
                }

                logger.debug("  source: " + element.getAttributeValue("source"));
                logger.debug("  target: " + element.getAttributeValue("target"));

                Vertex source = null;
                Vertex dest = null;

                for (Object vertice : vertices) {
                    Vertex vertex = (Vertex) vertice;

                    // Find source vertex
                    if (vertex.getIdKey().equals(element.getAttributeValue("source"))
                            && vertex.getFileKey().equals(fileName)) {
                        source = vertex;
                    }
                    if (vertex.getIdKey().equals(element.getAttributeValue("target"))
                            && vertex.getFileKey().equals(fileName)) {
                        dest = vertex;
                    }
                }
                if (source == null) {
                    String msg = "Could not find starting node for edge. Name: '"
                            + element.getAttributeValue("source") + "' In file '" + fileName + "'";
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }
                if (dest == null) {
                    String msg = "Could not find end node for edge. Name: '"
                            + element.getAttributeValue("target") + "' In file '" + fileName + "'";
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }

                e.setIdKey(element.getAttributeValue("id"));
                e.setFileKey(fileName);
                e.setIndexKey(getNewVertexAndEdgeIndex());

                // Parse description
                Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data"));
                while (iter_data.hasNext()) {
                    Object o3 = iter_data.next();
                    if (o instanceof Element) {
                        Element data = (Element) o3;
                        if (!data.getAttributeValue("key").equals("d9"))
                            continue;
                        e.setDesctiptionKey(data.getText());
                        break;
                    }
                }

                if (!graph.addEdge(e, source, dest)) {
                    String msg = "Failed adding edge: " + e + ", to graph: " + graph;
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }

                if (edgeLabel != null) {
                    // The label of an edge has the following format:
                    // Label Parameter [Guard] / Action1;Action2;ActionN;
                    // Keyword
                    // Where the Label, Parameter. Guard, Actions and Keyword are
                    // optional.

                    String str = edgeLabel.getText();

                    e.setFullLabelKey(str);
                    String[] guardAndAction = Edge.getGuardAndActions(str);
                    String[] labelAndParameter = Edge.getLabelAndParameter(str);
                    e.setGuardKey(guardAndAction[0]);
                    e.setActionsKey(guardAndAction[1]);
                    e.setLabelKey(labelAndParameter[0]);
                    e.setParameterKey(labelAndParameter[1]);
                    e.setWeightKey(Edge.getWeight(str));
                    e.setBlockedKey(AbstractElement.isBlocked(str));

                    Integer index = AbstractElement.getIndex(str);
                    if (index != 0) {
                        e.setIndexKey(index);
                    }

                    e.setReqTagKey(AbstractElement.getReqTags(str));
                }
                e.setVisitedKey(0);
                logger.debug("  Added edge: '" + e.getLabelKey() + "', with id: " + e.getIndexKey());

                // Extract any manual test instructions
                Iterator<Element> iterData = element.getDescendants(new ElementFilter("data"));
                while (iterData.hasNext() && e != null) {
                    Object o2 = iterData.next();
                    if (o2 instanceof Element) {
                        Element data = (Element) o2;
                        if (!data.getContent().isEmpty() && data.getContent(0) != null) {
                            String text = data.getContent(0).getValue().trim();
                            if (!text.isEmpty()) {
                                logger.debug("  Data: '" + text + "'");
                                e.setManualInstructions(text);
                            }
                        }
                    }
                }
            }
        }
    } catch (RuntimeException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    } catch (JDOMException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    }

    logger.debug("Finished parsing graph: " + graph);
    removeBlockedEntities(graph);
    logger.debug("Graph after removing BLOCKED entities: " + graph);

    return graph;
}

From source file:org.graphwalker.Util.java

License:Open Source License

private static String getScriptContent(final List<Element> scripts) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    for (Element element : scripts) {
        String internal = element.getTextTrim();
        if (internal != null && !internal.equals("")) {
            stringBuilder.append(internal);
            stringBuilder.append(System.getProperty("line.separator"));
        }/*  ww w .  ja v  a2s  .  c om*/
        String external = element.getAttributeValue("PATH");
        if (external != null && !external.equals("")) {
            stringBuilder.append(readFile(Util.getFile(external)));
            stringBuilder.append(System.getProperty("line.separator"));
        }
    }
    return stringBuilder.toString();
}