Example usage for java.nio.file StandardOpenOption CREATE_NEW

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

Introduction

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

Prototype

StandardOpenOption CREATE_NEW

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

Click Source Link

Document

Create a new file, failing if the file already exists.

Usage

From source file:org.opencb.opencga.core.common.networks.Layout.java

public LayoutResp layout(String layoutAlgorithm, String outputFormat, String dotData, String filename,
        String base64, String jsonpCallback) {
    LayoutResp resp = new LayoutResp();

    logger.debug("LayoutWSServer: layout() method");
    if (graphvizLayoutAlgorithms.contains(layoutAlgorithm)) {
        if (graphvizOutputFormats.containsKey(outputFormat)) {
            if (dotData != null && !dotData.equals("")) {
                logger.debug("Algorithm layout: " + layoutAlgorithm + ", output format: " + outputFormat
                        + ", dot: " + dotData);
                try {
                    //                        logger.info("defaultConfig:" + properties.toString());
                    Path randomFolder = Paths.get(properties.getProperty("TMP.FOLDER") + "/"
                            + StringUtils.randomString(20) + "_layout");
                    logger.debug("Creating output folder: " + randomFolder);
                    Files.createDirectory(randomFolder);

                    String inputFile = randomFolder + "/input.dot";
                    String outputFile = randomFolder + "/" + filename + "." + outputFormat;
                    Path inputPath = Paths.get(inputFile);
                    Path outputPath = Paths.get(outputFile);
                    logger.debug("Writting dot data file: " + inputFile);

                    //                        Files.write(completedFilePath, Files.readAllBytes(partPath), StandardOpenOption.APPEND);
                    Files.write(inputPath, dotData.getBytes(), StandardOpenOption.CREATE_NEW);
                    //                        IOUtils.write(inputFile, dotData);

                    int exitValue = executeGraphviz(new File(inputFile), layoutAlgorithm, outputFormat,
                            new File(outputFile));
                    if (exitValue == 0 && Files.exists(outputPath)) {
                        //                            FileUtils.checkFile(outputFile);
                        if (base64 != null && base64.trim().equalsIgnoreCase("true")) {
                            logger.debug("Encoding in Base64 the dot output file...");
                            byte[] binaryBytes = toByteArray(new FileInputStream(outputFile));
                            byte[] base64Bytes = Base64.encodeBase64(binaryBytes);
                            String encodedString = new String(base64Bytes);

                            if (jsonpCallback != null && !jsonpCallback.equals("")) {
                                //                           return Response.ok("var " + jsonpCallback + " = (" + encodedString + ")", MediaType.APPLICATION_JSON_TYPE).build();
                                resp.setData("var " + jsonpCallback + " = (" + encodedString + ")");
                                resp.setType("json");
                                return resp;
                            } else {
                                //                           return Response.ok(encodedString, MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+"."+outputFormat).build();
                                //                           return Response.ok(encodedString, MediaType.TEXT_PLAIN).build();
                                resp.setData(encodedString);
                                resp.setType("text");
                                return resp;
                            }/*from  w  w  w.j ava2 s .  c o  m*/
                        } else {
                            // returning the Graphviz output file
                            byte[] bytes = toByteArray(new FileInputStream(new File(outputFile)));
                            //                        return Response.ok(bytes, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition","attachment; filename = "+filename+"."+outputFormat).build();
                            //                        return createOkResponse(bytes, MediaType.APPLICATION_OCTET_STREAM_TYPE, filename+"."+outputFormat);
                            resp.setData(bytes);
                            resp.setType("bytes");
                            resp.setFileName(filename + "." + outputFormat);
                            return resp;
                        }
                    } else {
                        //                     return Response.ok("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+".err.log").build();
                        //                     return createOkResponse("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN_TYPE, filename+".err.log");
                        resp.setData("Graphviz exit status not 0: '" + exitValue + "'");
                        resp.setType("text");
                        resp.setFileName(filename + ".err.log");
                        return resp;
                    }
                } catch (Exception e) {
                    logger.error("Error in LayoutWSServer, layout() method: " + e);
                    if (base64 != null && base64.trim().equalsIgnoreCase("true")) {
                        //                     return Response.ok("Error in LayoutWSServer, layout() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN).build();
                        //                     return createOkResponse("Error in LayoutWSServer, layout() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN_TYPE);
                        resp.setData("Error in LayoutWSServer, layout() method:\n" + e);
                        resp.setType("text");
                        return resp;
                    } else {
                        //                     return Response.ok("Error in LayoutWSServer, layout() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+".err.log").build();
                        //                     return createOkResponse("Error in LayoutWSServer, layout() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN_TYPE, filename+".err.log");
                        resp.setData("Error in LayoutWSServer, layout() method:\n" + e);
                        resp.setType("text");
                        resp.setFileName(filename + ".err.log");
                        return resp;
                    }
                }
            } else {
                if (base64 != null && base64.trim().equalsIgnoreCase("true")) {
                    //                  return Response.ok("dot data '"+dotData+"' is not valid", MediaType.TEXT_PLAIN).build();
                    //                  return createOkResponse("dot data '"+dotData+"' is not valid", MediaType.TEXT_PLAIN_TYPE);
                    resp.setData("dot data '" + dotData + "' is not valid");
                    resp.setType("text");
                    return resp;
                } else {
                    //                  return Response.ok("dot data '"+dotData+"' is not valid", MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+".err.log").build();
                    //                  return createOkResponse("dot data '"+dotData+"' is not valid", MediaType.TEXT_PLAIN_TYPE, filename+".err.log");
                    resp.setData("dot data '" + dotData + "' is not valid");
                    resp.setType("text");
                    resp.setFileName(filename + ".err.log");
                    return resp;
                }
            }
        } else {
            if (base64 != null && base64.trim().equalsIgnoreCase("true")) {
                //               return Response.ok("Format '"+outputFormat+"' is not valid", MediaType.TEXT_PLAIN).build();
                //               return createOkResponse("Format '"+outputFormat+"' is not valid", MediaType.TEXT_PLAIN_TYPE);
                resp.setData("Format '" + outputFormat + "' is not valid");
                resp.setType("text");
                return resp;
            } else {
                //               return Response.ok("Format '"+outputFormat+"' is not valid", MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+".err.log").build();
                //               return createOkResponse("Format '"+outputFormat+"' is not valid", MediaType.TEXT_PLAIN_TYPE, filename+".err.log");
                resp.setData("Format '" + outputFormat + "' is not valid");
                resp.setType("text");
                resp.setFileName(filename + ".err.log");
                return resp;
            }
        }
    } else {
        if (base64 != null && base64.trim().equalsIgnoreCase("true")) {
            //            return Response.ok("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN).build();
            //            return createOkResponse("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN_TYPE);
            resp.setData("Algorithm '" + layoutAlgorithm + "' is not valid");
            resp.setType("text");
            return resp;
        } else {
            //            return Response.ok("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN).header("content-disposition","attachment; filename = "+filename+".err.log").build();
            //            return createOkResponse("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN_TYPE, filename+".err.log");
            resp.setData("Algorithm '" + layoutAlgorithm + "' is not valid");
            resp.setType("text");
            resp.setFileName(filename + ".err.log");
            return resp;
        }
    }
}

From source file:org.opencb.opencga.core.common.networks.Layout.java

public LayoutResp coordinates(String layoutAlgorithm, String dotData, String jsonpCallback) {
    LayoutResp resp = new LayoutResp();

    logger.debug("LayoutWSServer:  coordinates() method");
    if (graphvizLayoutAlgorithms.contains(layoutAlgorithm)) {
        StringBuilder sb = new StringBuilder("{");
        try {//  w  w w .j  a  va  2s .  c o m
            Path randomFolder = Paths
                    .get(properties.getProperty("TMP.FOLDER") + "/" + StringUtils.randomString(20) + "_layout");
            logger.debug("Creating output folder: " + randomFolder);
            Files.createDirectory(randomFolder);
            //                FileUtils.createDirectory(randomFolder);

            String inputFile = randomFolder + "/input.dot";
            String outputFile = randomFolder + "/output.plain";
            Path inputPath = Paths.get(inputFile);
            Path outputPath = Paths.get(outputFile);
            logger.debug("Writting dot data file: " + inputFile);
            //                IOUtils.write(inputFile, dotData);
            Files.write(inputPath, dotData.getBytes(), StandardOpenOption.CREATE_NEW);

            int exitValue = executeGraphviz(new File(inputFile), layoutAlgorithm, "plain",
                    new File(outputFile));
            if (exitValue == 0 && Files.exists(outputPath)) {
                //                    FileUtils.checkFile(outputFile);
                // getting the coords form the file

                // Grep the file
                BufferedReader br = Files.newBufferedReader(outputPath, Charset.defaultCharset());
                final Pattern pattern = Pattern.compile("^node.+");
                String currentLine;
                List<String> lines = new ArrayList<>();
                while ((currentLine = br.readLine()) != null) {
                    if (pattern.matcher(currentLine).matches()) {
                        lines.add(currentLine);
                    }
                }

                //                    List<String> lines = IOUtils.grep(new File(outputFile), "^node.+");
                String[] fields;
                double min = Double.POSITIVE_INFINITY;
                double max = Double.NEGATIVE_INFINITY;
                String[] ids = new String[lines.size()];
                double[][] coords = new double[lines.size()][2];
                for (int i = 0; i < lines.size(); i++) {
                    fields = lines.get(i).split(" ");
                    ids[i] = fields[1];
                    coords[i][0] = Double.parseDouble(fields[2]);
                    coords[i][1] = Double.parseDouble(fields[3]);
                    min = Math.min(min, Math.min(coords[i][0], coords[i][1]));
                    max = Math.max(max, Math.max(coords[i][0], coords[i][1]));
                }
                // max needs to be calculated after subtract min
                max -= min;
                for (int i = 0; i < ids.length; i++) {
                    sb.append("\"" + ids[i] + "\"").append(": {").append("\"id\":\"").append(ids[i])
                            .append("\", \"x\": ").append((coords[i][0] - min) / max).append(", \"y\": ")
                            .append((coords[i][1] - min) / max).append("}");
                    if (i < ids.length - 1) {
                        sb.append(", ");
                    }
                }
                sb.append("}");

                if (jsonpCallback != null && !jsonpCallback.equals("")) {
                    //                  return Response.ok("var " + jsonpCallback + " = (" + sb.toString() + ")", MediaType.APPLICATION_JSON_TYPE).build();
                    //                  return createOkResponse("var " + jsonpCallback + " = (" + sb.toString() + ")", MediaType.APPLICATION_JSON_TYPE);
                    resp.setData("var " + jsonpCallback + " = (" + sb.toString() + ")");
                    resp.setType("json");
                    return resp;
                } else {
                    //                  return Response.ok(sb.toString(), MediaType.TEXT_PLAIN).build();
                    //                  return createOkResponse(sb.toString(), MediaType.TEXT_PLAIN_TYPE);
                    resp.setData(sb.toString());
                    resp.setType("text");
                    return resp;
                }
            } else {
                //               return Response.ok("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN).build();
                //               return createOkResponse("Graphviz exit status not 0: '"+exitValue+"'", MediaType.TEXT_PLAIN_TYPE);
                resp.setData("Graphviz exit status not 0: '" + exitValue + "'");
                resp.setType("text");
                return resp;
            }
        } catch (Exception e) {
            logger.error("Error in LayoutWSServer, layout() method: " + e);
            //            return Response.ok("Error in LayoutWSServer, coordinates() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN).build();
            //            return createOkResponse("Error in LayoutWSServer, coordinates() method:\n"+StringUtils.getStackTrace(e), MediaType.TEXT_PLAIN_TYPE);
            resp.setData("Error in LayoutWSServer, coordinates() method:\n" + e);
            resp.setType("text");
            return resp;
        }
    } else {
        //         return Response.ok("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN).build();
        //         return createOkResponse("Algorithm '"+layoutAlgorithm+"' is not valid", MediaType.TEXT_PLAIN_TYPE);
        resp.setData("Algorithm '" + layoutAlgorithm + "' is not valid");
        resp.setType("text");
        return resp;
    }
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public long createFile(String fileName, InputStream inputStream) throws IOException {
    long fileSize;
    Path filePath = this.directory.resolve(fileName);
    try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            FileChannel fc = FileChannel.open(filePath, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }/*from w w w  .  j ava2  s.  c  om*/
    return fileSize;
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public void createFile(String fileName, String fileContents) throws IOException {
    Path filePath = this.directory.resolve(fileName);
    try (BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8,
            StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
        bufferedWriter.write(fileContents);
    }/*w  ww.  j  a va 2 s .  c o  m*/
}

From source file:record.wave.WaveWriter.java

/**
 * Opens the file and writes a wave header.
 *//*from   ww  w . j a v a2s  . co  m*/
private void open() throws IOException {
    int version = 2;

    while (Files.exists(mFile)) {
        mFile = Paths.get(mFile.toFile().getAbsolutePath().replace(".wav", "_" + version + ".wav"));
        version++;
    }

    mFileChannel = (FileChannel.open(mFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW));

    ByteBuffer header = WaveUtils.getWaveHeader(mAudioFormat);

    header.flip();

    while (header.hasRemaining()) {
        mFileChannel.write(header);
    }
}