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:de.digiway.rapidbreeze.server.model.download.Download.java

/**
 * Starts this {@linkplain Download}./* w w  w  . j a  va 2 s  .c o  m*/
 *
 */
void start() {
    switch (statusHandler.getCurrentStatus()) {
    case RUNNING:
        return;
    case PAUSE:
        statusHandler.newStatus(DownloadStatus.RUNNING);
        return;
    }

    try {
        long startAt = 0;
        if (Files.exists(tempFile)) {
            try {
                startAt = Files.size(tempFile);
            } catch (IOException ex) {
                // File might be removed in the meantime
                startAt = 0;
            }
        }

        StorageProviderDownloadClient storageDownload = getDownloadClient();
        throttledInputStream = new ThrottledInputStream(storageDownload.start(url, startAt));
        throttledInputStream.setThrottle(throttleMaxBytesPerSecond);
        sourceChannel = Channels.newChannel(throttledInputStream);
        targetChannel = FileChannel.open(tempFile, StandardOpenOption.WRITE, StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        targetChannel.position(startAt);
    } catch (IOException | RuntimeException ex) {
        LOG.log(Level.SEVERE, "An exception occured during data transfer setup for "
                + Download.class.getSimpleName() + ":" + this, ex);
        closeChannels();
        cachedUrlStatus = null;
        statusHandler.newException(ex);
        return;
    }

    done = false;
    statusHandler.newStatus(DownloadStatus.RUNNING);
}

From source file:org.springframework.boot.gradle.tasks.bundling.AbstractBootArchiveTests.java

@Test
public void customLaunchScriptCanBePrepended() throws IOException {
    this.task.setMainClassName("com.example.Main");
    File customScript = this.temp.newFile("custom.script");
    Files.write(customScript.toPath(), Arrays.asList("custom script"), StandardOpenOption.CREATE);
    this.task.launchScript((configuration) -> configuration.setScript(customScript));
    this.task.execute();
    assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())).startsWith("custom script".getBytes());
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

private void createMasterBranchIfNotExists() throws CitationDBException {
    try (Git git = new Git(repository)) {
        String master = Constants.MASTER;
        ObjectId head = repository.resolve(REF_MASTER);
        if (head == null) {
            git.commit().setMessage("Initial commit").call();
            String readmeFileName = "README.md";
            String[] text = new String[] { "DO NOT DELETE DIRECTORY. USED BY RECITABLE" };
            Files.write(Paths.get(getWorkingTreeDir(), readmeFileName), Arrays.asList(text),
                    StandardCharsets.UTF_8, StandardOpenOption.CREATE);
            git.add().addFilepattern(readmeFileName).call();
            PersonIdent personIdent = new PersonIdent("ReCitable", "recitable@fatlenny.net");
            git.commit().setMessage("Created README.md").setAuthor(personIdent).setCommitter(personIdent)
                    .call();//w ww . j a v  a2s.com
        }
    } catch (RevisionSyntaxException | IOException | GitAPIException e) {
        throw new CitationDBException("Error creating branch master", 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;//from www. j a va 2s .  c om
    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:com.adeptj.runtime.server.Server.java

private void createServerConfFile() {
    if (!Environment.isServerConfFileExists()) {
        try (InputStream stream = this.getClass().getResourceAsStream("/reference.conf")) {
            Files.write(Paths.get(USER_DIR, Constants.DIR_ADEPTJ_RUNTIME, Constants.DIR_DEPLOYMENT,
                    Constants.SERVER_CONF_FILE), IOUtils.toBytes(stream), StandardOpenOption.CREATE);
        } catch (IOException ex) {
            LOGGER.error("Exception while creating server conf file!!", ex);
        }/*  ww w  . ja v  a2 s  . co  m*/
    }
}

From source file:org.linagora.linshare.webservice.userv2.impl.FlowDocumentUploaderRestServiceImpl.java

@Path("/")
@POST/*from w  w w.ja  v a 2s .  c  o m*/
@Consumes("multipart/form-data")
@Override
public FlowDto uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber, @Multipart(TOTAL_CHUNKS) long totalChunks,
        @Multipart(CHUNK_SIZE) long chunkSize, @Multipart(CURRENT_CHUNK_SIZE) long currentChunkSize,
        @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier,
        @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath,
        @Multipart(FILE) InputStream file, MultipartBody body,
        @Multipart(value = WORK_GROUP_UUID, required = false) String workGroupUuid,
        @Multipart(value = WORK_GROUP_FOLDER_UUID, required = false) String workGroupFolderUuid,
        @Multipart(value = ASYNC_TASK, required = false) boolean async) throws BusinessException {
    logger.debug("upload chunk number : " + chunkNumber);
    identifier = cleanIdentifier(identifier);
    boolean isValid = FlowUploaderUtils.isValid(chunkNumber, chunkSize, totalSize, identifier, filename);
    Validate.isTrue(isValid);
    checkIfMaintenanceIsEnabled();
    FlowDto flow = new FlowDto(chunkNumber);
    try {
        logger.debug("writing chunk number : " + chunkNumber);
        java.nio.file.Path tempFile = FlowUploaderUtils.getTempFile(identifier, chunkedFiles);
        ChunkedFile currentChunkedFile = chunkedFiles.get(identifier);
        if (!currentChunkedFile.hasChunk(chunkNumber)) {
            FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(file, output);
            fc.write(ByteBuffer.wrap(output.toByteArray()), (chunkNumber - 1) * chunkSize);
            fc.close();
            if (sizeValidation) {
                if (output.size() != currentChunkSize) {
                    String msg = String.format("File size does not match, found : %1$d, announced : %2$d",
                            output.size(), currentChunkSize);
                    logger.error(msg);
                    flow.setChunkUploadSuccess(false);
                    flow.setErrorMessage(msg);
                    return flow;
                }
            }
            currentChunkedFile.addChunk(chunkNumber);
        } else {
            logger.error("currentChunkedFile.hasChunk(chunkNumber) !!! " + currentChunkedFile);
            logger.error("chunkedNumber skipped : " + chunkNumber);
        }

        logger.debug("nb uploading files : " + chunkedFiles.size());
        logger.debug("current chuckedfile uuid : " + identifier);
        logger.debug("current chuckedfiles" + chunkedFiles.toString());
        if (FlowUploaderUtils.isUploadFinished(identifier, chunkSize, totalSize, chunkedFiles)) {
            flow.setLastChunk(true);
            logger.debug("upload finished : " + chunkNumber + " : " + identifier);
            InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ);
            File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename);
            if (sizeValidation) {
                long currSize = tempFile2.length();
                if (currSize != totalSize) {
                    String msg = String.format("File size does not match, found : %1$d, announced : %2$d",
                            currSize, totalSize);
                    logger.error(msg);
                    flow.setChunkUploadSuccess(false);
                    flow.setErrorMessage(msg);
                    return flow;
                }
            }
            EntryDto uploadedDocument = new EntryDto();
            flow.setIsAsync(async);
            boolean isWorkGroup = !Strings.isNullOrEmpty(workGroupUuid);
            if (async) {
                logger.debug("Async mode is used");
                // Asynchronous mode
                AccountDto actorDto = documentFacade.getAuthenticatedAccountDto();
                AsyncTaskDto asyncTask = null;
                try {
                    if (isWorkGroup) {
                        ThreadEntryTaskContext threadEntryTaskContext = new ThreadEntryTaskContext(actorDto,
                                actorDto.getUuid(), workGroupUuid, tempFile2, filename, workGroupFolderUuid);
                        asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier),
                                filename, null, AsyncTaskType.THREAD_ENTRY_UPLOAD);
                        ThreadEntryUploadAsyncTask task = new ThreadEntryUploadAsyncTask(threadEntryAsyncFacade,
                                threadEntryTaskContext, asyncTask);
                        taskExecutor.execute(task);
                        flow.completeAsyncTransfert(asyncTask);
                    } else {
                        DocumentTaskContext documentTaskContext = new DocumentTaskContext(actorDto,
                                actorDto.getUuid(), tempFile2, filename, null, null);
                        asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier),
                                filename, null, AsyncTaskType.DOCUMENT_UPLOAD);
                        DocumentUploadAsyncTask task = new DocumentUploadAsyncTask(documentAsyncFacade,
                                documentTaskContext, asyncTask);
                        taskExecutor.execute(task);
                        flow.completeAsyncTransfert(asyncTask);
                    }
                } catch (Exception e) {
                    logAsyncFailure(asyncTask, e);
                    deleteTempFile(tempFile2);
                    ChunkedFile remove = chunkedFiles.remove(identifier);
                    Files.deleteIfExists(remove.getPath());
                    throw e;
                }
            } else {
                try {
                    if (isWorkGroup) {
                        uploadedDocument = threadEntryFacade.create(null, workGroupUuid, workGroupFolderUuid,
                                tempFile2, filename);
                    } else {
                        uploadedDocument = documentFacade.create(tempFile2, filename, "", null);
                    }
                    flow.completeTransfert(uploadedDocument);
                } finally {
                    deleteTempFile(tempFile2);
                    ChunkedFile remove = chunkedFiles.remove(identifier);
                    if (remove != null) {
                        Files.deleteIfExists(remove.getPath());
                    } else {
                        logger.error("Should not happen !!!");
                        logger.error("chunk number: " + chunkNumber);
                        logger.error("chunk identifier: " + identifier);
                        logger.error("chunk filename: " + filename);
                        logger.error("chunks : " + chunkedFiles.toString());
                    }
                }
            }
            return flow;
        } else {
            logger.debug("upload pending ");
            flow.setChunkUploadSuccess(true);
        }
    } catch (BusinessException e) {
        logger.error(e.getMessage());
        logger.debug("Exception : ", e);
        flow.setChunkUploadSuccess(false);
        flow.setErrorMessage(e.getMessage());
        flow.setErrCode(e.getErrorCode().getCode());
    } catch (Exception e) {
        logger.error(e.getMessage());
        logger.debug("Exception : ", e);
        flow.setChunkUploadSuccess(false);
        flow.setErrorMessage(e.getMessage());
    }
    return flow;
}

From source file:org.apache.nifi.controller.TemplateManager.java

/**
 * Persists the given template to disk/* w w w. ja v  a2 s .com*/
 *
 * @param template template
 * @throws IOException ioe
 */
private void persistTemplate(final Template template) throws IOException {
    final Path path = directory.resolve(template.getDetails().getId() + ".template");
    Files.write(path, TemplateSerializer.serialize(template.getDetails()), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private void replaceVariables(ServletContext context, List<CssAttribute> cssAttributes, String FILE_NAME,
        File destDir) throws IOException {
    InputStream lessIs = context.getResourceAsStream(FILE_NAME);
    Path outputPath = new File(destDir, FILE_NAME).toPath();
    String content = IOUtils.toString(lessIs, Constants.UTF8);
    for (CssAttribute attribute : cssAttributes) {
        if (!StringUtils.isEmpty(attribute.getCssValue())) {
            content = content.replaceAll(attribute.getCssDefaultValue(), attribute.getCssValue());
        }/*  w  w  w. j a v a2s .co  m*/
    }

    //overwrite variables.less in data directory
    if (!Files.exists(outputPath)) {
        if (!Files.exists(outputPath.getParent())) {
            Files.createDirectory(outputPath.getParent());
        }
        Files.createFile(outputPath);
    }
    Files.write(outputPath, content.getBytes(Constants.UTF8), StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
}

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
 *///from w w  w . j  a v  a2 s . c o  m
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:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.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();
    SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
    if (socialUser == null) {
        return;//from   w w  w  . j  av  a2  s . c om
    }
    String token = socialUser.getAccessToken();
    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("user.home").concat(env.getProperty("pictures.yahoo.path"))
                .concat(File.separator + imageName);

        try {
            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);
    }
}