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.alibaba.jstorm.cluster.StormConfig.java

public static void write_nimbus_topology_code(Map conf, String topologyId, byte[] data) throws IOException {
    String topologyRoot = StormConfig.masterStormdistRoot(conf, topologyId);
    String codePath = StormConfig.stormcode_path(topologyRoot);
    FileUtils.writeByteArrayToFile(new File(codePath), data);
}

From source file:com.alibaba.jstorm.cluster.StormConfig.java

public static void write_supervisor_topology_timestamp(Map conf, String topologyId, long timeStamp)
        throws IOException {
    String stormRoot = supervisor_stormdist_root(conf, topologyId);
    String timeStampPath = stormts_path(stormRoot);

    byte[] data = JStormUtils.longToBytes(timeStamp);
    FileUtils.writeByteArrayToFile(new File(timeStampPath), data);
}

From source file:com.music.Generator.java

public static void mainConvert(String[] args) throws Exception {
    Generator gen = new Generator();
    gen.maxConcurrentGenerations = 5;/*from  ww w. j a va  2s  .  c  o  m*/
    gen.configLocation = "c:/config/music";
    gen.init();
    byte[] bytes = FileUtils.readFileToByteArray(new File("c:/tmp/183.midi"));
    byte[] mp3 = gen.toMp3(bytes);
    FileUtils.writeByteArrayToFile(new File("c:/tmp/183.mp3"), mp3);
}

From source file:com.alibaba.jstorm.cluster.StormConfig.java

public static void write_nimbus_topology_timestamp(Map conf, String topologyId, long timeStamp)
        throws IOException {
    String stormRoot = masterStormdistRoot(conf, topologyId);
    String timeStampPath = stormts_path(stormRoot);

    byte[] data = JStormUtils.longToBytes(timeStamp);
    FileUtils.writeByteArrayToFile(new File(timeStampPath), data);
}

From source file:gov.nih.nci.firebird.service.annual.registration.AnnualRegistrationServiceBeanTest.java

private void generateFinancialDisclosureFormPdf(AnnualRegistration registration, String fileName)
        throws IOException {

    CtepFinancialDisclosure financialDisclosureForm = registration.getFinancialDisclosure();
    financialDisclosureForm.getFormType().setTemplate(financialDisclosureFile);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    bean.generatePdf(financialDisclosureForm, baos);
    byte[] bytes = baos.toByteArray();
    assertTrue(bytes.length > 0);/* w  w  w  . j a  va  2s.c o  m*/

    FileUtils.writeByteArrayToFile(new File(getTestClassesDirectory() + fileName), bytes);

    AnnualRegistrationFactory.getInstance().setupFinancialDisclosureWithFiles(registration);
}

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

/**
 * Saves the {@link de.xirp.mail.Attachment}
 * specifiend by the given/* w ww  . j  a  v a 2 s .c  om*/
 * {@link de.xirp.mail.AttachmentDescriptor} from the
 * given {@link de.xirp.mail.MailDescriptor} to the
 * given path. The {@link de.xirp.mail.Attachment} is
 * existing in the {@link de.xirp.mail.Mail}, so
 * that the {@link de.xirp.mail.MailDescriptor} is
 * used to load the correct {@link de.xirp.mail.Mail}
 * and then the {@link de.xirp.mail.Attachment} is
 * extracted from the {@link de.xirp.mail.Mail}. The
 * {@link de.xirp.mail.Attachment} is found by using
 * the {@link de.xirp.mail.AttachmentDescriptor}.
 * 
 * @param path
 *            The path to save the file to.
 * @param md
 *            The mail descriptor.
 * @param ad
 *            The attachment descriptor.
 * @throws SerializationException
 *             if something went wrong saving the attachment.
 * @throws IOException
 *             if something went wrong saving the attachment.
 * @see de.xirp.mail.Mail
 * @see de.xirp.mail.MailDescriptor
 * @see de.xirp.mail.Attachment
 * @see de.xirp.mail.AttachmentDescriptor
 */
public static void saveAttachment(String path, MailDescriptor md, AttachmentDescriptor ad)
        throws SerializationException, IOException {

    Mail mail = getMail(md);

    File outputFolder = new File(path);
    File attachment = new File(outputFolder, ad.getFileName());
    attachment.createNewFile();

    for (Attachment a : mail.getAttachments()) {
        if ((a.getFileName().equals(ad.getFileName())) && a.getFileType().equals(ad.getFileType())
                && a.getAttachmentFileContent().length == ad.getFileSize()) {
            FileUtils.writeByteArrayToFile(attachment, a.getAttachmentFileContent());
        }
    }
}

From source file:com.frostwire.bittorrent.BTEngine.java

private void saveResumeTorrent(TorrentInfo ti) {

    try {//  w w w .  j  a  v  a  2 s . c  om
        String name = getEscapedFilename(ti);

        entry e = ti.toEntry().swig();
        e.dict().set(TORRENT_ORIG_PATH_KEY, new entry(torrentFile(name).getAbsolutePath()));
        byte[] arr = Vectors.byte_vector2bytes(e.bencode());

        FileUtils.writeByteArrayToFile(resumeTorrentFile(ti.infoHash().toString()), arr);
    } catch (Throwable e) {
        LOG.warn("Error saving resume torrent", e);
    }
}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void actionPerformed(ActionEvent event) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Save Signer Certificate");
    int result = fileChooser.showSaveDialog(this);
    if (JFileChooser.APPROVE_OPTION == result) {
        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            int confirmResult = JOptionPane.showConfirmDialog(this,
                    "File already exists.\n" + file.getAbsolutePath() + "\n" + "Overwrite file?", "Overwrite",
                    JOptionPane.OK_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == confirmResult) {
                return;
            }/*from w w w .  j  ava2s.c  o  m*/
        }
        try {
            FileUtils.writeByteArrayToFile(file, this.signerCertificate.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("error writing file: " + e.getMessage(), e);
        }
    }
}

From source file:ch.silviowangler.dox.DocumentServiceImpl.java

@Override
@CacheEvict(value = CACHE_DOCUMENT_COUNT, allEntries = true)
@Transactional(propagation = REQUIRED, readOnly = false)
@PreAuthorize("hasRole('ROLE_USER')")
public DocumentReference importDocument(PhysicalDocument physicalDocumentApi)
        throws ValidationException, DocumentDuplicationException, DocumentClassNotFoundException {

    final String documentClassShortName = physicalDocumentApi.getDocumentClass().getShortName();
    ch.silviowangler.dox.domain.DocumentClass documentClassEntity = findDocumentClass(documentClassShortName);

    List<Attribute> attributes = attributeRepository.findAttributesForDocumentClass(documentClassEntity);

    logger.debug("Found {} attributes for document class '{}'", attributes.size(), documentClassShortName);

    verifyMandatoryAttributes(physicalDocumentApi, attributes);
    verifyUnknownKeys(physicalDocumentApi, documentClassShortName, attributes);
    try {//  w w  w  . j a v a 2 s .c om
        verifyDomainValues(physicalDocumentApi, attributes);
    } catch (ValueNotInDomainException e) {
        ch.silviowangler.dox.domain.Domain domain = domainRepository.findByShortName(e.getDomainName());

        if (domain.isStrict()) {
            logger.warn(
                    "Domain '{}' is defined as strict domain and can therefore only accept predefined value",
                    e.getDomainName());
            throw e;
        }
        logger.debug("Adding value '{}' to domain '{}'", e.getValue(), e.getDomainName());
        domain.getValues().add(e.getValue());
        domainRepository.save(domain);
        verifyDomainValues(physicalDocumentApi, attributes);
    }

    physicalDocumentApi.setIndices(fixDataTypesOfIndices(physicalDocumentApi.getIndices(), attributes));

    final String mimeType = investigateMimeType(physicalDocumentApi.getFileName());
    final String hash = DigestUtils.sha256Hex(physicalDocumentApi.getContent());

    final Document documentByHash = documentRepository.findByHash(hash);
    if (documentByHash != null) {
        throw new DocumentDuplicationException(documentByHash.getId(), hash);
    }

    IndexStore indexStore = new IndexStore();
    updateIndices(physicalDocumentApi, indexStore);

    User user = getPrincipal();

    Document document = new Document(hash, documentClassEntity, PAGE_NUMBER_NOT_RETRIEVABLE, mimeType,
            physicalDocumentApi.getFileName(), indexStore, user.getUsername());
    document.setClient(clientRepository.findByShortName(physicalDocumentApi.getClient()));
    indexStore.setDocument(document);

    document = documentRepository.save(document);
    indexStoreRepository.save(indexStore);

    updateIndexMapEntries(toEntityMap(physicalDocumentApi.getIndices()), document);

    File target = new File(this.archiveDirectory, hash);
    try {
        FileUtils.writeByteArrayToFile(target, physicalDocumentApi.getContent());
    } catch (IOException e) {
        logger.error("Unable to write file to store at {}", this.archiveDirectory.getAbsolutePath(), e);
    }

    try {
        final long size = Files.size(target.toPath());
        document.setFileSize(size);

        final int numberOfPages = documentInspectorFactory.findDocumentInspector(mimeType)
                .retrievePageCount(target);
        document.setPageCount(numberOfPages);

        document = documentRepository.save(document);
    } catch (IOException e) {
        logger.error("Unable to calculate file size of file {}", target.getAbsolutePath(), e);
    }
    DocumentReference docRef = toDocumentReference(document, null);
    return docRef;
}

From source file:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * folderclass??//from   w  ww.  j av  a 2  s. c  o m
 *
 * @param pool
 * @param folder
 * @param outFolder
 * @return
 * @throws IOException
 * @throws CannotCompileException
 * @throws NotFoundException
 * @throws Exception
 */
public static List<String> injectFolder(ClassPool pool, File folder, File outFolder, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    if (folder.exists() && folder.isDirectory()) {
        Collection<File> classFiles = FileUtils.listFiles(folder, new String[] { "class" }, true);
        for (File classFile : classFiles) {
            String className = toRelative(folder, classFile.getAbsolutePath());
            File outClassFile = new File(outFolder, className);
            outClassFile.getParentFile().mkdirs();
            className = StringUtils.replace(className, File.separator, ".");
            className = className.substring(0, className.length() - 6);
            byte[] codes;

            codes = inject(pool, className, injectParam);
            FileUtils.writeByteArrayToFile(outClassFile, codes);

        }
    }
    return errorFiles;
}