Example usage for org.apache.commons.vfs FileType FILE

List of usage examples for org.apache.commons.vfs FileType FILE

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileType FILE.

Prototype

FileType FILE

To view the source code for org.apache.commons.vfs FileType FILE.

Click Source Link

Document

A regular file.

Usage

From source file:org.bibalex.gallery.storage.BAGStorage.java

protected static List<String> listChildrenApacheHttpd(String dirUrlStr, FileType childrenType,
        DefaultHttpClient httpclient) throws BAGException {
    ArrayList<String> result = new ArrayList<String>();

    HttpGet httpReq = new HttpGet(dirUrlStr);
    try {/*from   w ww .j a va 2s. co  m*/

        HttpResponse response = httpclient.execute(httpReq);

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            throw new BAGException("Connection error: " + response.getStatusLine().toString());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if (entity.getContentType().getValue().startsWith("text/html")) {
                SAXBuilder saxBuilder = new SAXBuilder();

                saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
                saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
                saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                String htmlresponse = EntityUtils.toString(entity);
                String xmlResponse = light_html2xml.Html2Xml(htmlresponse);

                Document doc = saxBuilder.build(new StringReader(xmlResponse));
                XPath hrefXP = XPath.newInstance("//a/@href");

                for (Object obj : hrefXP.selectNodes(doc)) {
                    Attribute attr = (Attribute) obj;
                    String name = attr.getValue();
                    if (name.startsWith("/")) {
                        // parent dir
                        continue;
                    } else if (name.endsWith("/")) {
                        if (childrenType.equals(FileType.FOLDER)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name.substring(0, name.length() - 1));
                        }
                    } else {
                        if (childrenType.equals(FileType.FILE)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name);
                        }
                    }
                }
            }
        }

        return result;

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        httpReq.abort();
        throw ex;

    } catch (JDOMException e) {
        throw new BAGException(e);
    } finally {
        // connection closing is left for the caller to reuse connections

    }

}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generatePortletHTMLFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from   ww w .j  a v  a2  s  .  c o m*/
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            System.out.println("oaiId: " + oaiId);
            String url = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=html";
            statusCode = WAMCPStorage.myGetHttp(url);
            System.out.println(url + " ==> status code: " + statusCode);

            //            System.out.println(oaiId+" {Html}: "+statusCode);
            String urlDivOpt = host + "BAG-API/rest/desc/" + oaiId + "/transform?divOpt=true&type=html";
            statusCode = WAMCPStorage.myGetHttp(urlDivOpt);
            //            System.out.println(oaiId+" {Html, div}: "+statusCode);
            System.out.println(urlDivOpt + " ==> status code: " + statusCode);

            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, true);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, false);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generatePrintableMetadataHTMLFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*  ww  w  .j ava 2  s.c  o m*/
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            System.out.println("oaiId: " + oaiId);

            String urlMetadataHtml = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=meta";
            statusCode = WAMCPStorage.myGetHttp(urlMetadataHtml);
            System.out.println(urlMetadataHtml + " ==> status code: " + statusCode);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generateMARCFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from   w  w  w.  j  a  v a 2 s  .co m
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;
        String XMLFilePath;
        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            XMLFilePath = URLPathStrUtils.appendParts(dirUrlStr, childStr);

            //File XMLfile = new File(XMLFilePath);
            //   FileObject imageFO;

            //   imageFO = VFS.getManager().resolveFile(XMLFilePath);

            File XMLfile = null;
            try {
                XMLfile = File.createTempFile(FileUtils.makeSafeFileName(childStr), "msDescReleased");

                BAGStorage.readRemoteFile(XMLFilePath, new FileOutputStream(XMLfile));
            } catch (IOException e1) {
                this.handleException(e1);
            }

            //   URL url = new URL(XMLFilePath);
            //   InputStream is = url.openStream();

            try {
                WAMCPStorage.generateMARCFile(XMLfile, childStr, this.galleryBean.getGalleryRootUrlStr());
            } catch (WAMCPGeneralCorrectableException e) {
                // TODO Auto-generated catch block
                this.handleException(e);
            } catch (IOException e) {
                this.handleException(e);
            }

            //            int extIndx = childStr.indexOf('.');
            //            String localOaiId = childStr.substring(0, extIndx);
            //            
            //            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            //            String oaiId = oaiIdBuilder.buildId(localOaiId);
            //            System.out.println("oaiId: "+oaiId);
            //                        
            //            String urlMetadataHtml = host+"BAG-API/rest/desc/"+oaiId+"/transform?type=meta";
            //            statusCode = WAMCPStorage.myGetHttp(urlMetadataHtml);
            //            System.out.println(urlMetadataHtml +" ==> status code: "+statusCode);

        }

    } catch (BAGException e) {
        this.handleException(e);
    }
}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generateImagePdfFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");
    //      System.out.println("dirUrlStr: "+dirUrlStr);

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//w w w  . ja va  2  s . c  om
    String uri = request.getRequestURL().toString();
    //        System.out.println("uri: "+uri);
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //      String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    //        System.out.println("Host: "+host);

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        //         String rootUrlStr = this.galleryBean.getGalleryRootUrlStr();
        //         String tempUserName = this.wamcpSessionBBean.getUserName();
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            //            System.out.println("oaiId: "+oaiId);

            String urlImagesPdf = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=img";
            statusCode = WAMCPStorage.myGetHttp(urlImagesPdf);
            System.out.println(urlImagesPdf + " ==> status code: " + statusCode);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, true);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, false);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.codehaus.mojo.unix.core.CopyDirectoryOperation.java

public void perform(FileCollector fileCollector) throws IOException {
    Pattern pattern = this.pattern.isSome() ? Pattern.compile(this.pattern.some()._1()) : null;

    IncludeExcludeFileSelector selector = IncludeExcludeFileSelector.build(from.getName())
            .addStringIncludes(includes).addStringExcludes(excludes).create();

    List<FileObject> files = new ArrayList<FileObject>();
    from.findFiles(selector, true, files);

    for (FileObject f : files) {
        if (f.getName().getBaseName().equals("")) {
            continue;
        }//from  w  w  w. j a  va  2s .c o m

        String relativeName = from.getName().getRelativeName(f.getName());

        // Transform the path if the pattern is set. The input path will always have a leading slash
        // to make it possible to write more natural expressions.
        // With this one can write "/server-1.0.0/(.*)" => $1
        if (pattern != null) {
            String path = relativePath(relativeName).asAbsolutePath("/");
            relativeName = pattern.matcher(path).replaceAll(this.pattern.some()._2());
        }

        if (f.getType() == FileType.FILE) {
            fileCollector.addFile(f,
                    AssemblyOperationUtil.fromFileObject(to.add(relativeName), f, fileAttributes));
        } else if (f.getType() == FileType.FOLDER) {
            fileCollector.addDirectory(
                    AssemblyOperationUtil.dirFromFileObject(to.add(relativeName), f, directoryAttributes));
        }
    }
}

From source file:org.codehaus.mojo.unix.core.OperationTest.java

public void testExtractWithPattern() throws Exception {
    String archivePath = PlexusTestCase.getTestPath("src/test/resources/operation/extract.jar");

    FileSystemManager fsManager = VFS.getManager();
    FileObject archiveObject = fsManager.resolveFile(archivePath);
    assertEquals(FileType.FILE, archiveObject.getType());
    FileObject archive = fsManager.createFileSystem(archiveObject);

    FileObject fooLicense = archive.getChild("foo-license.txt");
    UnixFsObject.RegularFile fooLicenseUnixFile = fromFileObject(relativePath("licenses/foo-license.txt"),
            fooLicense, fileAttributes);

    FileObject barLicense = archive.getChild("mydir").getChild("bar-license.txt");
    UnixFsObject.RegularFile barLicenseUnixFile = fromFileObject(relativePath("licenses/bar-license.txt"),
            barLicense, fileAttributes);

    MockControl control = MockControl.createControl(FileCollector.class);
    FileCollector fileCollector = (FileCollector) control.getMock();

    control.expectAndReturn(fileCollector.addFile(barLicense, barLicenseUnixFile), fileCollector);
    control.expectAndReturn(fileCollector.addFile(fooLicense, fooLicenseUnixFile), fileCollector);
    control.replay();// w ww .j  a v  a2s.co  m

    new CopyDirectoryOperation(archive, relativePath("licenses"), asList("**/*license.txt"), null,
            some(p(".*/(.*license.*)", "$1")), fileAttributes, directoryAttributes).perform(fileCollector);

    control.verify();
}

From source file:org.docx4j.extras.vfs.LoadFromVFSZipFile.java

public OpcPackage getPackageFromFileObject(FileObject fo) throws Docx4JException {
    OpcPackage thePackage = null;/*from  ww  w .j  a  va 2s  .  c o  m*/

    if (!(fo instanceof LocalFile)) {
        //Non-Local file such as webdav file.
        //We make a temporary local copy of the file.
        //TODO: 28/03/08 - This is a second approach of dealing with non-local file.
        //The first approach which is more preferable and done in SVN version 233
        //does not create a temporary local copy of the file. 
        //It uses Commons-VFS "zip://" uri scheme to directly access the non-local file.
        //This second approach is being carried out because the writing operation cannot
        //use Commons-VFS "zip://" scheme as the scheme does not support writing to 
        //zip file yet.
        //TODO: 28/03/08 - DO NOT use "tmp://" scheme to make a temporary file. 
        //as it is going to fail. The current Commons-VFS library is still buggy. 
        StringBuffer sb = new StringBuffer("file:///");
        sb.append(System.getProperty("user.home"));
        sb.append("/.docx4j/tmp/");
        sb.append(fo.getName().getBaseName());
        String tmpPath = sb.toString().replace('\\', '/');

        LocalFile localCopy = null;
        try {
            localCopy = (LocalFile) VFS.getManager().resolveFile(tmpPath);
            localCopy.copyFrom(fo, new FileTypeSelector(FileType.FILE));
            localCopy.close();

            thePackage = getPackageFromLocalFile(localCopy);
        } catch (FileSystemException exc) {
            exc.printStackTrace();
            throw new Docx4JException("Could not create a temporary local copy", exc);
        } finally {
            if (localCopy != null) {
                try {
                    localCopy.delete();
                } catch (FileSystemException exc) {
                    exc.printStackTrace();
                    log.warn("Couldn't delete temporary file " + tmpPath);
                }
            }
        }
    } else {
        thePackage = getPackageFromLocalFile((LocalFile) fo);
    }

    return thePackage;
}

From source file:org.docx4j.extras.vfs.VFSDoc.java

/**
 * @param in//  w w w. j a  va2  s. co m
 * @return
 * @throws Exception
 */
public static WordprocessingMLPackage convert(org.apache.commons.vfs.FileObject in) throws Exception {

    LocalFile localCopy = null;
    if (!(in instanceof LocalFile)) {

        StringBuffer sb = new StringBuffer("file:///");
        sb.append(System.getProperty("user.home"));
        sb.append("/.docx4j/tmp/");
        sb.append(in.getName().getBaseName());
        String tmpPath = sb.toString().replace('\\', '/');

        try {
            localCopy = (LocalFile) VFS.getManager().resolveFile(tmpPath);
            localCopy.copyFrom(in, new FileTypeSelector(FileType.FILE));
            localCopy.close();
        } catch (FileSystemException exc) {
            exc.printStackTrace();
            throw new Docx4JException("Could not create a temporary local copy", exc);
        } finally {
            if (localCopy != null) {
                try {
                    localCopy.delete();
                } catch (FileSystemException exc) {
                    exc.printStackTrace();
                    log.warn("Couldn't delete temporary file " + tmpPath);
                }
            }
        }
    } else {
        localCopy = (LocalFile) in;
    }

    String localPath = VFSUtils.getLocalFilePath(in);
    if (localPath == null) {
        throw new Docx4JException("Couldn't get local path");
    }

    return Doc.convert(new FileInputStream(localPath));
}

From source file:org.efaps.webdav4vfs.test.ramvfs.RamFileSystem.java

/**
 * Import the given file with the name relative to the given root.
 *
 * @param _fo       file object/*from w  w  w  . ja  va 2  s.  com*/
 * @param _root     root file object
 * @throws FileSystemException if file object could not be imported
 */
void toRamFileObject(final FileObject _fo, final FileObject _root) throws FileSystemException {
    final RamFileObject memFo = (RamFileObject) this
            .resolveFile(_fo.getName().getPath().substring(_root.getName().getPath().length()));
    if (_fo.getType().hasChildren()) {
        // Create Folder
        memFo.createFolder();
        // Import recursively
        final FileObject[] fos = _fo.getChildren();
        for (int i = 0; i < fos.length; i++) {
            final FileObject child = fos[i];
            this.toRamFileObject(child, _root);
        }
    } else if (_fo.getType().equals(FileType.FILE)) {
        // Read bytes
        try {
            final InputStream is = _fo.getContent().getInputStream();
            try {
                final OutputStream os = new BufferedOutputStream(memFo.getOutputStream(), 512);
                int i;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
            } finally {
                try {
                    is.close();
                } catch (final IOException e) {
                    // ignore on close exception
                }
            }
        } catch (final IOException e) {
            throw new FileSystemException(e.getClass().getName() + " " + e.getMessage());
        }
    } else {
        throw new FileSystemException("File is not a folder nor a file " + memFo);
    }
}