Example usage for java.nio.file Files copy

List of usage examples for java.nio.file Files copy

Introduction

In this page you can find the example usage for java.nio.file Files copy.

Prototype

public static long copy(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java

@Override
public void saveMediaFile(ComponentMedia media, InputStream fileInput) {
    Objects.requireNonNull(media);
    Objects.requireNonNull(fileInput);

    if (StringUtils.isBlank(media.getComponentMediaId())) {
        media = saveComponentMedia(media);
    }/*from  w ww.j a  v a 2 s  .com*/
    media.setFileName(media.getComponentMediaId());
    try (InputStream in = fileInput) {
        Files.copy(in, media.pathToMedia());
        media.setUpdateUser(SecurityUtil.getCurrentUserName());
        saveComponentMedia(media);
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to store media file.",
                "Contact System Admin.  Check file permissions and disk space ", ex);
    }
}

From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java

@Override
public void saveResourceFile(ComponentResource resource, InputStream fileInput) {
    Objects.requireNonNull(resource);
    Objects.requireNonNull(fileInput);

    if (StringUtils.isBlank(resource.getResourceId())) {
        resource.setResourceId(persistenceService.generateId());
    }//from ww w. j  a v a2s. c  om
    resource.setFileName(resource.getResourceId());
    try (InputStream in = fileInput) {
        Files.copy(in, resource.pathToResource());
        resource.setUpdateUser(SecurityUtil.getCurrentUserName());
        saveComponentResource(resource);
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to store resource file.",
                "Contact System Admin.  Check file permissions and disk space ", ex);
    }
}

From source file:com.github.podd.example.ExamplePoddClient.java

public Map<Path, String> uploadToStorage(final List<Path> bagsToUpload, final String sshServerFingerprint,
        final String sshHost, final int portNo, final String username, final Path pathToPublicKey,
        final Path localRootPath, final Path remoteRootPath, final PasswordFinder keyExtractor)
        throws PoddClientException, NoSuchAlgorithmException, IOException {
    final Map<Path, String> results = new ConcurrentHashMap<>();

    final ConcurrentMap<Path, ConcurrentMap<PoddDigestUtils.Algorithm, String>> digests = PoddDigestUtils
            .getDigests(bagsToUpload);// w  w  w  . j  a  v a2 s . c  om

    try (SSHClient sshClient = new SSHClient(ExamplePoddClient.DEFAULT_CONFIG);) {
        sshClient.useCompression();
        sshClient.addHostKeyVerifier(sshServerFingerprint);
        sshClient.connect(sshHost, portNo);
        if (!Files.exists(pathToPublicKey)) {
            throw new PoddClientException("Could not find public key: " + pathToPublicKey);
        }
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            throw new PoddClientException("Bouncy castle needed");
        }
        final FileKeyProvider rsa = new PKCS8KeyFile();
        rsa.init(pathToPublicKey.toFile(), keyExtractor);
        sshClient.authPublickey(username, rsa);
        // Session session = sshClient.startSession();
        try (SFTPClient sftp = sshClient.newSFTPClient();) {
            for (final Path nextBag : bagsToUpload) {
                // Check to make sure that the bag was under the local root path
                final Path localPath = nextBag.toAbsolutePath();
                if (!localPath.startsWith(localRootPath)) {
                    this.log.error(
                            "Local bag path was not a direct descendant of the local root path: {} {} {}",
                            localRootPath, nextBag, localPath);
                    throw new PoddClientException(
                            "Local bag path was not a direct descendant of the local root path: " + localPath
                                    + " " + localRootPath);
                }

                // Take the local root path out to get the subpath to use on the remote
                final Path remoteSubPath = localPath.subpath(localRootPath.getNameCount(),
                        nextBag.getNameCount() - 1);

                this.log.info("Remote sub path: {}", remoteSubPath);

                final Path remoteDirPath = remoteRootPath.resolve(remoteSubPath);
                this.log.info("Remote dir path: {}", remoteDirPath);

                final Path remoteBagPath = remoteDirPath.resolve(nextBag.getFileName());

                this.log.info("Remote bag path: {}", remoteBagPath);

                boolean fileFound = false;
                boolean sizeCorrect = false;
                try {
                    // check details of a remote bag
                    final FileAttributes attribs = sftp.lstat(remoteBagPath.toAbsolutePath().toString());
                    final long localSize = Files.size(nextBag);
                    final long remoteSize = attribs.getSize();

                    if (localSize <= 0) {
                        this.log.error("Local bag was empty: {}", nextBag);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (remoteSize <= 0) {
                        this.log.warn("Remote bag was empty: {} {}", nextBag, attribs);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (localSize == remoteSize) {
                        this.log.info("Found file on remote already with same size as local: {} {}", nextBag,
                                remoteBagPath);
                        sizeCorrect = true;
                        fileFound = true;
                    } else {
                        sizeCorrect = false;
                        fileFound = true;
                        // We always assume that a non-zero local file is correct
                        // The bags contain time-stamps that will be modified when they are
                        // regenerated, likely changing the file-size, and hopefully changing
                        // the digest checksums
                        // throw new PoddClientException(
                        // "Could not automatically compare file sizes (need manual intervention to delete one) : "
                        // + nextBag + " " + remoteBagPath + " localSize=" + localSize
                        // + " remoteSize=" + remoteSize);
                    }
                } catch (final IOException e) {
                    // lstat() throws an IOException if the file does not exist
                    // Ignore
                    sizeCorrect = false;
                    fileFound = false;
                }

                final ConcurrentMap<Algorithm, String> bagDigests = digests.get(nextBag);
                if (bagDigests.isEmpty()) {
                    this.log.error("No bag digests were generated for bag: {}", nextBag);
                }
                for (final Entry<Algorithm, String> entry : bagDigests.entrySet()) {
                    final Path localDigestPath = localPath
                            .resolveSibling(localPath.getFileName() + entry.getKey().getExtension());
                    // Create the local digest file
                    Files.copy(
                            new ReaderInputStream(new StringReader(entry.getValue()), StandardCharsets.UTF_8),
                            localDigestPath);
                    final Path remoteDigestPath = remoteBagPath
                            .resolveSibling(remoteBagPath.getFileName() + entry.getKey().getExtension());
                    boolean nextDigestFileFound = false;
                    boolean nextDigestCorrect = false;
                    try {
                        final Path tempFile = Files.createTempFile("podd-digest-",
                                entry.getKey().getExtension());
                        final SFTPFileTransfer sftpFileTransfer = new SFTPFileTransfer(sftp.getSFTPEngine());
                        sftpFileTransfer.download(remoteBagPath.toAbsolutePath().toString(),
                                tempFile.toAbsolutePath().toString());
                        nextDigestFileFound = true;

                        final List<String> allLines = Files.readAllLines(tempFile, StandardCharsets.UTF_8);
                        if (allLines.isEmpty()) {
                            nextDigestCorrect = false;
                        } else if (allLines.size() > 1) {
                            nextDigestCorrect = false;
                        }
                        // Check if the digests match exactly
                        else if (allLines.get(0).equals(entry.getValue())) {
                            nextDigestCorrect = true;
                        } else {
                            nextDigestCorrect = false;
                        }
                    } catch (final IOException e) {
                        nextDigestFileFound = false;
                        nextDigestCorrect = false;
                    }
                    if (nextDigestFileFound && nextDigestCorrect) {
                        this.log.info(
                                "Not copying digest to remote as it exists and contains the same content as the local digest");
                    } else if (nextDigestFileFound && !nextDigestCorrect) {
                        this.log.error("Found remote digest but content was not correct: {} {}",
                                localDigestPath, remoteDigestPath);
                        sftp.rm(remoteDigestPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    } else if (!nextDigestFileFound) {
                        this.log.info("About to make directories on remote: {}", remoteDirPath);
                        sftp.mkdirs(remoteDirPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    }
                }

                if (fileFound && sizeCorrect) {
                    this.log.info("Not copying bag to remote as it exists and is the same size as local bag");
                } else if (fileFound && !sizeCorrect) {
                    this.log.error("Found remote bag but size was not correct: {} {}", nextBag, remoteBagPath);
                    sftp.rm(remoteBagPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                } else if (!fileFound) {
                    this.log.info("About to make directories on remote: {}", remoteDirPath);
                    sftp.mkdirs(remoteDirPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                }

            }
        }
    } catch (final IOException e) {
        throw new PoddClientException("Could not copy a bag to the remote location", e);
    }

    return results;
}

From source file:com.ut.healthelink.controller.adminProcessingActivity.java

/**
 * The 'inboundBatchOptions' function will process the batch according to the option submitted by admin
 *//*from   www . ja  va  2 s  .  c  o m*/
@RequestMapping(value = "/inboundBatchOptions", method = RequestMethod.POST)
public @ResponseBody boolean inboundBatchOptions(HttpSession session,
        @RequestParam(value = "tId", required = false) Integer transactionInId,
        @RequestParam(value = "batchId", required = true) Integer batchId, Authentication authentication,
        @RequestParam(value = "batchOption", required = true) String batchOption) throws Exception {

    String strBatchOption = "";
    User userInfo = usermanager.getUserByUserName(authentication.getName());
    batchUploads batchDetails = transactionInManager.getBatchDetails(batchId);

    if (userInfo != null && batchDetails != null) {
        if (batchOption.equalsIgnoreCase("processBatch")) {
            if (batchDetails.getstatusId() == 2) {
                strBatchOption = "Loaded Batch";
                transactionInManager.loadBatch(batchId);
            } else if (batchDetails.getstatusId() == 3 || batchDetails.getstatusId() == 36) {
                strBatchOption = "Processed Batch";
                transactionInManager.processBatch(batchId, false, 0);
            }
        } else if (batchOption.equalsIgnoreCase("cancel")) {
            strBatchOption = "Cancelled Batch";
            transactionInManager.updateBatchStatus(batchId, 4, "startDateTime");
            transactionInManager.updateTransactionStatus(batchId, 0, 0, 31);
            transactionInManager.updateBatchStatus(batchId, 32, "endDateTime");
            //need to cancel targets also
            transactionInManager.updateTranTargetStatusByUploadBatchId(batchId, 0, 31);
            transactionInManager.updateBatchDLStatusByUploadBatchId(batchId, 0, 32, "endDateTime");

        } else if (batchOption.equalsIgnoreCase("reset")) {
            strBatchOption = "Reset Batch";
            //1. Check
            boolean allowBatchClear = transactionInManager.allowBatchClear(batchId);
            if (allowBatchClear) {
                //if ftp or rhapsody, we flag as DNP and move file back to input folder
                if (batchDetails.gettransportMethodId() == 5 || batchDetails.gettransportMethodId() == 3) {
                    transactionInManager.updateBatchStatus(batchId, 4, "startDateTime");

                    strBatchOption = "Reset Batch  - FTP/Rhapsody Reset";

                    //targets could be created already so we need to update the target status by upload batchId 
                    transactionInManager.updateTranTargetStatusByUploadBatchId(batchId, 0, 31);
                    transactionInManager.updateBatchDLStatusByUploadBatchId(batchId, 0, 35, "endDateTime");
                    transactionInManager.updateTransactionStatus(batchId, 0, 0, 31);
                    transactionInManager.updateBatchStatus(batchId, 35, "endDateTime");

                    String fileExt = batchDetails.getoriginalFileName()
                            .substring(batchDetails.getoriginalFileName().lastIndexOf("."));
                    fileSystem fileSystem = new fileSystem();

                    File archiveFile = new File(
                            fileSystem.setPath(archivePath) + batchDetails.getutBatchName() + fileExt);
                    String fileToPath = fileSystem.setPathFromRoot(batchDetails.getOriginalFolder());
                    //we name it ut batch name when move so we know
                    String newFileName = transactionInManager.newFileName(fileToPath,
                            (batchDetails.getutBatchName() + fileExt));
                    File newFile = new File(fileToPath + newFileName);
                    Path source = archiveFile.toPath();
                    Path target = newFile.toPath();
                    Files.copy(source, target);

                } else {

                    transactionInManager.updateBatchStatus(batchId, 4, "");
                    //2. clear
                    boolean cleared = transactionInManager.clearBatch(batchId);

                    //copy archive file back to original folder
                    fileSystem dir = new fileSystem();

                    // we need to move unencoded file back from archive folder and replace current file
                    //we set archive path
                    try {

                        File archiveFile = new File(dir.setPath(archivePath) + batchDetails.getutBatchName()
                                + batchDetails.getoriginalFileName()
                                        .substring(batchDetails.getoriginalFileName().lastIndexOf(".")));
                        Path archive = archiveFile.toPath();
                        File toFile = new File(dir.setPath(batchDetails.getFileLocation())
                                + batchDetails.getoriginalFileName());
                        Path toPath = toFile.toPath();
                        //need to encode file first
                        if (batchDetails.getEncodingId() == 1) {
                            String strEncodedFile = filemanager.encodeFileToBase64Binary(archiveFile);
                            toFile.delete();
                            //we replace file with encoded
                            filemanager.writeFile(toFile.getAbsolutePath(), strEncodedFile);
                        } else { // already encoded
                            Files.copy(archive, toPath, StandardCopyOption.REPLACE_EXISTING);
                        }

                        cleared = true;

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        cleared = false;
                    }

                    if (cleared) {
                        transactionInManager.updateBatchStatus(batchId, 2, "startOver");
                    }
                }
            }
        } else if (batchOption.equalsIgnoreCase("releaseBatch")) {
            strBatchOption = "Released Batch";
            if (batchDetails.getstatusId() == 5) {
                transactionInManager.updateBatchStatus(batchId, 4, "startDateTime");
                //check once again to make sure all transactions are in final status
                if (transactionInManager.getRecordCounts(batchId, Arrays.asList(11, 12, 13, 16), false,
                        false) == 0) {
                    transactionInManager.updateBatchStatus(batchId, 6, "endDateTime");
                } else {
                    transactionInManager.updateBatchStatus(batchId, 5, "endDateTime");
                }
            }
        } else if (batchOption.equalsIgnoreCase("rejectMessage")) {
            strBatchOption = "Rejected Transaction";
            if (batchDetails.getstatusId() == 5) {
                transactionInManager.updateTranStatusByTInId(transactionInId, 13);
            }
        }
    }

    //log user activity
    UserActivity ua = new UserActivity();
    ua.setUserId(userInfo.getId());
    ua.setAccessMethod("POST");
    ua.setPageAccess("/inboundBatchOptions");
    ua.setActivity("Admin - " + strBatchOption);
    ua.setBatchUploadId(batchId);
    if (transactionInId != null) {
        ua.setTransactionInIds(transactionInId.toString());
    }
    usermanager.insertUserLog(ua);
    return true;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

private void saveIngestedOriginal(DataFile dataFile, InputStream originalFileStream) throws IOException {
    String ingestedFileName = dataFile.getStorageIdentifier();

    if (ingestedFileName != null && !ingestedFileName.equals("")) {
        Path savedOriginalPath = Paths.get(dataFile.getOwner().getFileSystemDirectory().toString(),
                "_" + ingestedFileName);
        Files.copy(originalFileStream, savedOriginalPath);
    } else {//from   www.j a v  a2s. c o m
        throw new IOException("Ingested tabular data file: no filesystem name.");
    }
}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

@Override
public Integer moveFilesByPath(String inPath, Integer transportMethodId, Integer orgId, Integer transportId) {
    Integer sysErrors = 0;/*  ww  w.j  ava 2  s  . c o m*/

    try {
        fileSystem fileSystem = new fileSystem();
        String fileInPath = fileSystem.setPathFromRoot(inPath);
        File folder = new File(fileInPath);

        //list files
        //we only list visible files
        File[] listOfFiles = folder.listFiles((FileFilter) HiddenFileFilter.VISIBLE);

        Organization orgDetails = organizationmanager.getOrganizationById(orgId);
        String defPath = "/bowlink/" + orgDetails.getcleanURL() + "/input files/";
        String outPath = fileSystem.setPath(defPath);

        //too many variables that could come into play regarding file types, will check files with one method
        //loop files 
        for (File file : listOfFiles) {
            String fileName = file.getName();
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
            Date date = new Date();
            /* Create the batch name (TransportMethodId+OrgId+Date/Time/Seconds) */
            String batchName = new StringBuilder().append(transportMethodId).append(orgId)
                    .append(dateFormat.format(date)).toString();

            if (!fileName.endsWith("_error")) {

                try {

                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

                    //figure out how many active transports are using fileExt method for this particular path
                    List<configurationTransport> transportList = configurationtransportmanager
                            .getTransportListForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    //figure out if files has distinct delimiters
                    List<configurationTransport> transports = configurationtransportmanager
                            .getConfigTransportForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    batchUploads batchInfo = new batchUploads();
                    batchInfo.setOrgId(orgId);
                    batchInfo.settransportMethodId(transportMethodId);
                    batchInfo.setstatusId(4);
                    batchInfo.setstartDateTime(date);
                    batchInfo.setutBatchName(batchName);
                    batchInfo.setOriginalFolder(inPath);

                    Integer batchId = 0;
                    String newFileName = "";
                    Integer statusId = 4;
                    Integer configId = 0;
                    Integer fileSize = 0;
                    Integer encodingId = 1;
                    Integer errorId = 0;

                    if (transportList.size() == 0 || transports.size() == 0) { //neither of them should be 0
                        //no source transport is associated with this method / file
                        batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                        batchInfo.setConfigId(0);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setFileLocation(defPath);
                        batchInfo.setEncodingId(encodingId);
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        //insert error
                        errorId = 13;
                        statusId = 7;
                    } else if (transports.size() == 1) {
                        encodingId = transports.get(0).getEncodingId();
                        configurationTransport ct = configurationtransportmanager
                                .getTransportDetailsByTransportId(transportId);
                        fileSize = ct.getmaxFileSize();
                        if (transportList.size() > 1) {
                            configId = 0;
                            fileSize = configurationtransportmanager.getMinMaxFileSize(fileExt,
                                    transportMethodId);
                        } else {
                            configId = ct.getconfigId();
                        }
                        batchInfo.setConfigId(configId);
                        batchInfo.setContainsHeaderRow(transports.get(0).getContainsHeaderRow());
                        batchInfo.setDelimChar(transports.get(0).getDelimChar());
                        batchInfo.setFileLocation(ct.getfileLocation());
                        outPath = fileSystem.setPath(ct.getfileLocation());
                        batchInfo.setOrgId(orgId);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setEncodingId(encodingId);

                        //find user 
                        List<User> users = usermanager.getSendersForConfig(Arrays.asList(ct.getconfigId()));
                        if (users.size() == 0) {
                            users = usermanager.getOrgUsersForConfig(Arrays.asList(ct.getconfigId()));
                        }

                        batchInfo.setuserId(users.get(0).getId());
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        statusId = 2;

                    } else if (transportList.size() > 1 && transports.size() > 1) {
                        //we loop though our delimiters for this type of fileExt
                        String delimiter = "";
                        Integer fileDelimiter = 0;
                        String fileLocation = "";
                        Integer userId = 0;
                        //get distinct delimiters
                        List<configurationTransport> delimList = configurationtransportmanager
                                .getDistinctDelimCharForFileExt(fileExt, transportMethodId);
                        List<configurationTransport> encodings = configurationtransportmanager
                                .getTransportEncoding(fileExt, transportMethodId);
                        //we reject file is multiple encodings/delimiters are found for extension type as we won't know how to decode it and read delimiter
                        if (encodings.size() != 1) {
                            batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                            statusId = 7;
                            errorId = 16;
                        } else {
                            encodingId = encodings.get(0).getEncodingId();
                            for (configurationTransport ctdelim : delimList) {
                                fileSystem dir = new fileSystem();
                                int delimCount = (Integer) dir.checkFileDelimiter(file, ctdelim.getDelimChar());
                                if (delimCount > 3) {
                                    delimiter = ctdelim.getDelimChar();
                                    fileDelimiter = ctdelim.getfileDelimiter();
                                    statusId = 2;
                                    fileLocation = ctdelim.getfileLocation();
                                    break;
                                }
                            }
                        }
                        // we don't have an error yet

                        if (errorId > 0) {
                            // some error detected from previous checks
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                        } else if (statusId != 2) {
                            //no vaild delimiter detected
                            statusId = 7;
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                            errorId = 15;
                        } else if (statusId == 2) {
                            encodingId = encodings.get(0).getEncodingId();
                            //we check to see if there is multi header row, if so, we reject because we don't know what header rows value to look for
                            List<configurationTransport> containsHeaderRowCount = configurationtransportmanager
                                    .getCountContainsHeaderRow(fileExt, transportMethodId);

                            if (containsHeaderRowCount.size() != 1) {
                                batchInfo.setuserId(
                                        usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                                statusId = 7;
                                errorId = 14;
                            } else {
                                List<Integer> totalConfigs = configurationtransportmanager
                                        .getConfigCount(fileExt, transportMethodId, fileDelimiter);

                                //set how many configs we have
                                if (totalConfigs.size() > 1) {
                                    configId = 0;
                                } else {
                                    configId = totalConfigs.get(0);
                                }

                                //get path
                                fileLocation = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getfileLocation();
                                fileSize = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getmaxFileSize();
                                List<User> users = usermanager.getSendersForConfig(totalConfigs);
                                if (users.size() == 0) {
                                    users = usermanager.getOrgUsersForConfig(totalConfigs);
                                }
                                userId = users.get(0).getId();
                                batchInfo.setContainsHeaderRow(
                                        containsHeaderRowCount.get(0).getContainsHeaderRow());
                                batchInfo.setDelimChar(delimiter);
                                batchInfo.setConfigId(configId);
                                batchInfo.setFileLocation(fileLocation);
                                outPath = fileSystem.setPath(fileLocation);
                                batchInfo.setOrgId(orgId);
                                newFileName = newFileName(outPath, fileName);
                                batchInfo.setoriginalFileName(newFileName);
                                batchInfo.setuserId(userId);
                                batchInfo.setEncodingId(encodingId);
                                batchId = (Integer) submitBatchUpload(batchInfo);
                            }
                        }
                    }
                    /** insert log**/
                    try {
                        //log user activity
                        UserActivity ua = new UserActivity();
                        ua.setUserId(0);
                        ua.setFeatureId(0);
                        ua.setAccessMethod("System");
                        ua.setActivity("System Uploaded File");
                        ua.setBatchUploadId(batchInfo.getId());
                        usermanager.insertUserLog(ua);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.err.println("moveFilesByPath - insert user log" + ex.toString());
                    }
                    //we encoded user's file if it is not
                    File newFile = new File(outPath + newFileName);
                    // now we move file
                    Path source = file.toPath();
                    Path target = newFile.toPath();

                    File archiveFile = new File(fileSystem.setPath(archivePath) + batchName
                            + newFileName.substring(newFileName.lastIndexOf(".")));
                    Path archive = archiveFile.toPath();
                    //we keep original file in archive folder
                    Files.copy(source, archive);

                    /**
                     * we check encoding here *
                     */
                    if (encodingId < 2) { //file is not encoded
                        String encodedOldFile = filemanager.encodeFileToBase64Binary(file);
                        filemanager.writeFile(newFile.getAbsolutePath(), encodedOldFile);
                        Files.delete(source);
                    } else {
                        Files.move(source, target);
                    }

                    if (statusId == 2) {
                        /**
                         * check file size if configId is 0 we go with the smallest file size *
                         */
                        long maxFileSize = fileSize * 1000000;
                        if (Files.size(target) > maxFileSize) {
                            statusId = 7;
                            errorId = 12;
                        }
                    }

                    if (statusId != 2) {
                        insertProcessingError(errorId, 0, batchId, null, null, null, null, false, false, "");
                    }

                    updateBatchStatus(batchId, statusId, "endDateTime");

                } catch (Exception exAtFile) {
                    exAtFile.printStackTrace();
                    System.err.println("moveFilesByPath " + exAtFile.toString());
                    try {
                        sendEmailToAdmin(
                                (exAtFile.toString() + "<br/>" + Arrays.toString(exAtFile.getStackTrace())),
                                "moveFilesByPath - at rename file to error ");
                        //we need to move that file out of the way
                        file.renameTo((new File(file.getAbsolutePath() + batchName + "_error")));
                    } catch (Exception ex1) {
                        ex1.printStackTrace();
                        System.err.println("moveFilesByPath " + ex1.getMessage());

                    }
                }
            }

        }

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            sendEmailToAdmin((ex.toString() + "<br/>" + Arrays.toString(ex.getStackTrace())),
                    "moveFilesByPath - issue with looping folder files");
        } catch (Exception ex1) {
            ex1.printStackTrace();
            System.err.println("moveFilesByPath " + ex1.getMessage());
        }
        return 1;
    }
    return sysErrors;
}

From source file:library.Form_Library.java

License:asdf

private void btImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btImageActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    int n = chooser.showOpenDialog(this);
    if (n == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        this.tfImage.setText(f.getName());
        File t = null;/*  w  w w.  ja  va  2s  . com*/
        if (!Files.isDirectory(Paths.get("directory"))) {
            new File("image").mkdir();
        }
        try {
            Files.copy(f.toPath(), new File("image/" + f.getName()).toPath());
        } catch (IOException ex) {
        }
        //            this.lbImage.setIcon(new ImageIcon(new ImageIcon("image/" + f.getName()).getImage().getScaledInstance(lbImage.WIDTH, lbImage.HEIGHT, Image.SCALE_SMOOTH)));
        this.lbImage.setIcon(BookList.loadIcon("image/" + f.getName(), 200, 300));
    }
}

From source file:library.Form_Library.java

License:asdf

private void btBrowseReaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBrowseReaderActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    int n = chooser.showOpenDialog(this);
    if (n == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        this.tfImageLink.setText(f.getName());
        File t = null;//from   w  ww . ja v  a  2 s  .  c  o  m
        if (!Files.isDirectory(Paths.get("directory"))) {
            new File("image").mkdir();
        }
        try {
            Files.copy(f.toPath(), new File("image/" + f.getName()).toPath());
        } catch (IOException ex) {
        }
        //            this.lbImage.setIcon(new ImageIcon(new ImageIcon("image/" + f.getName()).getImage().getScaledInstance(lbImage.WIDTH, lbImage.HEIGHT, Image.SCALE_SMOOTH)));
        this.lbImageLink.setIcon(ReaderList.loadIcon("image/" + f.getName(), 200, 300));
    }
}