Example usage for org.w3c.dom Node getOwnerDocument

List of usage examples for org.w3c.dom Node getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Node getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.opensingular.internal.lib.commons.xml.MElement.java

/**
 * Atualiza o Node (Element ou atributo) j exisitente. Se o Node no for
 * localizado, ento adiciona se o valor for diferente de null.
 *
 * @param xPath Caminho do Node a ser atualizado ou criado
 * @param value Novo valor do Node. Se for null, ento o valor  limpo. Se o
 *              element j existir e valor for null, ento transforma a tag em
 *              empty, mas a mantm no XML.
 * @return O Node alterado ou criado, ou null se no for possvel atualizar
 * o valor do mesmo.//from  w w  w. j  ava 2 s . c  o  m
 */
public final Node updateNode(String xPath, String value) {
    Node n = getNode(xPath);
    if ((n == null) && !StringUtils.isEmpty(value)) {
        return addElement(xPath, value);
    } else if (n instanceof Element) {
        Node filho = n.getFirstChild();
        if (filho == null) {
            if (!StringUtils.isEmpty(value)) {
                Document d = n.getOwnerDocument();
                Text txt = d.createTextNode(value);
                n.appendChild(txt);
            }
        } else if (XmlUtil.isNodeTypeText(filho)) {
            if (!StringUtils.isEmpty(value)) {
                filho.setNodeValue(value);
            } else {
                n.removeChild(filho);
            }
        } else {
            return null;
        }
    } else if (n instanceof Attr) {
        //No h como saber quem  o pai (n.getParentNode() retorna null)
        if (value == null) {
            return addElement(xPath, ""); //Fora a remoo do atributo
        }
        return addElement(xPath, value);
    } else {
        return null;
    }
    return n;
}

From source file:org.openvpms.web.echo.table.KeyTablePeer.java

/**
 * @see nextapp.echo2.webcontainer.DomUpdateSupport#renderHtml(nextapp.echo2.webcontainer.RenderContext,
 *      nextapp.echo2.app.update.ServerComponentUpdate, org.w3c.dom.Node, nextapp.echo2.app.Component)
 *///  w ww.  ja  va 2  s. co m
public void renderHtml(RenderContext rc, ServerComponentUpdate update, Node parentNode, Component component) {
    ServerMessage serverMessage = rc.getServerMessage();
    serverMessage.addLibrary(TABLE_SERVICE.getId());
    KeyTable table = (KeyTable) component;

    renderInitDirective(rc, table);

    Border border = (Border) table.getRenderProperty(Table.PROPERTY_BORDER);
    Extent borderSize = border == null ? null : border.getSize();

    String elementId = ContainerInstance.getElementId(table);

    Document document = parentNode.getOwnerDocument();

    Element container = document.createElement("div");
    container.setAttribute("id", elementId);

    Element focus = document.createElement("a");
    focus.setAttribute("id", elementId + "_focus");
    if (component.isFocusTraversalParticipant()) {
        focus.setAttribute("tabindex", Integer.toString(component.getFocusTraversalIndex()));
    } else {
        focus.setAttribute("tabindex", "-1");
    }

    Element tableElement = document.createElement("table");
    tableElement.setAttribute("id", elementId + "_table");

    CssStyle tableCssStyle = new CssStyle();
    tableCssStyle.setAttribute("border-collapse", "collapse");

    if (((Boolean) table.getRenderProperty(Table.PROPERTY_SELECTION_ENABLED, Boolean.FALSE))) {
        tableCssStyle.setAttribute("cursor", "pointer");
    }

    Insets tableInsets = (Insets) table.getRenderProperty(Table.PROPERTY_INSETS);

    String defaultInsetsAttributeValue = tableInsets == null ? "0px"
            : InsetsRender.renderCssAttributeValue(tableInsets);

    ColorRender.renderToStyle(tableCssStyle, component);
    FontRender.renderToStyle(tableCssStyle, component);
    BorderRender.renderToStyle(tableCssStyle, border);
    if (borderSize != null) {
        if (!rc.getContainerInstance().getClientProperties()
                .getBoolean(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_INSIDE)) {
            tableCssStyle.setAttribute("margin", ExtentRender.renderCssAttributeValueHalf(borderSize));
        }
    }

    Extent width = (Extent) table.getRenderProperty(Table.PROPERTY_WIDTH);
    boolean render100PercentWidthWorkaround = false;
    if (rc.getContainerInstance().getClientProperties()
            .getBoolean(ClientProperties.QUIRK_IE_TABLE_PERCENT_WIDTH_SCROLLBAR_ERROR)) {
        if (width != null && width.getUnits() == Extent.PERCENT && width.getValue() == 100) {
            width = null;
            render100PercentWidthWorkaround = true;
        }
    }
    ExtentRender.renderToStyle(tableCssStyle, "width", width);

    tableElement.setAttribute("style", tableCssStyle.renderInline());

    parentNode.appendChild(container);
    container.appendChild(focus);
    container.appendChild(tableElement);

    TableColumnModel columnModel = table.getColumnModel();
    int columnCount = columnModel.getColumnCount();

    boolean someColumnsHaveWidths = false;
    for (int i = 0; i < columnCount; ++i) {
        if (columnModel.getColumn(i).getWidth() != null) {
            someColumnsHaveWidths = true;
        }
    }
    if (someColumnsHaveWidths) {
        Element colGroupElement = document.createElement("colgroup");
        tableElement.appendChild(colGroupElement);

        for (int i = 0; i < columnCount; ++i) {
            Element colElement = document.createElement("col");
            Extent columnWidth = columnModel.getColumn(i).getWidth();
            if (columnWidth != null) {
                colElement.setAttribute("width", ExtentRender.renderCssAttributeValue(columnWidth));
            }
            colGroupElement.appendChild(colElement);
        }
    }

    Element tbodyElement = document.createElement("tbody");
    tbodyElement.setAttribute("id", elementId + "_tbody");
    tableElement.appendChild(tbodyElement);

    Element firstTrElement = null;

    if (table.isHeaderVisible()) {
        firstTrElement = renderRow(rc, update, tbodyElement, table, Table.HEADER_ROW,
                defaultInsetsAttributeValue);
    }

    int rows = table.getModel().getRowCount();
    for (int rowIndex = 0; rowIndex < rows; ++rowIndex) {
        if (firstTrElement == null && rowIndex == 0) {
            firstTrElement = renderRow(rc, update, tbodyElement, table, rowIndex, defaultInsetsAttributeValue);
        } else {
            renderRow(rc, update, tbodyElement, table, rowIndex, defaultInsetsAttributeValue);
        }
    }

    if (render100PercentWidthWorkaround && firstTrElement != null) {
        // Render string of "sizing dots" in first row of cells.
        NodeList childNodes = firstTrElement.getChildNodes();
        int length = childNodes.getLength();
        for (int i = 0; i < length; ++i) {
            if (!"td".equals(childNodes.item(i).getNodeName())) {
                continue;
            }
            Element tdElement = (Element) childNodes.item(i);
            Element sizingDivElement = document.createElement("div");
            sizingDivElement.setAttribute("style", "font-size:50px;height:0px;overflow:hidden;");
            sizingDivElement.appendChild(document.createTextNode(SIZING_DOTS));
            tdElement.appendChild(sizingDivElement);
        }
    }
}

From source file:org.pentaho.platform.repository.solution.SolutionRepositoryServiceImpl.java

protected void processRepositoryFile(IPentahoSession session, boolean isAdministrator,
        ISolutionRepository repository, Node parentNode, ISolutionFile file, String[] filters) {

    final String name = file.getFileName();

    // MDD 10/16/2008 Not always.. what about 'system'
    if (name.startsWith("system") || name.startsWith("tmp") || name.startsWith(".")) { //$NON-NLS-1$
        // slip hidden files (starts with .)
        // skip the system & tmp dir, we DO NOT ever want this to hit the client
        return;/* w w  w  .  j  ava  2  s. c  o  m*/
    }

    if (!accept(isAdministrator, repository, file)) {
        // we don't want this file, skip to the next one
        return;
    }

    if (file.isDirectory()) {
        // we always process directories

        // maintain legacy behavior
        if (repository.getRootFolder(ISolutionRepository.ACTION_EXECUTE).getFullPath()
                .equals(file.getFullPath())) {
            // never output the root folder as part of the repo doc; skip root and process its children
            ISolutionFile[] children = file.listFiles();
            for (ISolutionFile childSolutionFile : children) {
                processRepositoryFile(session, isAdministrator, repository, parentNode, childSolutionFile,
                        filters);
            }
            return;
        }

        Element child = null;
        final String key = file.getFullPath() + file.getLastModified() + LocaleHelper.getLocale();
        ICacheManager cacheManager = PentahoSystem.getCacheManager(null);
        if (cacheManager != null
                && cacheManager.cacheEnabled(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION)) {
            child = (Element) cacheManager
                    .getFromRegionCache(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION, key);
        }
        if (child == null) {
            child = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                    : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
            try {
                String localizedName = repository.getLocalizedFileProperty(file, "name", //$NON-NLS-1$
                        ISolutionRepository.ACTION_EXECUTE);
                child.setAttribute("localized-name", //$NON-NLS-1$
                        localizedName == null || "".equals(localizedName) ? name : localizedName); //$NON-NLS-1$
            } catch (Exception e) {
                child.setAttribute("localized-name", name); //$NON-NLS-1$
            }
            try {
                String visible = repository.getLocalizedFileProperty(file, "visible", //$NON-NLS-1$
                        ISolutionRepository.ACTION_EXECUTE);
                child.setAttribute("visible", visible == null || "".equals(visible) ? "false" : visible); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            } catch (Exception e) {
                e.printStackTrace();
                child.setAttribute("visible", "false"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                    ISolutionRepository.ACTION_EXECUTE);
            child.setAttribute("description", //$NON-NLS-1$
                    description == null || "".equals(description) ? name : description); //$NON-NLS-1$
            child.setAttribute("name", name); //$NON-NLS-1$
            child.setAttribute("isDirectory", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            child.setAttribute("lastModifiedDate", "" + file.getLastModified()); //$NON-NLS-1$ //$NON-NLS-2$
            if (cacheManager != null
                    && cacheManager.cacheEnabled(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION)) {
                cacheManager.putInRegionCache(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION, key, child);
            }
        } else {
            Element newChild = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                    : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
            NamedNodeMap attributes = child.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                Node attribute = attributes.item(i);
                newChild.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
            }
            child = newChild;
        }
        parentNode.appendChild(child);

        ISolutionFile[] children = file.listFiles();
        for (ISolutionFile childSolutionFile : children) {
            processRepositoryFile(session, isAdministrator, repository, child, childSolutionFile, filters);
        }
    } else {
        InputStream pluginInputStream = null;
        try {
            int lastPoint = name.lastIndexOf('.');
            String extension = ""; //$NON-NLS-1$
            if (lastPoint != -1) {
                // ignore anything with no extension
                extension = name.substring(lastPoint + 1).toLowerCase();
            }

            // xaction and URL support are built in
            boolean addFile = acceptFilter(name, filters) || "xaction".equals(extension) //$NON-NLS-1$
                    || "url".equals(extension); //$NON-NLS-1$
            boolean isPlugin = false;
            // see if there is a plugin for this file type
            IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
            if (pluginManager != null) {
                Set<String> types = pluginManager.getContentTypes();
                isPlugin = types != null && types.contains(extension);
                addFile |= isPlugin;
            }

            if (addFile) {

                ICacheManager cacheManager = PentahoSystem.getCacheManager(null);
                Element child = null;
                final String key = file.getFullPath() + file.getLastModified() + LocaleHelper.getLocale();
                if (cacheManager != null
                        && cacheManager.cacheEnabled(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION)) {
                    child = (Element) cacheManager
                            .getFromRegionCache(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION, key);
                }
                if (child == null) {
                    child = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                            : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
                    if (cacheManager != null
                            && cacheManager.cacheEnabled(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION)) {
                        cacheManager.putInRegionCache(ISolutionRepository.REPOSITORY_SERVICE_CACHE_REGION, key,
                                child);
                    }
                } else {
                    Element newChild = parentNode instanceof Document
                            ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                            : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$

                    NamedNodeMap attributes = child.getAttributes();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        Node attribute = attributes.item(i);
                        newChild.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
                    }

                    parentNode.appendChild(newChild);
                    return;
                }

                parentNode.appendChild(child);
                IFileInfo fileInfo = null;
                if (name.endsWith(".xaction")) { //$NON-NLS-1$
                    // add special props?
                    // localization..
                    String solution = file.getSolutionPath();
                    String path = ""; //$NON-NLS-1$
                    if (solution.startsWith(ISolutionRepository.SEPARATOR + "")) { //$NON-NLS-1$
                        solution = solution.substring(1);
                    }
                    final int pos = solution.indexOf(ISolutionRepository.SEPARATOR);
                    if (pos != -1) {
                        path = solution.substring(pos + 1);
                        solution = solution.substring(0, pos);
                    }
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    String contextPath = requestContext.getContextPath();
                    final String paramServiceUrl = contextPath + "ServiceAction?solution=" //$NON-NLS-1$
                            + URLEncoder.encode(solution, URL_ENCODING) + "&path=" + URLEncoder.encode(path, URL_ENCODING) + "&action=" + URLEncoder.encode(name, URL_ENCODING) + "&component=xaction-parameter";
                    child.setAttribute("param-service-url", paramServiceUrl);

                    final String url = contextPath + "ViewAction?solution=" //$NON-NLS-1$
                            + URLEncoder.encode(solution, URL_ENCODING) + "&path=" + URLEncoder.encode(path, URL_ENCODING) + "&action=" + URLEncoder.encode(name, URL_ENCODING);
                    child.setAttribute("url", url);

                } else if (name.endsWith(".url")) { //$NON-NLS-1$

                    // add special props
                    String props = new String(file.getData());
                    StringTokenizer tokenizer = new StringTokenizer(props, "\n"); //$NON-NLS-1$
                    while (tokenizer.hasMoreTokens()) {
                        String line = tokenizer.nextToken();
                        int pos = line.indexOf('=');
                        if (pos > 0) {
                            String propname = line.substring(0, pos);
                            String value = line.substring(pos + 1);
                            if ((value != null) && (value.length() > 0)
                                    && (value.charAt(value.length() - 1) == '\r')) {
                                value = value.substring(0, value.length() - 1);
                            }
                            if ("URL".equalsIgnoreCase(propname)) { //$NON-NLS-1$
                                child.setAttribute("url", value); //$NON-NLS-1$
                            }
                        }
                    }
                } else if (isPlugin) {
                    // must be a plugin - make it look like a URL
                    try {
                        // get the file info object for this file
                        // not all plugins are going to actually use the inputStream, so we have a special
                        // wrapper inputstream so that we can pay that price when we need to (2X speed boost)
                        pluginInputStream = new PluginFileInputStream(repository, file);
                        fileInfo = pluginManager.getFileInfo(extension, session, file, pluginInputStream);
                        String handlerId = pluginManager.getContentGeneratorIdForType(extension, session);
                        String fileUrl = pluginManager.getContentGeneratorUrlForType(extension, session);
                        String solution = file.getSolutionPath();
                        String path = ""; //$NON-NLS-1$
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        String contextPath = requestContext.getContextPath();
                        if (solution.startsWith(ISolutionRepository.SEPARATOR + "")) { //$NON-NLS-1$
                            solution = solution.substring(1);
                        }
                        int pos = solution.indexOf(ISolutionRepository.SEPARATOR);
                        if (pos != -1) {
                            path = solution.substring(pos + 1);
                            solution = solution.substring(0, pos);
                        }
                        String url = null;
                        if (!"".equals(fileUrl)) { //$NON-NLS-1$
                            url = contextPath + fileUrl + "?solution="
                                    + URLEncoder.encode(solution, URL_ENCODING) + "&path="
                                    + URLEncoder.encode(path, URL_ENCODING) + "&action=" //$NON-NLS-1$
                                    + URLEncoder.encode(name, URL_ENCODING); //$NON-NLS-2$ //$NON-NLS-3$
                        } else {
                            IContentInfo info = pluginManager.getContentInfoFromExtension(extension, session);
                            for (IPluginOperation operation : info.getOperations()) {
                                if (operation.getId().equalsIgnoreCase("RUN")) { //$NON-NLS-1$
                                    String command = operation.getCommand();

                                    command = command.replaceAll("\\{solution\\}", //$NON-NLS-1$
                                            URLEncoder.encode(solution, URL_ENCODING));
                                    command = command.replaceAll("\\{path\\}", //$NON-NLS-1$
                                            URLEncoder.encode(path, URL_ENCODING));
                                    command = command.replaceAll("\\{name\\}", //$NON-NLS-1$
                                            URLEncoder.encode(name, URL_ENCODING));
                                    url = contextPath + command;

                                    break;
                                }
                            }
                            if (url == null) {
                                url = contextPath + "content/" + handlerId + "?solution="
                                        + URLEncoder.encode(solution, URL_ENCODING) + "&path="
                                        + URLEncoder.encode(path, URL_ENCODING) + "&action=" //$NON-NLS-1$
                                        + URLEncoder.encode(name, URL_ENCODING); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            }
                        }
                        child.setAttribute("url", url); //$NON-NLS-1$

                        // do not come up with fantasy values for a non-existing service.
                        // if there is no param-service then do not claim that there is one.
                        String paramUrl = null;
                        final IContentInfo info = pluginManager.getContentInfoFromExtension(extension, session);
                        for (final IPluginOperation operation : info.getOperations()) {
                            if (operation.getId().equals("PARAMETER")) { //$NON-NLS-1$
                                String command = operation.getCommand();
                                command = command.replaceAll("\\{solution\\}", //$NON-NLS-1$
                                        URLEncoder.encode(solution, URL_ENCODING));
                                command = command.replaceAll("\\{path\\}", //$NON-NLS-1$
                                        URLEncoder.encode(path, URL_ENCODING));
                                command = command.replaceAll("\\{name\\}", //$NON-NLS-1$
                                        URLEncoder.encode(name, URL_ENCODING));
                                paramUrl = contextPath + command;

                                break;
                            }
                        }

                        if (StringUtil.isEmpty(paramUrl) == false) {
                            child.setAttribute("param-service-url", paramUrl); //$NON-NLS-1$
                        }
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }

                }

                if (fileInfo != null) {
                    if ("none".equals(fileInfo.getDisplayType())) // $NON-NLS-1$
                    {
                        child.setAttribute("visible", "false"); //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        child.setAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                } else {
                    try {
                        // the visibility flag for action-sequences is controlled by
                        // /action-sequence/documentation/result-type
                        // and we should no longer be looking at 'visible' because it was
                        // never actually used!
                        String visible = "none".equals(repository.getLocalizedFileProperty(file, //$NON-NLS-1$
                                "documentation/result-type", ISolutionRepository.ACTION_EXECUTE)) ? "false" //$NON-NLS-1$//$NON-NLS-2$
                                        : "true"; //$NON-NLS-1$
                        child.setAttribute("visible", //$NON-NLS-1$
                                (visible == null || "".equals(visible) || "true".equals(visible)) ? "true" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                        : "false"); //$NON-NLS-1$
                    } catch (Exception e) {
                        child.setAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }

                // localization
                try {
                    String localizedName = null;
                    if (name.endsWith(".url")) { //$NON-NLS-1$
                        localizedName = repository.getLocalizedFileProperty(file, "url_name", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                    } else if (fileInfo != null) {
                        localizedName = fileInfo.getTitle();
                    } else {
                        localizedName = repository.getLocalizedFileProperty(file, "title", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                    }
                    child.setAttribute("localized-name", //$NON-NLS-1$
                            localizedName == null || "".equals(localizedName) ? name : localizedName); //$NON-NLS-1$
                } catch (Exception e) {
                    child.setAttribute("localized-name", name); //$NON-NLS-1$
                }

                try {
                    // only folders, urls and xactions have descriptions
                    if (name.endsWith(".url")) { //$NON-NLS-1$
                        String url_description = repository.getLocalizedFileProperty(file, "url_description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        if (url_description == null && description == null) {
                            child.setAttribute("description", name); //$NON-NLS-1$
                        } else {
                            child.setAttribute("description", //$NON-NLS-1$
                                    url_description == null || "".equals(url_description) ? description //$NON-NLS-1$
                                            : url_description);
                        }
                    } else if (name.endsWith(".xaction")) { //$NON-NLS-1$
                        String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        child.setAttribute("description", //$NON-NLS-1$
                                description == null || "".equals(description) ? name : description); //$NON-NLS-1$
                    } else if (fileInfo != null) {
                        child.setAttribute("description", fileInfo.getDescription()); //$NON-NLS-1$
                    } else {
                        child.setAttribute("description", name); //$NON-NLS-1$
                    }
                } catch (Exception e) {
                    child.setAttribute("description", "xxxxxxx"); //$NON-NLS-1$ //$NON-NLS-2$
                }

                // add permissions for each file/folder
                child.setAttribute("name", name); //$NON-NLS-1$
                child.setAttribute("isDirectory", "" + file.isDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
                child.setAttribute("lastModifiedDate", "" + file.getLastModified()); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } catch (UnsupportedEncodingException e) {
            // if that happens, you are running on a JDK without UTF-8 support. Get a proper JDK!
            throw new IllegalStateException(e);
        } finally {
            IOUtils.closeQuietly(pluginInputStream);
        }
    } // else isfile
}

From source file:org.pentaho.platform.repository.solution.SolutionRepositoryServiceImplFast.java

protected void processRepositoryFile(IPentahoSession session, boolean isAdministrator,
        ISolutionRepository repository, Node parentNode, ISolutionFile file, String[] filters) {

    final String name = file.getFileName();

    // MDD 10/16/2008 Not always.. what about 'system'
    if (name.startsWith("system") || name.startsWith("tmp") || name.startsWith(".")) { //$NON-NLS-1$
        // slip hidden files (starts with .)
        // skip the system & tmp dir, we DO NOT ever want this to hit the client
        return;/*from w w w.  j  a  va2 s  .co m*/
    }

    if (!accept(isAdministrator, repository, file)) {
        // we don't want this file, skip to the next one
        return;
    }

    if (file.isDirectory()) {
        // we always process directories

        // maintain legacy behavior
        if (repository.getRootFolder(ISolutionRepository.ACTION_EXECUTE).getFullPath()
                .equals(file.getFullPath())) {
            // never output the root folder as part of the repo doc; skip root and process its children
            ISolutionFile[] children = file.listFiles();
            for (ISolutionFile childSolutionFile : children) {
                processRepositoryFile(session, isAdministrator, repository, parentNode, childSolutionFile,
                        filters);
            }
            return;
        }

        Element child = null;
        final String key = file.getFullPath() + file.getLastModified() + LocaleHelper.getLocale();
        ICacheManager cacheManager = PentahoSystem.getCacheManager(null);
        if (cacheManager != null && cacheManager.cacheEnabled(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION)) {
            child = (Element) cacheManager.getFromRegionCache(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION, key);
        }
        if (child == null) {
            child = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                    : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
            try {
                String localizedName = repository.getLocalizedFileProperty(file, "name", //$NON-NLS-1$
                        ISolutionRepository.ACTION_EXECUTE);
                child.setAttribute("localized-name", //$NON-NLS-1$
                        localizedName == null || "".equals(localizedName) ? name : localizedName); //$NON-NLS-1$
            } catch (Exception e) {
                child.setAttribute("localized-name", name); //$NON-NLS-1$
            }
            try {
                String visible = repository.getLocalizedFileProperty(file, "visible", //$NON-NLS-1$
                        ISolutionRepository.ACTION_EXECUTE);
                child.setAttribute("visible", visible == null || "".equals(visible) ? "false" : visible); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            } catch (Exception e) {
                e.printStackTrace();
                child.setAttribute("visible", "false"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                    ISolutionRepository.ACTION_EXECUTE);
            child.setAttribute("description", //$NON-NLS-1$
                    description == null || "".equals(description) ? name : description); //$NON-NLS-1$
            child.setAttribute("name", name); //$NON-NLS-1$
            child.setAttribute("isDirectory", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            child.setAttribute("lastModifiedDate", "" + file.getLastModified()); //$NON-NLS-1$ //$NON-NLS-2$
            if (cacheManager != null && cacheManager.cacheEnabled(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION)) {
                cacheManager.putInRegionCache(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION, key, child);
            }
        } else {
            Element newChild = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                    : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
            NamedNodeMap attributes = child.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                Node attribute = attributes.item(i);
                newChild.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
            }
            child = newChild;
        }
        parentNode.appendChild(child);

        ISolutionFile[] children = file.listFiles();
        for (ISolutionFile childSolutionFile : children) {
            processRepositoryFile(session, isAdministrator, repository, child, childSolutionFile, filters);
        }
    } else {
        InputStream pluginInputStream = null;
        try {
            int lastPoint = name.lastIndexOf('.');
            String extension = ""; //$NON-NLS-1$
            if (lastPoint != -1) {
                // ignore anything with no extension
                extension = name.substring(lastPoint + 1).toLowerCase();
            }

            // xaction and URL support are built in
            boolean addFile = acceptFilter(name, filters) || "xaction".equals(extension) //$NON-NLS-1$
                    || "url".equals(extension); //$NON-NLS-1$
            boolean isPlugin = false;
            // see if there is a plugin for this file type
            IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
            if (pluginManager != null) {
                Set<String> types = pluginManager.getContentTypes();
                isPlugin = types != null && types.contains(extension);
                addFile |= isPlugin;
            }

            if (addFile) {

                ICacheManager cacheManager = PentahoSystem.getCacheManager(null);
                Element child = null;
                final String key = file.getFullPath() + file.getLastModified() + LocaleHelper.getLocale();
                if (cacheManager != null
                        && cacheManager.cacheEnabled(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION)) {
                    child = (Element) cacheManager.getFromRegionCache(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION,
                            key);
                }
                if (child == null) {
                    child = parentNode instanceof Document ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                            : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$
                    if (cacheManager != null
                            && cacheManager.cacheEnabled(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION)) {
                        cacheManager.putInRegionCache(REPOSITORY_SERVICE_FILEINFO_CACHE_REGION, key, child);
                    }
                } else {
                    Element newChild = parentNode instanceof Document
                            ? ((Document) parentNode).createElement("file") //$NON-NLS-1$
                            : parentNode.getOwnerDocument().createElement("file"); //$NON-NLS-1$

                    NamedNodeMap attributes = child.getAttributes();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        Node attribute = attributes.item(i);
                        newChild.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
                    }

                    parentNode.appendChild(newChild);
                    return;
                }

                parentNode.appendChild(child);
                IFileInfo fileInfo = null;
                try {
                    // the visibility flag for action-sequences is controlled by
                    // /action-sequence/documentation/result-type
                    // and we should no longer be looking at 'visible' because it was
                    // never actually used!
                    String visible = "none".equals(repository.getLocalizedFileProperty(file, //$NON-NLS-1$
                            "documentation/result-type", ISolutionRepository.ACTION_EXECUTE)) ? "false" //$NON-NLS-1$//$NON-NLS-2$
                                    : "true"; //$NON-NLS-1$
                    child.setAttribute("visible", //$NON-NLS-1$
                            (visible == null || "".equals(visible) || "true".equals(visible)) ? "true" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                    : "false"); //$NON-NLS-1$
                } catch (Exception e) {
                    child.setAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
                }
                if (name.endsWith(".xaction")) { //$NON-NLS-1$
                    // add special props?
                    // localization..
                } else if (name.endsWith(".url")) { //$NON-NLS-1$

                    // add special props
                    String props = new String(file.getData());
                    StringTokenizer tokenizer = new StringTokenizer(props, "\n"); //$NON-NLS-1$
                    while (tokenizer.hasMoreTokens()) {
                        String line = tokenizer.nextToken();
                        int pos = line.indexOf('=');
                        if (pos > 0) {
                            String propname = line.substring(0, pos);
                            String value = line.substring(pos + 1);
                            if ((value != null) && (value.length() > 0)
                                    && (value.charAt(value.length() - 1) == '\r')) {
                                value = value.substring(0, value.length() - 1);
                            }
                            if ("URL".equalsIgnoreCase(propname)) { //$NON-NLS-1$
                                child.setAttribute("url", value); //$NON-NLS-1$
                            }
                        }
                    }
                } else if (isPlugin) {
                    // must be a plugin - make it look like a URL
                    try {
                        // get the file info object for this file
                        // not all plugins are going to actually use the inputStream, so we have a special
                        // wrapper inputstream so that we can pay that price when we need to (2X speed boost)
                        pluginInputStream = new PluginFileInputStream(repository, file);
                        fileInfo = pluginManager.getFileInfo(extension, session, file, pluginInputStream);
                        String handlerId = pluginManager.getContentGeneratorIdForType(extension, session);
                        String fileUrl = pluginManager.getContentGeneratorUrlForType(extension, session);
                        String solution = file.getSolutionPath();
                        String path = ""; //$NON-NLS-1$
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        String contextPath = requestContext.getContextPath();
                        if (solution.startsWith(ISolutionRepository.SEPARATOR + "")) { //$NON-NLS-1$
                            solution = solution.substring(1);
                        }
                        int pos = solution.indexOf(ISolutionRepository.SEPARATOR);
                        if (pos != -1) {
                            path = solution.substring(pos + 1);
                            solution = solution.substring(0, pos);
                        }
                        String url = null;
                        if (!"".equals(fileUrl)) { //$NON-NLS-1$
                            url = contextPath + fileUrl //$NON-NLS-1$
                                    + "?solution=" + solution + "&path=" + path + "&action=" + name; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        } else {
                            IContentInfo info = pluginManager.getContentInfoFromExtension(extension, session);
                            for (IPluginOperation operation : info.getOperations()) {
                                if (operation.getId().equalsIgnoreCase("RUN")) { //$NON-NLS-1$
                                    String command = operation.getCommand();
                                    command = command.replaceAll("\\{solution\\}", solution); //$NON-NLS-1$
                                    command = command.replaceAll("\\{path\\}", path); //$NON-NLS-1$
                                    command = command.replaceAll("\\{name\\}", name); //$NON-NLS-1$
                                    url = contextPath + command; //$NON-NLS-1$
                                    break;
                                }
                            }
                            if (url == null) {
                                url = contextPath + "content/" + handlerId + "?solution=" + solution + "&path=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                        + path + "&action=" + name; //$NON-NLS-1$
                            }
                        }
                        child.setAttribute("url", url); //$NON-NLS-1$

                        String paramServiceUrl = contextPath + "content/" + handlerId + "?solution=" + solution //$NON-NLS-1$//$NON-NLS-2$
                                + "&path=" + path + "&action=" + name; //$NON-NLS-1$ //$NON-NLS-2$

                        child.setAttribute("param-service-url", paramServiceUrl); //$NON-NLS-1$

                    } catch (Throwable t) {
                        t.printStackTrace();
                    }

                }

                // localization
                try {
                    String localizedName = null;
                    if (name.endsWith(".url")) { //$NON-NLS-1$
                        localizedName = repository.getLocalizedFileProperty(file, "url_name", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                    } else if (fileInfo != null) {
                        localizedName = fileInfo.getTitle();
                    } else {
                        localizedName = repository.getLocalizedFileProperty(file, "title", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                    }
                    child.setAttribute("localized-name", //$NON-NLS-1$
                            localizedName == null || "".equals(localizedName) ? name : localizedName); //$NON-NLS-1$
                } catch (Exception e) {
                    child.setAttribute("localized-name", name); //$NON-NLS-1$
                }
                try {
                    // only folders, urls and xactions have descriptions
                    if (name.endsWith(".url")) { //$NON-NLS-1$
                        String url_description = repository.getLocalizedFileProperty(file, "url_description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        if (url_description == null && description == null) {
                            child.setAttribute("description", name); //$NON-NLS-1$
                        } else {
                            child.setAttribute("description", //$NON-NLS-1$
                                    url_description == null || "".equals(url_description) ? description //$NON-NLS-1$
                                            : url_description);
                        }
                    } else if (name.endsWith(".xaction")) { //$NON-NLS-1$
                        String description = repository.getLocalizedFileProperty(file, "description", //$NON-NLS-1$
                                ISolutionRepository.ACTION_EXECUTE);
                        child.setAttribute("description", //$NON-NLS-1$
                                description == null || "".equals(description) ? name : description); //$NON-NLS-1$
                    } else if (fileInfo != null) {
                        child.setAttribute("description", fileInfo.getDescription()); //$NON-NLS-1$
                    } else {
                        child.setAttribute("description", name); //$NON-NLS-1$
                    }
                } catch (Exception e) {
                    child.setAttribute("description", "xxxxxxx"); //$NON-NLS-1$ //$NON-NLS-2$
                }

                // add permissions for each file/folder
                child.setAttribute("name", name); //$NON-NLS-1$
                child.setAttribute("isDirectory", "" + file.isDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
                child.setAttribute("lastModifiedDate", "" + file.getLastModified()); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } finally {
            IOUtils.closeQuietly(pluginInputStream);
        }
    } // else isfile
}

From source file:org.regenstrief.util.XMLUtil.java

/**
 * Strips namespaces and prefixes from a Node tree
 * //from   w  w w  . ja  v  a  2 s.co m
 * @param n the root Node
 * @return the stripped Node
 **/
public final static Node stripNamespaces(final Node n) {
    if (n == null) {
        return null;
    }

    final Document doc = n.getOwnerDocument();
    if (n instanceof Element) {
        final Element eOld = (Element) n;
        final Element eNew = doc.createElement(getLocalName(eOld));
        final NamedNodeMap map = eOld.getAttributes();
        for (int i = 0, size = size(map); i < size; i++) {
            final Attr attr = (Attr) map.item(i);
            String name = attr.getName();
            if (name == null) {
                name = attr.getLocalName();
            }
            if (!("xmlns".equals(name) || ((name != null) && name.startsWith("xmlns:"))
                    || "xmlns".equals(attr.getPrefix()))) {
                final int j = name.indexOf(':');
                eNew.setAttribute(j < 0 ? name : name.substring(j + 1), attr.getValue());
            }
        }
        final NodeList list = n.getChildNodes();
        for (int i = 0, size = size(list); i < size; i++) {
            appendChild(eNew, stripNamespaces(list.item(i)));
        }
        return eNew;
    } else if (n instanceof Attr) {
        return null;
    }
    return n.cloneNode(false);
}

From source file:org.sakaiproject.tool.assessment.qti.asi.ASIBaseClass.java

/**
 *
 *
 * @param xpath/*from  w ww.  java2  s . c  om*/
 * @param fieldlabel
 */
protected void createFieldentry(String xpath, String fieldlabel) {
    if (log.isDebugEnabled()) {
        log.debug("createFieldentry(String " + xpath + ", String " + fieldlabel + ")");
    }

    try {
        List qtimetadataNodes = this.selectNodes(xpath);
        if (qtimetadataNodes.size() > 0) {
            Node qtimetadataNode = (Node) qtimetadataNodes.get(0);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document newDocument = db.newDocument();

            Element qtimetadataField = newDocument.createElement(QTIConstantStrings.QTIMETADATAFIELD);
            Element fieldlabelElement = newDocument.createElement(QTIConstantStrings.FIELDLABEL);
            Element fieldentryElement = newDocument.createElement(QTIConstantStrings.FIELDENTRY);

            Text fieldlabelText = newDocument.createTextNode(QTIConstantStrings.FIELDLABEL);
            fieldlabelText.setNodeValue(fieldlabel);
            fieldlabelElement.appendChild(fieldlabelText);

            Text fieldentryText = newDocument.createTextNode(QTIConstantStrings.FIELDENTRY);
            fieldentryElement.appendChild(fieldentryText);

            Node importedFLE = qtimetadataField.getOwnerDocument().importNode(fieldlabelElement, true);
            Node importedFEE = qtimetadataField.getOwnerDocument().importNode(fieldentryElement, true);
            qtimetadataField.appendChild(importedFLE);
            qtimetadataField.appendChild(importedFEE);
            Node importedField = qtimetadataNode.getOwnerDocument().importNode(qtimetadataField, true);
            qtimetadataNode.appendChild(importedField);
        }
    } catch (ParserConfigurationException pce) {
        log.error("Exception thrown from createFieldentry()" + pce.getMessage(), pce);
        pce.printStackTrace();
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.sakaiproject.tool.assessment.qti.asi.ASIBaseClass.java

protected void wrappingMattext() {
    log.debug("wrappingMattext()");

    try {//from  ww  w .j  a  v  a  2  s . c o m
        NodeList list = this.getDocument().getElementsByTagName(QTIConstantStrings.MATTEXT);
        int size = list.getLength();
        for (int i = 0; i < size; i++) {
            Node node = list.item(i);
            Node childNode = node.getFirstChild();
            if ((childNode != null) && childNode instanceof CharacterData) {
                CharacterData cdi = (CharacterData) childNode;
                String data = cdi.getData();

                //modify this string;
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.newDocument();
                Comment comment = doc.createComment(data);
                node.appendChild(node.getOwnerDocument().importNode(comment, true));
                cdi.setData("");
            }
        }
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.springframework.oxm.xmlbeans.XmlBeansMarshaller.java

@Override
protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException {
    Document document = node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument();
    Node xmlBeansNode = ((XmlObject) graph).newDomNode(getXmlOptions());
    NodeList xmlBeansChildNodes = xmlBeansNode.getChildNodes();
    for (int i = 0; i < xmlBeansChildNodes.getLength(); i++) {
        Node xmlBeansChildNode = xmlBeansChildNodes.item(i);
        Node importedNode = document.importNode(xmlBeansChildNode, true);
        node.appendChild(importedNode);//from   w ww.j a v a  2  s . co m
    }
}

From source file:org.structr.web.entity.dom.PageTest.java

public void testAdoptNodes() {

    try {//from   w  ww . ja  va 2 s.  c o m
        try (final Tx tx = app.tx()) {

            Page srcPage = Page.createNewPage(securityContext, "srcPage");

            assertTrue(srcPage != null);
            assertTrue(srcPage instanceof Page);

            Node html = srcPage.createElement("html");
            Node head = srcPage.createElement("head");
            Node body = srcPage.createElement("body");
            Node title = srcPage.createElement("title");
            Node h1 = srcPage.createElement("h1");
            Node div = srcPage.createElement("div");
            Node p = srcPage.createElement("p");

            // add HTML element to page
            srcPage.appendChild(html);

            // add HEAD and BODY elements to HTML
            html.appendChild(head);
            html.appendChild(body);

            // add TITLE element to HEAD
            head.appendChild(title);

            // add H1 element to BODY
            body.appendChild(h1);

            // add DIV element to BODY
            body.appendChild(div);
            div.appendChild(p);

            // add text element to P
            p.appendChild(srcPage.createTextNode("First Paragraph"));

            Page dstPage = Page.createNewPage(securityContext, "dstPage");
            assertNotNull(dstPage);

            // test adopt method
            dstPage.adoptNode(html);

            // has parent been removed for the source element?
            assertNull(html.getParentNode());

            // has owner changed for all elements?
            assertEquals(dstPage, html.getOwnerDocument());
            assertEquals(dstPage, head.getOwnerDocument());
            assertEquals(dstPage, body.getOwnerDocument());
            assertEquals(dstPage, title.getOwnerDocument());
            assertEquals(dstPage, h1.getOwnerDocument());
            assertEquals(dstPage, div.getOwnerDocument());
            assertEquals(dstPage, p.getOwnerDocument());

            // have parents been kept for all other elements?
            assertEquals(html, head.getParentNode());
            assertEquals(html, body.getParentNode());
            assertEquals(head, title.getParentNode());
            assertEquals(body, h1.getParentNode());
            assertEquals(body, div.getParentNode());
            assertEquals(div, p.getParentNode());

            // srcPage should not have a document element any more
            assertNull(srcPage.getDocumentElement());

            // srcPage should have exactly one child element
            assertEquals(1, srcPage.getChildNodes().getLength());

            tx.success();

        } catch (DOMException dex) {

            throw new FrameworkException(422, dex.getMessage());
        }

    } catch (FrameworkException ex) {

        fail("Unexpected exception");
    }
}

From source file:org.structr.web.entity.dom.PageTest.java

public void testImportNodesDeep() {

    try (final Tx tx = app.tx()) {

        Page srcPage = Page.createNewPage(securityContext, "srcPage");

        assertTrue(srcPage != null);/*w  ww.  j  a  va  2s  .  c  o  m*/
        assertTrue(srcPage instanceof Page);

        Node html = srcPage.createElement("html");
        Node head = srcPage.createElement("head");
        Node body = srcPage.createElement("body");
        Node title = srcPage.createElement("title");
        Node h1 = srcPage.createElement("h1");
        Node div = srcPage.createElement("div");
        Node p = srcPage.createElement("p");

        // add HTML element to page
        srcPage.appendChild(html);

        // add HEAD and BODY elements to HTML
        html.appendChild(head);
        html.appendChild(body);

        // add TITLE element to HEAD
        head.appendChild(title);

        // add H1 element to BODY
        body.appendChild(h1);

        // add DIV element to BODY
        body.appendChild(div);
        div.appendChild(p);

        // add text element to P
        p.appendChild(srcPage.createTextNode("First Paragraph"));

        Page dstPage = Page.createNewPage(securityContext, "dstPage");
        assertNotNull(dstPage);

        // test
        assertEquals(srcPage, html.getOwnerDocument());

        makePublic(srcPage, dstPage, html, head, body, title, h1, div, p);

        // test import method
        dstPage.importNode(html, true);

        // has parent been removed for the source element?
        assertNull(html.getParentNode());

        // same owner for all elements?
        assertEquals(srcPage, html.getOwnerDocument());
        assertEquals(srcPage, head.getOwnerDocument());
        assertEquals(srcPage, body.getOwnerDocument());
        assertEquals(srcPage, title.getOwnerDocument());
        assertEquals(srcPage, h1.getOwnerDocument());
        assertEquals(srcPage, div.getOwnerDocument());
        assertEquals(srcPage, p.getOwnerDocument());

        // have parents been kept for all other elements?
        assertEquals(html, head.getParentNode());
        assertEquals(html, body.getParentNode());
        assertEquals(head, title.getParentNode());
        assertEquals(body, h1.getParentNode());
        assertEquals(body, div.getParentNode());
        assertEquals(div, p.getParentNode());

        tx.success();

    } catch (Exception ex) {
        ex.printStackTrace();
        fail("Unexpected exception");
    }

    try (final Tx tx = app.tx()) {

        Document srcDoc = Jsoup.connect(baseUri + "srcPage").get();
        Document dstDoc = Jsoup.connect(baseUri + "dstPage").get();

        // pages should render exactly identical
        assertEquals(srcDoc.outerHtml(), dstDoc.outerHtml());

        tx.success();

    } catch (Exception ex) {
        ex.printStackTrace();
        fail("Unexpected exception");
    }
}