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:de.fabianonline.telegram_backup.exporter.HTMLExporter.java

public void export(UserManager user) {
    try {//from   w  ww  . j a v  a2 s  .  co m
        Database db = new Database(user, null);

        // Create base dir
        logger.debug("Creating base dir");
        String base = user.getFileBase() + "files" + File.separatorChar;
        new File(base).mkdirs();
        new File(base + "dialogs").mkdirs();

        logger.debug("Fetching dialogs");
        LinkedList<Database.Dialog> dialogs = db.getListOfDialogsForExport();
        logger.trace("Got {} dialogs", dialogs.size());
        logger.debug("Fetching chats");
        LinkedList<Database.Chat> chats = db.getListOfChatsForExport();
        logger.trace("Got {} chats", chats.size());

        logger.debug("Generating index.html");
        HashMap<String, Object> scope = new HashMap<String, Object>();
        scope.put("user", user);
        scope.put("dialogs", dialogs);
        scope.put("chats", chats);

        // Collect stats data
        scope.put("count.chats", chats.size());
        scope.put("count.dialogs", dialogs.size());

        int count_messages_chats = 0;
        int count_messages_dialogs = 0;
        for (Database.Chat c : chats)
            count_messages_chats += c.count;
        for (Database.Dialog d : dialogs)
            count_messages_dialogs += d.count;

        scope.put("count.messages", count_messages_chats + count_messages_dialogs);
        scope.put("count.messages.chats", count_messages_chats);
        scope.put("count.messages.dialogs", count_messages_dialogs);

        scope.put("count.messages.from_me", db.getMessagesFromUserCount());

        scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix()));

        scope.putAll(db.getMessageAuthorsWithCount());
        scope.putAll(db.getMessageTypesWithCount());
        scope.putAll(db.getMessageMediaTypesWithCount());

        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile("templates/html/index.mustache");
        OutputStreamWriter w = getWriter(base + "index.html");
        mustache.execute(w, scope);
        w.close();

        mustache = mf.compile("templates/html/chat.mustache");

        int i = 0;
        logger.debug("Generating {} dialog pages", dialogs.size());
        for (Database.Dialog d : dialogs) {
            i++;
            logger.trace("Dialog {}/{}: {}", i, dialogs.size(), Utils.anonymize("" + d.id));
            LinkedList<HashMap<String, Object>> messages = db.getMessagesForExport(d);
            scope.clear();
            scope.put("user", user);
            scope.put("dialog", d);
            scope.put("messages", messages);

            scope.putAll(db.getMessageAuthorsWithCount(d));
            scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix(d)));
            scope.putAll(db.getMessageTypesWithCount(d));
            scope.putAll(db.getMessageMediaTypesWithCount(d));

            w = getWriter(base + "dialogs" + File.separatorChar + "user_" + d.id + ".html");
            mustache.execute(w, scope);
            w.close();
        }

        i = 0;
        logger.debug("Generating {} chat pages", chats.size());
        for (Database.Chat c : chats) {
            i++;
            logger.trace("Chat {}/{}: {}", i, chats.size(), Utils.anonymize("" + c.id));
            LinkedList<HashMap<String, Object>> messages = db.getMessagesForExport(c);
            scope.clear();
            scope.put("user", user);
            scope.put("chat", c);
            scope.put("messages", messages);

            scope.putAll(db.getMessageAuthorsWithCount(c));
            scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix(c)));
            scope.putAll(db.getMessageTypesWithCount(c));
            scope.putAll(db.getMessageMediaTypesWithCount(c));

            w = getWriter(base + "dialogs" + File.separatorChar + "chat_" + c.id + ".html");
            mustache.execute(w, scope);
            w.close();
        }

        logger.debug("Generating additional files");
        // Copy CSS
        URL cssFile = getClass().getResource("/templates/html/style.css");
        File dest = new File(base + "style.css");
        FileUtils.copyURLToFile(cssFile, dest);
        logger.debug("Done exporting.");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Exception above!");
    }
}

From source file:org.jvnet.hudson.generators.HudsonConfigGenerator.java

@Override
public String generate() {
    String configBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HUDSON_CONFIG_TEMPLATE,
            getModel());/*from w  w  w  .  j  a  v  a  2 s  . c o  m*/

    BufferedWriter bufferedWriter = null;
    try {
        File file = new File(outputDirectory);
        //noinspection ResultOfMethodCallIgnored
        file.mkdirs();
        file = new File(outputDirectory + File.separatorChar + CONFIG_FILE_NAME);

        bufferedWriter = new BufferedWriter(new FileWriter(file));
        bufferedWriter.write(configBody);
        bufferedWriter.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return configBody;
}

From source file:org.hawkular.apm.server.api.utils.zipkin.BinaryAnnotationMappingStorage.java

/**
 * Default storage. It loads mappings from jboss configuration directory.
 *///from   w w  w .  j  av a2s . co m
public BinaryAnnotationMappingStorage() {

    String jbossConfigDir = System.getProperties().getProperty("jboss.server.config.dir");
    if (jbossConfigDir == null) {
        log.errorf("Property jboss.server.config.dir is not set, Binary Annotation mapping rules set to empty");
        keyBasedMappings = Collections.emptyMap();
        return;
    }

    String path = System.getProperty("jboss.server.config.dir") + File.separatorChar
            + HAWKULAR_ZIPKIN_BINARY_ANNOTATION_MAPPING;

    loadMappings(path);
}

From source file:au.org.ala.delta.util.FileUtils.java

/**
 * Attempts to make a relative path from path to file. If path and file have different roots (like drives under Windows), then
 * the path cannot be made relative, and in these cases this function will return null.
 * /*from   w  ww  .j  ava  2  s. c om*/
 * @param path the source path
 * @param file the file/directory that will be made relative to the source path
 * @return either relative path from path to file, or null indicating that no common ancestor could be found (i.e. path cannot be made relative).
 * 
 */
public static String makeRelativeTo(String path, File file) {
    String relativePath;
    if (file.isAbsolute()) {
        File dataSetPath = new File(path);

        File parent = parent(file, dataSetPath);
        File commonParent = dataSetPath;
        String prefix = "";
        while (!parent.equals(commonParent) && commonParent != null) {
            prefix += ".." + File.separatorChar;
            commonParent = commonParent.getParentFile();
            parent = parent(file, commonParent);
        }

        if (commonParent == null) {
            // No common parent, cannot make relative
            return null;
        }

        String filePath = file.getAbsolutePath();
        String parentPath = parent.getAbsolutePath();

        int relativePathIndex = filePath.indexOf(parentPath) + parentPath.length();
        if (!parentPath.endsWith(File.separator)) {
            relativePathIndex++;
        }
        if (relativePathIndex > filePath.length()) {
            relativePathIndex = filePath.length();
        }
        relativePath = prefix + filePath.substring(relativePathIndex);
        if (StringUtils.isEmpty(relativePath)) {
            relativePath = ".";
        }
    } else {
        relativePath = file.getPath();
    }
    return relativePath;

}

From source file:Main.java

static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) {
    ArrayList<String> basePath = getPathComponents(canonicalBaseFile);
    ArrayList<String> pathToRelativize = getPathComponents(canonicalFileToRelativize);

    //if the roots aren't the same (i.e. different drives on a windows machine), we can't construct a relative
    //path from one to the other, so just return the canonical file
    if (!basePath.get(0).equals(pathToRelativize.get(0))) {
        return canonicalFileToRelativize.getPath();
    }//from   ww  w .  ja  v a2  s  .  c o  m

    int commonDirs;
    StringBuilder sb = new StringBuilder();

    for (commonDirs = 1; commonDirs < basePath.size() && commonDirs < pathToRelativize.size(); commonDirs++) {
        if (!basePath.get(commonDirs).equals(pathToRelativize.get(commonDirs))) {
            break;
        }
    }

    boolean first = true;
    for (int i = commonDirs; i < basePath.size(); i++) {
        if (!first) {
            sb.append(File.separatorChar);
        } else {
            first = false;
        }

        sb.append("..");
    }

    first = true;
    for (int i = commonDirs; i < pathToRelativize.size(); i++) {
        if (first) {
            if (sb.length() != 0) {
                sb.append(File.separatorChar);
            }
            first = false;
        } else {
            sb.append(File.separatorChar);
        }

        sb.append(pathToRelativize.get(i));
    }

    if (sb.length() == 0) {
        return ".";
    }

    return sb.toString();
}

From source file:de.thischwa.pmcms.tool.PathTool.java

/**
 * Changes an application context relative file to an absolute url.
 * //www .java  2  s .  c  om
 * @param fileName
 * @return url
 */
public static String getURLFromFile(final String fileName, boolean encode) {
    File file = new File(fileName);
    String temp = file.getPath().replace(File.separatorChar, '/');
    if (encode)
        temp = encodePath(temp);
    return (temp.startsWith("/")) ? temp : "/".concat(temp);
}

From source file:edu.stanford.muse.lens.LensPrefs.java

public LensPrefs(String cacheDir) {
    pathToPrefsFile = cacheDir + File.separatorChar + PREFS_FILENAME;
    String pathToPrefsFileTxt = pathToPrefsFile + ".txt";
    log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
    // read serialized state from file
    try {//  w  ww . j  a  v a  2s . c  o  m
        log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
        loadPrefs(pathToPrefsFile + ".txt");
    } catch (IOException ioe) {
        log.info("Unable to load text lens prefs from " + pathToPrefsFileTxt);
        try {
            log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
            FileInputStream fis = new FileInputStream(pathToPrefsFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            prefs = (Map<String, Map<String, Float>>) ois.readObject();
            ois.close();
        } catch (FileNotFoundException e) {
            // hilitePrefs = new ArrayList<BrowserPrefs>();
            log.info("No existing browser preferences file: " + pathToPrefsFile);
        } catch (Exception e) {
            log.warn("exception reading " + pathToPrefsFile + ": " + Util.stackTrace(e));
        }
    }
    log.info(prefs.size() + " terms have user-specified weights");
    if (log.isDebugEnabled())
        log.debug(" User prefs are : " + this);
}

From source file:net.lightbody.bmp.proxy.jetty.html.Include.java

/** Constructor.
 * Include file//from  ww w. ja  va 2s  .  com
 * @param directory Directory name
 * @param fileName file name
 * @exception IOException File not found
 */
public Include(String directory, String fileName) throws IOException {
    if (directory == null)
        directory = ".";

    if (File.separatorChar != '/') {
        directory = directory.replace('/', File.separatorChar);
        fileName = fileName.replace('/', File.separatorChar);
    }

    if (log.isDebugEnabled())
        log.debug("IncludeTag(" + directory + "," + fileName + ")");
    includeFile(new File(directory, fileName));
}

From source file:com.stimulus.archiva.presentation.ExportBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SearchBean searchBean = (SearchBean) form;

    String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String zipFileName = "export-" + sdf.format(new Date()) + ".zip";
    File zipFile = new File(outputDir + zipFileName);

    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(zipFileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {/*from  w  w  w. j  a v a 2  s. com*/
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
    }

    logger.debug("size of searchResult = " + searchBean.getSearchResults().size());
    //MessageBean.viewMessage
    List<File> files = new ArrayList<File>();
    for (SearchResultBean searchResult : searchBean.getSearchResults()) {
        if (searchResult.getSelected()) {
            Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(),
                    false);

            HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
            String baseURL = hsr.getRequestURL().substring(0,
                    hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
            MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message

            //              MessageBean mbean = new MessageBean();
            //              mbean.setMessageID(searchResult.getUniqueID());
            //              mbean.setVolumeID(searchResult.getVolumeID());
            //              writer.println(searchResult.toString());
            //              writer.println(messageExtraction.getFileName());

            File fileToAdd = new File(outputDir, messageExtraction.getFileName());
            if (!files.contains(fileToAdd)) {
                files.add(fileToAdd);
            }
        }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
        byte[] buf = new byte[1024];
        for (File f : files) {
            ZipEntry ze = new ZipEntry(f.getName());
            logger.debug("Adding file " + f.getName());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            for (;;) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                zos.write(buf, 0, len);
            }
            is.close();
            Config.getFileSystem().getTempFiles().markForDeletion(f);
        }
    } finally {
        zos.close();
    }
    logger.debug("download zipped emails {fileName='" + zipFileName + "'}");

    String contentType = "application/zip";
    Config.getFileSystem().getTempFiles().markForDeletion(zipFile);
    return new FileStreamInfo(contentType, zipFile);
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

public static PackageSet loadFromZip(ZipFile file) throws IOException, PackageNotFoundException {
    HashMap<String, HashMap<String, InputStream>> setMap = new HashMap<>();
    Enumeration<? extends ZipEntry> entries = file.entries();
    String setName = file.getName().substring(file.getName().lastIndexOf(File.separatorChar) + 1)
            .replace(".zip", "");
    // extract correct entries from the zip file
    while (true) {
        try {/*  ww w  .  j  a v a  2s. com*/
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // get the correct path separator (both can be used)
            char separator = (entryName.contains("/") ? '/' : '\\');
            // index of first separator used to get set name
            int index = entryName.indexOf(separator);
            // skip entry if there are no path separators (files in zip root like license, readme etc.)
            if (index < 0) {
                continue;
            }
            if (!entryName.endsWith(".yml")) {
                continue;
            }
            String[] parts = entryName.split(Pattern.quote(String.valueOf(separator)));
            String ymlName = parts[parts.length - 1].substring(0, parts[parts.length - 1].length() - 4);
            StringBuilder builder = new StringBuilder();
            int length = parts.length - 1;
            boolean conversation = false;
            if (parts[length - 1].equals("conversations")) {
                length--;
                conversation = true;
            }
            for (int i = 0; i < length; i++) {
                builder.append(parts[i] + '-');
            }
            String packName = builder.substring(0, builder.length() - 1);
            HashMap<String, InputStream> packMap = setMap.get(packName);
            if (packMap == null) {
                packMap = new HashMap<>();
                setMap.put(packName, packMap);
            }
            List<String> allowedNames = Arrays
                    .asList(new String[] { "main", "events", "conditions", "objectives", "journal", "items" });
            if (conversation) {
                packMap.put("conversations." + ymlName, file.getInputStream(entry));
            } else {
                if (allowedNames.contains(ymlName)) {
                    packMap.put(ymlName, file.getInputStream(entry));
                }
            }
        } catch (NoSuchElementException e) {
            break;
        }
    }
    PackageSet set = parseStreams(setName, setMap);
    BetonQuestEditor.getInstance().getSets().add(set);
    RootController.setPackages(BetonQuestEditor.getInstance().getSets());
    return set;
}