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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Take specified action to either move or delete the processed file, depending on the outcome
 * @param entry the PollTableEntry for the file that has been processed
 * @param fileObject the FileObject representing the file to be moved or deleted
 *//*from  w w  w  . jav a 2  s.com*/
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
            }
            break;

        case PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }
            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + dest.getName().getURI());
            }
            try {
                fileObject.moveTo(dest);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + fileObject + " to " + moveToDirectoryURI, e);
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + fileObject);
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + fileObject;
                    log.error(msg);
                    throw new AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + fileObject, e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : " + moveToDirectoryURI, e);
    }
}

From source file:com.googlecode.vfsjfilechooser2.plaf.metal.MetalVFSFileChooserUI.java

private String fileNameString(FileObject fileObject) {
    if (fileObject == null) {
        return null;
    } else {//w  w w  .  j a  v  a2 s .  co m
        VFSJFileChooser fc = getFileChooser();

        if ((fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled())
                || (fc.isDirectorySelectionEnabled() && fc.isFileSelectionEnabled()
                        && fc.getFileSystemView().isFileSystemRoot(fileObject))) {
            String url = null;

            try {
                url = fileObject.getURL().toExternalForm();
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }

            return url;
        } else {
            return fileObject.getName().getBaseName();
        }
    }
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void deleteFSDesignResource(RemoteSession session, String path) throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*w w  w. j a  va  2 s .  com*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject resource = fsSource.getDir().resolveFile(path);

            String basePath = fsSource.getDir().getURL().getPath();
            String resourcePath = resource.getURL().getPath();
            if (!resourcePath.startsWith(basePath)) {
                throw new WGAServiceException(
                        new IllegalArgumentException("Illegal design resource path '" + path + "'."));
            }

            if (resource.exists()) {
                resource.delete(new FileSelector() {

                    public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                        return true;
                    }

                    public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception {
                        return true;
                    }

                });
                clearDesignFileCache(fsSource, fsSource.getDir().getName().getRelativeName(resource.getName()));
            }
        } catch (FileSystemException e) {
            throw new WGAServiceException("Deleting FSDesignResource '" + path + "' failed.", e);
        }
    }
}

From source file:hadoopInstaller.installation.DeployInstallationFiles.java

public void run() throws InstallationError {
    FileObject dependenciesFolder;
    log.debug("DeployInstallationFiles.DeployingStarted", //$NON-NLS-1$
            this.host.getHostname());
    try {/*from w w  w .ja v  a  2s .com*/
        dependenciesFolder = this.installer.getLocalDirectory()
                .resolveFile(InstallerConstants.TGZ_BUNDLES_FOLDER);
    } catch (FileSystemException e) {
        throw new InstallationError(e, "DeployInstallationFiles.CouldNotOpenFile", //$NON-NLS-1$
                InstallerConstants.TGZ_BUNDLES_FOLDER);
    }
    if (this.installer.getConfig().deleteOldFiles()) {
        try {
            /*
             * Current version of commons-vfs can not delete symlinks to a
             * folder because it thinks of them as a folder and then fails
             * to delete them.
             * 
             * Workaround, connect and do rm -rf
             */
            // this.remoteDirectory.delete(new AllFileSelector());
            SshCommandExecutor command = new SshCommandExecutor(this.session);
            command.execute(MessageFormat.format("rm -rf {0}/*", //$NON-NLS-1$
                    this.remoteDirectory.getName().getPath()));
        } catch (ExecutionError e) {
            throw new InstallationError(e, "DeployInstallationFiles.CouldNotDeleteOldFiles", //$NON-NLS-1$
                    this.remoteDirectory.getName().getURI());
        }
        log.info("DeployInstallationFiles.DeletingOldFiles", //$NON-NLS-1$
                this.remoteDirectory.getName().getURI());
    }
    uploadFiles(dependenciesFolder);
    decompressFiles();
    try {
        dependenciesFolder.close();
    } catch (FileSystemException e) {
        log.warn("DeployInstallationFiles.CouldNotCloseFile", //$NON-NLS-1$
                dependenciesFolder.getName().getURI());
    }
    log.debug("DeployInstallationFiles.DeployingFinished", //$NON-NLS-1$
            this.host.getHostname());
}

From source file:com.seer.datacruncher.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l//w ww .j  av a2 s .c  o  m
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}

From source file:it.openprj.jValidator.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l/*w w w .j  a v a 2  s . c om*/
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Returns a VFS file object for a folder. If the  folder does not exist it is created.
 * @param parent The parent folder of the retrieved folder
 * @param name The name of the folder to retrieve
 * @return The folder/* w w w.  j a v  a2  s.c o  m*/
 * @throws IOException
 */
public static FileObject getOrCreateFolder(FileObject parent, String name) throws IOException {
    if (!parent.getType().equals(FileType.FOLDER)) {
        throw new IllegalArgumentException("Parent file is no folder: " + parent.getName().getPathDecoded());
    }

    FileObject folder = parent.resolveFile(name);
    if (!folder.exists()) {
        if (!folder.getFileSystem().hasCapability(Capability.CREATE)) {
            throw new IOException("File system of file " + folder.getURL().toString() + " is read only");
        }
        folder.createFolder();
    }
    if (!folder.getType().equals(FileType.FOLDER)) {
        throw new IllegalArgumentException("There is already a file of this name: " + name);
    }
    return folder;
}

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

private List<ModuleFile> getModuleFiles(int type, FileObject dir, String prefix, String category)
        throws WGDesignSyncException, FileSystemException {

    // Find the valid suffixes for the type: Standard plus registered conversions
    Set<String> suffixes = new HashSet<String>();
    suffixes.add(getFileStandardSuffix(type, category));
    for (ModuleDefinition def : _core.getModuleRegistry()
            .getModulesForType(DesignResourceConversionModuleType.class).values()) {
        DesignResourceConversionProperties props = (DesignResourceConversionProperties) def.getProperties();
        if (props.getDesignType() == type
                && (props.getCodeType() == null || props.getCodeType().equals(category))) {
            for (String sfx : props.getSuffixes()) {
                suffixes.add("." + sfx);
            }/*from w  ww  . j a v  a  2s  .c  o m*/
        }
    }

    List<ModuleFile> moduleFiles = new ArrayList<ModuleFile>();
    if (dir == null || !dir.exists()) {
        return moduleFiles;
    }

    FileObject[] files = dir.getChildren();
    if (files == null) {
        throw new WGDesignSyncException("Cannot collect files from directory '" + dir.getName().getPathDecoded()
                + "'. Please verify directory existence.");
    }

    FileObject file;
    for (int i = 0; i < files.length; i++) {
        file = files[i];
        if (!isValidDesignFile(file)) {
            continue;
        }
        if (file.getType().equals(FileType.FOLDER)) {
            if (file.getName().getBaseName().equals(DesignDirectory.NAME_METADATADIR)) {
                continue;
            }
            String newPrefix = (prefix.trim().equals("") ? file.getName().getBaseName().toLowerCase()
                    : prefix + DIRECTORY_DIVIDER + file.getName().getBaseName().toLowerCase());
            moduleFiles.addAll(getModuleFiles(type, file, newPrefix, category));
        } else {
            // Test the file suffix
            if (!suffixes.contains("." + file.getName().getExtension())) {
                continue;
            }
            moduleFiles.add(new ModuleFile(file, prefix, category, type));
        }
    }

    return moduleFiles;

}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Resolves an eventually present directory link file (variant with Commons VFS file objects). Use this with folders that either may be used themselves or that contain a directory link pointing to the directory to use.
 * @param file The directory that might contain a directory link file.
 * @return Either the path that an available directory link file points to or the given directory itself again.
 *//* w w w.  j a  va 2  s.c om*/
public static FileObject resolveDirLink(FileObject file) throws FileSystemException {

    if (file != null && file.exists()) {
        if (file.getType().equals(FileType.FOLDER)) {
            FileObject link = file.resolveFile(DIRLINK_FILE);
            if (link.exists()) {
                // dir link present resolve

                Document doc;
                try {
                    InputStream fileInputStream = link.getContent().getInputStream();
                    String linkLocation = readDirLinkLocation(fileInputStream);
                    if (linkLocation != null) {
                        if (linkLocation.startsWith("../")) {
                            return file.resolveFile(linkLocation);
                        } else {
                            return file.getFileSystem().resolveFile(linkLocation);
                        }
                    }
                } catch (Exception e) {
                    Logger.getLogger("wga.utils")
                            .error("Unable to resolve dir link. '" + link.getName().getPath() + "'.", e);
                }
            }
        }
    }
    // no dir link or file does not exist - just return
    return file;

}

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

/**
 * AJAX tree functions/*  w  ww .  j  ava  2  s  . co 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;
}