Example usage for java.io File separatorChar

List of usage examples for java.io File separatorChar

Introduction

In this page you can find the example usage for java.io File separatorChar.

Prototype

char separatorChar

To view the source code for java.io File separatorChar.

Click Source Link

Document

The system-dependent default name-separator character.

Usage

From source file:com.eviware.x.impl.swing.FileFormField.java

public String getValue() {
    String text = textField.getText().trim();

    if (projectRoot != null && text.length() > 0) {
        String tempName = projectRoot + File.separatorChar + text;
        if (new File(tempName).exists()) {
            text = tempName;/* w ww  .j a v a  2s .  com*/
        }
    }

    return text;
}

From source file:net.chaosserver.timelord.data.XmlDataReaderWriter.java

/**
 * Reads the timelordData using the default file name.
 *
 * @return a timelordData object as read from file.
 * @throws TimelordDataException indicates an error reading in the file
 *//*from   ww w  .jav a 2  s.c  o m*/
public TimelordData readTimelordData() throws TimelordDataException {

    /*
     * Need to do a sed on these two items:
     * net.chaosserver.timetracker.data.TimeTrackerData =
     *     net.chaosserver.timelord.data.TimelordData
     *
     * net.chaosserver.timetracker.data.TimeTrackerTask =
     *     net.chaosserver.timelord.data.TimelordTask
     */
    TimelordData timelordData;

    /*
    File homeDirectory = new File(System.getProperty("user.home"));
    File[] datafile = homeDirectory.listFiles(this);
    */
    File datafile = new File(
            System.getProperty("user.home") + File.separatorChar + DEFAULT_FILENAME + DEFAULT_EXTENSION);

    if (!datafile.exists()) {
        File oldfile = new File(
                System.getProperty("user.home") + File.separatorChar + "TimeTrackerData" + DEFAULT_EXTENSION);

        if (oldfile.exists()) {
            if (log.isInfoEnabled()) {
                log.info("Found older version of the file, " + "running the converstion.");
            }
            try {
                convertTrackerToLord(oldfile, datafile);
            } catch (IOException e) {
                throw new TimelordDataException("Failed to convert file", e);
            }
        }
    }

    if (datafile.exists()) {
        try {
            FileInputStream fileInputStream = new FileInputStream(datafile);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            XMLDecoder xmlDecoder = new XMLDecoder(bufferedInputStream);
            timelordData = (TimelordData) xmlDecoder.readObject();
            timelordData.setTimelordReaderWriter(this);

            if (log.isInfoEnabled()) {
                log.info("Finished loading [" + datafile + "]");
            }
        } catch (FileNotFoundException e) {
            throw new TimelordDataException("Failed to read", e);
        }
    } else {
        if (log.isInfoEnabled()) {
            log.info("Failed to find [" + datafile + "]");
        }
        timelordData = new TimelordData();
    }

    return timelordData;
}

From source file:edu.stanford.muse.launcher.Main.java

public static void main(String args[]) throws Exception {

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();/* ww w  . java2s.c o  m*/
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            out.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/muse/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:org.saiku.web.rest.resources.BasicRepositoryResource2.java

public void setPath(String path) throws Exception {
    FileSystemManager fileSystemManager;
    try {//from  w w w  . j  a  v  a2s. c  o  m
        if (!path.endsWith("" + File.separatorChar)) {
            path += File.separatorChar;
        }
        fileSystemManager = VFS.getManager();
        FileObject fileObject;
        fileObject = fileSystemManager.resolveFile(path);
        if (fileObject == null) {
            throw new IOException("File cannot be resolved: " + path);
        }
        if (!fileObject.exists()) {
            throw new IOException("File does not exist: " + path);
        }
        repo = fileObject;
    } catch (Exception e) {
        log.error("Error setting path for repository: " + path, e);
    }
}

From source file:at.ac.tuwien.big.testsuite.impl.task.UnzipTaskImpl.java

private void unzip(File zipFile, File baseDirectory, boolean extractContainedZipFiles,
        Collection<Exception> exceptions) {
    try (ZipFile zip = new ZipFile(zipFile)) {
        addTotalWork(zip.size());/*from   www. ja  v a 2  s.c  om*/
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String escapedEntryName = escapeFileName(entry.getName());
            File entryFile = new File(baseDirectory, escapedEntryName);

            if (entry.isDirectory()) {
                if (!contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                    entryFile.mkdir();
                }
            } else if (!endsWith(entryFile.getName(), ignoredExtensions)
                    && !contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                if (entryFile.getAbsolutePath().indexOf(File.separatorChar,
                        baseDirectory.getAbsolutePath().length()) > -1) {
                    // Only create dirs if file is not in the root dir
                    entryFile.getParentFile().mkdirs();
                }

                try (InputStream is = zip.getInputStream(entry);
                        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(entryFile))) {
                    copyInputStream(is, outputStream);
                }

                if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".zip")
                        || escapedEntryName.toLowerCase().endsWith(".war"))) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unzip(entryFile, zipFileBaseDir, false, exceptions);
                    entryFile.delete();
                } else if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".tar")
                        || escapedEntryName.toLowerCase().endsWith(".gz"))) {
                    String zipFileName = escapedEntryName;
                    int offset = escapedEntryName.toLowerCase().endsWith(".tar") ? 4 : 0;
                    offset = escapedEntryName.toLowerCase().endsWith(".tar.gz") ? 7 : offset;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - offset));
                    zipFileBaseDir.mkdir();

                    untar(entryFile, zipFileBaseDir, exceptions,
                            escapedEntryName.toLowerCase().endsWith(".tar.gz"));
                    entryFile.delete();
                } else if (extractContainedZipFiles && escapedEntryName.toLowerCase().endsWith(".rar")) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unrar(entryFile, zipFileBaseDir, exceptions);
                    entryFile.delete();
                }
            }

            addDoneWork(1);
        }
    } catch (Exception ex) {
        exceptions.add(ex);
    }
}

From source file:cz.cuni.amis.planning4j.validation.external.ValValidator.java

public static void extractAndPrepareValidator(File targetDirectory) {
    String folderName = getValidatorFolderName();
    try {/* w  w w  . j  a  va  2 s .  c o m*/
        for (String fileToExtractName : getAuxiliaryFiles()) {
            File binaryFile = new File(targetDirectory, folderName + File.separatorChar + fileToExtractName);

            ItSimpleUtils.extractFileIfNotExists(binaryFile, "/" + folderName + "/" + fileToExtractName);
        }
        String validatorExecutableName = getValidatorExecutableName();
        File mainExecutable = new File(targetDirectory,
                folderName + File.separatorChar + validatorExecutableName);
        ItSimpleUtils.extractFileIfNotExists(mainExecutable, "/" + folderName + "/" + validatorExecutableName);
        mainExecutable.setExecutable(true, false);
    } catch (Exception ex) {
        throw new ValidationException("Could not extract VAL binaries.", ex);
    }
}

From source file:apim.restful.importexport.utils.ArchiveGeneratorUtil.java

/**
 * Add files of the directory to the archive
 *
 * @param directoryToZip  Location of the archive
 * @param file            File to be included in the archive
 * @param zipOutputStream Output stream//from w  w w .  ja  v a 2s .c o  m
 * @throws APIExportException If an error occurs while writing files to the archive
 */
private static void addToArchive(File directoryToZip, File file, ZipOutputStream zipOutputStream)
        throws APIExportException {

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(file);

        // Get relative path from archive directory to the specific file
        String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
                file.getCanonicalPath().length());
        if (File.separatorChar != '/')
            zipFilePath = zipFilePath.replace(File.separatorChar,
                    APIImportExportConstants.ARCHIVE_PATH_SEPARATOR);
        ZipEntry zipEntry = new ZipEntry(zipFilePath);
        zipOutputStream.putNextEntry(zipEntry);

        IOUtils.copy(fileInputStream, zipOutputStream);

        zipOutputStream.closeEntry();
    } catch (IOException e) {
        log.error("I/O error while writing files to archive" + e.getMessage());
        throw new APIExportException("I/O error while writing files to archive", e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

/**
 * Unzips a file./*from   ww  w . java2s.  c  o  m*/
 * @param gzippedFile A gzipped file.
 * @return The gunzipped version of the file.
 * @throws IOException If you screw up.
 */
public static File gunzip(File gzippedFile) throws IOException {
    OutputStream out = null;
    GZIPInputStream gzipInputStream = null;
    File gunzippedFile = new File(System.getProperty("java.io.tmpdir") + File.separatorChar
            + gzippedFile.getName().replace(".gz", ""));
    try {
        InputStream in = new FileInputStream(gzippedFile);
        gzipInputStream = new GZIPInputStream(in);
        out = new FileOutputStream(gunzippedFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = gzipInputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } finally {
        if (gzipInputStream != null) {
            gzipInputStream.close();
        }
        if (out != null) {
            out.close();
        }
    }
    return gunzippedFile;
}

From source file:de.fabianonline.telegram_backup.mediafilemanager.StickerFileManager.java

public void download() throws RpcErrorException, IOException {
    String old_file = Config.FILE_BASE + File.separatorChar + Config.FILE_STICKER_BASE + File.separatorChar
            + getTargetFilename();// w ww .  j a  v a 2  s. c om

    logger.trace("Old filename exists: {}", new File(old_file).exists());

    if (new File(old_file).exists()) {
        Files.copy(Paths.get(old_file), Paths.get(getTargetPathAndFilename()),
                StandardCopyOption.REPLACE_EXISTING);
        return;
    }
    super.download();
}

From source file:com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.java

public synchronized InputStream load(String url) throws Exception {
    if (!PathUtils.isHttpPath(url)) {
        try {// w ww. j a va2  s .com
            File file = new File(url.replace('/', File.separatorChar));
            if (file.exists())
                url = file.toURI().toURL().toString();
        } catch (Exception e) {
        }
    }

    if (urlCache.containsKey(url)) {
        setNewBaseURI(url);
        return new ByteArrayInputStream(urlCache.get(url));
    }

    if (url.startsWith("file:")) {
        return handleFile(url);
    }

    log.debug("Getting wsdl component from [" + url + "]");

    createGetMethod(url);

    if (aborted)
        return null;

    LoaderWorker worker = new LoaderWorker();
    if (useWorker)
        worker.start();
    else
        worker.construct();

    while (!aborted && !finished) {
        Thread.sleep(200);
    }

    // wait for method to catch up - required in unit tests..
    // limited looping to 10 loops because of eclipse plugin which entered 
    // endless loop without it
    // 
    int counter = 0;
    while (!aborted && getMethod.getResponseBody() == null && counter < 10) {
        Thread.sleep(200);
        counter++;
    }

    try {
        if (aborted) {
            throw new Exception("Load of url [" + url + "] was aborted");
        } else {
            byte[] content = getMethod.getResponseBody();
            if (content != null) {
                String compressionAlg = HttpClientSupport.getResponseCompressionType(getMethod);
                if (compressionAlg != null)
                    content = CompressionSupport.decompress(compressionAlg, content);

                urlCache.put(url, content);
                String newUrl = getMethod.getURI().getURI();
                if (!url.equals(newUrl))
                    log.info("BaseURI was redirected to [" + newUrl + "]");
                setNewBaseURI(newUrl);
                urlCache.put(newUrl, content);
                return new ByteArrayInputStream(content);
            } else {
                throw new Exception(
                        "Failed to load url; " + getMethod.getStatusCode() + " - " + getMethod.getStatusText());
            }
        }
    }

    finally {
        getMethod.releaseConnection();
    }
}