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:com.spectralogic.ds3client.integration.GetJobManagement_Test.java

@Test(expected = AccessDeniedException.class)
public void testReadRetryBugFixWithUnwritableDirectory() throws IOException, URISyntaxException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException, InterruptedException {
    Assume.assumeFalse(iAmRoot());/*  ww w  .  ja  v  a  2s  . c  o m*/

    final String tempPathPrefix = null;
    final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String tempDirectoryName = tempDirectoryPath.toString();

    if (org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS) {
        // Deny write data access to everyone, making the directory unwritable.
        Runtime.getRuntime().exec("icacls " + tempDirectoryName + " /deny Everyone:(WD)").waitFor();
    } else {
        Runtime.getRuntime().exec("chmod -w " + tempDirectoryName).waitFor();
    }

    try {
        disableWritePermissionForRoot(tempDirectoryName);

        final String DIR_NAME = "largeFiles/";
        final String FILE_NAME = "lesmis-copies.txt";

        final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME);
        final long bookSize = Files.size(objPath);
        final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize);

        final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client);

        final int maxNumBlockAllocationRetries = 1;
        final int maxNumObjectTransferAttempts = 3;
        final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim,
                maxNumBlockAllocationRetries, maxNumObjectTransferAttempts);

        final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj));

        final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim
                .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId()));

        assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue()));

        readJob.transfer(new FileObjectGetter(tempDirectoryPath));

        final File originalFile = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME).toFile();
        final File fileCopiedFromBP = Paths.get(tempDirectoryPath.toString(), FILE_NAME).toFile();
        assertTrue(FileUtils.contentEquals(originalFile, fileCopiedFromBP));
    } finally {
        enableWritePermissionForRoot(tempDirectoryName);

        if (org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS) {
            // Grant write data access to everyone, so we can delete the directory
            Runtime.getRuntime().exec("icacls " + tempDirectoryName + " /grant Everyone:(WD)").waitFor();
        } else {
            Runtime.getRuntime().exec("chmod +w " + tempDirectoryName).waitFor();
        }
        FileUtils.deleteDirectory(tempDirectoryPath.toFile());
    }
}

From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java

private BinaryStoreContent pathToContent(Path path) {
    BinaryStoreContent content = new BinaryStoreContent();
    content.setPath(base.relativize(path).toString());
    if (Files.isDirectory(path)) {
        content.setType(Type.DIRECTORY);
    } else {/* w w  w .  j ava2  s  .c  om*/
        content.setType(Type.FILE);
    }
    try {
        content.setSize(Files.size(path));
        content.setLastModificationDate(Files.getLastModifiedTime(path).toMillis());
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Unable to retrieve binary store content information for path: " + path);
    }
    return content;
}

From source file:fr.duminy.jbackup.core.ConfigurationManagerTest.java

private Path writeConfigFile(boolean config1) throws IOException {
    Path configFile = configDir.resolve((config1 ? CONFIG1 : CONFIG2) + ".xml");
    String configXML = config1 ? CONFIG_XML : CONFIG_XML2;
    createFile(configFile, configXML);/*w ww  .jav a 2  s .c o m*/
    assertThat(Files.size(configFile)).as("config file size").isEqualTo(configXML.getBytes().length);
    return configFile;
}

From source file:ch.silviowangler.dox.DocumentServiceImpl.java

@Override
@CacheEvict(value = CACHE_DOCUMENT_COUNT, allEntries = true)
@Transactional(propagation = REQUIRED, readOnly = false)
@PreAuthorize("hasRole('ROLE_USER')")
public DocumentReference importDocument(PhysicalDocument physicalDocumentApi)
        throws ValidationException, DocumentDuplicationException, DocumentClassNotFoundException {

    final String documentClassShortName = physicalDocumentApi.getDocumentClass().getShortName();
    ch.silviowangler.dox.domain.DocumentClass documentClassEntity = findDocumentClass(documentClassShortName);

    List<Attribute> attributes = attributeRepository.findAttributesForDocumentClass(documentClassEntity);

    logger.debug("Found {} attributes for document class '{}'", attributes.size(), documentClassShortName);

    verifyMandatoryAttributes(physicalDocumentApi, attributes);
    verifyUnknownKeys(physicalDocumentApi, documentClassShortName, attributes);
    try {/*from   w w  w  .j av  a 2  s .  c  o m*/
        verifyDomainValues(physicalDocumentApi, attributes);
    } catch (ValueNotInDomainException e) {
        ch.silviowangler.dox.domain.Domain domain = domainRepository.findByShortName(e.getDomainName());

        if (domain.isStrict()) {
            logger.warn(
                    "Domain '{}' is defined as strict domain and can therefore only accept predefined value",
                    e.getDomainName());
            throw e;
        }
        logger.debug("Adding value '{}' to domain '{}'", e.getValue(), e.getDomainName());
        domain.getValues().add(e.getValue());
        domainRepository.save(domain);
        verifyDomainValues(physicalDocumentApi, attributes);
    }

    physicalDocumentApi.setIndices(fixDataTypesOfIndices(physicalDocumentApi.getIndices(), attributes));

    final String mimeType = investigateMimeType(physicalDocumentApi.getFileName());
    final String hash = DigestUtils.sha256Hex(physicalDocumentApi.getContent());

    final Document documentByHash = documentRepository.findByHash(hash);
    if (documentByHash != null) {
        throw new DocumentDuplicationException(documentByHash.getId(), hash);
    }

    IndexStore indexStore = new IndexStore();
    updateIndices(physicalDocumentApi, indexStore);

    User user = getPrincipal();

    Document document = new Document(hash, documentClassEntity, PAGE_NUMBER_NOT_RETRIEVABLE, mimeType,
            physicalDocumentApi.getFileName(), indexStore, user.getUsername());
    document.setClient(clientRepository.findByShortName(physicalDocumentApi.getClient()));
    indexStore.setDocument(document);

    document = documentRepository.save(document);
    indexStoreRepository.save(indexStore);

    updateIndexMapEntries(toEntityMap(physicalDocumentApi.getIndices()), document);

    File target = new File(this.archiveDirectory, hash);
    try {
        FileUtils.writeByteArrayToFile(target, physicalDocumentApi.getContent());
    } catch (IOException e) {
        logger.error("Unable to write file to store at {}", this.archiveDirectory.getAbsolutePath(), e);
    }

    try {
        final long size = Files.size(target.toPath());
        document.setFileSize(size);

        final int numberOfPages = documentInspectorFactory.findDocumentInspector(mimeType)
                .retrievePageCount(target);
        document.setPageCount(numberOfPages);

        document = documentRepository.save(document);
    } catch (IOException e) {
        logger.error("Unable to calculate file size of file {}", target.getAbsolutePath(), e);
    }
    DocumentReference docRef = toDocumentReference(document, null);
    return docRef;
}

From source file:onl.area51.filesystem.ftp.client.FTPClient.java

/**
 * Simple test to see if a remote file should be retrieved.
 * <p>/* ww  w.j a  va 2 s.co m*/
 * This returns true if file does not exist, if the lengths don't match or the remote file's date is newer than the local file
 * <p>
 * @param file
 * @param ftp
 *             <p>
 * @return
 */
default boolean isPathRetrievable(Path file, FTPFile ftp) throws IOException {
    return !Files.exists(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) != ftp.getSize()
            || Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis() < ftp.getTimestamp()
                    .getTimeInMillis();
}

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

@Test
public void testRecoverWriteJob()
        throws IOException, XmlProcessingException, JobRecoveryException, URISyntaxException {
    final String bucketName = "test_recover_write_job_bucket";
    final String book1 = "beowulf.txt";
    final String book2 = "ulysses.txt";

    try {/*w  w  w  .j  a va 2s  .c o m*/
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1);
        final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2);
        final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1));
        final Ds3Object obj2 = new Ds3Object(book2, Files.size(objPath2));

        final Ds3ClientHelpers.Job job = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName,
                Lists.newArrayList(obj1, obj2));

        final PutObjectResponse putResponse1 = client.putObject(new PutObjectRequest(job.getBucketName(), book1,
                new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book1), job.getJobId().toString(), 0,
                Files.size(objPath1)));
        assertThat(putResponse1, is(notNullValue()));
        assertThat(putResponse1.getStatusCode(), is(equalTo(200)));

        // Interuption...
        final Ds3ClientHelpers.Job recoverJob = HELPERS.recoverWriteJob(job.getJobId());

        final PutObjectResponse putResponse2 = client.putObject(new PutObjectRequest(recoverJob.getBucketName(),
                book2, new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book2),
                recoverJob.getJobId().toString(), 0, Files.size(objPath2)));
        assertThat(putResponse2, is(notNullValue()));
        assertThat(putResponse2.getStatusCode(), is(equalTo(200)));
    } finally {
        deleteAllContents(client, bucketName);
    }
}

From source file:divconq.tool.release.Main.java

@Override
public void run(Scanner scan, ApiSession api) {
    Path relpath = null;//  www . jav  a2s.c o m
    Path gitpath = null;
    Path wikigitpath = null;

    XElement fldset = Hub.instance.getConfig().selectFirst("CommandLine/Settings");

    if (fldset != null) {
        relpath = Paths.get(fldset.getAttribute("ReleasePath"));
        gitpath = Paths.get(fldset.getAttribute("GitPath"));
        wikigitpath = Paths.get(fldset.getAttribute("WikiGitPath"));
    }

    boolean running = true;

    while (running) {
        try {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("   Release Builder Menu");
            System.out.println("-----------------------------------------------");
            System.out.println("0)  Exit");

            if (relpath != null)
                System.out.println("1)  Build release package from Settings File");

            System.out.println("2)  Build custom release package [under construction]");

            System.out.println("4)  Pack the .jar files");

            if (gitpath != null)
                System.out.println("5)  Copy Source to GitHub folder");

            System.out.println("6)  Update AWWW");

            String opt = scan.nextLine();

            Long mopt = StringUtil.parseInt(opt);

            if (mopt == null)
                continue;

            switch (mopt.intValue()) {
            case 0:
                running = false;
                break;

            case 1: {
                ReleasesHelper releases = new ReleasesHelper();

                if (!releases.init(relpath))
                    break;

                System.out.println("Select a release to build");
                System.out.println("0) None");

                List<String> rnames = releases.names();

                for (int i = 0; i < rnames.size(); i++)
                    System.out.println((i + 1) + ") " + rnames.get(i));

                System.out.println("Option #: ");
                opt = scan.nextLine();

                mopt = StringUtil.parseInt(opt);

                if ((mopt == null) || (mopt == 0))
                    break;

                XElement relchoice = releases.get(mopt.intValue() - 1);

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                XElement prindesc = availpackages.get(inst.prinpackage);

                XElement prininst = prindesc.find("Install");

                if (prininst == null) {
                    System.out.println("Principle package: " + inst.prinpackagenm
                            + " cannot be released directly, it must be part of another package.");
                    break;
                }

                String relvers = prindesc.getAttribute("Version");

                System.out.println("Building release version " + relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    System.out.println("Previous release version " + prindesc.getAttribute("LastVersion"));

                String rname = relchoice.getAttribute("Name");
                Path destpath = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.exists(destpath)) {
                    System.out.println("Version " + relvers + " already exists, overwrite? (y/n): ");
                    if (!scan.nextLine().toLowerCase().startsWith("y"))
                        break;

                    Files.delete(destpath);
                }

                System.out.println("Preparing zip files");

                AtomicBoolean errored = new AtomicBoolean();
                Path tempfolder = FileUtil.allocateTempFolder2();

                ListStruct ignorepaths = new ListStruct();
                Set<String> nolongerdepends = new HashSet<>();
                Set<String> dependson = new HashSet<>();

                // put all the release files into a temp folder
                inst.instpkgs.forEach(pname -> {
                    availpackages.get(pname).selectAll("DependsOn").stream()
                            .filter(doel -> !doel.hasAttribute("Option")
                                    || inst.relopts.contains(doel.getAttribute("Option")))
                            .forEach(doel -> {
                                // copy all libraries we rely on
                                doel.selectAll("Library").forEach(libel -> {
                                    dependson.add(libel.getAttribute("File"));

                                    Path src = Paths.get("./lib/" + libel.getAttribute("File"));
                                    Path dest = tempfolder.resolve("lib/" + libel.getAttribute("File"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all files we rely on
                                doel.selectAll("File").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all folders we rely on
                                doel.selectAll("Folder").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }

                                    OperationResult cres = FileUtil.copyFileTree(src, dest);

                                    if (cres.hasErrors())
                                        errored.set(true);
                                });
                            });

                    availpackages.get(pname).selectAll("IgnorePaths/Ignore")
                            .forEach(doel -> ignorepaths.addItem(doel.getAttribute("Path")));

                    // NoLongerDependsOn functionally currently only applies to libraries
                    availpackages.get(pname).selectAll("NoLongerDependsOn/Library")
                            .forEach(doel -> nolongerdepends.add(doel.getAttribute("File")));

                    // copy the released packages folders
                    Path src = Paths.get("./packages/" + pname);
                    Path dest = tempfolder.resolve("packages/" + pname);

                    try {
                        Files.createDirectories(dest.getParent());
                    } catch (Exception x) {
                        errored.set(true);
                        System.out.println("Unable to copy file: " + src);
                    }

                    // we may wish to enhance filter to allow .JAR sometimes, but this is meant to prevent copying of packages/pname/lib/abc.lib.jar files 
                    OperationResult cres = FileUtil.copyFileTree(src, dest,
                            path -> !path.toString().endsWith(".jar"));

                    if (cres.hasErrors())
                        errored.set(true);

                    // copy the released packages libraries
                    Path libsrc = Paths.get("./packages/" + pname + "/lib");
                    Path libdest = tempfolder.resolve("lib");

                    if (Files.exists(libsrc)) {
                        cres = FileUtil.copyFileTree(libsrc, libdest);

                        if (cres.hasErrors())
                            errored.set(true);
                    }
                });

                if (errored.get()) {
                    System.out.println("Error with assembling package");
                    break;
                }

                // copy the principle config
                Path csrc = Paths.get("./packages/" + inst.prinpackage + "/config");
                Path cdest = tempfolder.resolve("config/" + inst.prinpackagenm);

                if (Files.exists(csrc)) {
                    Files.createDirectories(cdest);

                    OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                    if (cres.hasErrors()) {
                        System.out.println("Error with prepping config");
                        break;
                    }
                }

                boolean configpassed = true;

                // copy packages with config = true
                for (XElement pkg : relchoice.selectAll("Package")) {
                    if (!"true".equals(pkg.getAttribute("Config")))
                        break;

                    String pname = pkg.getAttribute("Name");

                    int pspos = pname.lastIndexOf('/');
                    String pnm = (pspos != -1) ? pname.substring(pspos + 1) : pname;

                    csrc = Paths.get("./packages/" + pname + "/config");
                    cdest = tempfolder.resolve("config/" + pnm);

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping extra config");
                            configpassed = false;
                            break;
                        }
                    }
                }

                if (!configpassed)
                    break;

                // also copy installer config if being used
                if (inst.includeinstaller) {
                    csrc = Paths.get("./packages/dc/dcInstall/config");
                    cdest = tempfolder.resolve("config/dcInstall");

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping install config");
                            break;
                        }
                    }
                }

                // write out the deployed file
                RecordStruct deployed = new RecordStruct();

                deployed.setField("Version", relvers);
                deployed.setField("PackageFolder", relpath.resolve(rname));
                deployed.setField("PackagePrefix", rname);

                OperationResult d1res = IOUtil.saveEntireFile(tempfolder.resolve("config/deployed.json"),
                        deployed.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployed");
                    break;
                }

                RecordStruct deployment = new RecordStruct();

                deployment.setField("Version", relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    deployment.setField("DependsOn", prindesc.getAttribute("LastVersion"));

                deployment.setField("UpdateMessage",
                        "This update is complete, you may accept this update as runnable.");

                nolongerdepends.removeAll(dependson);

                ListStruct deletefiles = new ListStruct();

                nolongerdepends.forEach(fname -> deletefiles.addItem("lib/" + fname));

                deployment.setField("DeleteFiles", deletefiles);
                deployment.setField("IgnorePaths", ignorepaths);

                d1res = IOUtil.saveEntireFile(tempfolder.resolve("deployment.json"),
                        deployment.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployment");
                    break;
                }

                // write env file
                d1res = IOUtil.saveEntireFile(tempfolder.resolve("env.bat"), "set mem="
                        + relchoice.getAttribute("Memory", "2048") + "\r\n" + "SET project="
                        + inst.prinpackagenm + "\r\n" + "SET service="
                        + relchoice.getAttribute("Service", inst.prinpackagenm) + "\r\n" + "SET servicename="
                        + relchoice.getAttribute("ServiceName", inst.prinpackagenm + " Service") + "\r\n");

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping env");
                    break;
                }

                System.out.println("Packing Release file.");

                Path relbin = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.notExists(relbin.getParent()))
                    Files.createDirectories(relbin.getParent());

                ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                try {
                    Files.walkFileTree(tempfolder, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                            new SimpleFileVisitor<Path>() {
                                @Override
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                        throws IOException {
                                    ZipArchiveEntry entry = new ZipArchiveEntry(
                                            tempfolder.relativize(file).toString());
                                    entry.setSize(Files.size(file));
                                    zipout.putArchiveEntry(entry);
                                    zipout.write(Files.readAllBytes(file));
                                    zipout.closeArchiveEntry();

                                    return FileVisitResult.CONTINUE;
                                }
                            });
                } catch (IOException x) {
                    System.out.println("Error building zip: " + x);
                }

                zipout.close();

                System.out.println("Release file written");

                FileUtil.deleteDirectory(tempfolder);

                break;
            } // end case 1

            case 3: {
                System.out.println("Note these utilities are only good from the main console,");
                System.out.println("if you are using a remote connection then the encryption will");
                System.out.println("not work as expected.  [we do not have access the master keys]");
                System.out.println();

                Foreground.utilityMenu(scan);

                break;
            }

            case 4: {
                System.out.println("Packing jar library files.");

                String[] packlist = new String[] { "divconq.core", "divconq.interchange", "divconq.web",
                        "divconq.tasks", "divconq.tasks.api", "ncc.uploader.api", "ncc.uploader.core",
                        "ncc.workflow", "sd.core" };

                String[] packnames = new String[] { "dcCore", "dcInterchange", "dcWeb", "dcTasks", "dcTasksApi",
                        "nccUploaderApi", "nccUploader", "nccWorkflow", "sd/sdBackend" };

                for (int i = 0; i < packlist.length; i++) {
                    String lib = packlist[i];
                    String pname = packnames[i];

                    Path relbin = Paths.get("./ext/" + lib + ".jar");
                    Path srcbin = Paths.get("./" + lib + "/bin");
                    Path packbin = Paths.get("./packages/" + pname + "/lib/" + lib + ".jar");

                    if (Files.notExists(relbin.getParent()))
                        Files.createDirectories(relbin.getParent());

                    Files.deleteIfExists(relbin);

                    ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                    try {
                        Files.walkFileTree(srcbin, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                                new SimpleFileVisitor<Path>() {
                                    @Override
                                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                            throws IOException {
                                        ZipArchiveEntry entry = new ZipArchiveEntry(
                                                srcbin.relativize(file).toString());
                                        entry.setSize(Files.size(file));
                                        zipout.putArchiveEntry(entry);
                                        zipout.write(Files.readAllBytes(file));
                                        zipout.closeArchiveEntry();

                                        return FileVisitResult.CONTINUE;
                                    }
                                });
                    } catch (IOException x) {
                        System.out.println("Error building zip: " + x);
                    }

                    zipout.close();

                    Files.copy(relbin, packbin, StandardCopyOption.REPLACE_EXISTING);
                }

                System.out.println("Done");

                break;
            }

            case 5: {
                System.out.println("Copying Source Files");

                System.out.println("Cleaning folders");

                OperationResult or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/resources"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("packages"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectoryContent(wikigitpath, ".git");

                if (or.hasErrors()) {
                    System.out.println("Error deleting wiki files");
                    break;
                }

                System.out.println("Copying folders");

                System.out.println("Copy tree ./divconq.core/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/divconq"),
                        gitpath.resolve("divconq.core/src/main/java/divconq"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/org"),
                        gitpath.resolve("divconq.core/src/main/java/org"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/localize"),
                        gitpath.resolve("divconq.core/src/main/resources/localize"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".xml");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.interchange/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.interchange/src"),
                        gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks/src"),
                        gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks.api/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks.api/src"),
                        gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.web/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.web/src"),
                        gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCore");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCore"), gitpath.resolve("packages/dcCore"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCorePublic");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCorePublic"),
                        gitpath.resolve("packages/dcCorePublic"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcInterchange");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcInterchange"),
                        gitpath.resolve("packages/dcInterchange"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasks");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasks"),
                        gitpath.resolve("packages/dcTasks"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksApi");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksApi"),
                        gitpath.resolve("packages/dcTasksApi"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksWeb"),
                        gitpath.resolve("packages/dcTasksWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTest");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTest"), gitpath.resolve("packages/dcTest"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcWeb"), gitpath.resolve("packages/dcWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.wiki/public");

                or = FileUtil.copyFileTree(Paths.get("./divconq.wiki/public"), wikigitpath);

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copying files");

                Files.copy(Paths.get("./README.md"), gitpath.resolve("README.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./RELEASE_NOTES.md"), gitpath.resolve("RELEASE_NOTES.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./NOTICE.txt"), gitpath.resolve("NOTICE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./LICENSE.txt"), gitpath.resolve("LICENSE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                System.out.println("Done");

                break;
            }
            case 6: {
                System.out.println("Are you sure you want to update AWWW Server? (y/n): ");
                if (!scan.nextLine().toLowerCase().startsWith("y"))
                    break;

                ReleasesHelper releases = new ReleasesHelper();
                if (!releases.init(relpath))
                    break;

                XElement relchoice = releases.get("AWWWServer");

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                ServerHelper ssh = new ServerHelper();
                if (!ssh.init(relchoice.find("SSH")))
                    break;

                ChannelSftp sftp = null;

                try {
                    Channel channel = ssh.session().openChannel("sftp");
                    channel.connect();
                    sftp = (ChannelSftp) channel;

                    // go to routines folder
                    sftp.cd("/usr/local/bin/dc/AWWWServer");

                    FileRepositoryBuilder builder = new FileRepositoryBuilder();

                    Repository repository = builder.setGitDir(new File(".git")).findGitDir() // scan up the file system tree
                            .build();

                    String lastsync = releases.getData("AWWWServer").getFieldAsString("LastCommitSync");

                    RevWalk rw = new RevWalk(repository);
                    ObjectId head1 = repository.resolve(Constants.HEAD);
                    RevCommit commit1 = rw.parseCommit(head1);

                    releases.getData("AWWWServer").setField("LastCommitSync", head1.name());

                    ObjectId rev2 = repository.resolve(lastsync);
                    RevCommit parent = rw.parseCommit(rev2);
                    //RevCommit parent2 = rw.parseCommit(parent.getParent(0).getId());

                    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
                    df.setRepository(repository);
                    df.setDiffComparator(RawTextComparator.DEFAULT);
                    df.setDetectRenames(true);

                    // list oldest first or change types are all wrong!!
                    List<DiffEntry> diffs = df.scan(parent.getTree(), commit1.getTree());

                    for (DiffEntry diff : diffs) {
                        String gnpath = diff.getNewPath();
                        String gopath = diff.getOldPath();

                        Path npath = Paths.get("./" + gnpath);
                        Path opath = Paths.get("./" + gopath);

                        if (diff.getChangeType() == ChangeType.DELETE) {
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if ((diff.getChangeType() == ChangeType.ADD)
                                || (diff.getChangeType() == ChangeType.MODIFY)
                                || (diff.getChangeType() == ChangeType.COPY)) {
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if (diff.getChangeType() == ChangeType.RENAME) {
                            // remove the old
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }

                            // add the new path
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else {
                            System.out.println("??????????????????????????????????????????????????????????");
                            System.out.println(": " + diff.getChangeType().name() + " - " + gnpath
                                    + " ?????????????????????????");
                            System.out.println("??????????????????????????????????????????????????????????");
                        }
                    }

                    rw.dispose();

                    repository.close();

                    releases.saveData();
                } catch (JSchException x) {
                    System.out.println("Sftp Error: " + x);
                } finally {
                    if (sftp.isConnected())
                        sftp.exit();

                    ssh.close();
                }

                break;
            }

            case 7: {
                Path sfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly");
                Path dfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly-js");

                Files.list(sfolder).forEach(file -> {
                    String fname = file.getFileName().toString();

                    if (!fname.endsWith(".xml"))
                        return;

                    FuncResult<XElement> lres = XmlReader.loadFile(file, false);

                    if (lres.isEmptyResult()) {
                        System.out.println("Unable to parse: " + file);
                        return;
                    }

                    String zc = fname.substring(5, 8);
                    String code = "zipsData['" + zc + "'] = ";
                    XElement root = lres.getResult();

                    /*
                    <polyline1 lng="-90.620897" lat="45.377447"/>
                    <polyline1 lng="-90.619327" lat="45.3805"/>
                            
                                   [-71.196845,41.67757],[-71.120168,41.496831],[-71.317338,41.474923],[-71.196845,41.67757]
                     */
                    ListStruct center = new ListStruct();
                    ListStruct cords = new ListStruct();
                    ListStruct currentPoly = null;
                    //String currentName = null;

                    for (XElement child : root.selectAll("*")) {
                        String cname = child.getName();

                        if (cname.startsWith("marker")) {
                            // not always accurate
                            if (center.isEmpty())
                                center.addItem(Struct.objectToDecimal(child.getAttribute("lng")),
                                        Struct.objectToDecimal(child.getAttribute("lat")));

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));

                            continue;
                        }

                        /*
                        if (cname.startsWith("info")) {
                           System.out.println("areas: " + child.getAttribute("areas"));
                           continue;
                        }
                        */

                        if (!cname.startsWith("polyline"))
                            continue;

                        if (currentPoly == null) {
                            //if (!cname.equals(currentName)) {
                            //if (currentName == null) {
                            //   currentName = cname;

                            //   System.out.println("new poly: " + cname);

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));
                        }

                        currentPoly.addItem(new ListStruct(Struct.objectToDecimal(child.getAttribute("lng")),
                                Struct.objectToDecimal(child.getAttribute("lat"))));
                    }

                    RecordStruct feat = new RecordStruct().withField("type", "Feature")
                            .withField("id", "zip" + zc)
                            .withField("properties",
                                    new RecordStruct().withField("name", "Prefix " + zc).withField("alias", zc))
                            .withField("geometry", new RecordStruct().withField("type", "MultiPolygon")
                                    .withField("coordinates", cords));

                    RecordStruct entry = new RecordStruct().withField("code", zc).withField("geo", feat)
                            .withField("center", center);

                    IOUtil.saveEntireFile2(dfolder.resolve("us-zips-" + zc + ".js"),
                            code + entry.toPrettyString() + ";");
                });

                break;
            }

            }
        } catch (Exception x) {
            System.out.println("CLI error: " + x);
        }
    }
}

From source file:org.apache.taverna.prov.W3ProvenanceExport.java

protected void storeFileReferences() {

    for (Entry<Path, T2Reference> entry : getFileToT2Reference().entrySet()) {
        Path file = entry.getKey();

        try {//  ww w  .j  a v a 2  s  .com
            T2Reference t2Ref = entry.getValue();
            URI dataURI = URI.create(uriGenerator.makeT2ReferenceURI(t2Ref.toUri().toASCIIString()));

            Individual entity = provModel.createArtifact(dataURI);

            String mediaType = saver.getMediaTypes().get(t2Ref);

            if (!Files.exists(file)) {
                continue;
            }
            URI contentUri;
            if (DataBundles.isReference(file)) {
                // TODO: Do we really need to read this back again from the
                // file?
                contentUri = DataBundles.getReference(file);
            } else {
                contentUri = toURI(file);
            }

            Individual content = provModel.setContent(entity, contentUri);
            if (mediaType != null) {
                mediaTypes.put(contentUri, mediaType);
            }
            if (!DataBundles.isValue(file)) {
                // Don't capture the checksum and content of references and
                // lists
                continue;
            }

            // Add checksums
            String sha1 = saver.getSha1sums().get(file.toRealPath());
            if (sha1 != null) {
                content.addLiteral(provModel.sha1, sha1);
            }
            String sha512 = saver.getSha512sums().get(file.toRealPath());
            if (sha512 != null) {
                content.addLiteral(provModel.sha512, sha512);
            }
            long byteCount = Files.size(file);
            content.addLiteral(provModel.byteCount, byteCount);

            if (byteCount < EMBEDDED_MAX_FILESIZE) {
                // Add content if it's "tiny"
                byte[] bytes = Files.readAllBytes(file);
                if (mediaType != null && mediaType.startsWith(TEXT)) {
                    // as string - assuming UTF8 (and declaring so)
                    String str = new String(bytes, UTF8);
                    content.addLiteral(provModel.chars, str);
                    content.addLiteral(provModel.characterEncoding, UTF8.name());
                    content.addRDFType(provModel.ContentAsText);
                } else {
                    // Or base64-encoded bytes
                    content.addRDFType(provModel.ContentAsBase64);
                    content.addLiteral(provModel.bytes, bytes);
                }
            }
        } catch (IOException e) {
            logger.warn("Could not read " + file + " as " + UTF8, e);
        }
    }
}

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

@Test
public void cancelAllJobsWithForce() throws Exception {

    final int testTimeOutSeconds = 5;
    final String book1 = "beowulf.txt";
    final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1);
    final String book2 = "ulysses.txt";
    final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2);
    final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1));
    final Ds3Object obj2 = new Ds3Object("place_holder_1", 5000000);
    final Ds3Object obj3 = new Ds3Object(book2, Files.size(objPath2));
    final Ds3Object obj4 = new Ds3Object("place_holder_2", 5000000);

    try {/*www. j  av  a2s  . c om*/
        final Ds3ClientHelpers.Job putJob1 = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj1, obj2));
        final UUID jobId1 = putJob1.getJobId();
        final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME)
                .buildChannel(book1);
        client.putObject(new PutObjectRequest(BUCKET_NAME, book1, book1Channel, jobId1.toString(), 0,
                Files.size(objPath1)));

        final Ds3ClientHelpers.Job putJob2 = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj3, obj4));
        final UUID jobId2 = putJob2.getJobId();
        final SeekableByteChannel book2Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME)
                .buildChannel(book2);
        client.putObject(new PutObjectRequest(BUCKET_NAME, book2, book2Channel, jobId2.toString(), 0,
                Files.size(objPath2)));

        HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(new Ds3Object("place_holder_3", 1000000)));

        ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId1, client, 20);
        ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId2, client, 20);

        client.cancelAllJobsSpectraS3(new CancelAllJobsSpectraS3Request());

        assertTrue(client.getActiveJobsSpectraS3(new GetActiveJobsSpectraS3Request()).getActiveJobListResult()
                .getActiveJobs().isEmpty());

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

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public void doDump(OutputStream out) throws IOException {
    final ZipOutputStream zout = new ZipOutputStream(out);
    final int cutLength = this.repositoryRoot.toString().length() + 1;

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

        @Override//w w  w  .j  a v a2  s .  c o m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if (dir.endsWith(".git")) {
                return FileVisitResult.SKIP_SUBTREE;
            } else {
                return FileVisitResult.CONTINUE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String name = file.toString().substring(cutLength);
            ZipEntry ze = new ZipEntry(name);
            try {
                ze.setTime(Files.getLastModifiedTime(file).toMillis());
                ze.setSize(Files.size(file));
                zout.putNextEntry(ze);
                Files.copy(file, zout);
                zout.closeEntry();
            } catch (IOException e) {
                FilebasedRepository.logger.debug(e.getMessage());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    zout.close();
}