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

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

Introduction

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

Prototype

boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test(expected = ClassNotFoundException.class)
public void testFindFailReading() throws ClassNotFoundException, IOException, KettleFileException {
    FileObject myFile = KettleVFS.getFileObject("ram://testFindFailReading");
    try (FileObject fileObject = myFile) {
        when(bundleWiring.findEntries(/* w w  w . j  a va  2s  . c om*/
                "/" + ShimBridgingClassloader.class.getPackage().getName().replace(".", "/"),
                ShimBridgingClassloader.class.getSimpleName() + ".class", 0))
                        .thenReturn(Arrays.asList(fileObject.getURL()));
        shimBridgingClassloader.findClass(ShimBridgingClassloader.class.getCanonicalName());
    } finally {
        myFile.delete();
    }
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

public void attach() {

    selectedDir = cb.getVfsUrl();//  w  w w. j  ava 2  s . c o m
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.sonicle.webtop.mail.MultipartIterator.java

/**
 * Creates a file on disk from the current mulitpart element
 * @param fileName the name of the multipart file
 *//*from  w  w w. j  a  va2 s  . c  o  m*/
protected FileObject createVFSFile(String filename) throws IOException {

    FileObject vfsfile = fileObjectDir.resolveFile(filename);
    int n = 0;
    String xfilename = filename;
    String xext = null;
    int ix = xfilename.lastIndexOf(".");
    if (ix > 0) {
        xext = xfilename.substring(ix + 1);
        xfilename = xfilename.substring(0, ix);
    }
    while (vfsfile.exists()) {
        ++n;
        filename = xfilename + " (" + n + ")";
        if (xext != null)
            filename += "." + xext;
        vfsfile = fileObjectDir.resolveFile(filename);
    }
    OutputStream fos = vfsfile.getContent().getOutputStream();
    try {
        writeStream(fos);
    } catch (IOException exc) {
        vfsfile.delete();
    }
    return vfsfile;
}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to execute file move operation.
 * //from   ww  w .j  a  v a 2 s .  c  o  m
 * @param file
 *            FileObject of the file to be moved
 * @param toDirectoryPath
 * @return true if give file was a file and it was successfully moved to
 *         destination directory. False if given file is not a file or given
 *         destination directory is not a directory
 * @throws FileSystemException
 *             If file move operation fails
 */
private boolean moveFile(FileObject file, String toDirectoryPath, boolean lockEnabled)
        throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        String targetPath = toDirectoryPath + "/" + file.getName().getBaseName();
        String lockFilePath = null;
        if (lockEnabled) {
            lockFilePath = createLockFile(targetPath);
        }
        FileObject newLocation = resolveFile(targetPath);
        try {
            log.debug("About to move " + fileObjectNameForDebug(file) + " to "
                    + fileObjectNameForDebug(newLocation));

            if (options.isStreamingTransferEnabled()) {
                streamFromFileToFile(file, resolveFile(targetPath));
            } else {
                newLocation.copyFrom(file, Selectors.SELECT_SELF);
            }

            newLocation.close();
            file.delete();
            file.close();
            log.debug("File moved to " + fileObjectNameForDebug(newLocation));
        } finally {
            if (lockFilePath != null) {
                deleteLockFile(lockFilePath);
            }
        }
        return true;
    } else {
        return false;
    }
}

From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Delete the file repsented by the file parameter.
 * /*  w w  w  . jav  a 2 s. c  o  m*/
 * @param file the file
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean deleteFile(FileObject file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(FileObject) - entering");
    }

    boolean deleted = false;
    try {

        if (file.exists()) {
            if (file.getType() != FileType.FILE) {
                throw new MotuException(String.format("Delete file '%s' is rejected: it is a folder. ",
                        file.getName().toString()));
            }

            deleted = file.delete();
        }
    } catch (FileSystemException e) {
        LOG.error("deleteFile(FileObject)", e);

        // throw new MotuException(String.format("Unable to copy file '%s' to '%s'",
        // foSrc.getURL().toString(), foDest.getURL().toString()), e);
        throw new MotuException(String.format("Unable to delete '%s'", file.getName().toString()), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(FileObject) - exiting");
    }
    return deleted;
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test(expected = InstantiationException.class)
public void testCreateFalureNoMatching()
        throws ClassNotFoundException, InvocationTargetException, InstantiationException, KettlePluginException,
        IllegalAccessException, KettleFileException, IOException {
    String testName = "testName";

    String canonicalName = ValueMetaInteger.class.getCanonicalName();
    FileObject myFile = KettleVFS.getFileObject("ram://testCreateSuccessWithArgs");
    try (FileObject fileObject = myFile) {
        try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) {
            IOUtils.copy(//from w w w.  j  a  v a  2s  . co  m
                    getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"),
                    outputStream);
        }
        String packageName = ValueMetaInteger.class.getPackage().getName();
        when(bundleWiring.findEntries("/" + packageName.replace(".", "/"),
                ValueMetaInteger.class.getSimpleName() + ".class", 0))
                        .thenReturn(Arrays.asList(fileObject.getURL()));
        when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() {
            @Override
            public Class<?> answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader())
                        .loadClass((String) arguments[0], (boolean) arguments[1]);
            }
        });
        when(pluginClassloaderGetter.getPluginClassloader(LifecyclePluginType.class.getCanonicalName(),
                ShimBridgingClassloader.HADOOP_SPOON_PLUGIN)).thenReturn(parentClassLoader);
        Object o = ShimBridgingClassloader.create(bundleContext, canonicalName, Arrays.<Object>asList(1.1));
    } finally {
        myFile.delete();
    }
}

From source file:maspack.fileutil.FileCacher.java

public File cache(URIx uri, File cacheFile, FileTransferMonitor monitor) throws FileSystemException {

    // For atomic operation, first download to temporary directory
    File tmpCacheFile = new File(cacheFile.getAbsolutePath() + TMP_EXTENSION);
    URIx cacheURI = new URIx(cacheFile.getAbsoluteFile());
    URIx tmpCacheURI = new URIx(tmpCacheFile.getAbsoluteFile());
    FileObject localTempFile = manager.resolveFile(tmpCacheURI.toString(true));
    FileObject localCacheFile = manager.resolveFile(cacheURI.toString(true));

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }/*from   w ww  .  j a  va  2  s. c  o  m*/

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(localTempFile, remoteFile, -1, cacheFile.getName());
        monitor.start();
        monitor.fireStartEvent(localTempFile);
    }

    // transfer content
    try {
        if (remoteFile.isFile()) {
            localTempFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        } else if (remoteFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            localTempFile.copyFrom(remoteFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(localTempFile);
        }
    } catch (Exception e) {
        // try to delete local file
        localTempFile.delete();
        throw new RuntimeException(
                "Failed to complete transfer of " + remoteFile.getURL() + " to " + localTempFile.getURL(), e);
    } finally {
        // close files if we need to
        localTempFile.close();
        remoteFile.close();
        if (monitor != null) {
            monitor.release(localTempFile);
            monitor.stop();
        }

    }

    // now that the copy is complete, do a rename operation
    try {
        if (tmpCacheFile.isDirectory()) {
            SafeFileUtils.moveDirectory(tmpCacheFile, cacheFile);
        } else {
            SafeFileUtils.moveFile(tmpCacheFile, cacheFile);
        }
    } catch (Exception e) {
        localCacheFile.delete(); // delete if possible
        throw new RuntimeException("Failed to atomically move " + "to " + localCacheFile.getURL(), e);
    }

    return cacheFile;

}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test
public void testFindClassSuccess() throws ClassNotFoundException, IOException, KettleFileException {
    String canonicalName = ShimBridgingClassloader.class.getCanonicalName();
    FileObject myFile = KettleVFS.getFileObject("ram://testFindClassSuccess");
    try (FileObject fileObject = myFile) {
        try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) {
            IOUtils.copy(//from  w  w  w  . j  a  v  a  2  s. c  o m
                    getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"),
                    outputStream);
        }
        String packageName = ShimBridgingClassloader.class.getPackage().getName();
        when(bundleWiring.findEntries("/" + packageName.replace(".", "/"),
                ShimBridgingClassloader.class.getSimpleName() + ".class", 0))
                        .thenReturn(Arrays.asList(fileObject.getURL()));
        when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() {
            @Override
            public Class<?> answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader())
                        .loadClass((String) arguments[0], (boolean) arguments[1]);
            }
        });
        Class<?> shimBridgingClassloaderClass = shimBridgingClassloader.findClass(canonicalName);
        assertEquals(canonicalName, shimBridgingClassloaderClass.getCanonicalName());
        assertEquals(shimBridgingClassloader, shimBridgingClassloaderClass.getClassLoader());
        assertEquals(packageName, shimBridgingClassloaderClass.getPackage().getName());
    } finally {
        myFile.delete();
    }
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test
public void testLoadClassFindClass() throws ClassNotFoundException, IOException, KettleFileException {
    String canonicalName = ShimBridgingClassloader.class.getCanonicalName();
    FileObject myFile = KettleVFS.getFileObject("ram://testLoadClassFindClass");
    try (FileObject fileObject = myFile) {
        try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) {
            IOUtils.copy(/*from w  ww . j a v a2s.  c  o  m*/
                    getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"),
                    outputStream);
        }
        String packageName = ShimBridgingClassloader.class.getPackage().getName();
        when(bundleWiring.findEntries("/" + packageName.replace(".", "/"),
                ShimBridgingClassloader.class.getSimpleName() + ".class", 0))
                        .thenReturn(Arrays.asList(fileObject.getURL()));
        when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() {
            @Override
            public Class<?> answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader())
                        .loadClass((String) arguments[0], (boolean) arguments[1]);
            }
        });
        Class<?> shimBridgingClassloaderClass = shimBridgingClassloader.loadClass(canonicalName, true);
        assertEquals(canonicalName, shimBridgingClassloaderClass.getCanonicalName());
        assertEquals(shimBridgingClassloader, shimBridgingClassloaderClass.getClassLoader());
        assertEquals(packageName, shimBridgingClassloaderClass.getPackage().getName());
        Class<?> shimBridgingClassloaderClass2 = shimBridgingClassloader.loadClass(canonicalName, false);
        assertEquals(shimBridgingClassloaderClass, shimBridgingClassloaderClass2);
    } finally {
        myFile.delete();
    }
}

From source file:net.sf.jabb.web.action.VfsTreeAction.java

/**
 * AJAX tree functions/* w  w w .  j a  v  a 2  s .  c o m*/
 */
public String execute() {
    normalizeTreeRequest();
    JsTreeResult result = new JsTreeResult();

    final AllFileSelector ALL_FILES = new AllFileSelector();
    FileSystemManager fsManager = null;
    FileObject rootFile = null;
    FileObject file = null;
    FileObject referenceFile = null;
    try {
        fsManager = VfsUtility.getManager();
        rootFile = fsManager.resolveFile(rootPath, fsOptions);

        if (JsTreeRequest.OP_GET_CHILDREN.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getId();
            List<JsTreeNodeData> nodes = null;
            try {
                nodes = getChildNodes(rootFile, parentPath);
                if (requestData.isRoot() && rootNodeName != null) { // add root node
                    JsTreeNodeData rootNode = new JsTreeNodeData();
                    rootNode.setData(rootNodeName);
                    Map<String, Object> attr = new HashMap<String, Object>();
                    rootNode.setAttr(attr);
                    attr.put("id", ".");
                    attr.put("rel", "root");
                    attr.put("fileType", FileType.FOLDER.toString());
                    rootNode.setChildren(nodes);
                    rootNode.setState(JsTreeNodeData.STATE_OPEN);
                    nodes = new LinkedList<JsTreeNodeData>();
                    nodes.add(rootNode);
                }
            } catch (Exception e) {
                log.error("Cannot get child nodes for: " + parentPath, e);
                nodes = new LinkedList<JsTreeNodeData>();
            }
            responseData = nodes;
        } else if (JsTreeRequest.OP_REMOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            try {
                file = rootFile.resolveFile(path, NameScope.DESCENDENT);
                boolean wasDeleted = false;
                if (file.getType() == FileType.FILE) {
                    wasDeleted = file.delete();
                } else {
                    wasDeleted = file.delete(ALL_FILES) > 0;
                }
                result.setStatus(wasDeleted);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot delete: " + path, e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_CREATE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getReferenceId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(parentPath, NameScope.DESCENDENT_OR_SELF);
                file = referenceFile.resolveFile(name, NameScope.CHILD);
                file.createFolder();
                result.setStatus(true);
                result.setId(rootFile.getName().getRelativeName(file.getName()));
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot create folder '" + name + "' under '" + parentPath + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_RENAME_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(path, NameScope.DESCENDENT);
                file = referenceFile.getParent().resolveFile(name, NameScope.CHILD);
                referenceFile.moveTo(file);
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot rename '" + path + "' to '" + name + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_MOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String newParentPath = requestData.getReferenceId();
            String originalPath = requestData.getId();
            try {
                referenceFile = rootFile.resolveFile(originalPath, NameScope.DESCENDENT);
                file = rootFile.resolveFile(newParentPath, NameScope.DESCENDENT_OR_SELF)
                        .resolveFile(referenceFile.getName().getBaseName(), NameScope.CHILD);
                if (requestData.isCopy()) {
                    file.copyFrom(referenceFile, ALL_FILES);
                } else {
                    referenceFile.moveTo(file);
                }
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot move '" + originalPath + "' to '" + newParentPath + "'", e);
            }
            responseData = result;
        }
    } catch (FileSystemException e) {
        log.error("Cannot perform file operation.", e);
    } finally {
        VfsUtility.close(fsManager, file, referenceFile, rootFile);
    }
    return SUCCESS;
}