Example usage for java.nio.file FileSystems getDefault

List of usage examples for java.nio.file FileSystems getDefault

Introduction

In this page you can find the example usage for java.nio.file FileSystems getDefault.

Prototype

public static FileSystem getDefault() 

Source Link

Document

Returns the default FileSystem .

Usage

From source file:com.dm.estore.common.config.Cfg.java

private Cfg(final Properties overrideProperties) throws IOException {
    this.overrideProperties = overrideProperties;
    this.watchService = FileSystems.getDefault().newWatchService();

    resetLogger();/*  ww w.  ja va 2s.c  om*/
    this.config = createConfiguration();
    this.rootActorSystem = createActorSystem();

    startWatcher(configurationHome);
    reloadLogConfiguration();
}

From source file:com.ccserver.digital.controller.CreditCardApplicationDocumentControllerTest.java

@Test
public void downloadDocumentAppIdMockTest() throws IOException, URISyntaxException {
    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    CreditCardApplicationDocumentDTO ccAppDocDTO = new CreditCardApplicationDocumentDTO();
    ccAppDocDTO.setId(1L);/*from  w  w w.  j a  v a 2  s  . com*/
    ccAppDocDTO.setDocument(idDocByteArray);
    ccAppDocDTO.setFileName("name");
    List<CreditCardApplicationDocumentDTO> ccAppDocDTOs = new ArrayList<CreditCardApplicationDocumentDTO>();
    ccAppDocDTOs.add(ccAppDocDTO);
    CreditCardApplicationDTO ccAppDTO = getCreditCardApplicationDTOMock(1L);

    Mockito.when(mockDocService.getDocumentsByApplicationId(1L)).thenReturn(ccAppDocDTOs);
    ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(1L);
    List<CreditCardApplicationDocumentDTO> result = (List<CreditCardApplicationDocumentDTO>) response.getBody();

    Assert.assertEquals(result.size(), 1);
}

From source file:net.rptools.gui.listeners.fxml.AbstractURLController.java

/**
 * Add a file to the GUI history section.
 * @param location file name to add//ww w.  j  a  va2s. co m
 * @throws IOException I/O error
 */
@ThreadPolicy(ThreadPolicy.ThreadId.ANY)
public void updateFile(final String location) throws IOException {
    final int historySize = getFileHistorySize();
    final String expandedFileName = Utility.expandEnvironment(location);
    final String probeName = expandedFileName.replaceFirst("file://", "");
    final String name = RptoolsFileTypeDetector.probeContentName(FileSystems.getDefault().getPath(probeName));
    LOGGER.debug("probeName={}; name={}; location={}", probeName, name, location);
    if (name == null || location == null) { // safeguard
        return;
    }
    final AssetTableRow newRow = new AssetTableRow(name, location);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            if (getURLList().getItems().size() == historySize) {
                getURLList().getItems().remove(historySize - 1);
            }
            // This moves existing rows to the front
            if (getURLList().getItems().contains(newRow)) {
                getURLList().getItems().remove(newRow);
            }
            getURLList().getItems().add(0, newRow);
            guiToState();
        }
    });
}

From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

private void setupInsertComboBox() {
    Gson gsonInserts = new Gson();
    //Load the file with the stored offsets
    String directoryName = ij.IJ.getDirectory("ImageJ");
    String objectFilepath = directoryName.concat("OPENFLIMHCA_JSONInsertOffsets.txt");
    String JSONInString = "";
    try {/* w  ww .  ja v a2s.c  om*/
        JSONInString = new String(Files.readAllBytes(FileSystems.getDefault().getPath(objectFilepath)));
    } catch (Exception e) {
    }
    insertType.removeAllItems();
    Insert_object[] inserts = gsonInserts.fromJson(JSONInString, Insert_object[].class);
    insertOffsetInfo = new String[inserts.length][inserts[0].getClass().getDeclaredFields().length];
    //System.out.println(inserts[0].getClass().getDeclaredFields().length);
    for (int i = 0; i < inserts.length; i++) {
        insertOffsetInfo[i][0] = inserts[i].getInsertName();
        insertOffsetInfo[i][1] = inserts[i].getInsertOffsets()[0].toString();
        insertOffsetInfo[i][2] = inserts[i].getInsertOffsets()[1].toString();
        insertOffsetInfo[i][3] = inserts[i].getInsertOffsets()[2].toString();
        insertType.addItem(inserts[i].getInsertName());
    }
    InsertOffsetsloaded = true;
}

From source file:io.stallion.boot.NewJavaPluginRunAction.java

public void makeNewApp(String javaFolder) throws Exception {
    targetFolder = javaFolder;//  ww  w  . j  a va2 s  . co m

    templating = new JinjaTemplating(targetFolder, false);

    setGroupId(promptForInputOfLength("What is the maven group name? ", 5));
    setPluginName(
            promptForInputOfLength("What is the plugin package name (will be appended to the groupid)? ", 2));
    setArtifactId(promptForInputOfLength("What maven artifact id? ", 5));

    setPluginNameTitleCase(getPluginName().substring(0, 1).toUpperCase() + getPluginName().substring(1));
    setJavaPackageName(getGroupId() + "." + getPluginName());

    File dir = new File(javaFolder);
    if (!dir.isDirectory()) {
        FileUtils.forceMkdir(dir);
    }

    String sourceFolder = "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/");
    List<String> paths = list(targetFolder + "/src/main/resources", targetFolder + "/src/main/resources/sql",
            targetFolder + "/src/test/resources",
            targetFolder + "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/"),
            targetFolder + "/src/test/java/" + getJavaPackageName().replaceAll("\\.", "/"));
    for (String path : paths) {
        File file = new File(path);
        if (!file.isDirectory()) {
            FileUtils.forceMkdir(file);
        }
    }
    new File(targetFolder + "/src/main/resources/sql/migrations.txt").createNewFile();

    Map ctx = map(val("config", this));
    copyTemplate("/templates/wizard/pom.xml.jinja", "pom.xml", ctx);
    copyTemplate("/templates/wizard/PluginBooter.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Plugin.java", ctx);
    copyTemplate("/templates/wizard/PluginSettings.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Settings.java", ctx);
    copyTemplate("/templates/wizard/MainRunner.java.jinja", sourceFolder + "/MainRunner.java", ctx);
    copyTemplate("/templates/wizard/Endpoints.java.jinja", sourceFolder + "/Endpoints.java", ctx);
    copyTemplate("/templates/wizard/build.py.jinja", "build.py", ctx);
    copyTemplate("/templates/wizard/run-dev.jinja", "run-dev.sh", ctx);

    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/build.py"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/run-dev.sh"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    copyFile("/templates/wizard/app.bundle", "src/main/resources/assets/app.bundle");
    copyFile("/templates/wizard/app.js", "src/main/resources/assets/app.js");
    copyFile("/templates/wizard/app.scss", "src/main/resources/assets/app.scss");
    copyFile("/templates/wizard/file1.js", "src/main/resources/assets/common/file1.js");
    copyFile("/templates/wizard/file2.js", "src/main/resources/assets/common/file2.js");
    copyFile("/assets/vendor/jquery-1.11.3.js", "src/main/resources/assets/vendor/jquery-1.11.3.js");
    copyFile("/assets/basic/stallion.js", "src/main/resources/assets/vendor/stallion.js");
    copyFile("/templates/wizard/app.jinja", "src/main/resources/templates/app.jinja");

}

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

@Override
public ReturnValue do_run() {
    Path randomTempDirectory = null;
    Path originalReport = null;// w  ww  . j  a  va2  s  .c  o  m
    Path bulkImportFile = null;
    try {
        if (options.has(this.inFileSpec)) {
            originalReport = FileSystems.getDefault().getPath(options.valueOf(inFileSpec));
        } else {
            originalReport = populateOriginalReportFromWS();
        }

        List<String> headers;
        List<Boolean> numericDataType;
        // construct column name and datatypes
        // convert file provenance report into derby bulk load format
        try (BufferedReader originalReader = Files.newBufferedReader(originalReport,
                Charset.defaultCharset())) {
            // construct column name and datatypes
            String headerLine = originalReader.readLine();
            headers = Lists.newArrayList();
            numericDataType = Lists.newArrayList();
            for (String column : headerLine.split("\t")) {
                String editedColumnName = StringUtils.lowerCase(column).replaceAll(" ", "_").replaceAll("-",
                        "_");
                headers.add(editedColumnName);
                // note that Parent Sample SWID is a silly column that has colons in it
                numericDataType.add(
                        !editedColumnName.contains("parent_sample") && (editedColumnName.contains("swid")));
            }
            bulkImportFile = Files.createTempFile("import", "txt");
            try (BufferedWriter derbyImportWriter = Files.newBufferedWriter(bulkImportFile,
                    Charset.defaultCharset())) {
                Log.debug("Bulk import file written to " + bulkImportFile.toString());
                while (originalReader.ready()) {
                    String line = originalReader.readLine();
                    StringBuilder builder = new StringBuilder();
                    int i = 0;
                    for (String colValue : line.split("\t")) {
                        if (i != 0) {
                            builder.append("\t");
                        }
                        if (numericDataType.get(i)) {
                            if (!colValue.trim().isEmpty()) {
                                builder.append(colValue);
                            }
                        } else {
                            // assume that this is a string
                            // need to double quotes to preserve them, see
                            // https://db.apache.org/derby/docs/10.4/tools/ctoolsimportdefaultformat.html
                            builder.append("\"").append(colValue.replaceAll("\"", "\"\"")).append("\"");
                        }
                        i++;
                    }
                    derbyImportWriter.write(builder.toString());
                    derbyImportWriter.newLine();
                }
            }
        }
        randomTempDirectory = Files.createTempDirectory("randomFileProvenanceQueryDir");

        // try using in-memory for better performance
        String protocol = "jdbc:h2:";
        if (options.has(useH2InMemorySpec)) {
            protocol = protocol + "mem:";
        }
        Connection connection = spinUpEmbeddedDB(randomTempDirectory, "org.h2.Driver", protocol);

        // drop table if it exists already (running in IDE?)
        Statement dropTableStatement = null;
        try {
            dropTableStatement = connection.createStatement();
            dropTableStatement.executeUpdate("DROP TABLE " + TABLE_NAME);
        } catch (SQLException e) {
            Log.debug("Report table didn't exist (normal)");
        } finally {
            DbUtils.closeQuietly(dropTableStatement);
        }

        // create table creation query
        StringBuilder tableCreateBuilder = new StringBuilder();
        // tableCreateBuilder
        tableCreateBuilder.append("CREATE TABLE " + TABLE_NAME + " (");
        for (int i = 0; i < headers.size(); i++) {
            if (i != 0) {
                tableCreateBuilder.append(",");
            }
            if (numericDataType.get(i)) {
                tableCreateBuilder.append(headers.get(i)).append(" INT ");
            } else {
                tableCreateBuilder.append(headers.get(i)).append(" VARCHAR ");
            }
        }
        tableCreateBuilder.append(")");

        bulkImportH2(tableCreateBuilder, connection, bulkImportFile);

        // query the database and dump the results to
        try (BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(options.valueOf(outFileSpec)),
                Charset.defaultCharset(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            // query the database and dump the results to
            QueryRunner runner = new QueryRunner();
            List<Map<String, Object>> mapList = runner.query(connection, options.valueOf(querySpec),
                    new MapListHandler());
            // output header
            if (mapList.isEmpty()) {
                Log.fatal("Query had no results");
                System.exit(-1);
            }
            StringBuilder builder = new StringBuilder();
            for (String columnName : mapList.get(0).keySet()) {
                if (builder.length() != 0) {
                    builder.append("\t");
                }
                builder.append(StringUtils.lowerCase(columnName));
            }
            outputWriter.append(builder);
            outputWriter.newLine();
            for (Map<String, Object> rowMap : mapList) {
                StringBuilder rowBuilder = new StringBuilder();
                for (Entry<String, Object> e : rowMap.entrySet()) {
                    if (rowBuilder.length() != 0) {
                        rowBuilder.append("\t");
                    }
                    rowBuilder.append(e.getValue());
                }
                outputWriter.append(rowBuilder);
                outputWriter.newLine();
            }
        }
        DbUtils.closeQuietly(connection);
        Log.stdoutWithTime("Wrote output to " + options.valueOf(outFileSpec));
        return new ReturnValue();
    } catch (IOException | SQLException | ClassNotFoundException | InstantiationException
            | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (originalReport != null) {
            FileUtils.deleteQuietly(originalReport.toFile());
        }
        if (bulkImportFile != null) {
            FileUtils.deleteQuietly(bulkImportFile.toFile());
        }
        if (randomTempDirectory != null && randomTempDirectory.toFile().exists()) {
            FileUtils.deleteQuietly(randomTempDirectory.toFile());
        }

    }
}

From source file:com.garyclayburg.filesystem.WatchDir.java

private void init(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<>();

    if (recursive) {
        log.info("Scanning {} ...\n", dir);
        registerAll(dir);//from  w  ww .  ja  v a  2 s  . c  o  m
        log.debug("Scanning Done.");
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}

From source file:com.twosigma.beaker.javash.utils.JavaEvaluator.java

public void setShellOptions(String cp, String in, String od) throws IOException {
    if (od == null || od.isEmpty()) {
        od = FileSystems.getDefault().getPath(System.getenv("beaker_tmp_dir"), "dynclasses", sessionId)
                .toString();/*from   w w  w.j a va  2s.  c  om*/
    } else {
        od = od.replace("$BEAKERDIR", System.getenv("beaker_tmp_dir"));
    }

    // check if we are not changing anything
    if (currentClassPath.equals(cp) && currentImports.equals(in) && outDir.equals(od))
        return;

    currentClassPath = cp;
    currentImports = in;
    outDir = od;

    if (cp.isEmpty())
        classPath = new ArrayList<String>();
    else
        classPath = Arrays.asList(cp.split("[\\s" + File.pathSeparatorChar + "]+"));
    if (in.isEmpty())
        imports = new ArrayList<String>();
    else
        imports = Arrays.asList(in.split("\\s+"));

    try {
        (new File(outDir)).mkdirs();
    } catch (Exception e) {
    }

    resetEnvironment();
}

From source file:org.ng200.openolympus.services.StorageService.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
public void writeTaskDescription(Task task, InputStream inputStream) throws ExecuteException, IOException {
    final Path source = FileSystems.getDefault().getPath(this.storagePath, "tasks", "descriptions",
            task.getDescriptionFile(), "source");

    try (OutputStream outputStream = Files.newOutputStream(source)) {
        IOUtils.copy(inputStream, outputStream);
    }//from  ww w  .j  a v  a2 s .co  m

    final Path compiled = FileSystems.getDefault().getPath(this.storagePath, "tasks", "descriptions",
            task.getDescriptionFile(), "compiled");
    this.taskDescriptionProvider.transform(source, compiled);
}