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

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

Introduction

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

Prototype

void copyFrom(FileObject srcFile, FileSelector selector) throws FileSystemException;

Source Link

Document

Copies another file, and all its descendants, to this file.

Usage

From source file:maspack.fileutil.FileCacher.java

public boolean copy(URIx from, URIx to, FileTransferMonitor monitor) throws FileSystemException {

    FileObject fromFile = null;//w  w  w . j av  a 2  s  . c om
    FileObject toFile = null;

    // clear authenticators
    setAuthenticator(fsOpts, null);
    setIdentityFactory(fsOpts, null);

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (toFile == null && cancel == false) {
        toFile = resolveRemote(to);
    }

    cancel = false;
    while (fromFile == null && cancel == false) {
        fromFile = resolveRemote(from);
    }

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

    if (toFile == null) {
        throw new FileSystemException("Cannot find destination <" + to.toString() + ">",
                new FileNotFoundException("<" + to.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(fromFile, toFile, -1, fromFile.getName().getBaseName());
        monitor.start();
        monitor.fireStartEvent(toFile);
    }

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

        if (monitor != null) {
            monitor.fireCompleteEvent(toFile);
        }
    } catch (Exception e) {
        throw new FileTransferException(
                "Failed to complete transfer of " + fromFile.getURL() + " to " + toFile.getURL(), e);
    } finally {
        // close files if we need to
        fromFile.close();
        toFile.close();
        if (monitor != null) {
            monitor.release(toFile);
            monitor.stop();
        }
    }

    return true;

}

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

/**
 * AJAX tree functions//from   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;
}

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//  www . ja v a  2  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//from  ww w .j  a  v 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,
                                "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:org.aludratest.service.file.impl.FileActionImpl.java

/** Copies a file or folder.
 *  @param fromPath the file/folder to copy
 *  @param toPath the name/location of the copy
 *  @param overwrite flag which indicates if an existing file may be overwritten by the operation
 *  @return true if a formerly existing file was overwritten.
 *  @throws FilePresentException if a file was already present and overwriting was disabled. */
@Override/*from w  ww .j  a v a 2s  .  co m*/
public boolean copy(String fromPath, String toPath, boolean overwrite) {
    assertWritingPermitted("copy()");
    FileUtil.verifyFilePath(fromPath);
    FileUtil.verifyFilePath(toPath);
    FileObject target = getFileObject(toPath);
    boolean existedBefore = checkWritable(target, overwrite);
    try {
        FileObject source = getFileObject(fromPath);
        FileSelector sourceSelector = new FilePathSelector(source.getName().getPath());
        target.copyFrom(source, sourceSelector);
        LOGGER.info("Copied {} to {}", fromPath, toPath);
        return existedBefore;
    } catch (FileSystemException e) {
        throw new TechnicalException("Error copying file " + fromPath + " -> " + toPath, e);
    }
}

From source file:org.aludratest.service.file.impl.FileInteractionImpl.java

/** Copies a file or folder.
 * @param fromPath the file/folder to copy
 * @param toPath the name/location of the copy
 * @param overwrite flag which indicates if an existing file may be overwritten by the operation
 * @return true if a formerly existing file was overwritten.
 * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
@Override/*ww  w  .j  a  v a2s. c om*/
public boolean copy(String fromPath, String toPath, boolean overwrite) {
    assertWritingPermitted("copy()");
    File.verifyFilePath(fromPath);
    File.verifyFilePath(toPath);
    try {
        FileObject target = getFileObject(toPath);
        boolean existedBefore = checkWritable(target, overwrite);
        FileObject source = getFileObject(fromPath);
        FileSelector sourceSelector = new FilePathSelector(source.getName().getPath());
        target.copyFrom(source, sourceSelector);
        logger.debug("Copied {} to {}", fromPath, toPath);
        return existedBefore;
    } catch (IOException e) {
        throw new TechnicalException("Error copying file " + fromPath + " -> " + toPath, e);
    }
}

From source file:org.apache.accumulo.start.classloader.vfs.UniqueFileReplicator.java

@Override
public File replicateFile(FileObject srcFile, FileSelector selector) throws FileSystemException {
    String baseName = srcFile.getName().getBaseName();

    try {/*  ww w  .  j av a  2 s .  co m*/
        String safeBasename = UriParser.encode(baseName, TMP_RESERVED_CHARS).replace('%', '_');
        File file = File.createTempFile("vfsr_", "_" + safeBasename, tempDir);
        file.deleteOnExit();

        final FileObject destFile = context.toFileObject(file);
        destFile.copyFrom(srcFile, selector);

        return file;
    } catch (IOException e) {
        throw new FileSystemException(e);
    }
}

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

/**
 * Does a 'cp' command./*from w  ww  .  j  ava2s.  c  om*/
 */
private void cp(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
        throw new Exception("USAGE: cp <src> <dest>");
    }

    final FileObject src = mgr.resolveFile(cwd, cmd[1]);
    FileObject dest = mgr.resolveFile(cwd, cmd[2]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
        dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method copies a file or folder//w ww .j  av a  2s .  co m
 * @param file_s
 * @param file_d
 * @throws FileSystemException 
 */
public void cp(FileObject file_s, FileObject file_d) throws FileSystemException {
    if (file_d.exists() && file_d.getType() == FileType.FOLDER) {
        file_d = file_d.resolveFile(file_s.getName().getBaseName());
    }
    file_d.copyFrom(file_s, Selectors.SELECT_ALL);
}

From source file:org.cloudifysource.esc.installer.filetransfer.VfsFileTransfer.java

@Override
public void copyFiles(final InstallationDetails details, final Set<String> excludedFiles,
        final List<File> additionalFiles, final long endTimeMillis)
        throws TimeoutException, InstallerException {

    logger.fine("Copying files to: " + host + " from local dir: " + localDir.getName().getPath() + " excluding "
            + excludedFiles.toString());

    try {/*from  w  w w .  j a  v a  2s.c  o  m*/

        if (remoteDir.exists()) {
            FileType type = remoteDir.getType();
            if (!type.equals(FileType.FOLDER)) {
                throw new InstallerException("The remote location: " + remoteDir.getName().getFriendlyURI()
                        + " exists but is not a directory");
            }

            if (deleteRemoteDirectoryContents) {
                logger.info("Deleting contents of remote directory: " + remoteDir.getName().getFriendlyURI());
                remoteDir.delete(new FileDepthSelector(1, Integer.MAX_VALUE));
            }
            FileObject[] children = remoteDir.getChildren();
            if (children.length > 0) {

                throw new InstallerException(
                        "The remote directory: " + remoteDir.getName().getFriendlyURI() + " is not empty");
            }
        }

        remoteDir.copyFrom(localDir, new FileSelector() {

            @Override
            public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
                if (excludedFiles.contains(fileInfo.getFile().getName().getBaseName())) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " excluded");
                    return false;

                }
                final FileObject remoteFile = fileSystemManager.resolveFile(remoteDir,
                        localDir.getName().getRelativeName(fileInfo.getFile().getName()));

                if (!remoteFile.exists()) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " missing on server");
                    return true;
                }

                if (fileInfo.getFile().getType() == FileType.FILE) {
                    final long remoteSize = remoteFile.getContent().getSize();
                    final long localSize = fileInfo.getFile().getContent().getSize();
                    final boolean res = localSize != remoteSize;
                    if (res) {
                        logger.fine(fileInfo.getFile().getName().getBaseName() + " different on server");
                    }
                    return res;
                }
                return false;

            }

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

        for (final File file : additionalFiles) {
            logger.fine("copying file: " + file.getAbsolutePath() + " to remote directory");
            final FileObject fileObject = fileSystemManager.resolveFile("file:" + file.getAbsolutePath());
            final FileObject remoteFile = remoteDir.resolveFile(file.getName());
            remoteFile.copyFrom(fileObject, new AllFileSelector());
        }

        logger.fine("Copying files to: " + host + " completed.");
    } catch (final FileSystemException e) {
        throw new InstallerException("Failed to copy files to remote host " + host + ": " + e.getMessage(), e);

    }
    checkTimeout(endTimeMillis);

}