Example usage for java.nio.file Files size

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

Introduction

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

Prototype

public static long size(Path path) throws IOException 

Source Link

Document

Returns the size of a file (in bytes).

Usage

From source file:org.dcm4chee.storage.test.unit.tar.TarContainerProviderTest.java

private byte[] readFile(Path path) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) Files.size(path));
    Files.copy(path, out);//from   w ww. j a  v a  2  s . c  om
    return out.toByteArray();
}

From source file:com.spectralogic.ds3client.integration.Smoke_Test.java

@Test
public void testHelperMetadata() throws IOException, URISyntaxException, XmlProcessingException {
    final String bucketName = "helper_metadata";
    try {//w  ww.j  a  va  2s .co m
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> objects = new ArrayList<>();
        for (final String book : BOOKS) {
            final Path objPath = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book);
            final long bookSize = Files.size(objPath);
            final Ds3Object obj = new Ds3Object(book, bookSize);

            objects.add(obj);
        }

        final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(bucketName, objects);

        final AtomicBoolean calledWithMetadata = new AtomicBoolean(false);

        job.withMetadata(new Ds3ClientHelpers.MetadataAccess() {
            @Override
            public Map<String, String> getMetadataValue(final String filename) {
                if (filename.equals("beowulf.txt")) {
                    calledWithMetadata.set(true);
                    return ImmutableMap.of("fileType", "text");
                }

                return null;
            }
        });

        job.transfer(new ResourceObjectPutter(RESOURCE_BASE_NAME));

        assertTrue(calledWithMetadata.get());

        final HeadObjectResponse response = client.headObject(new HeadObjectRequest(bucketName, "beowulf.txt"));
        final Metadata metadata = response.getMetadata();
        final List<String> values = metadata.get("fileType");
        assertThat(values.size(), is(1));
        assertThat(values.get(0), is("text"));

    } finally {
        deleteAllContents(client, bucketName);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

@Override
public InputStream getStream() {
    ////  www  . java  2 s.co m
    // Grab our working repository
    //
    final Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
    Path workspacePath = ((XacmlAdminUI) getUI()).getUserWorkspace();
    final Path tarFile = Paths.get(workspacePath.toString(), "Repository.tgz");

    try (OutputStream os = Files.newOutputStream(tarFile)) {
        try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(os)) {
            try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzOut)) {

                tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

                Files.walkFileTree(repoPath, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        if (dir.getFileName().toString().startsWith(".git")) {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                        Path relative = repoPath.relativize(dir);
                        if (relative.toString().isEmpty()) {
                            return super.preVisitDirectory(dir, attrs);
                        }
                        TarArchiveEntry entry = new TarArchiveEntry(relative.toFile());
                        tarOut.putArchiveEntry(entry);
                        tarOut.closeArchiveEntry();
                        return super.preVisitDirectory(dir, attrs);
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (file.getFileName().toString().endsWith(".xml") == false) {
                            return super.visitFile(file, attrs);
                        }
                        Path relative = repoPath.relativize(file);
                        TarArchiveEntry entry = new TarArchiveEntry(relative.toFile());
                        entry.setSize(Files.size(file));
                        tarOut.putArchiveEntry(entry);
                        try {
                            IOUtils.copy(Files.newInputStream(file), tarOut);
                        } catch (IOException e) {
                            logger.error(e);
                        }
                        tarOut.closeArchiveEntry();
                        return super.visitFile(file, attrs);
                    }

                });
                tarOut.finish();
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }
    try {
        return Files.newInputStream(tarFile);
    } catch (IOException e) {
        logger.error(e);
    }
    return null;
}

From source file:io.minio.MinioClient.java

/**
 * Gets object's data in the given bucket and stores it to given file name.
 *
 * </p><b>Example:</b><br>
 * <pre>{@code minioClient.getObject("my-bucketname", "my-objectname", "photo.jpg"); }</pre>
 *
 * @param bucketName  Bucket name.//from   ww w  .jav a  2  s . co  m
 * @param objectName  Object name in the bucket.
 * @param fileName    file name.
 *
 * @throws InvalidBucketNameException  upon invalid bucket name is given
 * @throws NoResponseException         upon no response from server
 * @throws IOException                 upon connection error
 * @throws XmlPullParserException      upon parsing response xml
 * @throws ErrorResponseException      upon unsuccessful execution
 * @throws InternalException           upon internal library error
 */
public void getObject(String bucketName, String objectName, String fileName)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException, InvalidArgumentException {
    Path filePath = Paths.get(fileName);
    boolean fileExists = Files.exists(filePath);

    if (fileExists && !Files.isRegularFile(filePath)) {
        throw new InvalidArgumentException(fileName + ": not a regular file");
    }

    ObjectStat objectStat = statObject(bucketName, objectName);
    long length = objectStat.length();
    String etag = objectStat.etag();

    String tempFileName = fileName + "." + etag + ".part.minio";
    Path tempFilePath = Paths.get(tempFileName);
    boolean tempFileExists = Files.exists(tempFilePath);

    if (tempFileExists && !Files.isRegularFile(tempFilePath)) {
        throw new IOException(tempFileName + ": not a regular file");
    }

    long tempFileSize = 0;
    if (tempFileExists) {
        tempFileSize = Files.size(tempFilePath);
        if (tempFileSize > length) {
            Files.delete(tempFilePath);
            tempFileExists = false;
            tempFileSize = 0;
        }
    }

    if (fileExists) {
        long fileSize = Files.size(filePath);
        if (fileSize == length) {
            // already downloaded. nothing to do
            return;
        } else if (fileSize > length) {
            throw new InvalidArgumentException(
                    "'" + fileName + "': object size " + length + " is smaller than file size " + fileSize);
        } else if (!tempFileExists) {
            // before resuming the download, copy filename to tempfilename
            Files.copy(filePath, tempFilePath);
            tempFileSize = fileSize;
            tempFileExists = true;
        }
    }

    InputStream is = null;
    OutputStream os = null;
    try {
        is = getObject(bucketName, objectName, tempFileSize);
        os = Files.newOutputStream(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        long bytesWritten = ByteStreams.copy(is, os);
        is.close();
        os.close();

        if (bytesWritten != length - tempFileSize) {
            throw new IOException(tempFileName + ": unexpected data written.  expected = "
                    + (length - tempFileSize) + ", written = " + bytesWritten);
        }

        Files.move(tempFilePath, filePath, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
}

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);// www.  ja  v  a  2s .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:io.minio.MinioClient.java

/**
 * Uploads given file as object in given bucket.
 * <p>/*from w  w w . ja  va2s .  co  m*/
 * If the object is larger than 5MB, the client will automatically use a multipart session.
 * </p>
 * <p>
 * If the session fails, the user may attempt to re-upload the object by attempting to create
 * the exact same object again. The client will examine all parts of any current upload session
 * and attempt to reuse the session automatically. If a mismatch is discovered, the upload will fail
 * before uploading any more data. Otherwise, it will resume uploading where the session left off.
 * </p>
 * <p>
 * If the multipart session fails, the user is responsible for resuming or removing the session.
 * </p>
 *
 * @param bucketName  Bucket name.
 * @param objectName  Object name to create in the bucket.
 * @param fileName    File name to upload.
 *
 * @throws InvalidBucketNameException  upon invalid bucket name is given
 * @throws NoResponseException         upon no response from server
 * @throws IOException                 upon connection error
 * @throws XmlPullParserException      upon parsing response xml
 * @throws ErrorResponseException      upon unsuccessful execution
 * @throws InternalException           upon internal library error
 */
public void putObject(String bucketName, String objectName, String fileName)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException, InvalidArgumentException, InsufficientDataException {
    if (fileName == null || "".equals(fileName)) {
        throw new InvalidArgumentException("empty file name is not allowed");
    }

    Path filePath = Paths.get(fileName);
    if (!Files.isRegularFile(filePath)) {
        throw new InvalidArgumentException("'" + fileName + "': not a regular file");
    }

    String contentType = Files.probeContentType(filePath);
    long size = Files.size(filePath);

    RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r");
    try {
        putObject(bucketName, objectName, contentType, size, file);
    } finally {
        file.close();
    }
}

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;/*w ww . j  av  a 2 s . c om*/

    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;
}