Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:io.stallion.dataAccess.file.TextFilePersister.java

public T fromString(String fileContent, Path fullPath) {
    if (fullPath.toString().endsWith(".html") || fullPath.toString().endsWith(".htm")) {
        return fromHtml(fileContent, fullPath);
    }/*from   www  .  j a  v a  2  s.  co  m*/
    String relativePath = fullPath.toString().replace(getBucketFolderPath(), "");
    Path path = fullPath;

    T item = null;
    try {
        item = getModelClass().newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    item.setTags(new ArrayList<String>()).setElementById(new HashMap<>()).setElements(new ArrayList<>())
            .setPublishDate(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"))).setTitle("")
            .setDraft(false).setTemplate("").setContent("").setSlug("");

    /* Get the id and slug */

    item.setSlug(FilenameUtils.removeExtension(relativePath));
    if (!item.getSlug().startsWith("/")) {
        item.setSlug("/" + item.getSlug());
    }
    if (item.getSlug().endsWith("/index")) {
        item.setSlug(item.getSlug().substring(item.getSlug().length() - 6));
    }

    if (empty(fileContent.trim())) {
        return item;
    }

    /* Parse out toml properties, if found */
    String tomlContent;
    Matcher tomlMatcher = tomlPattern.matcher(fileContent);
    if (tomlMatcher.find()) {
        tomlContent = tomlMatcher.group(1).trim();
        fileContent = tomlMatcher.replaceAll("\n");
        Map tomlMap = new Toml().read(tomlContent).to(HashMap.class);
        for (Object key : tomlMap.keySet()) {
            Object value = tomlMap.get(key);
            setProperty(item, key.toString(), value);
        }
    }

    List<String> allLines = Arrays.asList(fileContent.split("\n"));

    if (allLines.size() == 0) {
        return item;
    }

    if (empty(item.getTitle())) {
        item.setTitle(allLines.get(0));
    }

    String titleLine = "";
    List<String> propertiesSection = list();
    String rawContent = "";
    int propertiesStartAt = 0;
    if (allLines.size() > 1) {
        if (allLines.get(1).startsWith("----") || allLines.get(1).startsWith("====")) {
            titleLine = allLines.get(0);
            propertiesStartAt = 2;
            item.setTitle(titleLine);
        }
    }

    int propertiesEndAt = propertiesStartAt;
    for (; propertiesEndAt < allLines.size(); propertiesEndAt++) {
        String line = allLines.get(propertiesEndAt);
        if (line.trim().equals("---")) {
            continue;
        }
        int colon = line.indexOf(':');
        if (colon == -1) {
            break;
        }
        String key = line.substring(0, colon).trim();
        String value = line.substring(colon + 1, line.length()).trim();
        if ("oldUrls".equals(key)) {
            setProperty(item, key, apply(list(StringUtils.split(value, ";")), (aUrl) -> aUrl.trim()));
        } else {
            setProperty(item, key, value);
        }
    }
    if (propertiesEndAt < allLines.size()) {
        rawContent = StringUtils.join(allLines.subList(propertiesEndAt, allLines.size()), "\n").trim();
    }

    Boolean isMarkdown = false;
    if (path.toString().toLowerCase().endsWith(".txt") || path.toString().toLowerCase().endsWith(".md")) {
        isMarkdown = true;
    }
    item.setElements(StElementParser.parseElements(rawContent, isMarkdown));
    List<StElement> items = item.getElements();
    for (StElement ele : items) {
        item.getElementById().put(ele.getId(), ele);
    }

    String itemContent = StElementParser.removeTags(rawContent).trim();
    item.setOriginalContent(itemContent);

    if (isMarkdown) {
        Log.fine("Parse for page {0} {1} {2}", item.getId(), item.getSlug(), item.getTitle());
        String cacheKey = DigestUtils.md5Hex("markdown-to-html" + Literals.GSEP + itemContent);
        String cached = null;
        if (!"test".equals(Settings.instance().getEnv())) {
            cached = PermaCache.get(cacheKey);
        }
        if (cached == null) {
            itemContent = Markdown.instance().process(itemContent);
            PermaCache.set(cacheKey, itemContent);
        } else {
            itemContent = cached;
        }

        item.setContent(itemContent);
    }

    if (empty(item.getId())) {
        item.setId(makeIdFromFilePath(relativePath));
    }

    Log.fine("Loaded text item: id:{0} slug:{1} title:{2} draft:{3}", item.getId(), item.getSlug(),
            item.getTitle(), item.getDraft());
    return item;
}

From source file:at.ac.tuwien.qse.sepm.dao.impl.JDBCPhotoDAO.java

@Override
public Photo getByFile(Path file) throws DAOException {
    if (file == null)
        throw new IllegalArgumentException();
    logger.debug("Get photo with path {}", file);

    try {/*www .  j  ava  2  s.co  m*/
        return jdbcTemplate.queryForObject(GET_BY_FILE_STATEMENT, new Object[] { file.toString() },
                new PhotoRowMapper());
    } catch (DataAccessException ex) {
        logger.error("Failed to get photo");
        throw new DAOException("Failed to get photo", ex);
    }
}

From source file:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java

/**
 * Take custom screen shot.//from w w w  . ja v  a  2s.c o m
 * @param fileNames the file names
 */
@Override
public void takeCustomScreenShot(final String... fileNames) {

    try {
        smallWait();
        final String dir = System.getProperty("user.dir");
        final Path screenshot = ((TakesScreenshot) getDeviceDriver()).getScreenshotAs(OutputType.FILE).toPath();
        smallWait();
        final String folders = arrayToStringDelimited(fileNames, "/");
        final Path screenShotDir = Paths.get(dir, "target",
                folders.indexOf('/') == -1 ? "" : folders.substring(0, folders.lastIndexOf('/')));

        Files.createDirectories(screenShotDir);
        LOGGER.debug("screenShotDir: " + screenShotDir.toString() + "; folders: " + folders);
        final Path screenShotFile = Paths.get(dir, "target", folders + ".png");

        Files.copy(screenshot, screenShotFile, StandardCopyOption.REPLACE_EXISTING);
        if (Files.exists(screenShotFile)) {
            LOGGER.info("Saved custom screenshot for " + fileNames + AT_STRING + screenShotFile);
        } else {
            LOGGER.info("Unable to save custom screenshot for " + fileNames + AT_STRING + screenShotFile);
        }
    } catch (WebDriverException | IOException e) {
        LOGGER.error("Error taking custom screenshot for " + fileNames, e);
    }
}

From source file:dk.sublife.docker.integration.Container.java

/**
 /**/* w  w w . j  ava2 s. c  om*/
 * Copies a local directory to the container.
 *
 * @param localDirectory The local directory to send to the container.
 * @param containerDirectory The directory inside the container where the files are copied to.
 */
public void copyToContainer(final Path localDirectory, final Path containerDirectory)
        throws InterruptedException, DockerException, IOException {
    final String id = container.id();
    dockerClient.copyToContainer(localDirectory, id, containerDirectory.toString());
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectoryV2.java

private void loadSharedParameters(Path instanceDir, Map<String, SharedParametersV2> sharedParams)
        throws Exception {
    String instanceId = instanceDir.getFileName().toString();

    Path sharedParametersPath = Paths.get(instanceDir.toString(), SHARED_PARAMETERS_XML);
    if (Files.exists(sharedParametersPath)) {
        log.trace("Loading shared parameters from {}", sharedParametersPath);

        sharedParams.put(instanceId, loadParameters(sharedParametersPath, SharedParametersV2.class,
                this.sharedParameters.get(instanceId)));
    } else {//  w w  w.j a va  2s .  co m
        log.trace("Not loading shared parameters from {}, " + "file does not exist", sharedParametersPath);
    }
}

From source file:com.willwinder.universalgcodesender.utils.Settings.java

public void setLastOpenedFilename(String absolutePath) {
    Path p = Paths.get(absolutePath).toAbsolutePath();
    this.fileName = p.toString();
    updateRecentFiles(p.toString());/*w w w. jav  a 2 s. co m*/
    updateRecentDirectory(p.getParent().toString());
    changed();
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectoryV1.java

private void loadSharedParameters(Path instanceDir, Map<String, SharedParametersV1> sharedParams)
        throws Exception {
    String instanceId = instanceDir.getFileName().toString();

    Path sharedParametersPath = Paths.get(instanceDir.toString(), SHARED_PARAMETERS_XML);
    if (Files.exists(sharedParametersPath)) {
        log.trace("Loading shared parameters from {}", sharedParametersPath);

        sharedParams.put(instanceId, loadParameters(sharedParametersPath, SharedParametersV1.class,
                this.sharedParameters.get(instanceId)));
    } else {/*from  www  .ja v a  2  s.com*/
        log.trace("Not loading shared parameters from {}, " + "file does not exist", sharedParametersPath);
    }
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectoryV2.java

private void loadPrivateParameters(Path instanceDir, Map<String, PrivateParametersV2> privateParams)
        throws Exception {
    String instanceId = instanceDir.getFileName().toString();

    Path privateParametersPath = Paths.get(instanceDir.toString(), PRIVATE_PARAMETERS_XML);

    if (Files.exists(privateParametersPath)) {
        log.trace("Loading private parameters from {}", privateParametersPath);

        privateParams.put(instanceId, loadParameters(privateParametersPath, PrivateParametersV2.class,
                this.privateParameters.get(instanceId)));
    } else {// w  w  w.  j  av a 2 s. c o  m
        log.trace("Not loading private parameters from {}, " + "file does not exist", privateParametersPath);
    }
}

From source file:io.seqware.pipeline.plugins.FileProvenanceQueryTool.java

private Connection spinUpEmbeddedDB(Path randomTempDirectory, String driver, String protocol)
        throws IllegalAccessException, SQLException, ClassNotFoundException, InstantiationException {
    Class.forName(driver).newInstance();
    Connection connection = DriverManager
            .getConnection(protocol + randomTempDirectory.toString() + "/tempDB;create=true");
    return connection;
}