Example usage for org.apache.commons.io FilenameUtils separatorsToUnix

List of usage examples for org.apache.commons.io FilenameUtils separatorsToUnix

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils separatorsToUnix.

Prototype

public static String separatorsToUnix(String path) 

Source Link

Document

Converts all separators to the Unix separator of forward slash.

Usage

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

private int parseResourceDefinitions(final Node actionRootNode, final ILogger logger) {

    resourceDefinitions = new ListOrderedMap();

    try {//w  w  w .j  a v a  2s.  c  o m
        List resources = actionRootNode.selectNodes("resources/*"); //$NON-NLS-1$

        // TODO create objects to represent the types
        // TODO need source variable list
        Iterator resourcesIterator = resources.iterator();

        Node resourceNode;
        String resourceName;
        String resourceTypeName;
        String resourceMimeType;
        int resourceType;
        ActionSequenceResource resource;
        Node typeNode, mimeNode;
        while (resourcesIterator.hasNext()) {
            resourceNode = (Node) resourcesIterator.next();
            typeNode = resourceNode.selectSingleNode("./*"); //$NON-NLS-1$
            if (typeNode != null) {
                resourceName = resourceNode.getName();
                resourceTypeName = typeNode.getName();
                resourceType = ActionSequenceResource.getResourceType(resourceTypeName);
                String resourceLocation = XmlDom4JHelper.getNodeText("location", typeNode); //$NON-NLS-1$
                if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                        || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                    if (resourceLocation == null) {
                        logger.error(Messages.getInstance().getErrorString(
                                "SequenceDefinition.ERROR_0008_RESOURCE_NO_LOCATION", resourceName)); //$NON-NLS-1$
                        continue;
                    }
                } else if (resourceType == IActionSequenceResource.STRING) {
                    resourceLocation = XmlDom4JHelper.getNodeText("string", resourceNode); //$NON-NLS-1$
                } else if (resourceType == IActionSequenceResource.XML) {
                    //resourceLocation = XmlHelper.getNodeText("xml", resourceNode); //$NON-NLS-1$
                    Node xmlNode = typeNode.selectSingleNode("./location/*"); //$NON-NLS-1$
                    // Danger, we have now lost the character encoding of the XML in this node
                    // see BISERVER-895
                    resourceLocation = (xmlNode == null) ? "" : xmlNode.asXML(); //$NON-NLS-1$
                }
                mimeNode = typeNode.selectSingleNode("mime-type"); //$NON-NLS-1$
                if (mimeNode != null) {
                    resourceMimeType = mimeNode.getText();
                    if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                            || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                        resourceLocation = FilenameUtils.separatorsToUnix(resourceLocation);
                        if (!resourceLocation.startsWith("/")) { //$NON-NLS-1$
                            String parentDir = FilenameUtils.getFullPathNoEndSeparator(xactionPath);
                            if (parentDir.length() == 0) {
                                parentDir = RepositoryFile.SEPARATOR;
                            }
                            resourceLocation = FilenameUtils
                                    .separatorsToUnix(FilenameUtils.concat(parentDir, resourceLocation));
                        }
                    }
                    resource = new ActionSequenceResource(resourceName, resourceType, resourceMimeType,
                            resourceLocation);
                    resourceDefinitions.put(resourceName, resource);
                } else {
                    logger.error(Messages.getInstance().getErrorString(
                            "SequenceDefinition.ERROR_0007_RESOURCE_NO_MIME_TYPE", resourceName)); //$NON-NLS-1$
                }
            }
            // input = new ActionParameter( resourceName, resourceType, null
            // );
            // resourceDefinitions.put( inputName, input );
        }
        return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0006_PARSING_RESOURCE"), //$NON-NLS-1$
                e);
    }
    return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_INVALID_ACTION_DOC;

}

From source file:org.pentaho.platform.plugin.action.xml.xquery.XQueryBaseComponent.java

protected boolean runQuery(final IPentahoConnection localConnection, String rawQuery) {
    XQueryAction xQueryAction = (XQueryAction) getActionDefinition();
    try {//  w w w.j  a  va 2s  . c o  m
        if (localConnection == null) {
            return false;
        }
        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("XQueryBaseComponent.DEBUG_RUNNING_QUERY", rawQuery)); //$NON-NLS-1$
        }
        String documentPath = null;
        int resourceType = -1;
        String srcXml = xQueryAction.getSourceXml().getStringValue();
        org.pentaho.actionsequence.dom.IActionResource xmlResource = xQueryAction.getXmlDocument();
        InputStream inputStream = null;
        URL url = null;
        if (srcXml != null) {
            inputStream = new FileInputStream(new File(createTempXMLFile(srcXml)));
        } else if (xmlResource != null) {
            // we have a local document to use as the data source
            IActionSequenceResource resource = getResource(xmlResource.getName());
            resourceType = resource.getSourceType();
            if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                    || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                inputStream = resource.getInputStream(RepositoryFilePermission.READ);
            } else if (resourceType == IActionSequenceResource.XML) {
                inputStream = new FileInputStream(new File(createTempXMLFile(resource.getAddress())));
            } else {
                url = new URL(documentPath);
            }
        }

        // Retrieve the column types
        String[] columnTypes = null;
        if (retrieveColumnTypes()) {
            try {
                SAXReader reader = new SAXReader();
                Document document;
                if (url != null) {
                    document = reader.read(url);
                } else {
                    document = reader.read(inputStream);
                }
                Node commentNode = document.selectSingleNode("/result-set/comment()"); //$NON-NLS-1$
                if (commentNode != null) {
                    String commentString = commentNode.getText();
                    StringTokenizer st = new StringTokenizer(commentString, ","); //$NON-NLS-1$
                    List columnTypesList = new LinkedList();
                    while (st.hasMoreTokens()) {
                        String token = st.nextToken().trim();
                        columnTypesList.add(token);
                    }
                    columnTypes = (String[]) columnTypesList.toArray(new String[0]);
                }
            } catch (Exception e) {
                getLogger().warn(Messages.getInstance()
                        .getString("XQueryBaseComponent.ERROR_0009_ERROR_BUILDING_COLUMN_TYPES"), e); //$NON-NLS-1$
            }
        }

        if (rawQuery != null) {
            if (rawQuery.indexOf("{" + XQueryBaseComponent.XML_DOCUMENT_TAG + "}") >= 0) { //$NON-NLS-1$//$NON-NLS-2$
                rawQuery = TemplateUtil.applyTemplate(rawQuery, XQueryBaseComponent.XML_DOCUMENT_TAG,
                        documentPath);
            } else {
                Calendar now = Calendar.getInstance();
                File temp = File.createTempFile("tempXQuery" + now.getTimeInMillis(), ".xml");
                temp.deleteOnExit();

                OutputStream out = new FileOutputStream(temp);
                IActionSequenceResource resource = getResource(xmlResource.getName());
                inputStream = resource.getInputStream(RepositoryFilePermission.READ);
                byte[] buf = new byte[1024];
                int len;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.close();
                inputStream.close();
                documentPath = temp.getAbsolutePath();
                documentPath = FilenameUtils.separatorsToUnix(documentPath);

                rawQuery = "doc(\"" + documentPath + "\")" + rawQuery; //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        if (xQueryAction.getOutputPreparedStatement() != null) {
            return prepareFinalQuery(rawQuery, columnTypes);
        } else {
            return runFinalQuery(localConnection, rawQuery, columnTypes);
        }
    } catch (Exception e) {
        getLogger().error(
                Messages.getInstance().getString("XQueryBaseComponent.ERROR_0010_ERROR_RUNNING_QUERY"), e); //$NON-NLS-1$
        return false;
    }
}

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Converts all separators to the Repository (Unix) separator of forward slash.
 * //from   w ww.ja v  a  2 s. co m
 * @param path
 *          the path to be changed, null ignored
 * @return the updated path
 */
public static String separatorsToRepository(final String path) {
    return FilenameUtils.separatorsToUnix(path);
}

From source file:org.qedeq.kernel.se.common.DefaultModuleAddressTest.java

public void testDefaultModuleAddressFile() throws Exception {
    final File file = new File("unknown/hulouo.xml");
    dflt = new DefaultModuleAddress(file);
    assertEquals("hulouo.xml", dflt.getFileName());
    assertEquals("file://", dflt.getHeader());
    assertEquals("hulouo", dflt.getName());
    assertEquals(/*  w w  w.j  a  v  a2 s.  c om*/
            (SystemUtils.IS_OS_WINDOWS ? "/" : "")
                    + FilenameUtils.separatorsToUnix(file.getCanonicalFile().getParentFile().getPath()) + "/",
            dflt.getPath());
    assertEquals("file://" + (SystemUtils.IS_OS_WINDOWS ? "/" : "")
            + FilenameUtils.separatorsToUnix(file.getCanonicalPath()), dflt.getUrl());
    assertEquals(true, dflt.isFileAddress());
    assertEquals(false, dflt.isRelativeAddress());
    assertEquals(dflt, dflt.createModuleContext().getModuleLocation());
}

From source file:org.silverpeas.components.silvercrawler.model.FileFolder.java

public FileFolder(String rootPath, String path, boolean isAdmin, String componentId) {
    this.path = path;
    files = new ArrayList<>(0);
    folders = new ArrayList<>(0);
    IndexReader reader = null;/*from  ww w . ja  v a2  s.  c  om*/
    try {
        // Check security access : cannot browse inside rootPath
        FileUtil.validateFilename(path, rootPath);
        File f = new File(path);

        writable = f.canWrite();

        if (f.exists()) {
            this.name = f.getName();
            this.readable = f.canRead();
            File[] children = f.listFiles();
            boolean isIndexed = false;

            if (isAdmin) {
                // ouverture de l'index
                Directory indexPath = FSDirectory
                        .open(Paths.get(IndexFileManager.getAbsoluteIndexPath(componentId)));
                if (DirectoryReader.indexExists(indexPath)) {
                    reader = DirectoryReader.open(indexPath);
                }
            }
            if (children != null && children.length > 0) {
                for (File childFile : children) {
                    isIndexed = false;
                    if (isAdmin) {
                        // rechercher si le rpertoire (ou le fichier) est index
                        StringBuilder pathIndex = new StringBuilder(componentId).append("|");
                        if (childFile.isDirectory()) {
                            pathIndex.append("LinkedDir").append("|");
                        } else {
                            pathIndex.append("LinkedFile").append("|");
                        }
                        pathIndex.append(FilenameUtils.separatorsToUnix(childFile.getPath()));
                        Term term = new Term("key", pathIndex.toString());
                        if (reader != null && reader.docFreq(term) == 1) {
                            isIndexed = true;
                        }
                    }

                    if (childFile.isDirectory()) {
                        folders.add(new FileDetail(childFile.getName(), childFile.getPath(), null,
                                childFile.length(), true, isIndexed));
                    } else {
                        String childPath = FileUtils.getFile(childFile.getPath().substring(rootPath.length()))
                                .getPath();
                        files.add(new FileDetail(childFile.getName(), childPath, childFile.getPath(),
                                childFile.length(), false, isIndexed));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new SilverpeasRuntimeException(e);
    } finally {
        // fermeture de l'index
        if (reader != null && isAdmin) {
            try {
                reader.close();
            } catch (IOException e) {
                SilverLogger.getLogger(this).warn(e);
            }
        }
    }
}

From source file:org.silverpeas.components.silvercrawler.servlets.SilverCrawlerFileServer.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String sourceFile = req.getParameter("SourceFile");
    String componentId = req.getParameter("ComponentId");
    String typeUpload = req.getParameter("TypeUpload");
    String path = req.getParameter("Path");

    try {//from   w w w .j a v a  2s .co m
        FileUtil.assertPathNotRelative(sourceFile);
    } catch (RelativeFileAccessException e) {
        SilverLogger.getLogger(this).warn(e);
        throwHttpForbiddenError();
    }

    MainSessionController mainSessionCtrl = getMainSessionController(req);
    String userId = mainSessionCtrl.getUserId();

    // Check user rights on identified component
    if (!OrganizationControllerProvider.getOrganisationController().isComponentAvailable(componentId, userId)) {
        throwHttpForbiddenError();
    }

    File rootPath = FileUtils
            .getFile(organizationController.getComponentParameterValue(componentId, "directory"));

    // 2 cas :
    // - tlchargement d'un zip dans rpertoire temporaire
    // - tlchargement d'un fichier depuis le rpertoire crawl
    File fileToSend;
    String type;
    File fileStat;
    if ("link".equals(typeUpload)) {
        type = Statistic.FILE;
        if (sourceFile.startsWith(FilenameUtils.separatorsToUnix(rootPath.getPath()))) {
            //Path into index is stored absolute and with Unix separators
            fileStat = fileToSend = FileUtils.getFile(sourceFile);
        } else {
            fileStat = fileToSend = FileUtils.getFile(rootPath, sourceFile);
        }
    } else {
        type = Statistic.DIRECTORY;
        fileToSend = FileUtils.getFile(FileRepositoryManager.getTemporaryPath(null, componentId), sourceFile);
        fileStat = FileUtils.getFile(rootPath, path);
    }

    sendFile(res, fileToSend);

    // ajout dans la table des tlchargements
    Statistic.addStat(userId, fileStat, componentId, type);
}

From source file:org.silverpeas.core.index.indexing.model.RepositoryIndexer.java

private void indexDirectory(Path directory, LocalDate creationDate, String creatorId, String action) {
    String unixDirectory = FilenameUtils.separatorsToUnix(directory.toString());
    if (ADD_ACTION.equals(action)) {
        // indexer le rpertoire
        FullIndexEntry fullIndexEntry = new FullIndexEntry(getComponentId(), "LinkedDir", unixDirectory);
        fullIndexEntry.setTitle(directory.toFile().getName());
        fullIndexEntry.setCreationDate(creationDate);
        fullIndexEntry.setCreationUser(creatorId);
        IndexEngineProxy.addIndexEntry(fullIndexEntry);
        count++;//from  www.  java 2 s  .  c om
    } else if (REMOVE_ACTION.equals(action)) {
        IndexEntryKey indexEntry = new IndexEntryKey(getComponentId(), "LinkedDir", unixDirectory);
        IndexEngineProxy.removeIndexEntry(indexEntry);
    }
}

From source file:org.silverpeas.core.index.indexing.model.RepositoryIndexer.java

private void indexFile(File file, LocalDate creationDate, String creatorId, String action) {

    String unixFilePath = FilenameUtils.separatorsToUnix(file.getPath());

    if (ADD_ACTION.equals(action)) {
        String fileName = file.getName();

        // Add file in index
        FullIndexEntry fullIndexEntry = new FullIndexEntry(getComponentId(), "LinkedFile", unixFilePath);
        fullIndexEntry.setTitle(fileName);

        boolean haveGotExtension = (fileName.lastIndexOf('.') != -1);

        if (haveGotExtension) {
            fullIndexEntry.setPreview(fileName.substring(0, fileName.lastIndexOf('.')));
        } else {// ww w  . j a  va 2s .c  om
            fullIndexEntry.setPreview(fileName);
        }

        fullIndexEntry.setCreationDate(creationDate);
        fullIndexEntry.setCreationUser(creatorId);

        if (haveGotExtension && !fileName.startsWith("~")) {
            String format = FileUtil.getMimeType(fileName);
            String lang = "fr";
            fullIndexEntry.addFileContent(unixFilePath, null, format, lang);
        }
        IndexEngineProxy.addIndexEntry(fullIndexEntry);
        count++;
    } else if (REMOVE_ACTION.equals(action)) {
        // Remove file from index
        IndexEntryKey indexEntry = new IndexEntryKey(getComponentId(), "LinkedFile", unixFilePath);
        IndexEngineProxy.removeIndexEntry(indexEntry);
    }
}

From source file:org.silverpeas.core.process.io.file.AbstractFileHandler.java

/**
 * Gets handled root directories of a base path from the session. (reads, writes, deletes)
 * @param basePath/* ww w.j av a2  s.c o  m*/
 * @param skipDeleted
 * @return
 */
protected Collection<String> getSessionHandledRootPathNames(final FileBasePath basePath,
        final boolean skipDeleted) {
    final Set<String> rootPathNames = new HashSet<>();
    if (isHandledPath(basePath)) {

        // reads and writes
        final String[] directories = getSessionPath(basePath).list(DirectoryFileFilter.DIRECTORY);
        if (directories != null) {
            rootPathNames.addAll(Arrays.asList(directories));
        }

        // deletes
        if (!skipDeleted) {
            String[] deletedFileNameParts;
            for (final File deleted : getMarkedToDelete(basePath)) {
                if (deleted.getPath().startsWith(basePath.getPath())) {
                    deletedFileNameParts = FilenameUtils
                            .separatorsToUnix(deleted.getPath().substring(basePath.getPath().length()))
                            .replaceAll("^/", "").split("/");
                    if (deletedFileNameParts != null && deletedFileNameParts.length > 0) {
                        rootPathNames.add(deletedFileNameParts[0]);
                    }
                }
            }
        }

        // Potential items to remove
        rootPathNames.remove(SESSION_TEMP_NODE);
        rootPathNames.remove(null);
        rootPathNames.remove("");
    }
    return rootPathNames;
}

From source file:org.silverpeas.core.util.file.FileUtil.java

/**
 * Asserts that the path doesn't contain relative navigation between pathes.
 *
 * @param path the path to check/*from  w w w  . j a  v a  2  s  .com*/
 * @throws RelativeFileAccessException when a relative path is detected.
 */
public static void assertPathNotRelative(String path) throws RelativeFileAccessException {
    String unixPath = FilenameUtils.separatorsToUnix(path);
    if (unixPath != null && (unixPath.contains("../") || unixPath.contains("/.."))) {
        throw new RelativeFileAccessException(
                SilverpeasExceptionMessages.failureOnGetting("path with relative parts", path));
    }
}