Example usage for org.apache.commons.io FileUtils writeByteArrayToFile

List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeByteArrayToFile.

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:com.edduarte.protbox.core.registry.PReg.java

private PbxEntry addOnlyToPRegFromShared(File file, boolean conflicted) throws ProtboxException {
    try {//from  ww  w . j a v a 2s  . c o  m
        String encodedName = file.getName();
        String realName = convertEncodedNameToRealName(encodedName);
        if (conflicted && !file.isDirectory()) {
            realName = realNameToConflicted(realName);
            encodedName = convertRealNameToEncodedName(realName);
            File newConflictFile = new File(file.getParentFile(), encodedName);
            SKIP_WATCHER_ENTRIES.add(newConflictFile.getAbsolutePath());
            SKIP_WATCHER_ENTRIES.add(file.getAbsolutePath());

            // get the data from the added file
            byte[] sharedFileData = FileUtils.readFileToByteArray(file);

            // move data to a new shared folder file and delete old file
            FileUtils.writeByteArrayToFile(newConflictFile, sharedFileData);
            Constants.delete(file);
        }

        String parentPath = file.getParentFile().getAbsolutePath();
        PbxFolder parent = null;
        if (!parentPath.equalsIgnoreCase(pair.getSharedFolderPath()))
            parent = goToFolder(parentPath, FolderOption.SHARED);

        if (parent == null)
            parent = root;

        return addFinal(file, parent, realName, encodedName, FolderOption.SHARED);
    } catch (IOException | GeneralSecurityException ex) {
        throw new ProtboxException(ex);
    }
}

From source file:edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestService.java

/**
 * Write update log.//from   w w  w .  j  av a2  s .  c  o m
 *
 * @param lastUpdate the last update
 */
private void writeUpdateLog(Date lastUpdate) {
    log.info("Writing update log");

    File file = this.getUpdateLogFile();

    try {
        if (!file.exists()) {
            log.info("Creating new update log file at: " + file.getPath());
            file.getParentFile().mkdirs();
            file.createNewFile();
        }

        byte[] data = SerializationUtils.serialize(lastUpdate);
        FileUtils.writeByteArrayToFile(file, data);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tohours.imo.module.AttractModule.java

private void generateFile(int fileId) {
    if (Constants.isTest) {
        System.out.println(fileId);
    }//from  w w w .j  a va2s  .  c  o  m
    Files files = dao.fetch(Files.class, fileId);
    String path = files.getPath();
    String realPath = this.getRealPath(path);
    String folderPath = realPath.replaceAll("[^/]*$", "");
    File folder = new File(folderPath);
    if (folder.exists() == false) {
        folder.mkdirs();
    }
    File file = new File(realPath);
    if (file.exists() == false) {
        try {
            FileUtils.writeByteArrayToFile(file, files.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.redhat.red.offliner.Main.java

/**
 * Given a list of Maven POM files, generate appropriate Maven repository metadata files by parsing the POM's paths
 * and extracting GroupId / ArtifactId / Version information.
 * @param pomPaths List of POM paths to parse
 *///from   w  w  w .j  av a  2  s. co  m
private void generateMetadata(Set<String> pomPaths) {
    Map<ProjectRef, List<SingleVersion>> metas = new HashMap<ProjectRef, List<SingleVersion>>();
    for (String path : pomPaths) {
        ArtifactPathInfo artifactPathInfo = ArtifactPathInfo.parse(path);
        ProjectVersionRef gav = artifactPathInfo.getProjectId();
        List<SingleVersion> singleVersions = new ArrayList<SingleVersion>();
        if (!metas.isEmpty() && metas.containsKey(gav.asProjectRef())) {
            singleVersions = metas.get(gav.asProjectRef());
        }
        singleVersions.add((SingleVersion) gav.getVersionSpec());
        metas.put(gav.asProjectRef(), singleVersions);
    }
    for (ProjectRef ga : metas.keySet()) {
        List<SingleVersion> singleVersions = metas.get(ga);
        Collections.sort(singleVersions);

        Metadata master = new Metadata();
        master.setGroupId(ga.getGroupId());
        master.setArtifactId(ga.getArtifactId());
        Versioning versioning = new Versioning();
        for (SingleVersion v : singleVersions) {
            versioning.addVersion(v.renderStandard());
        }
        String latest = singleVersions.get(singleVersions.size() - 1).renderStandard();
        versioning.setLatest(latest);
        versioning.setRelease(latest);
        master.setVersioning(versioning);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        File metadataFile = Paths.get(opts.getDownloads().getAbsolutePath(),
                ga.getGroupId().replace('.', File.separatorChar), ga.getArtifactId(), "maven-metadata.xml")
                .toFile();
        try {
            new MetadataXpp3Writer().write(baos, master);
            FileUtils.writeByteArrayToFile(metadataFile, baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            System.err.printf(
                    "\n\nFailed to generate maven-metadata file: %s. See above for more information.\n",
                    metadataFile);
        }
    }
}

From source file:com.iyonger.apm.web.service.PerfTestService.java

/**
 * Prepare files for distribution. This method stores the files on the path
 * ${NGRINDER_HOME}/perftest/{test_id}/dist folder.
 *
 * @param perfTest perfTest/*  w w  w . jav  a 2s . co m*/
 * @return File location in which the perftest script and resources are distributed.
 */
public ScriptHandler prepareDistribution(PerfTest perfTest) {
    File perfTestDistDirectory = getDistributionPath(perfTest);
    User user = perfTest.getCreatedUser();
    FileEntry scriptEntry = checkNotNull(fileEntryService.getOne(user,
            checkNotEmpty(perfTest.getScriptName(), "perfTest should have script name"),
            getSafe(perfTest.getScriptRevision())), "script should exist");
    // Get all files in the script path
    ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry);

    ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(new ByteArrayOutputStream());
    handler.prepareDist(perfTest.getId(), user, scriptEntry, perfTestDistDirectory,
            config.getControllerProperties(), processingResult);
    LOGGER.info("File write is completed in {}", perfTestDistDirectory);
    if (!processingResult.isSuccess()) {
        File logDir = new File(getLogFileDirectory(perfTest), "distribution_log.txt");
        try {
            FileUtils.writeByteArrayToFile(logDir, processingResult.getLogByteArray());
        } catch (IOException e) {
            noOp();
        }
        throw processException("Error while file distribution is prepared.");
    }
    return handler;
}

From source file:de.xirp.mail.MailManager.java

/**
 * Prints the corresponding {@link de.xirp.mail.Mail}
 * of the given {@link de.xirp.mail.MailDescriptor}.
 * /*from  w w w  .j  av  a2  s.  c  om*/
 * @param md
 *            The mail descriptor.
 * @throws MessagingException
 *             if something went wrong while printing.
 * @see de.xirp.mail.MailDescriptor
 * @see de.xirp.mail.Mail
 */
public static void printMail(MailDescriptor md) throws MessagingException {
    try {
        Mail mail = getMail(md);

        List<File> docs = new ArrayList<File>();

        long millis = System.currentTimeMillis();

        File text = new File(Constants.TMP_DIR, millis + "_printtmp_mailtext.txt"); //$NON-NLS-1$
        text.createNewFile();
        docs.add(text);
        DeleteManager.deleteOnShutdown(text);
        FileUtils.writeStringToFile(text, md.getSubject(), "Unicode"); //$NON-NLS-1$

        for (Attachment a : mail.getAttachments()) {
            if (a.isPrintable()) {
                File attachment = new File(Constants.TMP_DIR, millis + "_printtmp_" + a.getFileName()); //$NON-NLS-1$
                attachment.createNewFile();
                docs.add(attachment);
                DeleteManager.deleteOnShutdown(attachment);
                FileUtils.writeByteArrayToFile(attachment, a.getAttachmentFileContent());
            }
        }
        PrintManager.print(docs);
    } catch (FileNotFoundException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    } catch (SerializationException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.jaspersoft.jasperserver.api.common.service.impl.JdbcDriverServiceImpl.java

private String copyJdbcDriverToTempFolder(FileResource driverResource) throws IOException {
    String pathToJdbcDriverFile = getUniqueFilePath();
    File file = new File(pathToJdbcDriverFile);
    FileUtils.writeByteArrayToFile(file,
            getFileResourceData(ExecutionContextImpl.getRuntimeExecutionContext(), driverResource));
    file.deleteOnExit();/*from  w  w  w  .  j  av  a  2s  .c o  m*/

    return pathToJdbcDriverFile;
}

From source file:com.jaspersoft.jasperserver.api.common.service.impl.JdbcDriverServiceImpl.java

private String createTempFile(byte[] fileData) throws IOException {
    String tempFilePath = getUniqueFilePath();
    File file = new File(tempFilePath);
    FileUtils.writeByteArrayToFile(file, fileData);
    file.deleteOnExit();//from  ww  w.j av a2s.  co  m
    return tempFilePath;
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleLicenseGenerator.java

private void returnLicenseData(byte[] licenseData, Properties properties) throws Exception {
    if (properties == null) {
        if (this.promptToWriteLicenseToFile()) {
            String fileName = this
                    .promptForString("Please enter the name of the file to save the license to: ");
            while (fileName == null) {
                fileName = this.promptForString(
                        "Invalid file name. Please enter the name of the file to save " + "the license to: ");
            }/*from ww  w. ja  v a2  s .co m*/

            File file = new File(fileName);
            FileUtils.writeByteArrayToFile(file, licenseData);
        } else {
            this.device.printOutLn("License Data:");
            this.device.printOutLn(new String(Base64.encodeBase64(licenseData), LicensingCharsets.UTF_8));
        }
    } else {
        String fileName = properties.getProperty(ConsoleLicenseGenerator.PROPERTY_LICENSE_FILE);
        if (fileName != null && fileName.trim().length() > 0) {
            File file = new File(fileName);
            FileUtils.writeByteArrayToFile(file, licenseData);
        } else {
            this.device.printOut(new String(Base64.encodeBase64(licenseData), LicensingCharsets.UTF_8));
        }
    }
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private void menuTapExportAsWavActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTapExportAsWavActionPerformed
    this.stepSemaphor.lock();
    try {/*from  w ww  .  j a  v a 2 s.co  m*/
        final byte[] wav = this.keyboardAndTapeModule.getTap().getAsWAV();
        final File fileToSave = chooseFileForSave("Select WAV file", null, new WavFileFilter());
        if (fileToSave != null) {
            FileUtils.writeByteArrayToFile(fileToSave, wav);
            log.info("Exported current TAP file as WAV file " + fileToSave + " size " + wav.length + " bytes");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        log.log(Level.WARNING, "Can't export as WAV", ex);
        JOptionPane.showMessageDialog(this, "Can't export as WAV", ex.getMessage(), JOptionPane.ERROR_MESSAGE);
    } finally {
        this.stepSemaphor.unlock();
    }
}