Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:net.sf.taverna.t2.commandline.data.InputsHandler.java

private void setValue(Path port, Object userInput) throws IOException {
    if (userInput instanceof File) {
        DataBundles.setReference(port, ((File) userInput).toURI());
    } else if (userInput instanceof URL) {
        try {/*from  w ww.j a  va 2s.c  o  m*/
            DataBundles.setReference(port, ((URL) userInput).toURI());
        } catch (URISyntaxException e) {
            logger.warn(String.format("Error converting %1$s to URI", userInput), e);
        }
    } else if (userInput instanceof String) {
        DataBundles.setStringValue(port, (String) userInput);
    } else if (userInput instanceof byte[]) {
        Files.write(port, (byte[]) userInput, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
    } else if (userInput instanceof List<?>) {
        DataBundles.createList(port);
        List<?> list = (List<?>) userInput;
        for (Object object : list) {
            setValue(DataBundles.newListItem(port), object);
        }
    } else {
        logger.warn("Unknown input type : " + userInput.getClass().getName());
    }
}

From source file:revisaoswing.FormCadastro.java

private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
    String nome = txtNome.getText();

    if (nome.isEmpty()) {
        JOptionPane.showMessageDialog(this, "Erro", "Nome no informado", JOptionPane.ERROR_MESSAGE);
        return;/*from w  w w  .j  av a  2 s .  c o m*/
    }
    String dataNasc = txtDtNasc.getText();
    String sexo = "f";
    if (rbMasc.isSelected()) {
        sexo = "m";
    }
    String funcao = cbFuncao.getSelectedItem().toString();
    boolean vt = ckbVT.isSelected();

    JSONObject obj = new JSONObject();
    obj.put("Nome", nome);
    obj.put("Data", dataNasc);
    obj.put("Sexo", sexo);
    obj.put("Funcao", funcao);
    obj.put("VT", vt);

    try {
        RevisaoSwing.carregarArray();
        RevisaoSwing.array.add(obj);

        byte[] bytes = RevisaoSwing.array.toJSONString().getBytes();
        Files.write(RevisaoSwing.arquivo, bytes, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
    } catch (IOException ex) {
        Logger.getLogger(FormCadastro.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(this, "Salvo com Sucesso!");

    txtNome.setText(null);
    txtDtNasc.setText(null);
    rbMasc.setSelected(true);
    ckbVT.setSelected(false);
    cbFuncao.setSelectedIndex(0);
}

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

@Override
public ReturnValue do_run() {
    Path randomTempDirectory = null;
    Path originalReport = null;/* w ww.  j av a 2 s  .co  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.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testAnnotateFileContentsUrlClient() throws Exception {
    File f = new File("test-file");
    try {/*w  ww.  jav  a  2  s .com*/
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        AnnotatedDocument result = apiUrl.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertTrue(result.getText().contains("Barack"));
    } finally {
        f.delete();
    }
}

From source file:org.basinmc.maven.plugins.bsdiff.DiffMojo.java

/**
 * Retrieves a remote artifact and stores it in a pre-defined cache directory.
 *///from w  w  w . j  a  v  a 2  s. co  m
@Nonnull
private Path retrieveSourceFile() throws MojoFailureException {
    HttpClient client = HttpClients.createMinimal();
    String fileName;

    {
        String path = this.sourceURL.getPath();

        int i = path.lastIndexOf('/');
        fileName = path.substring(i + 1);
    }

    try {
        this.getLog().info("Downloading source artifact from " + this.sourceURL.toExternalForm());

        HttpGet request = new HttpGet(this.sourceURL.toURI());
        HttpResponse response = client.execute(request);

        if (response.containsHeader("Content-Disposition")) {
            String disposition = response.getLastHeader("Content-Disposition").getValue();
            Matcher matcher = DISPOSITION_PATTERN.matcher(disposition);

            if (matcher.matches()) {
                fileName = URLDecoder.decode(matcher.group(1), "UTF-8");
            }
        }

        this.getLog().info("Storing " + fileName + " in cache directory");
        Path outputPath = this.cacheDirectory.toPath().resolve(fileName);

        if (!Files.isDirectory(outputPath.getParent())) {
            Files.createDirectories(outputPath.getParent());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                    outputChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }

        return outputPath;
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to read/write source artifact: " + ex.getMessage(), ex);
    } catch (URISyntaxException ex) {
        throw new MojoFailureException("Invalid source URI: " + ex.getMessage(), ex);
    }
}

From source file:org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient.java

private String createImageFromSingleConfig(String serviceName, String dockerEnv, String ballerinaConfig,
        boolean isService, String imageName, String imageVersion)
        throws BallerinaDockerClientException, IOException, InterruptedException {

    imageName = getImageName(serviceName, imageName, imageVersion);

    // 1. Create a tmp docker context
    Path tmpDir = prepTempDockerfileContext();

    // 2. Create a .bal file inside context/files
    Path ballerinaFile = Files.createFile(
            Paths.get(tmpDir + File.separator + PATH_FILES + File.separator + serviceName + PATH_BAL_FILE_EXT));

    Files.write(ballerinaFile, ballerinaConfig.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);

    // 3. Create a docker image from the temp context
    String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssXX").format(new Date());
    String buildArgs = "{\"" + ENV_SVC_MODE + "\":\"" + String.valueOf(isService) + "\", " + "\""
            + ENV_FILE_MODE + "\":\"true\", \"BUILD_DATE\":\"" + timestamp + "\"}";
    buildImage(dockerEnv, imageName, tmpDir, buildArgs);

    // 4. Cleanup
    cleanupTempDockerfileContext(tmpDir);

    return getImage(imageName, dockerEnv);
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
    ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("pictures.yahoo.path").concat(File.separator + imageName);

        try {/*from  w  ww.ja va  2  s  .  com*/
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

From source file:org.apache.kylin.cube.inmemcubing.ConcurrentDiskStore.java

private void openWriteChannel(long startOffset) throws IOException {
    if (startOffset > 0) { // TODO does not support append yet
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND,
                StandardOpenOption.WRITE);
    } else {/*from   ww w  .j  av a 2s .c  o  m*/
        diskFile.delete();
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE);
    }
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testClassifyFileContentsUrlClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);

    File f = new File("test-file");
    try {/* ww  w  .  j a  v  a  2 s  . co m*/
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        ClassifiedDocument result = client.classifyFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertNotNull(result.getCategory());
        assertEquals(3, result.getAllScores().size());
    } finally {
        f.delete();
    }
}

From source file:com.diffplug.gradle.FileMisc.java

/** Concats the first files and writes them to the last file. */
public static void concat(Iterable<File> toMerge, File dst) throws IOException {
    try (FileChannel dstChannel = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
        for (File file : toMerge) {
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                FileChannel channel = raf.getChannel();
                dstChannel.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, raf.length()));
            }//from ww  w .j av  a  2 s.c  om
        }
    }
}