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:apiserver.services.image.controllers.filters.ImageDespeckleTests.java

@Test
public void testDespeckleByIdRESTPost() throws Exception {
    InputStream fileStream = this.getClass().getClassLoader().getResourceAsStream("IMG_5932.JPG");

    MockMultipartFile file = new MockMultipartFile("file", "IMG_5932.JPG", "image/jpeg", fileStream);

    MvcResult result = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context).build()
            .perform(fileUpload(rootUrl + "/api/image/filter/despeckle").file(file).param("format", "jpg"))
            .andExpect(status().is(200)).andExpect(content().contentType("image/jpeg")).andReturn();

    Assert.assertEquals(1203634, result.getResponse().getContentLength());
    FileUtils.writeByteArrayToFile(new File("/Users/mnimer/Desktop/despeckle-post.jpg"),
            result.getResponse().getContentAsByteArray());
}

From source file:com.truebanana.data.SecureDataFile.java

public synchronized void save() {
    try {//from www  . ja  v a  2  s .co m
        FileUtils.writeByteArrayToFile(file, toByteArray());
        Log.d("SecureDataFile", "Successfully written data file");
    } catch (IOException e) {
        Log.d("SecureDataFile", "Could not write data file");
    }
}

From source file:de.xirp.managers.PrintManager.java

/**
 * Prints the corresponding report pdf for the given
 * {@link de.xirp.report.ReportDescriptor}
 * /*from   w ww .  j  ava  2  s  . c  om*/
 * @param rd
 *            The descriptor to print the corresponding pdf for.
 */
public static void print(final ReportDescriptor rd) {
    File tmp = new File(Constants.TMP_DIR, rd.getFileName());
    DeleteManager.deleteOnShutdown(tmp);
    try {
        FileUtils.writeByteArrayToFile(tmp, rd.getPdfData());
        print(tmp);
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:cognition.common.service.DocumentConversionService.java

public String tryOCRByConvertingToTiff(DNCWorkCoordinate coordinate, byte[] bytes)
        throws CanNotProcessCoordinateException {
    validateImageMagick();//from  w w  w .  ja va  2s . com
    File pdfFile = null;
    File tiffFile = null;
    try {
        pdfFile = File.createTempFile(coordinate.getFileName(), ".pdf");
        FileUtils.writeByteArrayToFile(pdfFile, bytes);
        tiffFile = makeTiffFromPDF(coordinate, pdfFile);
        if (tiffFile == null) {
            throw new CanNotProcessCoordinateException("Could not convert PDF to Tiff: " + coordinate);
        }
        return getOCRResultFromTiff(tiffFile);
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        FileTools.deleteFiles(pdfFile, tiffFile);
    }
    throw new CanNotProcessCoordinateException("Could not convert PDF to Tiff: " + coordinate);
}

From source file:com.bandstand.web.ImagesController.java

@PutChild
public Image uploadImage(ImagesRoot root, String newName, byte[] bytes, AnnoCollectionResource parentCol)
        throws IOException {
    System.out.println("upload. parent=" + parentCol);
    Transaction tx = SessionManager.session().beginTransaction();
    File fRoot = getContentRoot();
    File content = new File(fRoot, UUID.randomUUID().toString());
    FileUtils.writeByteArrayToFile(content, bytes);

    Image i = new Image();
    i.setDisplayName(newName);//  w ww .  j a va  2s  .  co  m
    i.setFileName(content.getAbsolutePath());
    i.setBaseEntity(root.getEntity());
    if (root.getEntity().getImages() == null) {
        root.getEntity().setImages(new ArrayList<Image>());
    }
    root.getEntity().getImages().add(i);
    SessionManager.session().save(i);
    SessionManager.session().save(root.getEntity());
    SessionManager.session().flush();
    tx.commit();
    System.out.println("added image: " + i.getDisplayName());
    return i;
}

From source file:ch.tatool.core.module.creator.FileDownloadWorker.java

/** Loads the module file from the data server using the provided code. */
public void loadFile(String url, int timeout) {
    // give it a timeout to ensure the user does not wait forever in case of connectivity problems
    HttpParams params = new BasicHttpParams();
    if (timeout > 0) {
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
    }//  ww w.  j a  v a  2  s.c  om

    // remove whitespaces since they are not allowed
    url = url.replaceAll("\\s+", "").trim();

    // create a http client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpGet = new HttpGet(url);

    errorTitle = null;
    errorText = null;
    file = null;
    try {
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            errorTitle = messages.getString("General.errorMessage.windowTitle.error");
            errorText = messages.getString("DataExportError.online.http");
            errorText += "\n" + response.getStatusLine().getReasonPhrase() + " ("
                    + response.getStatusLine().getStatusCode() + ")";
        } else {
            // copy the response into a temporary file
            HttpEntity entity = response.getEntity();
            byte[] data = EntityUtils.toByteArray(entity);
            File tmpFile = File.createTempFile("tatool_module", "tmp");
            FileUtils.writeByteArrayToFile(tmpFile, data);
            tmpFile.deleteOnExit();
            this.file = tmpFile;
        }
    } catch (IOException ioe) {
        errorTitle = messages.getString("General.errorMessage.windowTitle.error");
        errorText = messages.getString("DataExportError.online.http");
    } finally {
        // make sure we close the connection manager
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.omertron.themoviedbapi.AbstractTests.java

/**
 * Write out the object to a file/*from  w w w.  j a  v  a2  s.  c o  m*/
 *
 * @param object
 * @param filename
 * @return
 */
private static boolean writeObject(final Serializable object, final String baseFilename) {
    String filename = baseFilename + FILENAME_EXT;
    File serFile = new File(filename);

    if (serFile.exists()) {
        serFile.delete();
    }

    try {
        byte[] serObject = SerializationUtils.serialize(object);
        FileUtils.writeByteArrayToFile(serFile, serObject);
        return true;
    } catch (IOException ex) {
        LOG.info("Failed to write object to '{}': {}", filename, ex.getMessage(), ex);
        return false;
    }
}

From source file:de.micromata.tpsb.doc.renderer.XStreamRenderer.java

public void save(byte[] data) {
    try {/*from  w  ww. j  ava  2  s. c om*/
        log.info("Schreibe Datei " + getOutputFilename());
        File file = new File(getOutputFilename());
        FileUtils.writeByteArrayToFile(file, data);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.nubits.nubot.utils.Utils.java

/**
 * @param originalString//from  w w  w .  ja v a2  s. c  o  m
 * @param passphrase
 * @param pathToOutput
 * @return
 */
public static String encodeToFile(String originalString, String passphrase, String pathToOutput) {
    String encodedString = "";
    MessageDigest digest;
    try {

        //System.out.println("Writing " +originalString +" to "+ pathToOutput +" with \npassphrase = "+passphrase);

        //Encapsule the passphrase in a 16bit SecretKeySpec key
        digest = MessageDigest.getInstance("SHA");
        digest.update(passphrase.getBytes());
        SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");

        //Cypher the message
        Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
        aes.init(Cipher.ENCRYPT_MODE, key);

        byte[] ciphertext = aes.doFinal(originalString.getBytes());
        encodedString = new String(ciphertext);

        FileUtils.writeByteArrayToFile(new File(pathToOutput), ciphertext);

    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | IllegalBlockSizeException | BadPaddingException ex) {
        LOG.error(ex.toString());
    }

    return encodedString;
}

From source file:edu.ku.brc.util.thumbnails.ImageThumbnailGenerator.java

@Override
public boolean generateThumbnail(final String originalFile, final String thumbnailFile,
        final boolean doHighQuality) throws IOException {
    byte[] origData = GraphicsUtils.readImage(originalFile);
    if (origData != null) {
        byte[] thumb = generateThumbnail(origData, doHighQuality);
        if (thumb != null) {
            FileUtils.writeByteArrayToFile(new File(thumbnailFile), thumb);
            return true;
        }// w  w w  .  ja v  a 2s  .  c om
    }

    return false;
}