Example usage for java.nio.file Path getParent

List of usage examples for java.nio.file Path getParent

Introduction

In this page you can find the example usage for java.nio.file Path getParent.

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java

@Test
public void testOneLineReadFromBeginningFullLinesTruncate() throws Exception {
    Path file = createFile(Arrays.asList("Hello123456\n", "Hello2\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 10);

    Assert.assertTrue(lfr.hasNext());/*from   w w  w  .j ava2 s . c  o  m*/
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNotNull(chunk);
    Assert.assertTrue(chunk.isTruncated());
    Assert.assertEquals(0, chunk.getOffset());
    Assert.assertEquals(10, chunk.getLength());
    Assert.assertEquals("Hello12345", readChunk(chunk));
    Assert.assertEquals(-10, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNotNull(chunk);
    Assert.assertFalse(chunk.isTruncated());
    Assert.assertEquals(12, chunk.getOffset());
    Assert.assertEquals(7, chunk.getLength());
    Assert.assertEquals("Hello2\n", readChunk(chunk));
    Assert.assertEquals(19, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(19, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(19, lfr.getOffset());

    Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString()));
    Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1);

    Assert.assertFalse(lfr.hasNext());
    Assert.assertEquals(19, lfr.getOffset());

    lfr.close();
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Recursively imports the given definitions
 * /* w  w  w .  j  av  a  2s .c o  m*/
 * @param tmf the TOSCAMetaFile object holding the parsed content of a TOSCA meta file. If null,
 *        no files must be referenced from the given definitions
 * @param overwrite true: existing contents are overwritten
 * @param asyncWPDParsing
 * @param definitions the path to the definitions to import
 * 
 * @throws IOException
 */
public void importDefinitions(TOSCAMetaFile tmf, Path defsPath, final List<String> errors, boolean overwrite,
        boolean asyncWPDParsing) throws IOException {
    if (defsPath == null) {
        throw new IllegalStateException("path to definitions must not be null");
    }
    if (!Files.exists(defsPath)) {
        errors.add(String.format("Definitions %1$s does not exist", defsPath.getFileName()));
        return;
    }

    TDefinitions defs;
    defs = createDefinitionsByThirdparty(errors, defsPath);
    if (defs == null) {
        defs = getXMLDefs(errors, defsPath);
    }

    if (defs == null) {
        return;
    }

    List<TImport> imports = defs.getImport();
    this.importImports(defsPath.getParent(), tmf, imports, errors, overwrite, asyncWPDParsing);
    // imports has been modified to contain necessary imports only

    // this method adds new imports to defs which may not be imported using "importImports".
    // Therefore, "importTypes" has to be called *after* importImports
    this.importTypes(defs, errors);

    String defaultNamespace = defs.getTargetNamespace();
    List<TExtensibleElements> componentInstanceList = defs
            .getServiceTemplateOrNodeTypeOrNodeTypeImplementation();
    for (final TExtensibleElements ci : componentInstanceList) {
        // Determine namespace
        String namespace = this.getNamespace(ci, defaultNamespace);
        // Ensure that element has the namespace
        this.setNamespace(ci, namespace);

        // Determine id
        String id = ModelUtilities.getId(ci);
        if (ci instanceof TServiceTemplate) {
            this.serviceTemplate = (TServiceTemplate) ci;
        }

        if (isYamlFormat(defsPath)) {
            new NameSpaceHelper().updateNameSpace(ci);
        }

        // Determine WineryId
        Class<? extends TOSCAComponentId> widClass = org.eclipse.winery.repository.Utils
                .getComponentIdClassForTExtensibleElements(ci.getClass());
        final TOSCAComponentId wid = BackendUtils.getTOSCAcomponentId(widClass, namespace, id, false);

        if (Repository.INSTANCE.exists(wid)) {
            if (overwrite) {
                Repository.INSTANCE.forceDelete(wid);
                String msg = String.format("Deleted %1$s %2$s to enable replacement", ci.getClass().getName(),
                        wid.getQName().toString());
                CSARImporter.logger.debug(msg);
            } else {
                String msg = String.format("Skipped %1$s %2$s, because it already exists",
                        ci.getClass().getName(), wid.getQName().toString());
                CSARImporter.logger.debug(msg);
                // this is not displayed in the UI as we currently do not distinguish between pre-existing
                // types and types created during the import.
                continue;
            }
        }

        // Create a fresh definitions object without the other data.
        final Definitions newDefs = BackendUtils.createWrapperDefinitions(wid);

        // copy over the inputs determined by this.importImports
        newDefs.getImport().addAll(imports);

        // add the current TExtensibleElements as the only content to it
        newDefs.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(ci);

        adjustRefFiles(tmf, defsPath, errors, ci, wid);

        // node types and relationship types are subclasses of TEntityType
        // Therefore, we check the entity type separately here
        if (ci instanceof TEntityType) {
            if (asyncWPDParsing) {
                // Adjusting takes a long time
                // Therefore, we first save the type as is and convert to Winery-Property-Definitions in
                // the background
                CSARImporter.storeDefinitions(wid, newDefs);
                CSARImporter.entityTypeAdjestmentService.submit(new Runnable() {

                    @Override
                    public void run() {
                        CSARImporter.adjustEntityType((TEntityType) ci, (EntityTypeId) wid, newDefs, errors);
                        CSARImporter.storeDefinitions(wid, newDefs);
                    }
                });
            } else {
                CSARImporter.adjustEntityType((TEntityType) ci, (EntityTypeId) wid, newDefs, errors);
                CSARImporter.storeDefinitions(wid, newDefs);
            }
        } else {
            CSARImporter.storeDefinitions(wid, newDefs);
        }
    }
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Asynchronously loads the given file// www  .ja  va2s  . co  m
 * @param url the URL to load
 * @param path the path to save the file to
 */
private Future<Path> asyncLoadFile(final String url, final Path path) {
    Callable<Path> job = () -> {
        long t0 = System.currentTimeMillis();

        // For the resulting file, drop the ".download" suffix
        String name = path.getFileName().toString();
        name = name.substring(0, name.length() - DOWNLOAD_SUFFIX.length());

        try {

            // Set up a few timeouts and fetch the attachment
            URLConnection con = new URL(url).openConnection();
            con.setConnectTimeout(60 * 1000); // 1 minute
            con.setReadTimeout(60 * 60 * 1000); // 1 hour

            if (!StringUtils.isEmpty(authHeader)) {
                con.setRequestProperty("Authorization", authHeader);
            }

            try (ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
                    FileOutputStream fos = new FileOutputStream(path.toFile())) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
            log.info(String.format("Copied %s -> %s in %d ms", url, path, System.currentTimeMillis() - t0));

        } catch (Exception e) {
            log.log(Level.SEVERE, "Failed downloading " + url + ": " + e.getMessage());

            // Delete the old file
            if (Files.exists(path)) {
                try {
                    Files.delete(path);
                } catch (IOException e1) {
                    log.finer("Failed deleting old file " + path);
                }
            }

            // Save an error file
            Path errorFile = path.getParent().resolve(name + ".err.txt");
            try (PrintStream err = new PrintStream(new FileOutputStream(errorFile.toFile()))) {
                e.printStackTrace(err);
            } catch (IOException ex) {
                log.finer("Failed generating error file " + errorFile);
            }
            return errorFile;
        }

        Path resultPath = path.getParent().resolve(name);
        try {
            Files.move(path, resultPath);
        } catch (IOException e) {
            log.log(Level.SEVERE, "Failed renaming path " + path + ": " + e.getMessage());
        }
        return resultPath;
    };

    log.info("Submitting new job: " + url);
    return processPool.submit(job);
}

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

protected void renamePolicy(final File policy) {
    ////w ww  . ja  v  a2  s .  co  m
    // Run the rename window
    //
    final RenamePolicyFileWindow window = new RenamePolicyFileWindow(policy.getName());
    window.setCaption("Rename Policy");
    window.setModal(true);
    window.addCloseListener(new CloseListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void windowClose(CloseEvent event) {
            String newFilename = window.getNewFilename();
            if (newFilename == null) {
                //
                // User cancelled
                //
                return;
            }
            Path newPolicy = Paths.get(policy.getParent(), newFilename);
            if (Files.exists(newPolicy)) {
                Notification.show("Cannot rename to an existing file", Notification.Type.ERROR_MESSAGE);
                return;
            }
            try {
                if (policy.renameTo(newPolicy.toFile()) == false) {
                    throw new Exception("No known error, rename failed");
                }
                self.treeContainer.updateItem(newPolicy.getParent().toFile());
            } catch (Exception e) {
                Notification.show("Failed to rename file: " + e.getLocalizedMessage());
            }
        }
    });
    window.center();
    UI.getCurrent().addWindow(window);
}

From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java

@Test
public void testTruncateMultipleReads() throws Exception {
    Path file = createFile(Arrays.asList("Hello1234567890\n", "Hello\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 6);

    Assert.assertTrue(lfr.hasNext());//  www. ja  v  a2s  .c  om
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNotNull(chunk);
    Assert.assertTrue(chunk.isTruncated());
    Assert.assertEquals(0, chunk.getOffset());
    Assert.assertEquals(6, chunk.getLength());
    Assert.assertEquals("Hello1", readChunk(chunk));
    Assert.assertEquals(-6, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(-12, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNotNull(chunk);

    Assert.assertFalse(chunk.isTruncated());
    Assert.assertEquals(16, chunk.getOffset());
    Assert.assertEquals(6, chunk.getLength());
    Assert.assertEquals("Hello\n", readChunk(chunk));
    Assert.assertEquals(22, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(22, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(22, lfr.getOffset());

    Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString()));
    Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1);

    Assert.assertFalse(lfr.hasNext());
    Assert.assertEquals(22, lfr.getOffset());

    lfr.close();
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * SIDE EFFECT: modifies the location of imp to point to the correct relative location (when read
 * from the exported CSAR)//  w  w  w . ja  v a2 s . c  o  m
 * 
 * @param rootPath the absolute path where to resolve files from
 */
private void importOtherImport(Path rootPath, TImport imp, final List<String> errors, String type,
        boolean overwrite) {
    assert (!type.equals(Namespaces.TOSCA_NAMESPACE));
    String loc = imp.getLocation();

    if (!Util.isRelativeURI(loc)) {
        // This is just an information message
        errors.add("Absolute URIs are not resolved by Winery (" + loc + ")");
        return;
    }

    // location URLs are encoded: http://www.w3.org/TR/2001/WD-charmod-20010126/#sec-URIs, RFC
    // http://www.ietf.org/rfc/rfc2396.txt
    loc = Util.URLdecode(loc);
    Path path;
    try {
        path = rootPath.resolve(loc);
    } catch (Exception e) {
        // java.nio.file.InvalidPathException could be thrown which is a RuntimeException
        errors.add(e.getMessage());
        return;
    }
    if (!Files.exists(path)) {
        // fallback for older CSARs, where the location is given from the root
        path = rootPath.getParent().resolve(loc);
        if (!Files.exists(path)) {
            errors.add(String.format("File %1$s does not exist", loc));
            return;
        }
    }
    String namespace = imp.getNamespace();
    String fileName = path.getFileName().toString();
    String id = fileName;
    id = FilenameUtils.removeExtension(id);
    // Convention: id of import is filename without extension

    GenericImportId rid;
    if (type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        rid = new XSDImportId(namespace, id, false);
    } else {
        rid = new GenericImportId(namespace, id, false, type);
    }

    boolean importDataExistsInRepo = Repository.INSTANCE.exists(rid);

    if (!importDataExistsInRepo) {
        // We have to
        // a) create a .definitions file
        // b) put the file itself in the repo

        // Create the definitions file
        TDefinitions defs = BackendUtils.createWrapperDefinitions(rid);
        defs.getImport().add(imp);
        // QUICK HACK: We change the imp object's location here and below again
        // This is "OK" as "storeDefinitions" serializes the current state and not the future state of
        // the imp object
        // change the location to point to the file in the folder of the .definitions file
        imp.setLocation(fileName);

        // put the definitions file to the repository
        CSARImporter.storeDefinitions(rid, defs);
    }

    // put the file itself to the repo
    // ref is required to generate fileRef
    RepositoryFileReference ref = BackendUtils.getRefOfDefinitions(rid);
    RepositoryFileReference fileRef = new RepositoryFileReference(ref.getParent(), fileName);

    // location is relative to Definitions/
    // even if the import already exists, we have to adapt the path
    // URIs are encoded
    String newLoc = "../" + Utils.getURLforPathInsideRepo(BackendUtils.getPathInsideRepo(fileRef));
    imp.setLocation(newLoc);

    if (!importDataExistsInRepo || overwrite) {
        // finally write the file to the storage
        try (InputStream is = Files.newInputStream(path);
                BufferedInputStream bis = new BufferedInputStream(is)) {
            MediaType mediaType;
            if (type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                mediaType = MediaType.valueOf(MimeTypes.MIMETYPE_XSD);
            } else {
                String mimeType = Utils.getMimeType(bis, path.getFileName().toString());
                mediaType = MediaType.valueOf(mimeType);
            }
            Repository.INSTANCE.putContentToFile(fileRef, bis, mediaType);
        } catch (IllegalArgumentException | IOException e) {
            throw new IllegalStateException(e);
        }

        // we have to update the cache in case of a new XSD to speedup usage of winery
        if (rid instanceof XSDImportId) {
            // We do the initialization asynchronously
            // We do not check whether the XSD has already been checked
            // We cannot just checck whether an XSD already has been handled since the XSD could change
            // over time
            // Synchronization at
            // org.eclipse.winery.repository.resources.imports.xsdimports.XSDImportResource.getAllDefinedLocalNames(short)
            // also isn't feasible as the backend doesn't support locks
            CSARImporter.xsdParsingService.submit(new Runnable() {

                @Override
                public void run() {
                    CSARImporter.logger.debug("Updating XSD import cache data");
                    // We call the queries without storing the result:
                    // We use the SIDEEFFECT that a cache is created
                    Utils.getAllXSDElementDefinitionsForTypeAheadSelection();
                    Utils.getAllXSDTypeDefinitionsForTypeAheadSelection();
                    CSARImporter.logger.debug("Updated XSD import cache data");
                }
            });
        }
    }
}

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

@Override
public void run(Scanner scan, ApiSession api) {
    Path relpath = null;//ww  w .j a v  a2  s . co 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:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/**
 * Uses the given `http_client` to download `url` into `out_tmp`.
 * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field.
 * Returns a path to the renamed file.//from w ww. ja v  a2  s .c om
 *
 * @param http_client synchronous interruptible HTTP client.
 * @param out_tmp download destination file on disk (will be created if does not exist).
 * @param url what to download.
 * @return Path to file with its actual name.
 * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field
 *       Content-Disposition is missing).
 * @throws InterruptedException Thread has been interrupted.
 */
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url)
        throws IOException, InterruptedException {
    try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {

        HttpResponse response = http_client.interruptibleGet(url, output);

        // If the response's status code is not 200, something wrong happened
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Formatter ff = new Formatter();
            ff.format(
                    "Synchronizer#%d cannot download product at %s,"
                            + " remote dhus returned message '%s' (HTTP%d)",
                    getId(), url, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode());
            throw new IOException(ff.out().toString());
        }

        // Gets the filename from the HTTP header field `Content-Disposition'
        Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE);
        String contdis = response.getFirstHeader("Content-Disposition").getValue();
        Matcher m = pat.matcher(contdis);
        if (!m.find()) {
            throw new IOException("Synchronizer#" + getId()
                    + " Missing HTTP header field `Content-Disposition` that determines the filename");
        }
        String filename = m.group(1);
        if (filename == null || filename.isEmpty()) {
            throw new IOException(
                    "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`");
        }

        // Renames the downloaded file
        output.close();
        Path dest = out_tmp.getParent().resolve(filename);
        Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE);

        DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(),
                response.getEntity().getContentLength());

        return res;
    } finally {
        if (Files.exists(out_tmp)) {
            Files.delete(out_tmp);
        }
    }
}

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

protected void savePolicy(final Path newPolicyPath, final Object policyData, Path oldPolicyPath) {
    //// ww  w  .  jav  a 2  s  .c o m
    // Are they overwriting another policy?
    //
    String version = "1.0";
    boolean delete = false;
    if (oldPolicyPath != null) {
        //
        // This policy name was being edited. Is it still the same?
        //
        try {
            delete = true;
            if (Files.exists(newPolicyPath) && Files.isSameFile(newPolicyPath, oldPolicyPath)) {
                delete = false;
            }
        } catch (Exception e) {
            logger.error("Could not determine if same file", e);
            return;
        }
        logger.info("Deleting old file: " + delete);
    }
    //
    // Are we now overwriting another file?
    //
    if (Files.exists(newPolicyPath)) {
        //
        // Yes
        //
        logger.info("Overwriting file");
        //
        // Overwrite is happening. Bump the version (IF WE CAN)
        //
        //TODO - What if user wants to change something other than the last number?  For example, changing 1.5.23 to 2.0.0.
        //TODO     We need a mechanism that allows the user to specify the new policy version (disallowing backtracking) if they desire
        //TODO     and get that new number (if any) passed down to here.  This code then becomes the "then" branch of "If new version has been specified..."
        try {
            int[] versionArray = StdPDPPolicy
                    .versionStringToArray(XACMLPolicyScanner.getVersion(newPolicyPath));
            // increment the right-most digit
            versionArray[versionArray.length - 1]++;
            version = StdPDPPolicy.versionArrayToString(versionArray);
        } catch (NumberFormatException | IOException e) {
            try {
                logger.warn("Previous version '" + XACMLPolicyScanner.getVersion(newPolicyPath)
                        + "' not a series of itegers");
            } catch (IOException e1) {
                logger.error("could not get previous version");
            }
            //TODO - This may not be wise since the intent is to increase the version number.  Perhaps we should abort this an go back to the user?
            version = "1.0";
        }
        if (policyData instanceof PolicySetType) {
            ((PolicySetType) policyData).setVersion(version);
        } else if (policyData instanceof PolicyType) {
            ((PolicyType) policyData).setVersion(version);
        }
    } else {
        //
        // Nope, a completely new file
        //
        logger.info("New file");
    }
    //
    // Is the root a PolicySet or Policy?
    //
    Path finalPolicyPath;
    if (policyData instanceof PolicySetType) {
        //
        // Write it out
        //
        finalPolicyPath = XACMLPolicyWriter.writePolicyFile(newPolicyPath, (PolicySetType) policyData);
    } else if (policyData instanceof PolicyType) {
        //
        // Write it out
        //
        finalPolicyPath = XACMLPolicyWriter.writePolicyFile(newPolicyPath, (PolicyType) policyData);
    } else {
        logger.error("Unknown data type sent back.");
        return;
    }
    //
    // Did it get written?
    //
    if (finalPolicyPath == null || !Files.exists(finalPolicyPath)) {
        logger.error("Failed to write policy file.");
        return;
    }
    //
    // Add it into our tree
    //
    this.addPolicyFileToTree(finalPolicyPath.getParent().toFile(), finalPolicyPath.toFile());
    //
    // Do we need to delete the old file?
    //
    if (oldPolicyPath != null && delete) {
        try {
            Files.delete(oldPolicyPath);
        } catch (Exception e) {
            logger.error("Failed to delete old policy", e);
        }
        if (self.treeWorkspace.removeItem(oldPolicyPath.toFile()) == false) {
            logger.warn("Failed to remove old policy path");
        }
    }
}

From source file:me.ryanhamshire.griefprevention.GriefPreventionPlugin.java

public void loadConfig() {
    try {/*from   w  ww  .  j  a  va2s.  c o  m*/
        if (Files.notExists(DataStore.dataLayerFolderPath)) {
            Files.createDirectories(DataStore.dataLayerFolderPath);
        }
        if (Files.notExists(DataStore.softMuteFilePath)) {
            Files.createFile(DataStore.softMuteFilePath);
        }
        DataStore.loadBannedWords();

        Path rootConfigPath = this.getConfigPath().resolve("worlds");
        DataStore.globalConfig = new GriefPreventionConfig<GlobalConfig>(Type.GLOBAL,
                rootConfigPath.resolve("global.conf"));
        String localeString = DataStore.globalConfig.getConfig().message.locale;
        try {
            LocaleUtils.toLocale(localeString);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            this.logger.error("Could not validate the locale '" + localeString + "'. Defaulting to 'en_US'...");
            localeString = "en_US";
        }
        final Path localePath = this.getConfigPath().resolve("lang").resolve(localeString + ".conf");
        if (!localePath.toFile().exists()) {
            // Check for a default locale asset and copy to lang folder
            final Asset asset = this.pluginContainer.getAsset("lang/" + localeString + ".conf").orElse(null);
            if (asset != null) {
                asset.copyToDirectory(localePath.getParent());
            }
        }
        messageStorage = new MessageStorage(localePath);
        messageData = messageStorage.getConfig();
        DataStore.USE_GLOBAL_PLAYER_STORAGE = DataStore.globalConfig
                .getConfig().playerdata.useGlobalPlayerDataStorage;
        GPFlags.populateFlagStatus();
        CLAIM_BLOCK_SYSTEM = DataStore.globalConfig.getConfig().playerdata.claimBlockSystem;
        this.modificationTool = Sponge.getRegistry()
                .getType(ItemType.class, DataStore.globalConfig.getConfig().claim.modificationTool)
                .orElse(ItemTypes.GOLDEN_SHOVEL);
        this.investigationTool = Sponge.getRegistry()
                .getType(ItemType.class, DataStore.globalConfig.getConfig().claim.investigationTool)
                .orElse(ItemTypes.STICK);
        this.maxInspectionDistance = DataStore.globalConfig.getConfig().general.maxClaimInspectionDistance;
        for (World world : Sponge.getGame().getServer().getWorlds()) {
            DimensionType dimType = world.getProperties().getDimensionType();
            Path dimPath = rootConfigPath.resolve(((IMixinDimensionType) dimType).getModId())
                    .resolve(((IMixinDimensionType) dimType).getEnumName());
            if (!Files.exists(dimPath.resolve(world.getProperties().getWorldName()))) {
                try {
                    Files.createDirectories(rootConfigPath.resolve(dimType.getId()).resolve(world.getName()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            DataStore.dimensionConfigMap.put(world.getProperties().getUniqueId(),
                    new GriefPreventionConfig<DimensionConfig>(Type.DIMENSION,
                            dimPath.resolve("dimension.conf")));
            DataStore.worldConfigMap.put(world.getProperties().getUniqueId(), new GriefPreventionConfig<>(
                    Type.WORLD, dimPath.resolve(world.getProperties().getWorldName()).resolve("world.conf")));

            // refresh player data
            final GPClaimManager claimManager = GriefPreventionPlugin.instance.dataStore
                    .getClaimWorldManager(world.getProperties());
            for (GPPlayerData playerData : claimManager.getPlayerDataMap().values()) {
                if (playerData.playerID.equals(WORLD_USER_UUID) || playerData.playerID.equals(ADMIN_USER_UUID)
                        || playerData.playerID.equals(PUBLIC_UUID)) {
                    continue;
                }
                playerData.refreshPlayerOptions();
            }
            // refresh default permissions
            this.dataStore.setupDefaultPermissions(world);
        }
        GPBlacklists.populateBlacklistStatus();
    } catch (Exception e) {
        e.printStackTrace();
    }
}