Example usage for java.nio.file StandardOpenOption TRUNCATE_EXISTING

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

Introduction

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

Prototype

StandardOpenOption TRUNCATE_EXISTING

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

Click Source Link

Document

If the file already exists and it is opened for #WRITE access, then its length is truncated to 0.

Usage

From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java

protected void deleteInCsv(String username) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath()));
    Iterator<String> iterator = lines.iterator();
    while (iterator.hasNext()) {
        String line = iterator.next();
        String[] cols = line.split(",");
        if (cols[0].matches("\"" + username + "\"")) {
            iterator.remove();//ww w.  ja v  a 2s. co m
        }
    }
    Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

@Override
public void execute() throws MojoExecutionException {
    if (!inputDirectory.exists() || !inputDirectory.isDirectory()) {
        throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory);
    }// w  ww  . ja  v  a 2  s.  c om

    if (module == null) {
        throw new MojoExecutionException("You must provide a module or namespace for filtering");
    }

    moduleStrings_.add(module + "");

    outputDirectory.mkdirs();
    File temp = new File(outputDirectory, inputDirectory.getName());
    temp.mkdirs();

    Path source = inputDirectory.toPath();
    Path target = temp.toPath();
    try {
        getLog().info("Reading from " + inputDirectory.getAbsolutePath());
        getLog().info("Writing to " + outputDirectory.getCanonicalPath());

        summary_.append("This content was filtered by an RF2 filter tool.  The parameters were module: "
                + module + " software version: " + converterVersion);
        summary_.append("\r\n\r\n");

        getLog().info("Checking for nested child modules");

        //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the 
        //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith("sct2_Relationship_")) {
                    //don't look for quotes, the data is bad, and has floating instances of '"' all by itself
                    CSVReader csvReader = new CSVReader(
                            new InputStreamReader(new FileInputStream(file.toFile())), '\t',
                            CSVParser.NULL_CHARACTER);
                    String[] line = csvReader.readNext();
                    if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) {
                        csvReader.close();
                        throw new IOException("Unexpected error looking for nested modules");
                    }
                    line = csvReader.readNext();
                    while (line != null) {
                        if (line[5].equals(moduleStrings_.get(0))) {
                            moduleStrings_.add(line[4]);
                        }
                        line = csvReader.readNext();
                    }
                    csvReader.close();
                }
                return FileVisitResult.CONTINUE;
            }
        });

        log("Full module list (including detected nested modules: "
                + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()])));

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetdir = target.resolve(source.relativize(dir));
                try {
                    //this just creates the sub-directory in the target
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                handleFile(file, target.resolve(source.relativize(file)));
                return FileVisitResult.CONTINUE;
            }
        });

        Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new MojoExecutionException("Failure", e);
    }

    getLog().info("Filter Complete");

}

From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java

public static void generateVideoData(String outputFolder, String filePrefix, int nVideos, int nFrames,
        int width, int height, int numShapesPerVideo, boolean backgroundNoise, int numDistractorsPerFrame,
        long seed) throws Exception {
    Random r = new Random(seed);

    for (int i = 0; i < nVideos; i++) {
        String videoPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".mp4");
        String labelsPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".txt");
        int[] labels = generateVideo(videoPath, nFrames, width, height, numShapesPerVideo, r, backgroundNoise,
                numDistractorsPerFrame);

        //Write labels to text file
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < labels.length; j++) {
            sb.append(labels[j]);/*w  ww .  j  av a2s. com*/
            if (j != labels.length - 1)
                sb.append("\n");
        }
        Files.write(Paths.get(labelsPath), sb.toString().getBytes("utf-8"), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    }
}

From source file:at.tfr.securefs.xnio.MessageHandlerImpl.java

@Override
public void handleMessage(String json, MessageSender messageSender) throws IOException {

    log.debug("handleMessage: " + json);
    final Message message = objectMapper.readValue(json, Message.class);

    Path path = configuration.getBasePath().resolve(message.getPath());
    if (!path.relativize(configuration.getBasePath()).toString().equals("..")) {
        throw new SecurityException("invalid path spec: " + message.getPath());
    }//from w  ww  .  j a va2  s. co  m

    try {
        final String uniqueKey = message.getUniqueKey();
        // find the Channel for this data stream:
        StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>> info = activeStreams.getStreams()
                .get(uniqueKey);

        if (message.getType() == MessageType.OPEN && info != null) {
            log.warn("illegal state on Open stream: " + message);
            IoUtils.safeClose(info.getStream().getRightSide());
            messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
        }

        switch (message.getType()) {
        case ERROR:
            log.info("error from Client: " + json);
        case CLOSE: {
            if (info != null) {
                IoUtils.safeClose(info.getStream().getRightSide());
            }
        }
            break;

        case OPEN: {
            switch (message.getSubType()) {
            case READ: {
                final InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
                final InputStream cis = new CipherInputStream(is, getCipher(message, Cipher.DECRYPT_MODE));

                final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker
                        .createHalfDuplexPipe();
                pipe.getLeftSide().getReadSetter().set(new SecureChannelWriterBase(message) {
                    @Override
                    protected void write(Message message) {
                        try {
                            messageSender.send(message);
                        } catch (Exception e) {
                            log.warn("cannot write message=" + message + " : " + e, e);
                        }
                    }
                });
                pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        activeStreams.getStreams().remove(uniqueKey);
                        messageSender.send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                    }
                });
                pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
                    private byte[] bytes = new byte[Constants.BUFFER_SIZE];

                    @Override
                    public void handleEvent(StreamSinkChannel channel) {
                        try {
                            int count = 0;
                            while ((count = cis.read(bytes, 0, bytes.length)) > 0) {
                                if (count > 0) {
                                    Channels.writeBlocking(pipe.getRightSide(),
                                            ByteBuffer.wrap(bytes, 0, count));
                                }
                                if (count < 0) {
                                    pipe.getRightSide().close();
                                } else {
                                    channel.resumeWrites();
                                }
                            }
                        } catch (Exception e) {
                            log.warn("cannot read from cypher: " + e, e);
                            IoUtils.safeClose(channel);
                        }
                    }
                });

                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start sending data:
                pipe.getLeftSide().resumeReads();
                pipe.getRightSide().resumeWrites();
            }
                break;

            case WRITE: {
                Files.createDirectories(path.getParent());
                OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                OutputStream cos = new CipherOutputStream(os, getCipher(message, Cipher.ENCRYPT_MODE));

                ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe();

                pipe.getLeftSide().getReadSetter().set(new SecureChannelReaderBase() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        readChannel(message, cos, pipe, channel);
                    }
                });

                pipe.getLeftSide().getCloseSetter().set(new SecureChannelReaderBase() {
                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        try {
                            cos.close();
                            activeStreams.getStreams().remove(pipe.toString());
                            messageSender
                                    .send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                            log.info("closed channel: " + pipe.toString());
                        } catch (IOException e) {
                            log.warn("cannot close stream: message=" + message + " : " + e, e);
                        }
                    }
                });
                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start receiving data:
                pipe.getLeftSide().resumeReads();
            }
                break;

            default:
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
                break;

            }
        }
            break;

        case DATA: {
            if (info != null) {
                Channels.writeBlocking(info.getStream().getRightSide(), ByteBuffer.wrap(message.getBytes()));
            } else {
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
            }
        }
            break;
        }

    } catch (IOException e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw e;
    } catch (Exception e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw new IOException("cannot handle message: " + message + " : " + e, e);
    }
}

From source file:org.wrml.runtime.service.file.FileSystemService.java

public static void writeModelFile(final Model model, final Path modelFilePath, final URI fileFormatUri,
        final ModelWriteOptions writeOptions) throws IOException, ModelWriterException {

    final Context context = model.getContext();
    OutputStream out = null;// w ww  .j  a v a 2 s.co  m
    try {
        Files.createDirectories(modelFilePath.getParent());
        Files.deleteIfExists(modelFilePath);
        Files.createFile(modelFilePath);
        out = Files.newOutputStream(modelFilePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING);
    } catch (final IOException e) {
        IOUtils.closeQuietly(out);
        throw e;
    }

    try {
        context.writeModel(out, model, writeOptions, fileFormatUri);
    } catch (final ModelWriterException e) {
        IOUtils.closeQuietly(out);
        throw e;
    }

    IOUtils.closeQuietly(out);
}

From source file:org.ballerinalang.test.packaging.ImportModuleTestCase.java

/**
 * Importing installed modules from both normal sources and test sources.
 *
 * @throws BallerinaTestException When an error occurs executing the command.
 *//*from www .j  a  v  a  2 s  .c  o m*/
@Test(description = "Test importing installed modules in test sources")
public void testResolveImportsInBoth() throws BallerinaTestException, IOException {
    Path projPath = tempProjectDirectory.resolve("fourthProj");
    Files.createDirectories(projPath);

    FileUtils.copyDirectory(
            Paths.get((new File("src/test/resources/import-in-both")).getAbsolutePath()).toFile(),
            projPath.toFile());
    Files.createDirectories(projPath.resolve(".ballerina"));

    // ballerina install abc
    balClient.runMain("install", new String[] { "mod2" }, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    // Delete module 'abc' from the project
    PackagingTestUtils.deleteFiles(projPath.resolve("mod2"));
    PackagingTestUtils.deleteFiles(projPath.resolve(".ballerina").resolve("repo"));

    // Rename org-name to "natasha" in Ballerina.toml
    Path tomlFilePath = projPath.resolve("Ballerina.toml");
    String content = "[project]\norg-name = \"natasha\"\nversion = \"1.0.0\"\n";
    Files.write(tomlFilePath, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);

    // Module manny/mod2 will be picked from home repository since it was installed before
    balClient.runMain("build", new String[] {}, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    Assert.assertTrue(Files.exists(projPath.resolve(".ballerina").resolve("repo").resolve("natasha")
            .resolve("mod1").resolve("1.0.0").resolve("mod1.zip")));

    LogLeecher fLeecher = new LogLeecher("Hello Manny !! I got a message --> 100");
    balClient.runMain("test", new String[] { "mod1" }, envVariables, new String[] {},
            new LogLeecher[] { fLeecher }, projPath.toString());
    fLeecher.waitForText(3000);

    LogLeecher sLeecher = new LogLeecher("Hello Manny !! I got a message --> 100 <---->244");
    balClient.runMain("run", new String[] { "mod1" }, envVariables, new String[] {},
            new LogLeecher[] { sLeecher }, projPath.toString());
    sLeecher.waitForText(3000);
}

From source file:org.epics.archiverappliance.TomcatSetup.java

/**
 * @param testName/*from   w  ww  .  java  2 s .co  m*/
 * @param applianceName
 * @param port
 * @param startupPort
 * @return Returns the CATALINA_BASE for this instance
 * @throws IOException
 */
private File makeTomcatFolders(String testName, String applianceName, int port, int startupPort)
        throws IOException {
    File testFolder = new File("tomcat_" + testName);
    assert (testFolder.exists());
    File workFolder = new File(testFolder, applianceName);
    assert (workFolder.mkdir());

    File webAppsFolder = new File(workFolder, "webapps");
    assert (webAppsFolder.mkdir());
    File logsFolder = new File(workFolder, "logs");
    assert (logsFolder.mkdir());
    FileUtils.copyFile(new File("log4j.properties"), new File(logsFolder, "log4j.properties"));
    File tempFolder = new File(workFolder, "temp");
    tempFolder.mkdir();

    logger.debug("Copying the webapps wars to " + webAppsFolder.getAbsolutePath());
    FileUtils.copyFile(new File("../mgmt.war"), new File(webAppsFolder, "mgmt.war"));
    FileUtils.copyFile(new File("../retrieval.war"), new File(webAppsFolder, "retrieval.war"));
    FileUtils.copyFile(new File("../etl.war"), new File(webAppsFolder, "etl.war"));
    FileUtils.copyFile(new File("../engine.war"), new File(webAppsFolder, "engine.war"));

    File confOriginal = new File(System.getenv("TOMCAT_HOME"), "conf_original");
    File confFolder = new File(workFolder, "conf");
    logger.debug("Copying the config from " + confOriginal.getAbsolutePath() + " to "
            + confFolder.getAbsolutePath());
    if (!confOriginal.exists()) {
        throw new IOException(
                "For the tomcat tests to work, we expect that when you extract the tomcat distrbution to "
                        + System.getenv("TOMCAT_HOME")
                        + ", you copy the pristine conf folder to a folder called conf_original. This folder "
                        + confOriginal.getAbsolutePath() + " does not seem to exist.");
    }
    // We expect that when you set up TOMCAT_HOME, 
    FileUtils.copyDirectory(confOriginal, confFolder);

    // We then replace the server.xml with one we generate.
    // TomcatSampleServer.xml is a simple MessageFormat template with entries for 
    // 0) server http port
    // 1) server startup port
    String serverXML = new String(
            Files.readAllBytes(Paths.get("./src/test/org/epics/archiverappliance/TomcatSampleServer.xml")));
    String formattedServerXML = MessageFormat.format(serverXML, port, startupPort);
    Files.write(Paths.get(confFolder.getAbsolutePath(), "server.xml"), formattedServerXML.getBytes(),
            StandardOpenOption.TRUNCATE_EXISTING);
    logger.debug("Done generating server.xml");

    return workFolder;
}

From source file:cloudeventbus.pki.CertificateUtils.java

/**
 * Saves a collection of certificates to the specified file.
 *
 * @param fileName the file to which the certificates will be saved
 * @param certificates the certificate to be saved
 * @throws IOException if an I/O error occurs
 *///  w w  w . j  ava 2s.  c om
public static void saveCertificates(String fileName, Collection<Certificate> certificates) throws IOException {
    final Path path = Paths.get(fileName);
    final Path directory = path.getParent();
    if (directory != null && !Files.exists(directory)) {
        Files.createDirectories(directory);
    }
    try (final OutputStream fileOut = Files.newOutputStream(path, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING); final OutputStream out = new Base64OutputStream(fileOut)) {
        CertificateStoreLoader.store(out, certificates);
    }
}

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  w  w  . j  a  v a 2s  .c om*/
            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 ww  .j  av  a2  s.c om
    }
    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);
}