Example usage for org.apache.commons.vfs2 FileObject createFile

List of usage examples for org.apache.commons.vfs2 FileObject createFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject createFile.

Prototype

void createFile() throws FileSystemException;

Source Link

Document

Creates this file, if it does not exist.

Usage

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java

protected FileObject initialDeployScriptModule(WGCSSJSModule script) throws IOException, InstantiationException,
        IllegalAccessException, WGAPIException, WGDesignSyncException {

    if (script.isMetadataModule()) {
        return null;
    }/*from  w w w .j  a v  a  2 s  . c o  m*/

    ScriptInformation info = DesignDirectory.getScriptInformation(script.getCodeType());
    if (info == null) {
        _log.warn("Cannot deploy unknown script code type: " + script.getCodeType());
        return null;
    }

    // Get script type folder
    FileObject scriptTypeFolder = getScriptTypeFolder(info.getFolder());

    // Eventually create intermediate directories
    List<String> path = WGUtils.deserializeCollection(script.getName(), ":", true);
    String localName = (String) path.get(path.size() - 1);
    FileObject currentDir = scriptTypeFolder;
    for (int i = 0; i < path.size() - 1; i++) {
        currentDir = currentDir.resolveFile((String) path.get(i));
        if (!currentDir.exists()) {
            _log.info("Creating script category directory" + getRelativePath(currentDir));
            try {
                currentDir.createFolder();
            } catch (FileSystemException e) {
                throw new WGInitialDeployException(
                        "Could not create script category folder '" + getRelativePath(currentDir) + "'", e);
            }
        } else if (!currentDir.getType().equals(FileType.FOLDER)) {
            throw new WGInitialDeployException(
                    "Cannot deploy " + script.getDocumentKey() + " to sync folder because the directory name '"
                            + path.get(i) + "' is already used by another file");
        }
    }

    // Create code file
    FileObject codeFile = currentDir.resolveFile(localName + info.getSuffix());
    _log.info("Creating script module file " + getRelativePath(codeFile));
    try {
        codeFile.createFile();
    } catch (FileSystemException e) {
        throw new WGInitialDeployException(
                "Could not create script code file '" + codeFile.getName().getPathDecoded() + "'");
    }
    Writer writer = createWriter(codeFile);
    writer.write(script.getCode());
    writer.close();

    // Create metadata file
    ScriptMetadata metaData = new ScriptMetadata(script);
    FileObject metadataDir = currentDir.resolveFile(DesignDirectory.NAME_METADATADIR);
    if (!metadataDir.exists()) {
        _log.info("Creating script metadata directory " + getRelativePath(metadataDir));
        try {
            metadataDir.createFolder();
        } catch (FileSystemException e) {
            throw new WGInitialDeployException(
                    "Could not create metadata folder '" + getRelativePath(metadataDir) + "'");
        }
    }
    FileObject metadataFile = metadataDir.resolveFile(localName + DesignDirectory.SUFFIX_METADATA);
    _log.info("Creating script metadata file " + getRelativePath(metadataFile));
    writer = createWriter(metadataFile);
    writer.write(_xstream.toXML(metaData.getInfo()));
    writer.close();

    return codeFile;
}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java

protected FileObject initialDeployTMLModule(WGTMLModule mod) throws IOException, InstantiationException,
        IllegalAccessException, WGAPIException, WGDesignSyncException {

    // Find/create media key folder
    FileObject mediaKeyFolder = getTmlFolder().resolveFile(mod.getMediaKey());
    if (!mediaKeyFolder.exists()) {
        _log.info("Creating media key folder " + getRelativePath(mediaKeyFolder));
        try {/*from  w w w.j  av a  2  s.c o  m*/
            mediaKeyFolder.createFolder();
        } catch (FileSystemException e) {
            throw new WGInitialDeployException(
                    "Could not create media key folder '" + mediaKeyFolder.getName().getPathDecoded() + "'");
        }
    }

    // Eventually create intermediate directories
    List<String> path = WGUtils.deserializeCollection(mod.getName(), ":", true);
    String localName = (String) path.get(path.size() - 1);
    FileObject currentDir = mediaKeyFolder;
    for (int i = 0; i < path.size() - 1; i++) {
        currentDir = currentDir.resolveFile((String) path.get(i));
        if (!currentDir.exists()) {
            _log.info("Creating tml category directory " + getRelativePath(currentDir));
            try {
                currentDir.createFolder();
            } catch (FileSystemException e) {
                throw new WGInitialDeployException(
                        "Could not create tml category folder '" + getRelativePath(currentDir) + "'", e);
            }
        } else if (!currentDir.getType().equals(FileType.FOLDER)) {
            throw new WGInitialDeployException(
                    "Cannot deploy " + mod.getDocumentKey() + " to sync folder because the directory name '"
                            + path.get(i) + "' is already used by another file");

        }
    }

    // Create code file
    FileObject tmlCodeFile = currentDir.resolveFile(localName + DesignDirectory.SUFFIX_TML);
    _log.info("Creating tml module file " + getRelativePath(tmlCodeFile));
    try {
        tmlCodeFile.createFile();
    } catch (FileSystemException e) {
        throw new WGInitialDeployException(
                "Could not create tml code file '" + getRelativePath(tmlCodeFile) + "'");
    }
    Writer writer = createWriter(tmlCodeFile);
    writer.write(mod.getCode());
    writer.close();

    // Create metadata file
    TMLMetadata metaData = new TMLMetadata(mod);
    FileObject metadataDir = currentDir.resolveFile(DesignDirectory.NAME_METADATADIR);
    if (!metadataDir.exists()) {
        _log.info("Creating tml metadata directory " + getRelativePath(metadataDir));
        try {
            metadataDir.createFolder();
        } catch (FileSystemException e) {
            throw new WGInitialDeployException(
                    "Could not create metadata folder '" + metadataDir.getName().getPathDecoded() + "'");
        }
    }

    FileObject metadataFile = metadataDir.resolveFile(localName + DesignDirectory.SUFFIX_METADATA);
    _log.info("Creating tml metadata file " + getRelativePath(metadataFile));
    writer = createWriter(metadataFile);
    writer.write(_xstream.toXML(metaData.getInfo()));
    writer.close();

    return tmlCodeFile;
}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java

public WGDocumentCore createDesignDocument(int type, String name, String mediaKey)
        throws WGAuthorisationException, WGCreationException {

    try {//from   w ww .j a va  2  s  .  c  o  m
        switch (type) {

        case WGDocument.TYPE_TML: {
            FileObject newTml = getTmlFolder()
                    .resolveFile(mediaKey.toLowerCase() + "/" + name.replace(":", "/") + ".tml");
            if (newTml.exists()) {
                throw new WGCreationException(
                        "Document already exists: " + (new WGDocumentKey(type, name, mediaKey)).toString());
            }
            newTml.createFile();
            break;
        }

        case WGDocument.TYPE_CSSJS: {
            String suffix = DesignDirectory.getScriptInformation(mediaKey).getSuffix();
            FileObject newScript = getScriptTypeFolder(mediaKey)
                    .resolveFile(mediaKey.toLowerCase() + "/" + name.replace(":", "/") + suffix);
            if (newScript.exists()) {
                throw new WGCreationException(
                        "Document already exists: " + (new WGDocumentKey(type, name, mediaKey)).toString());
            }
            newScript.createFile();
            break;
        }

        case WGDocument.TYPE_FILECONTAINER: {
            FileObject newFC = getFilesFolder().resolveFile(name.replace(":", "/"));
            if (newFC.exists()) {
                throw new WGCreationException(
                        "Document already exists: " + (new WGDocumentKey(type, name, mediaKey)).toString());
            }
            newFC.createFolder();
            break;
        }

        }

        clearCache();
        return getDesignObject(type, name, mediaKey);
    } catch (Exception e) {
        throw new WGCreationException(
                "Exception creating design document " + (new WGDocumentKey(type, name, mediaKey)).toString(),
                e);
    }

}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java

protected FileObject initialDeployFileContainer(WGFileContainer con) throws IOException, InstantiationException,
        IllegalAccessException, WGAPIException, WGDesignSyncException {

    // Create container folder
    FileObject containerFolder = getFilesFolder().resolveFile(con.getName());
    _log.info("Creating file container folder " + getRelativePath(containerFolder));
    try {//from  w w w  .  j a  v  a 2  s .c o m
        containerFolder.createFolder();
    } catch (FileSystemException e) {
        throw new WGInitialDeployException(
                "Could not create file container folder '" + containerFolder.getName().getPathDecoded() + "'",
                e);
    }

    // Create metadata file
    FCMetadata metaData = new FCMetadata(con);
    FileObject metadataFile = containerFolder
            .resolveFile(AbstractDesignFile.FILECONTAINER_METADATA_FILENAME + DesignDirectory.SUFFIX_METADATA);
    _log.info("Creating file container metadata file " + getRelativePath(metadataFile));
    Writer writer = createWriter(metadataFile);
    writer.write(_xstream.toXML(metaData.getInfo()));
    writer.close();

    // Create contained files
    Iterator fileNames = con.getFileNames().iterator();
    String fileName;
    FileObject file;
    while (fileNames.hasNext()) {
        fileName = (String) fileNames.next();
        InputStream in = con.getFileData(fileName);
        file = containerFolder.resolveFile(fileName);
        _log.info("Creating file container file " + getRelativePath(file));
        try {
            file.createFile();
        } catch (FileSystemException e) {
            throw new WGInitialDeployException(
                    "Could not create container file '" + getRelativePath(file) + "'", e);
        }
        OutputStream out = file.getContent().getOutputStream();
        WGUtils.inToOut(in, out, 2048);
        in.close();
        out.close();
    }

    return containerFolder;

}

From source file:fr.cls.atoll.motu.processor.iso19139.ServiceMetadata.java

/**
 * Marshall iso19139./*from   w w  w . j  a v a  2  s.c  o m*/
 * 
 * @param element the element
 * @param xmlFile the xml file
 * 
 * @throws MotuMarshallException the motu marshall exception
 * @throws FileSystemException the file system exception
 * @throws MotuException the motu exception
 */
public void marshallIso19139(JAXBElement<?> element, String xmlFile)
        throws MotuMarshallException, FileSystemException, MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("marshallIso19139(JAXBElement<?>, String) - entering");
    }

    FileObject fileObject = Organizer.resolveFile(xmlFile);
    fileObject.createFile();

    marshallIso19139(element, fileObject);

    if (LOG.isDebugEnabled()) {
        LOG.debug("marshallIso19139(JAXBElement<?>, String) - exiting");
    }
}

From source file:com.google.code.docbook4j.renderer.BaseRenderer.java

public InputStream render() throws Docbook4JException {

    assertNotNull(xmlResource, "Value of the xml source should be not null!");

    FileObject xsltResult = null;
    FileObject xmlSourceFileObject = null;
    FileObject xslSourceFileObject = null;
    FileObject userConfigXmlSourceFileObject = null;

    try {/*w w  w  .  j  av a  2  s .  com*/

        xmlSourceFileObject = FileObjectUtils.resolveFile(xmlResource);
        if (xslResource != null) {
            xslSourceFileObject = FileObjectUtils.resolveFile(xslResource);
        } else {
            xslSourceFileObject = getDefaultXslStylesheet();
        }

        if (userConfigXmlResource != null) {
            userConfigXmlSourceFileObject = FileObjectUtils.resolveFile(userConfigXmlResource);
        }

        SAXParserFactory factory = createParserFactory();
        final XMLReader reader = factory.newSAXParser().getXMLReader();

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {

                log.debug("Resolving file {}", systemId);

                FileObject inc = FileObjectUtils.resolveFile(systemId);
                return new InputSource(inc.getContent().getInputStream());
            }
        };

        // prepare xml sax source
        ExpressionEvaluatingXMLReader piReader = new ExpressionEvaluatingXMLReader(reader, vars);
        piReader.setEntityResolver(resolver);

        SAXSource source = new SAXSource(piReader,
                new InputSource(xmlSourceFileObject.getContent().getInputStream()));
        source.setSystemId(xmlSourceFileObject.getURL().toExternalForm());

        // prepare xslt result
        xsltResult = FileObjectUtils.resolveFile("tmp://" + UUID.randomUUID().toString());
        xsltResult.createFile();

        // create transofrmer and do transformation
        final Transformer transformer = createTransformer(xmlSourceFileObject, xslSourceFileObject);
        transformer.transform(source, new StreamResult(xsltResult.getContent().getOutputStream()));

        // do post processing
        FileObject target = postProcess(xmlSourceFileObject, xslSourceFileObject, xsltResult,
                userConfigXmlSourceFileObject);

        FileObjectUtils.closeFileObjectQuietly(xsltResult);
        FileObjectUtils.closeFileObjectQuietly(target);
        return target.getContent().getInputStream();

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (ParserConfigurationException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error transofrming xml !", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(xmlSourceFileObject);
        FileObjectUtils.closeFileObjectQuietly(xslSourceFileObject);
    }

}

From source file:org.apache.commons.vfs2.example.Shell.java

/**
 * Does a 'touch' command./* w  w w.j a  v  a2s.  c  om*/
 */
private void touch(final String[] cmd) throws Exception {
    if (cmd.length < 2) {
        throw new Exception("USAGE: touch <path>");
    }
    final FileObject file = mgr.resolveFile(cwd, cmd[1]);
    if (!file.exists()) {
        file.createFile();
    }
    file.getContent().setLastModifiedTime(System.currentTimeMillis());
}

From source file:org.apache.hadoop.gateway.topology.file.FileTopologyProviderTest.java

private FileObject createFile(FileObject parent, String name, String resource, long timestamp)
        throws IOException {
    FileObject file = parent.resolveFile(name);
    if (!file.exists()) {
        file.createFile();
    }/*from  w w w. ja  va2 s .  com*/
    InputStream input = ClassLoader.getSystemResourceAsStream(resource);
    OutputStream output = file.getContent().getOutputStream();
    IOUtils.copy(input, output);
    output.flush();
    input.close();
    output.close();
    file.getContent().setLastModifiedTime(timestamp);
    assertTrue("Failed to create test file " + file.getName().getFriendlyURI(), file.exists());
    assertTrue("Failed to populate test file " + file.getName().getFriendlyURI(),
            file.getContent().getSize() > 0);

    //    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    //    IOUtils.copy( file.getContent().getInputStream(), buffer );
    //    System.out.println( new String( buffer.toString( "UTF-8" ) ) );

    return file;
}

From source file:org.apache.olingo.fit.utils.FSManager.java

public final FileObject putInMemory(final InputStream is, final String path) throws IOException {
    LOG.info("Write in memory {}", path);
    final FileObject memObject = fsManager.resolveFile(MEM_PREFIX + path);

    if (memObject.exists()) {
        memObject.delete();//from   w w  w . j  a  v a 2  s .  c o  m
    }

    // create in-memory file
    memObject.createFile();

    // read in-memory content
    final OutputStream os = memObject.getContent().getOutputStream();
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);

    return memObject;
}

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

/**
 * Acquires a file item lock before processing the item, guaranteing that
 * the file is not processed while it is being uploaded and/or the item is
 * not processed by two listeners//from ww w.  j  a va 2s  . c om
 * 
 * @param fsManager
 *            used to resolve the processing file
 * @param fo
 *            representing the processing file item
 * @param fso
 *            represents file system options used when resolving file from file system manager.
 * @return boolean true if the lock has been acquired or false if not
 */
public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo, VFSParamDTO paramDTO,
        FileSystemOptions fso) {

    // generate a random lock value to ensure that there are no two parties
    // processing the same file
    Random random = new Random();
    // Lock format random:hostname:hostip:time
    String strLockValue = String.valueOf(random.nextLong());
    try {
        strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostName();
        strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException ue) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to get the Hostname or IP.");
        }
    }
    strLockValue += STR_SPLITER + (new Date()).getTime();
    byte[] lockValue = strLockValue.getBytes();

    try {
        // check whether there is an existing lock for this item, if so it is assumed
        // to be processed by an another listener (downloading) or a sender (uploading)
        // lock file is derived by attaching the ".lock" second extension to the file name
        String fullPath = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject lockObject = fsManager.resolveFile(fullPath + ".lock", fso);
        if (lockObject.exists()) {
            log.debug("There seems to be an external lock, aborting the processing of the file "
                    + maskURLPassword(fo.getName().getURI())
                    + ". This could possibly be due to some other party already "
                    + "processing this file or the file is still being uploaded");
            if (paramDTO != null && paramDTO.isAutoLockRelease()) {
                releaseLock(lockValue, strLockValue, lockObject, paramDTO.isAutoLockReleaseSameNode(),
                        paramDTO.getAutoLockReleaseInterval());
            }
        } else {
            // write a lock file before starting of the processing, to ensure that the
            // item is not processed by any other parties
            lockObject.createFile();
            OutputStream stream = lockObject.getContent().getOutputStream();
            try {
                stream.write(lockValue);
                stream.flush();
                stream.close();
            } catch (IOException e) {
                lockObject.delete();
                log.error(
                        "Couldn't create the lock file before processing the file " + maskURLPassword(fullPath),
                        e);
                return false;
            } finally {
                lockObject.close();
            }

            // check whether the lock is in place and is it me who holds the lock. This is
            // required because it is possible to write the lock file simultaneously by
            // two processing parties. It checks whether the lock file content is the same
            // as the written random lock value.
            // NOTE: this may not be optimal but is sub optimal
            FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock", fso);
            if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) {
                return true;
            }
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " before processing");
    }
    return false;
}