Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createDocument.

Prototype

public static Document createDocument() 

Source Link

Usage

From source file:it.eng.qbe.datasource.configuration.dao.fileimpl.CalculatedFieldsDAOFileImpl.java

License:Mozilla Public License

public void saveCalculatedFields(Map<String, List<ModelCalculatedField>> calculatedFields) {

    File calculatedFieldsFile;// ww w  .  j av  a  2  s. co  m
    Iterator it;
    String entityName;
    List fields;
    Document document;
    Element root;
    ModelCalculatedField modelCalculatedField;

    logger.debug("IN");

    calculatedFieldsFile = null;

    try {
        Assert.assertNotNull(calculatedFields, "Input parameter [calculatedFields] cannot be null");

        calculatedFieldsFile = getUserCalculatedFieldsFile();
        Assert.assertNotNull(calculatedFieldsFile, "Destination file cannot be null");
        logger.debug("Calculated fields will be saved on file [" + calculatedFieldsFile + "]");

        if (!calculatedFieldsFile.getParentFile().exists()) {
            DAOException e = new DAOException(
                    "Destination file folder [" + calculatedFieldsFile.getPath() + "] does not exist");
            e.addHint("Check if [" + calculatedFieldsFile.getPath()
                    + "] folder exist on your server filesystem. If not create it.");
            throw e;
        }

        if (calculatedFieldsFile.exists()) {
            logger.warn("File [" + calculatedFieldsFile
                    + "] already exists. New settings will override the old ones.");
        }

        document = DocumentHelper.createDocument();
        root = document.addElement(ROOT_TAG);

        logger.debug("In the target model there are [" + calculatedFields.keySet()
                + "] entity/es that contain calculated fields");
        it = calculatedFields.keySet().iterator();
        while (it.hasNext()) {
            entityName = (String) it.next();
            logger.debug("Serializing [" + calculatedFields.size() + "] calculated fields for entity ["
                    + entityName + "]");
            fields = (List) calculatedFields.get(entityName);
            for (int i = 0; i < fields.size(); i++) {
                modelCalculatedField = (ModelCalculatedField) fields.get(i);
                logger.debug("Serializing calculated field [" + modelCalculatedField.getName()
                        + "] for entity [" + entityName + "]");
                Element fieldElement = root.addElement(FIELD_TAG).addAttribute(FIELD_TAG_ENTIY_ATTR, entityName)
                        .addAttribute(FIELD_TAG_NAME_ATTR, modelCalculatedField.getName())
                        .addAttribute(FIELD_TAG_TYPE_ATTR, modelCalculatedField.getType())
                        .addAttribute(FIELD_TAG_NATURE_ATTR, modelCalculatedField.getNature())
                        .addAttribute(FIELD_TAG_IN_LINE_ATTR, "" + modelCalculatedField.isInLine());

                fieldElement.addElement(EXPRESSION_TAG).addCDATA(modelCalculatedField.getExpression());

                List<Slot> slots = modelCalculatedField.getSlots();
                if (slots != null && slots.size() > 0) {
                    Element slotsElement = fieldElement.addElement(SLOTS_TAG);
                    if (modelCalculatedField.getDefaultSlotValue() != null) {
                        slotsElement.addAttribute("defaultSlotValue",
                                modelCalculatedField.getDefaultSlotValue());
                    }

                    for (Slot slot : slots) {
                        Element slotElement = slotsElement.addElement(SLOT_TAG);
                        slotElement.addAttribute("value", slot.getName());
                        saveValueSets(slot, slotElement);
                    }
                }
            }
        }

        guardedWrite(document, calculatedFieldsFile);

    } catch (Throwable t) {
        if (t instanceof DAOException)
            throw (DAOException) t;
        throw new DAOException("An unpredicetd error occurred while saving calculated fields on file ["
                + calculatedFieldsFile + "]");
    } finally {
        logger.debug("OUT");
    }
}

From source file:it.pdfsam.env.EnvWorker.java

License:Open Source License

/**
 * Saves the environment//  ww w.jav a  2 s. c o m
 * 
 */
public void saveJob() {
    try {
        file_chooser.setApproveButtonText(GettextResource.gettext(i18n_messages, "Save job"));
        int return_val = file_chooser.showOpenDialog(null);
        File chosen_file = null;
        if (return_val == JFileChooser.APPROVE_OPTION) {
            chosen_file = file_chooser.getSelectedFile();
            if (chosen_file != null) {
                try {
                    Document document = DocumentHelper.createDocument();
                    Element root = document.addElement("pdfsam_saved_jobs");
                    root.addAttribute("version", MainGUI.NAME);
                    root.addAttribute("savedate", new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
                    for (int i = 0; i < pl_panel.length; i++) {
                        Element node = (Element) root.addElement("plugin");
                        node.addAttribute("class", pl_panel[i].getClass().getName());
                        node.addAttribute("name", pl_panel[i].getPluginName());
                        pl_panel[i].getJobNode(node);
                        fireLogPropertyChanged(GettextResource.gettext(i18n_messages,
                                pl_panel[i].getPluginName() + " job node loaded."), LogPanel.LOG_DEBUG);
                    }
                    FileWriter file_writer = new FileWriter(chosen_file);
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter xml_file_writer = new XMLWriter(file_writer, format);
                    xml_file_writer.write(document);
                    xml_file_writer.flush();
                    xml_file_writer.close();
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Job saved."),
                            LogPanel.LOG_INFO);
                } catch (Exception ex) {
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                            LogPanel.LOG_ERROR);

                }
            }
        }
    } catch (RuntimeException re) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "RuntimeError:")
                + " Unable to load environment. " + re.getMessage(), LogPanel.LOG_ERROR);
    } catch (Exception e) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error:")
                + " Unable to load environment. " + e.getMessage(), LogPanel.LOG_ERROR);
    }
}

From source file:it.unibz.inf.xmlssd.metadator.sqlite.Photo.java

License:Apache License

/**
 * Method which returns the whole stored data in the database.
 * @return XML Documents of the data./*  www. j  a va2  s.  c o  m*/
 * @throws SQLException
 */
public Document get() throws SQLException {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("metadator");

    Statement stat = aConnection.createStatement();
    ResultSet rs = stat.executeQuery(Photo.SELECT);

    while (rs.next()) {
        Element photo = root.addElement("photo");

        // attributes
        photo.addAttribute("id", rs.getString("id"));
        photo.addAttribute("filename", rs.getString("filename"));
        photo.addAttribute("width", rs.getString("width"));
        photo.addAttribute("height", rs.getString("height"));

        // nodes
        photo.addElement("camera").addAttribute("manufactor", rs.getString("manufactor")).addAttribute("model",
                rs.getString("model"));
        photo.addElement("title").addText(rs.getString("title"));
        photo.addElement("author").addText(rs.getString("author"));
        photo.addElement("copyright").addText(rs.getString("copyright"));
        photo.addElement("exposure").addText(rs.getString("exposure"));
        photo.addElement("aperture").addText(dec.format(Float.parseFloat(rs.getString("aperture"))));
        photo.addElement("focalLength").addText(dec.format(Float.parseFloat(rs.getString("focalLength"))));
        photo.addElement("iso").addText(rs.getString("iso"));
        photo.addElement("flash").addText(boolToString(Boolean.parseBoolean(rs.getString("flash"))));
    }

    rs.close();
    stat.close();

    return document;
}

From source file:it.unibz.inf.xmlssd.metadator.sqlite.SQLiteManager.java

License:Apache License

/**
 * Method which constructs a XML document from the data stored in the 
 * Database.// ww  w  .  j a v a 2  s. co  m
 * @return
 */
public Document get() {
    Document document = DocumentHelper.createDocument();

    try {
        Photo photo = new Photo(aConnection);
        document = photo.get();
    } catch (SQLException e) {
        log.error("SQL Error in getting XML: " + e.getMessage());
    }

    return document;
}

From source file:it.unibz.inf.xmlssd.metadator.xml.XMLProcessor.java

License:Apache License

/**
 * Method which returns only a simple list of photos for displaying it in the
 * deletion dialog./*from  www  . java 2  s.  co m*/
 * @return
 * @throws IOException 
 */
public String getListOfPhotos() throws IOException {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("metadator");

    List list = backend.get().selectNodes("//metadator/photo");
    for (Iterator i = list.iterator(); i.hasNext();) {
        Element element = (Element) i.next();

        Node author = element.selectSingleNode("//author");
        Node title = element.selectSingleNode("//title");

        root.addElement("photo").addAttribute("id", element.attributeValue("id"))
                .addAttribute("author", author.getStringValue())
                .addAttribute("filename", element.attributeValue("filename"))
                .addAttribute("title", title.getStringValue());
    }

    return UIHelper.prettyPrintString(document.asXML());
}

From source file:itensil.kb.web.KbServlet.java

License:Open Source License

/**
 *  /listByRef//from  www .ja  va2 s. c  om
 *
 *  Output:
 *      article header list
 *
 */
@SuppressWarnings("unchecked")
@ContentType("text/xml")
public void webListByRef(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String uri = request.getParameter("uri");
    String refId = request.getParameter("refId");
    if (!Check.isEmpty(uri) && !Check.isEmpty(refId)) {
        RepositoryHelper.beginTransaction();
        RepositoryHelper.useReadOnly();
        uri = RepositoryHelper.resolveUri(uri);
        Document doc = XMLDocument.readStream(RepositoryHelper.loadContent(uri));
        Document resDoc = DocumentHelper.createDocument();
        Element resRoot = resDoc.addElement("articles");
        for (Element elem : (List<Element>) doc.getRootElement().elements("article")) {
            if (refId.equals(elem.attributeValue("refId"))) {
                // just the node, no content
                elem.setText("");
                resRoot.add(elem.createCopy());
            }
        }
        RepositoryHelper.commitTransaction();
        if (resRoot.hasContent())
            ServletUtil.cacheTimeout(response, 27);
        else
            ServletUtil.noCache(response);
        resDoc.write(response.getWriter());
    } else {
        throw new NotFoundException("[blank]");
    }
}

From source file:itensil.repository.web.ShellServlet.java

License:Open Source License

/**
 *  /list/* w w  w. j  a  v  a 2  s  .com*/
 *
 * List folder contents
 *
 */
@ContentType("text/xml")
public void webList(HttpServletRequest request, HttpServletResponse response) throws Exception {

    RepositoryHelper.beginTransaction();
    RepositoryHelper.useReadOnly();
    String uri = request.getParameter("uri");
    boolean alwaysFolders = "1".equals(request.getParameter("folders"));
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("list");
    if (!(Check.isEmpty(uri) || uri.length() < 2)) {

        // trim trailing slashes
        while (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);

        // check for wildcard
        WildcardPattern pat = null;
        String name = UriHelper.name(uri);
        if (name.indexOf("*") >= 0) {
            pat = new WildcardPattern(name);
            uri = UriHelper.getParent(uri);
            root.addAttribute("pattern", name);
        }
        uri = RepositoryHelper.resolveUri(uri);
        MutableRepositoryNode node = getNode(uri);
        if (!node.isCollection()) {
            node = (MutableRepositoryNode) node.getParent();
        }
        String pUri = node.getUri();
        root.addAttribute("uri", pUri);
        for (RepositoryNode kid : node.getChildren()) {
            String kName = UriHelper.localizeUri(pUri, kid.getUri());
            if (pat == null || (alwaysFolders && kid.isCollection()) || pat.match(kName)) {
                Element rnElem = root.addElement("node");
                rnElem.addAttribute("uri", kName);
                rnElem.addAttribute("owner", kid.getOwner().getUserId());
                rnElem.addAttribute("collection", kid.isCollection() ? "1" : "0");
            }
        }
    } else {
        root.addAttribute("uri", "/");
        RepositoryManager man = RepositoryManagerFactory.getManager((User) request.getUserPrincipal());
        for (Repository repo : man.getRepositories()) {
            Element rnElem = root.addElement("node");
            rnElem.addAttribute("uri", repo.getMount().substring(1));
            rnElem.addAttribute("collection", "1");
        }
    }
    RepositoryHelper.commitTransaction();
    ServletUtil.setExpired(response);
    doc.write(response.getWriter());
}

From source file:itensil.repository.web.ShellServlet.java

License:Open Source License

/**
 *  /newFolder// ww  w .ja va 2  s .  c  o m
 *
 * List folder contents
 *
 */
@ContentType("text/xml")
public void webNewFolder(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Map<String, String> params = RequestUtil.readParameters(request,
            new String[] { "uri", "name", "description" });

    String description = params.get("description");
    String uri = params.get("uri");
    String name = params.get("name");

    if (Check.isEmpty(name) || Check.isEmpty(uri)) {
        throw new NotFoundException("[blank]");
    }
    RepositoryHelper.beginTransaction();
    uri = RepositoryHelper.resolveUri(uri);
    String dstUri = UriHelper.absoluteUri(uri, UriHelper.filterName(name));
    dstUri = RepositoryHelper.getAvailableUri(dstUri);
    MutableRepositoryNode node = RepositoryHelper.createCollection(dstUri);

    if (!Check.isEmpty(description)) {
        HashMap<QName, String> props = new HashMap<QName, String>();
        props.put(PropertyHelper.itensilQName("description"), description);

        PropertyHelper.setNodeValues(node, props);
    }

    RepositoryHelper.commitTransaction();

    // expire since probably get
    ServletUtil.setExpired(response);
    Document doc = DocumentHelper.createDocument();
    doc.addElement("ok").addAttribute("result", dstUri);
    doc.write(response.getWriter());
}

From source file:itensil.repository.web.ShellServlet.java

License:Open Source License

/**
 *  /getProps//  w  ww. j a  va2  s  .c  o  m
 *
 * Get node properties
 *
 */
@ContentType("text/xml")
public void webGetProps(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String uri = request.getParameter("uri");
    if (!(Check.isEmpty(uri) || uri.length() < 2)) {

        RepositoryHelper.beginTransaction();
        RepositoryHelper.useReadOnly();
        uri = RepositoryHelper.resolveUri(uri);
        MutableRepositoryNode node = getNode(uri);
        NodeProperties props = node.getProperties(new DefaultNodeVersion());
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("properties");
        Namespace davNs = DocumentHelper.createNamespace(PropertyHelper.DEFAULT_PREFIX,
                PropertyHelper.DEFAULT_QNAMESPACE);
        root.add(davNs);
        root.add(DocumentHelper.createNamespace(PropertyHelper.ITENSIL_PREFIX,
                PropertyHelper.ITENSIL_QNAMESPACE));
        root.add(DocumentHelper.createNamespace(PropertyHelper.ITENSIL_ENTITY_PREFIX,
                PropertyHelper.ITENSIL_ENTITY_QNAMESPACE));
        root.addAttribute("uri", node.getUri());
        root.addElement(new org.dom4j.QName("displayname", davNs)).addText(UriHelper.name(uri));
        if (node.isCollection()) {
            root.addElement(new org.dom4j.QName("collection", davNs));
        }
        int nsCount = 0;
        if (props != null) {
            for (Map.Entry<QName, String> prop : props.getPropertyMap().entrySet()) {
                Namespace ns = root.getNamespaceForURI(prop.getKey().getNamespaceURI());
                if (ns == null) {
                    nsCount++;
                    root.addNamespace(prop.getKey().getNamespaceURI(), "ns" + nsCount);
                }
                Element pElem = root.addElement(new org.dom4j.QName(prop.getKey().getLocalPart(), ns));
                String val = prop.getValue();
                if (val != null)
                    pElem.addText(val);
            }
        }
        RepositoryHelper.commitTransaction();
        ServletUtil.setExpired(response);
        doc.write(response.getWriter());
    } else {
        throw new NotFoundException("[blank]");
    }
}

From source file:itensil.repository.web.ShellServlet.java

License:Open Source License

/**
*  /getPerms/*from w  ww . j  a va 2 s .c o  m*/
*
* Get node properties
*
*/
@ContentType("text/xml")
public void webGetPerms(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String uri = request.getParameter("uri");
    if (!(Check.isEmpty(uri) || uri.length() < 2)) {
        RepositoryHelper.beginTransaction();
        RepositoryHelper.useReadOnly();
        uri = RepositoryHelper.resolveUri(uri);
        MutableRepositoryNode node = getNode(uri);

        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("permissions");
        root.addAttribute("uri", node.getUri());
        root.addAttribute("collection", node.isCollection() ? "1" : "0");

        boolean canManage = node
                .hasPermission(DefaultNodePermission.managePermission(request.getUserPrincipal()));

        root.addAttribute("manageable", canManage ? "1" : "0");

        String oid = node.getOwner().getUserId();
        root.addAttribute("owner", oid);
        Element ownerElem = root.addElement("perm");
        ownerElem.addAttribute("level", "4");
        ownerElem.addAttribute("user", oid);
        ownerElem.addAttribute("inherit", "1");
        ownerElem.addAttribute("owner", "1");

        Group ctxGroup = node.getContextGroup();
        root.addAttribute("contextGroup", ctxGroup != null ? ctxGroup.getGroupId() : "");

        for (NodePermission perm : node.getPermissions()) {
            Element elem = root.addElement("perm");
            elem.addAttribute("level", "" + DefaultNodePermission.permissionToInteger(perm));
            String prinId = "";
            if (perm.getPrincipal() instanceof User) {
                prinId = ((User) perm.getPrincipal()).getUserId();
                elem.addAttribute("user", prinId);
            } else if (perm.isRelativeRole()) {
                GroupAxis axis = perm.getAxis();
                elem.addAttribute("relative", "1");
                elem.addAttribute("axis", axis != null && axis != GroupAxis.SELF ? axis.toString() : "");
                String role = Check.emptyIfNull(perm.getRole());
                elem.addAttribute("position", role);
                prinId = ((Group) perm.getPrincipal()).getGroupId();
            } else {
                prinId = ((Group) perm.getPrincipal()).getGroupId();
                elem.addAttribute("group", prinId);
            }
            elem.addAttribute("oprin", prinId);
            elem.addAttribute("inherit", perm.isInheritable() ? "1" : "0");
            elem.addAttribute("change", "0");
        }
        RepositoryHelper.commitTransaction();
        ServletUtil.setExpired(response);
        doc.write(response.getWriter());
    } else {
        throw new NotFoundException("[blank]");
    }
}