Example usage for java.nio.file Path toFile

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

Introduction

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

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:com.yqboots.initializer.core.builder.excel.MenuItemSheetBuilder.java

@Override
protected void doBuild(final Path root, final ProjectMetadata metadata, final Sheet sheet) throws IOException {
    final List<MenuItem> items = new ArrayList<>();

    for (Row row : sheet) {
        // ignore the header
        if (row.getRowNum() < 1) {
            continue;
        }/*from ww w .j a v a2 s .  c o  m*/

        items.add(getMenuItem(row));
    }

    // generate an XML for the application importing into Database
    Path targetPath = Paths.get(root + File.separator + properties.getExportRelativePath());
    if (!Files.exists(targetPath)) {
        Files.createDirectories(targetPath);
    }

    Path file = Paths.get(targetPath + File.separator + properties.getExportName() + FileType.DOT_XML);
    try (FileWriter writer = new FileWriter(file.toFile())) {
        marshaller.marshal(new MenuItems(items), new StreamResult(writer));
    }
}

From source file:de.ks.flatadocdb.defaults.DefaultEntityPersister.java

@Override
public Object load(Repository repository, EntityDescriptor descriptor, Path path,
        Map<Relation, Collection<String>> relationIds) {
    try {//from   w  ww  .  ja  v a 2s .  co m
        JsonNode jsonNode = mapper.readTree(path.toFile());
        descriptor.getAllRelations().forEach(rel -> {
            String name = rel.getRelationField().getName();
            JsonNode jsonValue = jsonNode.findValue(name);
            if (jsonValue.elements().hasNext()) {
                jsonValue = jsonValue.elements().next();
            }

            ArrayList<String> ids = new ArrayList<>();

            relationIds.put(rel, ids);

            if (jsonValue.isContainerNode()) {
                jsonValue.elements().forEachRemaining(id -> ids.add(id.asText()));
            } else if (!jsonValue.isNull()) {
                ids.add(jsonValue.asText());
            }
            log.debug("Found {} relation id's in {}: {}", ids.size(), name, ids);
        });
        return mapper.readValue(path.toFile(), descriptor.getEntityClass());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.marklogic.hub.RestAssetLoader.java

/**
 * FileVisitor method that determines if we should visit the directory or not via the fileFilter.
 *//*from   w w  w .java 2  s .  c  o m*/
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attributes) throws IOException {
    logger.info("filename: " + path.toFile().getName());
    boolean accept = fileFilter.accept(path.toFile());
    if (accept) {
        if (logger.isDebugEnabled()) {
            logger.debug("Visiting directory: " + path);
        }
        return FileVisitResult.CONTINUE;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping directory: " + path);
        }
        return FileVisitResult.SKIP_SUBTREE;
    }
}

From source file:com.digitalpebble.stormcrawler.spout.FileSpout.java

private void populateBuffer() throws IOException {
    if (currentBuffer == null) {
        String file = _inputFiles.poll();
        if (file == null)
            return;
        Path inputPath = Paths.get(file);
        currentBuffer = new BufferedReader(new FileReader(inputPath.toFile()));
    }/*ww w .ja  va  2 s.  c  o  m*/

    // no more files to read from
    if (currentBuffer == null)
        return;

    String line = null;
    int linesRead = 0;
    while (linesRead < BATCH_SIZE && (line = currentBuffer.readLine()) != null) {
        if (StringUtils.isBlank(line))
            continue;
        buffer.add(line.getBytes(StandardCharsets.UTF_8));
        linesRead++;
    }

    // finished the file?
    if (line == null) {
        currentBuffer.close();
        currentBuffer = null;
    }
}

From source file:com.rotty3000.websocket.demo.WebsocketEndpoint.java

@Override
public void onOpen(Session session, EndpointConfig config) {
    Async remote = session.getAsyncRemote();

    session.addMessageHandler(new MessageHandler.Whole<String>() {

        public void onMessage(String text) {
            try {
                JSONObject jsonObject = new JSONObject(text);

                if (!jsonObject.has("file")) {
                    remote.sendText("[ERROR] No log file specified!");

                    return;
                }//from  ww  w.ja  va2 s .c  o m

                String fileName = jsonObject.getString("file");

                Path filePath = Paths.get(fileName);
                File file = filePath.toFile();

                if (!file.exists() || !file.canRead()) {
                    remote.sendText("[ERROR] The file [" + fileName + "] cannot be found!");

                    return;
                }

                int lines = 0;
                if (jsonObject.has("lines")) {
                    lines = jsonObject.getInt("lines");
                }

                remote.sendText(
                        "[CON] Here come the logs for [" + fileName + "] with [" + lines + "] of history.");

                logReader = new LogReader(remote, file, lines);

                logReader.start();
            } catch (Exception e) {
                remote.sendText("[ERROR] " + e.getMessage());
            }
        }

    });
}

From source file:com.kumarvv.setl.Setl.java

/**
 * load definition file//from w  w  w . j a  va2s  . com
 * @param filePath
 * @return
 */
protected Def loadFile(String filePath) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        Path path = Paths.get(filePath);
        final Def def = mapper.readValue(path.toFile(), Def.class);
        def.setFilePath(path);

        initCsvPaths(def, path);

        loadDataStores(def);

        LoggingContext.put("def", StringUtils.defaultIfBlank(def.getName(), ""));

        if (def.getFromDS() != null) {
            Logger.info("fromDS = {}@{}", def.getFromDS().getUsername(), def.getFromDS().getUrl());
        }
        if (def.getToDS() != null) {
            Logger.info("toDS = {}@{}", def.getToDS().getUsername(), def.getToDS().getUrl());
        }

        return def;
    } catch (Exception e) {
        Logger.error("Invalid definition file: {}", e.getMessage());
        Logger.trace(e);
    }
    return null;
}

From source file:de.ks.file.FileStore.java

public File getFile(FileReference fileReference) {
    Path path = Paths.get(getFileStoreDir(), fileReference.getMd5Sum(), fileReference.getName());
    return path.toFile();
}

From source file:io.fabric8.vertx.maven.plugin.ConfigConversionUtilTest.java

@Test
public void convertSimpleYamlToJson() throws Exception {
    Path yamlFile = Paths.get(this.getClass().getResource("/testconfig.yaml").toURI());
    Path jsonFilePath = Files.createTempFile("testconfig", ".json");
    assertNotNull(yamlFile);/*from w ww .  j  ava  2  s.c o m*/
    assertTrue(yamlFile.toFile().isFile());
    assertTrue(yamlFile.toFile().exists());
    ConfigConverterUtil.convertYamlToJson(yamlFile, jsonFilePath);
    assertNotNull(jsonFilePath);
    String jsonDoc = new String(Files.readAllBytes(jsonFilePath));
    assertNotNull(jsonDoc);
    JSONObject jsonMap = new JSONObject(jsonDoc);
    assertNotNull(jsonMap);
    assertEquals(jsonMap.get("http.port"), 8080);

}

From source file:com.sastix.cms.server.services.content.ResourceServiceTest.java

@Test
public void shouldCreateResourceFromExternalUri() throws Exception {
    URL localFile = getClass().getClassLoader().getResource("./logo.png");
    CreateResourceDTO createResourceDTO = new CreateResourceDTO();
    createResourceDTO.setResourceAuthor("Demo Author");
    createResourceDTO.setResourceExternalURI(localFile.getProtocol() + "://" + localFile.getFile());
    createResourceDTO.setResourceMediaType("image/png");
    createResourceDTO.setResourceName("logo.png");
    createResourceDTO.setResourceTenantId("zaq12345");
    ResourceDTO resourceDTO = resourceService.createResource(createResourceDTO);

    String resourceUri = resourceDTO.getResourceURI();

    //Extract TenantID
    final String tenantID = resourceUri.substring(resourceUri.lastIndexOf('-') + 1, resourceUri.indexOf("/"));

    final Path responseFile = hashedDirectoryService.getDataByURI(resourceUri, tenantID);
    File file = responseFile.toFile();

    byte[] actualBytes = Files.readAllBytes(file.toPath());
    byte[] expectedBytes = Files.readAllBytes(Paths.get(localFile.getPath()));
    Assert.assertArrayEquals(expectedBytes, actualBytes);
}

From source file:com.yqboots.initializer.core.builder.excel.DataDictSheetBuilder.java

@Override
protected void doBuild(final Path root, final ProjectMetadata metadata, final Sheet sheet) throws IOException {
    final List<DataDict> items = new ArrayList<>();

    for (Row row : sheet) {
        // ignore the header
        if (row.getRowNum() < 1) {
            continue;
        }//from   w w  w .ja va2s.  c o  m

        items.add(getDataDicts(row));
    }

    // generate an XML for the application importing into Database
    final Path targetPath = Paths.get(root + File.separator + properties.getExportRelativePath());
    if (!Files.exists(targetPath)) {
        Files.createDirectories(targetPath);
    }

    final Path file = Paths.get(targetPath + File.separator + properties.getExportName() + FileType.DOT_XML);
    try (FileWriter writer = new FileWriter(file.toFile())) {
        marshaller.marshal(new DataDicts(items), new StreamResult(writer));
    }
}