Example usage for org.jdom2 Element getAttributeValue

List of usage examples for org.jdom2 Element getAttributeValue

Introduction

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

Prototype

public String getAttributeValue(final String attname) 

Source Link

Document

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

Usage

From source file:de.danielluedecke.zettelkasten.DesktopFrame.java

License:Open Source License

/**
 * This method updates the jTreeView. Each time an update for the treevuew is needed, this
 * method is called. It then recursevly traverses all XML-Elements of the currently activated
 * desktop-element, where the starting desktop-element is passed in the parameter {@code e}.
 * <br><br>/*from   w  w  w .  j  a  v a 2s. c o m*/
 * The method retrieves each element, checks whether the element is an entry- or a bullet-element,
 * than either, in case of a bullet point, uses the name-attribute as node-name and appends the
 * timestamp-attribute as ID; or it retrieves the entry's title from the entry-number that is stored
 * in each entry-element, and appends the entry's timestamp-attribute as ID.
 * <br><br>
 * After that, the node is inserted in the jTree.
 *
 * @param e
 * @param n
 * @param dtm
 */
private void fillChildren(Element e, DefaultMutableTreeNode n, DefaultTreeModel dtm) {
    // get a list with all children of the element
    List<Element> children = e.getChildren();
    // create an iterator
    Iterator<Element> it = children.iterator();
    // go through all children
    while (it.hasNext()) {
        // get the child
        e = it.next();
        // create a new node
        DefaultMutableTreeNode node;
        // we have to ignore the comment-tags here. comments are no tags that will
        // be displayed in the jtree, but that store comments which will be displayed
        // in the jeditorpane (see "updateDisplay" method for further details)
        if (!e.getName().equals("comment")) {
            // if the child is a bullet...
            if (e.getName().equals("bullet")) {
                // create new stringbuilder
                StringBuilder sb = new StringBuilder("");
                // append name of bullet point
                sb.append(e.getAttributeValue("name"));
                //                    // and append unique id, which is the element's timestamp
                //                    sb.append(" [id#").append(e.getAttributeValue("timestamp")).append("]");
                //                    // create a node with the element's name-attribute
                //                    node = new DefaultMutableTreeNode(sb.toString());
                // create a node with the element's name-attribute
                node = new DefaultMutableTreeNode(
                        new TreeUserObject(sb.toString(), e.getAttributeValue("timestamp"), ""));
                // and tell node to have children
                node.setAllowsChildren(true);
            } else {
                // now we know we have an entry. so get the entry number...
                int nr = Integer.parseInt(e.getAttributeValue("id"));
                // get the zettel title
                String title = TreeUtil.retrieveNodeTitle(dataObj, settingsObj.getShowDesktopEntryNumber(),
                        String.valueOf(nr));
                // create a new node
                node = new DefaultMutableTreeNode(
                        new TreeUserObject(title, e.getAttributeValue("timestamp"), String.valueOf(nr)));
                // and tell node not to have children
                node.setAllowsChildren(false);
            }
            // add new node to treeview
            dtm.insertNodeInto(node, n, n.getChildCount());
            // when the new element also has children, call this method again,
            // so we go through the strucuture recursively...
            if (desktopObj.hasChildren(e)) {
                fillChildren(e, node, dtm);
            }
        }
    }
}

From source file:de.danielluedecke.zettelkasten.DesktopFrame.java

License:Open Source License

/**
 * This method retrieves all entries on the desktop and adds their number to the
 * list {@code liste}. This array of entry-numbers is needed in the export-dialog.
 *
 * @param e the starting point for the jTree-enumeration, either the root elementor a bullet (if only
 * a bullet should be exported, see {@link #exportDesktopBullet() exportDesktopBullet()}).
 * @param liste an array-object that will hold the found entry-nubers
 *///from w w  w.  j  av  a 2s .  c o m
private void createExportEntries(Element e, ArrayList<Object> liste) {
    // if we have no element, return.
    if (null == e)
        return;
    // get a list with all children of the element
    List<Element> children = e.getChildren();
    // create an iterator
    Iterator<Element> it = children.iterator();
    // go through all children
    while (it.hasNext()) {
        // get the child
        e = it.next();
        // we have to ignore the comment-tags here. comments are no tags that will
        // be displayed in the jtree, but that store comments which will be displayed
        // in the jeditorpane (see "updateDisplay" method for further details)
        if (!e.getName().equals("comment")) {
            // if the child is a bullet...
            if (e.getName().equals("bullet")) {
                // first, we want to retrieve the header-level
                int headerlevel = 1;
                // get bullet's parent
                Element f = e.getParentElement();
                // as long as we have not reached the root, get further parent-elements
                // and increase counter for header-level
                while (!f.isRootElement()) {
                    f = f.getParentElement();
                    headerlevel++;
                }
                // add the element's name-attribute. since headers might consist of only numbers,
                // we add a char here. this is necessary, since the export-methods distinguish
                // between headers and entry-numbers simply by parsing integer-values. if the parsing
                // succeeds, we have an entry, if a NumberFormatException is thrown, we have a headline.
                // to treat headline with numbers only as headlines, we add a char to be sure that every
                // headline will throw an exception when parsing the array's elements to integer.
                liste.add("h" + String.valueOf(headerlevel) + e.getAttributeValue("name"));
            } else {
                // now we know we have an entry. so get the entry number...
                int nr = Integer.parseInt(e.getAttributeValue("id"));
                liste.add(nr);
            }
            // when the new element also has children, call this method again,
            // so we go through the strucuture recursively...
            if (desktopObj.hasChildren(e)) {
                createExportEntries(e, liste);
            }
        }
    }
}

From source file:de.danielluedecke.zettelkasten.tasks.importtasks.ImportFromZkx.java

License:Open Source License

@Override
protected Object doInBackground() {
    // what we do here is importing new zettelkasten-data (.zkn3).
    // in the beginning, we simply load the data-file. but when appending
    // it to the existing data, we need to convert the author- and keyword-
    // index-numbers. therefore, for each entry the author and keyword-strings
    // are retrieved, added to the existing author and keyword-file, and the
    // new index-numbers replace the old ones. finally, when the complete
    // data-file is converted, it is appended to the existing data-file.
    ////from   w w w .j  a va 2 s  .  co  m

    // TODO unique-Zettel-IDs durch Verweise auf entsprechende Zettel (Zettelnummer) ersetzen.
    // dies gilt fr:
    // - Schreibtischdaten
    // - Suchergebnisse

    // create dummy-documents, where the imported data is stored.
    Document zkn3Doc = new Document(new Element("zettelkasten"));
    Document author3Doc = new Document(new Element("authors"));
    Document keyword3Doc = new Document(new Element(Daten.ELEMENT_KEYWORD));
    Document bookmark3Doc = new Document(new Element("bookmarks"));
    Document search3Doc = new Document(new Element("searches"));
    Document desktop3Doc = new Document(new Element("desktops"));
    Document desktopModifiedEntries3Doc = new Document(new Element("modifiedEntries"));
    Document meta3Doc = new Document(new Element("metainformation"));
    try {
        // it looks like the SAXBuilder is closing an input stream. So we have to
        // re-open the ZIP-file each time we want to retrieve an XML-file from it
        // this is necessary, because we want tot retrieve the zipped xml-files
        // *without* temporarily saving them to harddisk
        for (int cnt = 0; cnt < dataObj.getFilesToLoadCount(); cnt++) {
            // open the zip-file
            ZipInputStream zip = new ZipInputStream(new FileInputStream(filepath));
            ZipEntry zentry;
            // now iterate the zip-file, searching for the requested file in it
            while ((zentry = zip.getNextEntry()) != null) {
                String entryname = zentry.getName();
                // if the found file matches the requested one, start the SAXBuilder
                if (entryname.equals(dataObj.getFileToLoad(cnt))) {
                    try {
                        SAXBuilder builder = new SAXBuilder();
                        Document doc = builder.build(zip);
                        // compare, which file we have retrieved, so we store the data
                        // correctly on our data-object
                        if (entryname.equals(Constants.metainfFileName)) {
                            meta3Doc = doc;
                        }
                        if (entryname.equals(Constants.zknFileName)) {
                            zkn3Doc = doc;
                        }
                        if (entryname.equals(Constants.authorFileName)) {
                            author3Doc = doc;
                        }
                        if (entryname.equals(Constants.keywordFileName)) {
                            keyword3Doc = doc;
                        }
                        if (entryname.equals(Constants.bookmarksFileName)) {
                            bookmark3Doc = doc;
                        }
                        if (entryname.equals(Constants.searchrequestsFileName)) {
                            search3Doc = doc;
                        }
                        if (entryname.equals(Constants.desktopFileName)) {
                            desktop3Doc = doc;
                        }
                        if (entryname.equals(Constants.desktopModifiedEntriesFileName)) {
                            desktopModifiedEntries3Doc = doc;
                        }
                        break;
                    } catch (JDOMException e) {
                        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
                    }
                }
            }
            zip.close();
        }
        // retrieve version-element
        Element ver_el = meta3Doc.getRootElement().getChild("version");
        // store fileformat-information
        String importedFileFormat = "";
        // check whether it's null or not
        if (null == ver_el) {
            taskinfo.setImportOk(false);
        } else {
            // get data-version of imported file
            importedFileFormat = ver_el.getAttributeValue("id");
            float lv = Float.parseFloat(importedFileFormat);
            // get fileversion of backward compatibility
            // float cv = Float.parseFloat(currentFileFormat);
            float cv = Float.parseFloat(Daten.backwardCompatibleVersion);
            // check whether the current data-version is newer than the loaded one
            taskinfo.setImportOk(lv >= cv);
        }
        // if we have not the right file-format, tell this the user...
        if (!taskinfo.isImportOk()) {
            // log error-message
            Constants.zknlogger.log(Level.WARNING,
                    "Failed when importing Zettelkasten-data. Import-Fileversion: {0} Requested Fileversion: {1}",
                    new Object[] { importedFileFormat, Daten.backwardCompatibleVersion });
            // display error message box
            JOptionPane.showMessageDialog(null,
                    resourceMap.getString("importDlgErrWrongFileFormat", Daten.backwardCompatibleVersion,
                            importedFileFormat),
                    resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
            // leave thread
            return null;
        }
        // remove all entries with identical ID, because we can't have these entries twice
        // in the database. if the user wants to update entries (with same IDs), the synch feature
        // can be used.
        removeDoubleEntries(zkn3Doc);
        // get the length of the data
        final int len = zkn3Doc.getRootElement().getContentSize();
        // reset the progressbar
        setProgress(0, 0, len);
        msgLabel.setText(resourceMap.getString("importDlgMsgEdit"));
        //
        // at first, add the description of the new importet zettelkasten
        //
        // get the child element
        Element el = meta3Doc.getRootElement().getChild(Daten.ELEMEMT_DESCRIPTION);
        // if we have any element, add description
        if (el != null) {
            dataObj.addZknDescription(el.getText());
        }
        //
        // now, convert the old index-numbers of the authors and keywords
        // to the new numbers and add the entries to the existing data file
        //
        // go through all entries and prepare them and add them to the
        // main data file. especially the new author- and keyword-index-numbers
        // have to be prepared
        for (int cnt = 0; cnt < len; cnt++) {
            // get each child
            Element z = (Element) zkn3Doc.getRootElement().getContent(cnt);
            // we only need to convert the author- and keyword-index-numbers.
            // first we start with the author-index-numbers...
            // if the author-element is not empty...
            if (!z.getChild(Daten.ELEMENT_AUTHOR).getText().isEmpty()) {
                // ...get the autors indexnumbers
                String[] aun = z.getChild(Daten.ELEMENT_AUTHOR).getText().split(",");
                // create new stringbuilder that will contain the new index-numbers
                StringBuilder sb = new StringBuilder("");
                // iterate the array
                for (int c = 0; c < aun.length; c++) {
                    // get the related author-element from the author-file.
                    // the needed author-index-number is stored as integer (string-value)
                    // in the author-indexnumbers-array "aun".
                    Element dummyauthor = (Element) author3Doc.getRootElement()
                            .getContent(Integer.parseInt(aun[c]) - 1);
                    // get the string value for that author
                    String authorstring = dummyauthor.getText();
                    // if we have any author, go on..
                    if (!authorstring.isEmpty()) {
                        // add author to the data file
                        // and store the position of the new added author in the
                        // variable authorPos
                        int authorPos = dataObj.addAuthor(authorstring, 1);
                        // store author position as string value
                        sb.append(String.valueOf(authorPos));
                        sb.append(",");
                    }
                }
                // truncate last comma
                if (sb.length() > 1) {
                    sb.setLength(sb.length() - 1);
                }
                // set new author-index-numbers
                z.getChild(Daten.ELEMENT_AUTHOR).setText(sb.toString());
            }
            // now that the authors are converted, we need to convert
            // the keyword-index-numbers
            // if the keyword-element is not empty...
            if (!z.getChild(Daten.ELEMENT_KEYWORD).getText().isEmpty()) {
                // ...get the keywords-index-numbers
                String[] kwn = z.getChild(Daten.ELEMENT_KEYWORD).getText().split(",");
                // create new stringbuilder that will contain the new index-numbers
                StringBuilder sb = new StringBuilder("");
                // iterate the array
                for (int c = 0; c < kwn.length; c++) {
                    // get the related keyword-element from the keyword-file.
                    // the needed keyword-index-number is stored as integer (string-value)
                    // in the keyword-indexnumbers-array "kwn".
                    Element dummykeyword = (Element) keyword3Doc.getRootElement()
                            .getContent(Integer.parseInt(kwn[c]) - 1);
                    // get the string value for that keyword
                    String keywordstring = dummykeyword.getText();
                    // if we have any keywords, go on..
                    if (!keywordstring.isEmpty()) {
                        // add it to the data file
                        // and store the position of the new added keyword in the
                        // variable keywordPos
                        int keywordPos = dataObj.addKeyword(keywordstring, 1);
                        // store author position as string value
                        sb.append(String.valueOf(keywordPos));
                        sb.append(",");
                    }
                }
                // truncate last comma
                if (sb.length() > 1) {
                    sb.setLength(sb.length() - 1);
                }
                // set new keyword-index-numbers
                z.getChild(Daten.ELEMENT_KEYWORD).setText(sb.toString());
            }
            // update progressbar
            setProgress(cnt, 0, len);
        }
        // now that all entries are converted, append the data to the existing file
        dataObj.appendZknData(zkn3Doc);
        // TODO append desktop-data
        // TODO append search-data                        
        // append bookmarks
        bookmarksObj.appendBookmarks(dataObj, bookmark3Doc);
    } catch (IOException e) {
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
    }
    return null; // return your result
}

From source file:de.danielluedecke.zettelkasten.tasks.importtasks.ImportFromZkx.java

License:Open Source License

/**
 * /*  ww w  .j av a2 s.c o m*/
 * @param zdoc 
 */
private void removeDoubleEntries(Document zdoc) {
    // set new import message, telling that data conversion is proceeded
    msgLabel.setText(resourceMap.getString("importDlgMsgRemoveDouble"));
    // create a list of all elements from the given xml file
    List<?> elementList = zdoc.getRootElement().getContent();
    // reset the progressbar
    setProgress(0, 0, elementList.size());
    // the outer loop for the imported data
    for (int cnt = 0; cnt < elementList.size(); cnt++) {
        // get element of imported data file
        Element importentry = (Element) elementList.get(cnt);
        // now add id to zettel-element
        String id = importentry.getAttributeValue(Daten.ATTRIBUTE_ZETTEL_ID);
        // check for valid value
        if (id != null && !id.isEmpty()) {
            // check whether Zettel with unique ID already exists
            // in the current database
            if (dataObj.findZettelFromID(id) != -1) {
                // if yes, remove double entry from imported document
                zdoc.getRootElement().getContent().remove(cnt);
                // add number of removed entry to list. remember that
                // the entry-number adds on to our counter, which starts
                // at zero.
            }
        }
        setProgress(cnt, 0, elementList.size());
    }
}

From source file:de.danielluedecke.zettelkasten.util.Tools.java

License:Open Source License

/**
 * This method prepares a message that tells the user which entries already appear in the desktop, and
 * at which position. the complete message is returned as string.
 *
 * @param list a linked list which contains the multiple-entry-data. see
 * {@link #retrieveDoubleEntries(zettelkasten.CDesktopData, java.util.LinkedList) retrieveDoubleEntries(zettelkasten.CDesktopData, java.util.LinkedList)}
 * for more details on how this parameter is created. use the return result of this method as this parameter
 * @return a string with the message which entries are at which position in the desktop-data, or {@code null}
 * if no occurences appear.// w w  w  .j  a v  a  2s.  c  o  m
 */
public static String prepareDoubleEntriesMessage(List<Object[]> list) {
    // retrieve system's line-separator
    String lineseparator = System.getProperty("line.separator");
    // get an iterator for the multiple entries and check
    // whether we have any multiple occurences at all. if yes,
    // tell the user about that
    Iterator<Object[]> i = list.iterator();
    // prepare a string builder that will contain the information-message in case
    // we have any multiple occurences of entries...
    StringBuilder multipleOccurencesMessage = new StringBuilder("");
    // go through all entries of the linked list and check
    // whether we have found anything
    while (i.hasNext()) {
        // get element
        Object[] desktopdata = i.next();
        // if second element in array is not null, we have a match. now retrieve
        // the entry's data, so we can inform the user about the
        // entry's details...
        if (desktopdata[1] != null) {
            // retrieve desktop name
            String dn = resourceMap.getString("multipleOccurencesDesktop") + " " + (String) desktopdata[0];
            StringBuilder dnsl = new StringBuilder("");
            // now we add a separator line, so check length of string
            for (int dnl = 0; dnl < dn.length(); dnl++)
                dnsl.append("-");
            // first, append desktop-name
            multipleOccurencesMessage.append(dn).append(lineseparator);
            multipleOccurencesMessage.append(dnsl.toString()).append(lineseparator);
            // now retrieve the elements...
            List<Element> elements = (ArrayList<Element>) desktopdata[1];
            // create iterator for each found element
            Iterator<Element> entryIterator = elements.iterator();
            // go through the found entries in that desktop
            while (entryIterator.hasNext()) {
                // get each found entry as element
                Element entry = entryIterator.next();
                // get the timestamp of the found entry
                String timestamp = entry.getAttributeValue("timestamp");
                // get the entrynumber of the found entry
                String id = entry.getAttributeValue("id");
                // create a linked list that will hold the path to the desktop
                List<String> path = new ArrayList<String>();
                // as long as the found element has parents, we have path-elements/information
                // to add...
                while (entry.getParentElement() != null) {
                    // retrieve parent-element
                    entry = entry.getParentElement();
                    // if it's a bullet, add the path-name to our path-list
                    if (entry.getName().equals("bullet")) {
                        path.add(0, entry.getAttributeValue("name"));
                    }
                }
                // now we can prepare the output string...
                multipleOccurencesMessage.append(
                        resourceMap.getString("multipleOccurencesMsg", id, getProperDate(timestamp, false)));
                multipleOccurencesMessage.append(lineseparator)
                        .append(resourceMap.getString("multipleOccurencesLevel")).append(" ");
                // go through the path-list and append all path-elements, so the user
                // knows where to find the entry
                for (int cnt = 0; cnt < path.size(); cnt++) {
                    // add path
                    multipleOccurencesMessage.append(path.get(cnt));
                    // as long as we have a path-element left, append a separating comma
                    if (cnt < path.size() - 1) {
                        multipleOccurencesMessage.append(" >>> ");
                    }
                }
                // append two line-separators for the next element...
                multipleOccurencesMessage.append(lineseparator).append(lineseparator);
            }
        }
    }
    // delete the last two trailing lineseparators
    if (multipleOccurencesMessage.length() > 0) {
        multipleOccurencesMessage.setLength(multipleOccurencesMessage.length() - 2 * lineseparator.length());
    }
    // if we have any content, return string. else return null
    return (multipleOccurencesMessage.length() > 0) ? multipleOccurencesMessage.toString() : null;
}

From source file:de.hbrs.oryx.yawl.converter.handler.yawl.element.AtomicTaskHandler.java

License:Open Source License

private HashMap<String, String> convertResourcing(final Element resourcingSpecs) {
    HashMap<String, String> properties = new HashMap<String, String>();

    if (resourcingSpecs == null) {
        getContext().addConversionWarnings("No resourcing specification " + getNetElement().getID(), null);
        return properties;
    }//w w w  .j a  v a2s . c o m

    Element offer = resourcingSpecs.getChild("offer", resourcingSpecs.getNamespace());
    if (offer != null) {
        properties.put("offerinitiator", offer.getAttributeValue("initiator"));
        properties.put("offerinteraction", YAWLUtils.elementToString(offer.getChildren()));
    }

    Element allocate = resourcingSpecs.getChild("allocate", resourcingSpecs.getNamespace());
    if (allocate != null) {
        properties.put("allocateinitiator", allocate.getAttributeValue("initiator"));
        properties.put("allocateinteraction", YAWLUtils.elementToString(allocate.getChildren()));
    }

    Element start = resourcingSpecs.getChild("start", resourcingSpecs.getNamespace());
    if (start != null) {
        properties.put("startinitiator", start.getAttributeValue("initiator"));
        properties.put("startinteraction", YAWLUtils.elementToString(start.getChildren()));
    }

    Element privileges = resourcingSpecs.getChild("privileges", resourcingSpecs.getNamespace());
    if (privileges != null) {
        properties.put("privileges", YAWLUtils.elementToString(privileges.getChildren()));
    }

    return properties;
}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutArranger.java

License:Open Source License

private void createNet(Element yawlDecomposition) {
    String isRootNet = yawlDecomposition.getAttributeValue("isRootNet");
    if (Boolean.parseBoolean(isRootNet)) {
        String id = yawlDecomposition.getAttributeValue("id");
        sb.append("<net id=\"" + id + "\">");
        createFakeXYWH();//from  w  w  w .j av  a 2 s.co m
        Element yawlProcessControlElements = yawlDecomposition.getChild("processControlElements",
                yawlDecomposition.getNamespace());
        if (yawlProcessControlElements != null) {
            createVertexesAndFlows(yawlProcessControlElements);
        }
        sb.append("</net>");
    }

}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutArranger.java

License:Open Source License

private void createVertexesAndFlows(Element yawlProcessControlElements) {
    List<Element> vertexes = new LinkedList<Element>();
    vertexes.addAll(yawlProcessControlElements.getChildren());
    List<String> flowOpenTags = new LinkedList<String>();
    for (Element element : vertexes) {
        sb.append("<vertex id=\"" + element.getAttributeValue("id") + "\">");
        createFakeAttributes();//from w  w  w  .ja va2 s . c om
        sb.append("</vertex>");
        flowOpenTags.addAll(searchFlows(element));
    }
    for (String flowOpenTag : flowOpenTags) {
        createFlow(flowOpenTag);
    }

}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutArranger.java

License:Open Source License

private List<String> searchFlows(Element element) {
    List<String> res = new LinkedList<String>();
    String sourceId = element.getAttributeValue("id"), targetId;
    List<Element> flowsIntos = element.getChildren("flowsInto", element.getNamespace());
    for (Element flowInto : flowsIntos) {
        List<Element> nextElementRefs = flowInto.getChildren("nextElementRef", element.getNamespace());
        for (Element nextElementRef : nextElementRefs) {
            targetId = nextElementRef.getAttributeValue("id");
            res.add("<flow source=\"" + sourceId + "\" target=\"" + targetId + "\">");
        }//  w ww .jav a 2s  . c  om
    }
    return res;
}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutConverter.java

License:Open Source License

private void setYAWLLocale(final Element e) {
    Element eLocale = e.getChild("locale", yawlNamespace);
    if (eLocale != null) {
        String language = eLocale.getAttributeValue("language");
        String country = eLocale.getAttributeValue("country");
        yawlLocale = new Locale(language, country);
    } else {/*  w ww.  ja v  a  2s.c om*/
        yawlLocale = Locale.getDefault();
    }

    numberFormatter = NumberFormat.getInstance(yawlLocale);
}