Example usage for java.nio.file Path endsWith

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

Introduction

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

Prototype

default boolean endsWith(String other) 

Source Link

Document

Tests if this path ends with a Path , constructed by converting the given path string, in exactly the manner specified by the #endsWith(Path) endsWith(Path) method.

Usage

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;/*from w  w  w.  j  a va  2  s . c o  m*/
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:de.prozesskraft.pkraft.Manager.java

/**
 * erstellt fuer jeden running step einen watchkey
 * es soll jedes stepverzeichnis mit dem status 'working' observiert werden bis das file ".exit" erscheint
 * @param process//from w ww .  j  a  v  a 2s . c o m
 * @throws IOException 
 */
private static void createWatchKeysForAllRunningSteps(Process process) throws IOException {
    // diesen Thread ablegen, damit er vom zyklischen thread gekillt werden kann
    watcherThread = Thread.currentThread();

    // einen neuen map erzeugen fuer die watchKeys
    keys = new HashMap<WatchKey, Path>();

    WatchService watcher = FileSystems.getDefault().newWatchService();

    // Anlegen des WatchKeys fuer den Prozess (falls er gestoppt wird, erfolgt die Komunikation mit diesem manager ueber das binaerfile)
    Path processDir = Paths.get(process.getRootdir());
    System.err.println("info: creating a watchkey for the process path " + process.getRootdir());
    WatchKey keyProcess = processDir.register(watcher, ENTRY_MODIFY);
    keys.put(keyProcess, processDir);

    // Anlegen der WatchKeys fuer jeden laufenden Step
    for (Step actStep : process.getStep()) {
        if (actStep.getStatus().equals("working")) {
            Path stepDir = Paths.get(actStep.getAbsdir());
            try {
                System.err.println("info: step " + actStep.getName()
                        + " is working -> creating a watchkey for its path " + actStep.getAbsdir());
                System.err.println("debug: creating...");
                WatchKey key = stepDir.register(watcher, ENTRY_CREATE);
                System.err.println("debug: creating...done. putting to the map");
                keys.put(key, stepDir);
                System.err.println("debug: creating...done. putting to the map...done");
            } catch (IOException e) {
                System.err.println(e);
            } catch (Exception e) {
                System.err.println(e);
            }

            java.io.File stepDirExitFile = new java.io.File(actStep.getAbsdir() + "/.exit");
            java.io.File stepDirStatusFile = new java.io.File(actStep.getAbsdir() + "/.status");

            // falls die datei bereits existiert, wird sofort erneut der Prozess weitergeschoben
            // dies ist dann der fall, wenn ein step gestartet wurde, und danach der manager neu gestartet wurde
            if (stepDirExitFile.exists()) {
                System.err.println("info: .exit file already exists -> shortcutting to pushing the process");

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            // falls der step ein process ist, bibts dort kein .exit file sondern ein .status file
            else if (stepDirStatusFile.exists()) {
                System.err.println("info: .status file already exists.");
                try {
                    java.util.List<String> statusInhalt = Files.readAllLines(stepDirStatusFile.toPath(),
                            Charset.defaultCharset());
                    if (statusInhalt.size() > 0) {
                        String firstLine = statusInhalt.get(0);
                        System.err.println("info: status changed to: " + firstLine);

                        System.err.println("info: .status file contains status " + firstLine);
                        // wenn ein finaler status, dann soll manager aufgeweckt werden
                        if (firstLine.equals("error") || firstLine.equals("finished")) {
                            System.err.println("info: --> shortcutting to pushing process");
                            // alle keys loeschen
                            keys = null;

                            // den prozess weiter pushen
                            pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.err.println(
                            "IOException: trying to read file: " + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                } catch (ExceptionInInitializerError e) {
                    System.err.println("ExceptionInInitializerError: trying to read file: "
                            + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                }
            }

        }
    }

    process.log("info", "now into the watchloop");

    // warten auf ein Signal von einem WatchKey
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            System.err.println(new Timestamp(System.currentTimeMillis())
                    + ": ---- watcher thread: interrupted! returning to alternativer Thread");
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            //            System.err.println("debug: poll event " + event);

            WatchEvent.Kind kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            // dieses logging fuehrt zur aenderung von stderr.txt und .log, was wiederum ein ENTRY_MODIFY ausloest etc. endlosschleife bis platte volllaeuft
            //            System.err.println("debug: poll context " + name);
            Path child = dir.resolve(name);
            //            System.err.println("debug: poll child " + child);

            if (kind == ENTRY_CREATE) {
                if (child.endsWith(".exit")) {
                    System.err.println("info: waking up, because file created: " + child.toString());

                    // alle keys loeschen
                    keys = null;

                    // den prozess weiter pushen
                    pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                }
            }
            if ((kind == ENTRY_MODIFY) && (child.endsWith("process.pmb"))) {
                //               System.err.println("info: waking up, because process binary file has been modified: " + child.toString());

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                if (child.endsWith(".status")) {
                    try {
                        java.util.List<String> statusInhalt = Files.readAllLines(child,
                                Charset.defaultCharset());
                        if (statusInhalt.size() > 0) {
                            String firstLine = statusInhalt.get(0);
                            System.err.println("info: status changed to: " + firstLine);

                            // wenn ein finaler status, dann soll manager aufgeweckt werden
                            if (firstLine.equals("error") || firstLine.equals("finished")) {
                                System.err.println("info: waking up, because status changed to: " + firstLine);
                                // alle keys loeschen
                                keys = null;

                                // den prozess weiter pushen
                                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                            }
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.err.println("IOException: trying to read file: " + child.toString());
                        e.printStackTrace();
                    } catch (ExceptionInInitializerError e) {
                        System.err.println(
                                "ExceptionInInitializerError: trying to read file: " + child.toString());
                        e.printStackTrace();
                    }

                }
            }

            // reset the triggered key
            key.reset();
        }
    }
}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {//  w ww .  j a va  2s .c  om
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}

From source file:nz.co.fortytwo.signalk.server.SignalKServer.java

protected SignalKServer(String configDir) throws Exception {
    // init config
    Properties props = System.getProperties();
    props.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperties(props);//ww w .  j  a va2  s .  c o m

    Util.getConfig();
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("SignalKServer starting....");

    // do we have a USB drive connected?
    //logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();
    //main.setApplicationContextUri("classpath:META-INF/spring/camel-context.xml");
    // enable hangup support which mean we detect when the JVM terminates,
    // and stop Camel graceful
    main.enableHangupSupport();

    // Start activemq broker
    BrokerService broker = ActiveMqBrokerFactory.newInstance();

    broker.start();
    //DNS-SD, zeroconf mDNS
    startMdns();
    configureRouteManager(main);
    // and run, which keeps blocking until we terminate the JVM (or stop
    // CamelContext)
    main.start();

    WatchService service = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("./conf");
    dir.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
    WatchKey key = null;
    while (true) {
        key = service.take();
        // Dequeueing events
        Kind<?> kind = null;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            // Get the type of the event
            kind = watchEvent.kind();
            logger.debug(
                    "SignalKServer conf/ event:" + watchEvent.kind() + " : " + watchEvent.context().toString());
            if (StandardWatchEventKinds.OVERFLOW == kind) {
                continue; //loop
            } else if (StandardWatchEventKinds.ENTRY_MODIFY == kind) {
                // A new Path was created 
                @SuppressWarnings("unchecked")
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                // Output
                if (newPath.endsWith("signalk-restart")) {
                    logger.info("SignalKServer conf/signalk-restart changed, stopping..");
                    main.stop();
                    main.getCamelContexts().clear();
                    main.getRouteBuilders().clear();
                    main.getRouteDefinitions().clear();

                    // so now shutdown serial reader and server
                    RouteManager routeManager = RouteManagerFactory.getInstance();
                    routeManager.stopNettyServers();
                    routeManager.stopSerial();
                    if (server != null) {
                        server.stop();
                        server = null;
                    }
                    RouteManagerFactory.clear();
                    configureRouteManager(main);
                    main.start();
                }

            }
        }

        if (!key.reset()) {
            break; //loop
        }
    }

    stopMdns();
    broker.stop();
    // write out the signalk model
    SignalKModelFactory.save(SignalKModelFactory.getInstance());
    System.exit(0);
}

From source file:org.tallison.cc.CCGetter.java

private void execute(Path indexFile, Path rootDir, Path statusFile) throws IOException {

    int count = 0;
    BufferedWriter writer = Files.newBufferedWriter(statusFile, StandardCharsets.UTF_8);
    InputStream is = null;//from  w w  w.  java 2  s .  c  o  m
    try {
        if (indexFile.endsWith(".gz")) {
            is = new BufferedInputStream(new GZIPInputStream(Files.newInputStream(indexFile)));
        } else {
            is = new BufferedInputStream(Files.newInputStream(indexFile));
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line = reader.readLine();
            while (line != null) {
                processRow(line, rootDir, writer);
                if (++count % 100 == 0) {
                    logger.info(indexFile.getFileName().toString() + ": " + count);
                }
                line = reader.readLine();
            }

        }
    } finally {
        IOUtils.closeQuietly(is);
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.liferay.sync.engine.util.FileUtilTest.java

@Test
public void testRenameFile() throws Exception {
    Path sourceFilePath = Files.createTempFile("test", null);

    Path parentFilePath = sourceFilePath.getParent();

    String sourceFilePathFileName = String.valueOf(sourceFilePath.getFileName());

    Path targetFilePath = parentFilePath.resolve(sourceFilePathFileName.toUpperCase());

    FileUtil.moveFile(sourceFilePath, targetFilePath);

    Path realFilePath = targetFilePath.toRealPath();

    Path realFilePathFileName = realFilePath.getFileName();

    Assert.assertFalse(sourceFilePath.endsWith(realFilePathFileName));
    Assert.assertTrue(targetFilePath.endsWith(realFilePathFileName));
}

From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java

private long searchAndAppendAfter(final ServletConfig config, final Element agglomerateElement,
        final String scriptSrc, final String pathPrefix, final String pathSuffix, final String urlAttribute,
        long lastModified) throws MalformedURLException, IOException, URISyntaxException {
    if (mode == Mode.DEVELOPMENT) {
        // add a watch for that directory
        final Path path = Paths.get(config.getServletContext().getRealPath(scriptSrc));
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
    }/* w  w  w  .  j  av a 2  s.  co  m*/
    final Set<String> childrenPaths = config.getServletContext().getResourcePaths(scriptSrc);
    for (final String path : childrenPaths) {
        if (path.endsWith(pathSuffix)) {
            // add that JS
            final StringBuilder targetScript = new StringBuilder("<");
            targetScript.append(agglomerateElement.tagName());
            // copy all the origin attributes
            for (final Attribute attribute : agglomerateElement.attributes()) {
                final String key = attribute.getKey();
                if (!ATTRIBUTE_NAME.equalsIgnoreCase(key) && !urlAttribute.equalsIgnoreCase(key)
                        && !URL_ATTRIBUTE_ATTRIBUTE_NAME.equalsIgnoreCase(key)) {
                    targetScript.append(" ").append(attribute.html());
                }
            }
            // specify the src path
            final String childUrl = StringUtils.removeStart(path, pathPrefix);
            targetScript.append(" ").append(new Attribute(urlAttribute, childUrl).html()).append(" />");
            agglomerateElement.after(targetScript.toString());
            lastModified = Math.max(
                    config.getServletContext().getResource(childUrl).openConnection().getLastModified(),
                    lastModified);
        } else if (path.endsWith("/")) {
            // it's a directory, recurse search & append
            lastModified = Math.max(searchAndAppendAfter(config, agglomerateElement, path, pathPrefix,
                    pathSuffix, urlAttribute, lastModified), lastModified);
        }
    }
    return lastModified;
}

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/*from   ww w  . j  a  va 2s.  co 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();
}

From source file:org.codice.ddf.security.migratable.impl.SecurityMigratableTest.java

private void setup(String ddfHomeStr, String tag, String productVersion) throws IOException {
    ddfHome = tempDir.newFolder(ddfHomeStr).toPath().toRealPath();
    Path binDir = ddfHome.resolve("bin");
    Files.createDirectory(binDir);
    System.setProperty(DDF_HOME_SYSTEM_PROP_KEY, ddfHome.toRealPath().toString());
    setupBrandingFile(SUPPORTED_BRANDING);
    setupVersionFile(productVersion);/*w w  w  . j av  a2  s .  c o m*/
    setupMigrationProperties(SUPPORTED_PRODUCT_VERSION);
    for (Path path : PROPERTIES_FILES) {
        Path p = ddfHome.resolve(path);
        Files.createDirectories(p.getParent());
        Files.createFile(p);
        if (p.endsWith(Paths.get("server", "encryption.properties"))) {
            writeProperties(p, CRL_PROP_KEY, CRL.toString(),
                    String.format("%s&%s", p.toRealPath().toString(), tag));
        } else {
            writeProperties(p, "something", "else", String.format("%s&%s", p.toRealPath().toString(), tag));
        }
    }
    Files.createDirectory(ddfHome.resolve(PDP_POLICIES_DIR));

    setupCrl(tag);
    setupPdpFiles(tag);
    Files.createDirectory(ddfHome.resolve(SECURITY_POLICIES_DIR));
    setupPolicyFiles(tag);
}

From source file:io.warp10.worf.WorfCLI.java

public int execute(String[] args) {
    try {/*  w w w.  ja v  a2s .c om*/
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        String inputFile = null;
        boolean interactive = false;
        boolean token = false;
        String outputFile = null;
        String keyStoreFile = null;

        String producerUID = null;
        String ownerUID = null;
        String appName = null;
        long ttl = 0L;

        PrintWriter out = new PrintWriter(System.out);

        if (cmd.hasOption(HELP)) {
            help();
            return 0;
        }

        if (cmd.hasOption(VERSION)) {
            version(out);
            return 0;
        }

        if (cmd.hasOption(VERBOSE)) {
            verbose = true;
        }

        if (cmd.hasOption(INTERACTIVE)) {
            interactive = true;
        }

        if (cmd.hasOption(OUTPUT)) {
            outputFile = cmd.getOptionValue(OUTPUT);
        }

        if (cmd.hasOption(KEYSTORE)) {
            keyStoreFile = cmd.getOptionValue(KEYSTORE);
        }

        if (cmd.hasOption(TOKEN)) {
            token = true;
            // PRODUCER UUID OPTION (mandatory)
            // --------------------------------------------------------------------
            if (cmd.hasOption(UUIDGEN_PRODUCER)) {
                producerUID = UUID.randomUUID().toString();
            } else if (cmd.hasOption(P_UUID)) {
                producerUID = cmd.getOptionValue(P_UUID);
                UUID.fromString(producerUID);
            }

            // OWNER UUID OPTION (mandatory)
            // --------------------------------------------------------------------
            if (cmd.hasOption(UUIDGEN_OWNER)) {
                ownerUID = UUID.randomUUID().toString();
            } else if (cmd.hasOption(O_UUID)) {
                ownerUID = cmd.getOptionValue(O_UUID);
                UUID.fromString(ownerUID);
            } else {
                ownerUID = producerUID;
            }

            if (cmd.hasOption(APPNAME)) {
                appName = cmd.getOptionValue(APPNAME);
            }

            if (cmd.hasOption(TTL)) {
                ttl = Long.parseLong(cmd.getOptionValue(TTL));
                long ttlMax = Long.MAX_VALUE - System.currentTimeMillis();

                if (ttl >= ttlMax) {
                    throw new WorfException("TTL can not be upper than " + ttlMax + " ms");
                }

            } else {
                throw new WorfException("The option 'ttl' is missing ");
            }
        }

        // get the input file name
        switch (cmd.getArgs().length) {
        case 0:
            throw new WorfException("Config or template file missing.");

        case 1:
            inputFile = cmd.getArgs()[0];
            break;

        default:
            throw new WorfException("Too many arguments, only one config or template file expected.");
        }

        // load the interactive mode
        if (interactive) {
            return runInteractive(inputFile);
        }

        Properties config = Worf.readConfig(inputFile, out);

        //
        // TEMPLATE CONFIGURATION
        //
        if (WorfTemplate.isTemplate(config)) {

            // load keystore if needed
            WorfKeyMaster templateKeyMaster = null;
            if (!Strings.isNullOrEmpty(keyStoreFile)) {
                // read config
                Properties keyStoreConfig = Worf.readConfig(keyStoreFile, out);
                // load key master
                templateKeyMaster = new WorfKeyMaster(keyStoreConfig);

                if (!templateKeyMaster.loadKeyStore()) {
                    throw new WorfException("Template Keystore not loaded");
                }
            }

            WorfTemplate tpl = new WorfTemplate(config, inputFile);

            // GENERATE CRYPTO KEYS
            for (String cryptoKey : tpl.getCryptoKeys()) {
                String keySize = tpl.generateCryptoKey(cryptoKey);
                if (keySize != null) {
                    out.println(keySize + " bits secured key for " + cryptoKey + "  generated");
                } else {
                    throw new WorfException("Unable to generate " + cryptoKey + ", template error");
                }
            }

            // read defaults
            if (token) {
                Properties defaultProperties = Worf.readDefault(inputFile, out);
                appName = Worf.getDefault(defaultProperties, out, appName, APPNAME);
                producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID);
                ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID);
            }
            // GENERATE TOKENS
            for (String tokenKey : tpl.getTokenKeys()) {
                if (!token) {
                    throw new WorfException("Unable to generate template tokens missing -t option");
                }
                if (templateKeyMaster == null) {
                    throw new WorfException("Unable to generate template tokens missing -ks option");
                }

                String tokenIdent = tpl.generateTokenKey(tokenKey, appName, ownerUID, producerUID, ttl,
                        templateKeyMaster);
                out.println("Token generated key=" + tokenKey + "  ident=" + tokenIdent);
            }

            // GET INTERACTIVE CONFIGURATION
            if (tpl.getFieldsStack().size() > 0) {
                throw new WorfException("Unable the update template, you are not in interactive mode");
            }

            // save the template
            if (Strings.isNullOrEmpty(outputFile)) {
                Path inputConfigurationPath = Paths.get(inputFile);
                String outputFileName = inputConfigurationPath.getFileName().toString();
                outputFileName = outputFileName.replace("template", "conf");

                StringBuilder sb = new StringBuilder();
                sb.append(inputConfigurationPath.getParent().toString());
                if (!inputConfigurationPath.endsWith(File.separator)) {
                    sb.append(File.separator);
                }
                sb.append(outputFileName);

                outputFile = sb.toString();
            }
            tpl.saveConfig(outputFile);
            out.println("Warp configuration saved (" + outputFile + ")");
            out.flush();
            inputFile = outputFile;

            // Keystore is given as input
            //end of the job
            if (!Strings.isNullOrEmpty(keyStoreFile)) {
                out.println("Warp configuration file used for tokens generation in templates");
                out.println("For generate tokens, reload Worf without 'ks' option");
                out.flush();
                System.exit(0);
            }
        }

        //
        // GENERATE TOKEN
        //
        if (token) {
            // read config
            config = Worf.readConfig(inputFile, out);
            // load key master
            WorfKeyMaster keyMaster = new WorfKeyMaster(config);

            if (!keyMaster.loadKeyStore()) {
                throw new WorfException("Keystore not loaded");
            }

            Properties defaultProperties = Worf.readDefault(inputFile, out);
            appName = Worf.getDefault(defaultProperties, out, appName, APPNAME);
            producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID);
            ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID);

            // save default
            if (defaultProperties == null) {
                Worf.saveDefault(inputFile, appName, producerUID, ownerUID);
            }

            // deliver token
            String readToken = keyMaster.deliverReadToken(appName, producerUID, ownerUID, ttl);
            String writeToken = keyMaster.deliverWriteToken(appName, producerUID, ownerUID, ttl);

            // write outputformat
            JSONObject jsonOutput = new JSONObject();
            JSONObject jsonToken = new JSONObject();
            jsonToken.put("token", readToken);
            jsonToken.put("tokenIdent", keyMaster.getTokenIdent(readToken));
            jsonToken.put("ttl", ttl);
            jsonToken.put("application", appName);
            jsonToken.put("owner", ownerUID);
            jsonToken.put("producer", producerUID);

            jsonOutput.put("read", jsonToken);

            jsonToken = new JSONObject();
            jsonToken.put("token", writeToken);
            jsonToken.put("tokenIdent", keyMaster.getTokenIdent(writeToken));
            jsonToken.put("ttl", ttl);
            jsonToken.put("application", appName);
            jsonToken.put("owner", ownerUID);
            jsonToken.put("producer", producerUID);

            jsonOutput.put("write", jsonToken);

            System.out.println(jsonOutput.toString());
        }

    } catch (Exception we) {
        if (verbose) {
            we.printStackTrace();
        } else {
            System.out.println(we.getMessage() + "\n");
        }
        help();
        return -1;
    }
    return 0;
}