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.ruesga.rview.misc.CacheHelper.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void writeFileCache(Context context, Account account, String name, byte[] data)
        throws IOException {
    File file = new File(getAccountCacheDir(context, account), name);
    file.getParentFile().mkdirs();//from w  w w  . j ava  2  s  . c o  m
    FileUtils.writeByteArrayToFile(file, data);
}

From source file:de.blizzy.documentr.page.PageStore.java

private MergeConflict savePageInternal(String projectName, String branchName, String path, String suffix,
        Page page, String baseCommit, String rootDir, User user, ILockedRepository repo, boolean push)
        throws IOException, GitAPIException {

    Git git = Git.wrap(repo.r());/*from w w  w . ja v  a 2  s  . c  o m*/

    String headCommit = CommitUtils.getHead(repo.r()).getName();
    if ((baseCommit != null) && headCommit.equals(baseCommit)) {
        baseCommit = null;
    }

    String editBranchName = "_edit_" + String.valueOf((long) (Math.random() * Long.MAX_VALUE)); //$NON-NLS-1$
    if (baseCommit != null) {
        git.branchCreate().setName(editBranchName).setStartPoint(baseCommit).call();

        git.checkout().setName(editBranchName).call();
    }

    Map<String, Object> metaMap = new HashMap<String, Object>();
    metaMap.put(TITLE, page.getTitle());
    metaMap.put(CONTENT_TYPE, page.getContentType());
    if (!page.getTags().isEmpty()) {
        metaMap.put(TAGS, page.getTags());
    }
    metaMap.put(VIEW_RESTRICTION_ROLE, page.getViewRestrictionRole());
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    String json = gson.toJson(metaMap);
    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, rootDir);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.META_SUFFIX);
    FileUtils.write(workingFile, json, Charsets.UTF_8);

    PageData pageData = page.getData();
    if (pageData != null) {
        workingFile = Util.toFile(pagesDir, path + suffix);
        FileUtils.writeByteArrayToFile(workingFile, pageData.getData());
    }

    AddCommand addCommand = git.add().addFilepattern(rootDir + "/" + path + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
    if (pageData != null) {
        addCommand.addFilepattern(rootDir + "/" + path + suffix); //$NON-NLS-1$
    }
    addCommand.call();

    PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
    git.commit().setAuthor(ident).setCommitter(ident).setMessage(rootDir + "/" + path + suffix).call(); //$NON-NLS-1$

    MergeConflict conflict = null;

    if (baseCommit != null) {
        git.rebase().setUpstream(branchName).call();

        if (repo.r().getRepositoryState() != RepositoryState.SAFE) {
            String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
            conflict = new MergeConflict(text, headCommit);

            git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
        }

        git.checkout().setName(branchName).call();

        if (conflict == null) {
            git.merge().include(repo.r().resolve(editBranchName)).call();
        }

        git.branchDelete().setBranchNames(editBranchName).setForce(true).call();
    }

    if (push && (conflict == null)) {
        git.push().call();
    }

    page.setParentPagePath(getParentPagePath(path, repo.r()));

    if (conflict == null) {
        PageUtil.updateProjectEditTime(projectName);
    }

    return conflict;
}

From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java

/**
 * Transform a tiff image into a jpeg image
 * // ww  w . java  2s  .c  o  m
 * @param bytes
 * @return
 */
public static byte[] tiff2Jpeg(byte[] bytes) {
    try {
        File tiffFile = File.createTempFile("upload", "tif.tmp");
        FileUtils.writeByteArrayToFile(tiffFile, bytes);
        SeekableStream s = new FileSeekableStream(tiffFile);
        TIFFDecodeParam param = new TIFFDecodeParam();
        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
        return image2Jpeg(tiffFile, dec);
    } catch (Exception e) {
        throw new RuntimeException("Error transforming tiff to jpeg", e);
    }
}

From source file:com.github.ambry.utils.UtilsTest.java

@Test
public void testReadFileToByteBuffer() throws IOException {
    File file = File.createTempFile("test", "1");
    file.deleteOnExit();/*from w ww.j a v  a2  s  .  c  o m*/
    FileChannel fileChannel = Utils.openChannel(file, false);
    byte[] referenceBytes = new byte[20];
    new Random().nextBytes(referenceBytes);
    FileUtils.writeByteArrayToFile(file, referenceBytes);

    // fill up fresh byteBuffer
    ByteBuffer buffer = ByteBuffer.allocate(20);
    Utils.readFileToByteBuffer(fileChannel, 0, buffer);
    assertArrayEquals("Data mismatch", referenceBytes, buffer.array());

    // write to byteBuffer based on buffer remaining
    buffer.limit(10);
    buffer.position(0);
    assertEquals("buffer remaining should be 10", 10, buffer.remaining());
    Utils.readFileToByteBuffer(fileChannel, 10, buffer);
    assertEquals("buffer remaining should be 0", 0, buffer.remaining());
    for (int i = 0; i < 10; i++) {
        assertEquals("First 10 bytes in buffer should match last 10 bytes in file", buffer.array()[i],
                referenceBytes[i + 10]);
    }

    // byteBuffer.remaining() + starting offset > file size, exception is expected.
    buffer.clear();
    assertEquals("buffer remaining should be 20", 20, buffer.remaining());
    try {
        Utils.readFileToByteBuffer(fileChannel, 1, buffer);
        fail("Should fail");
    } catch (IOException e) {
    }

    // starting offset exceeds file size, exception is expected.
    buffer.clear();
    assertEquals("buffer remaining should be 20", 20, buffer.remaining());
    try {
        Utils.readFileToByteBuffer(fileChannel, 21, buffer);
        fail("Should fail");
    } catch (IOException e) {
    }
}

From source file:com.chiorichan.factory.event.PostImageProcessor.java

@EventHandler()
public void onEvent(PostEvalEvent event) {
    try {/*from www.  ja v a 2  s .co m*/
        if (event.context().contentType() == null
                || !event.context().contentType().toLowerCase().startsWith("image"))
            return;

        float x = -1;
        float y = -1;

        boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true);
        boolean grayscale = false;

        ScriptingContext context = event.context();
        HttpRequestWrapper request = context.request();
        Map<String, String> rewrite = request.getRewriteMap();

        if (rewrite != null) {
            if (rewrite.get("serverSideOptions") != null) {
                String[] params = rewrite.get("serverSideOptions").trim().split("_");

                for (String p : params)
                    if (p.toLowerCase().startsWith("width") && x < 0)
                        x = Integer.parseInt(p.substring(5));
                    else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w"))
                            && p.length() > 1 && x < 0)
                        x = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().startsWith("height") && y < 0)
                        y = Integer.parseInt(p.substring(6));
                    else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h"))
                            && p.length() > 1 && y < 0)
                        y = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().equals("thumb")) {
                        x = 150;
                        y = 0;
                        break;
                    } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale"))
                        grayscale = true;
            }

            if (request.getArgument("width") != null && request.getArgument("width").length() > 0)
                x = request.getArgumentInt("width");

            if (request.getArgument("height") != null && request.getArgument("height").length() > 0)
                y = request.getArgumentInt("height");

            if (request.getArgument("w") != null && request.getArgument("w").length() > 0)
                x = request.getArgumentInt("w");

            if (request.getArgument("h") != null && request.getArgument("h").length() > 0)
                y = request.getArgumentInt("h");

            if (request.getArgument("thumb") != null) {
                x = 150;
                y = 0;
            }

            if (request.hasArgument("bw") || request.hasArgument("grayscale"))
                grayscale = true;
        }

        // Tests if our Post Processor can process the current image.
        List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames());
        List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames());
        if (context.contentType() != null
                && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
            return;

        int inx = event.context().buffer().readerIndex();
        BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer()));
        event.context().buffer().readerIndex(inx);

        if (img == null)
            return;

        float w = img.getWidth();
        float h = img.getHeight();
        float w1 = w;
        float h1 = h;

        if (x < 1 && y < 1) {
            x = w;
            y = h;
        } else if (x > 0 && y < 1) {
            w1 = x;
            h1 = x * (h / w);
        } else if (y > 0 && x < 1) {
            w1 = y * (w / h);
            h1 = y;
        } else if (x > 0 && y > 0) {
            w1 = x;
            h1 = y;
        }

        boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h;
        boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8;

        if (!resize && !argb && !grayscale)
            return;

        // Produce a unique encapsulated id based on this image processing request
        String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale);
        File tmp = context.site() == null ? AppConfig.get().getDirectoryCache()
                : context.site().directoryTemp();
        File file = new File(tmp, encapId + "_" + new File(context.filename()).getName());

        if (cacheEnabled && file.exists()) {
            event.context().resetAndWrite(FileUtils.readFileToByteArray(file));
            return;
        }

        Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1),
                AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST
                        : Image.SCALE_SMOOTH)
                : img;

        // TODO Report malformed parameters to user

        if (argb) {
            FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(),
                    new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16)));
            image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
        }

        BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType());
        Graphics2D graphics = rtn.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();

        if (grayscale) {
            ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
            op.filter(rtn, rtn);
        }

        if (resize)
            Log.get().info(EnumColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h)
                    + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px");

        if (rtn != null) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            if (context.contentType() != null
                    && writerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
                ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs);
            else
                ImageIO.write(rtn, "png", bs);

            if (cacheEnabled && !file.exists())
                FileUtils.writeByteArrayToFile(file, bs.toByteArray());

            event.context().resetAndWrite(bs.toByteArray());
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return;
}

From source file:de.tntinteractive.portalsammler.gui.DocumentTable.java

private boolean exportDocument(final JFileChooser chooser, final int row) {
    try {/*from  w  w w  .j a v a 2  s.  co m*/
        final DocumentInfo di = this.getDocumentInRow(row);
        final byte[] content = this.store.getDocument(di);

        chooser.setSelectedFile(new File(this.makeFilenameFor(di)));
        final int result = chooser.showSaveDialog(this.table);
        if (result != JFileChooser.APPROVE_OPTION) {
            return true;
        }

        FileUtils.writeByteArrayToFile(chooser.getSelectedFile(), content);
        this.store.markAsRead(di);
        this.store.writeMetadata();
    } catch (final GeneralSecurityException e) {
        this.gui.showError(e);
    } catch (final IOException e) {
        this.gui.showError(e);
    }
    return false;
}

From source file:com.cprassoc.solr.auth.SolrAuthActionController.java

public static String doPushConfigToSolrAction(SecurityJson json) {
    String result = "";
    try {/* w w  w.ja  va  2  s .co m*/
        String mime = "sh";
        if (Utils.isWindows()) {
            mime = "bat";
        }
        String pathToScript = System.getProperty("user.dir") + File.separator + "solrAuth." + mime;
        String jsonstr = json.export();
        String filePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator
                + "security.json";
        File backup = new File("backup");
        if (!backup.exists()) {
            backup.mkdirs();
        }

        File file = new File(filePath);
        if (file.exists()) {
            // String newFilePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator + System.currentTimeMillis() + "_security.json";
            // File newFile = new File(newFilePath);
            // file.renameTo(newFile);
            FileUtils.copyFileToDirectory(file, backup);
        }
        FileUtils.writeByteArrayToFile(file, jsonstr.getBytes());
        Thread.sleep(500);
        ProcessBuilder pb = new ProcessBuilder(pathToScript);

        Log.log("Run PUSH command");

        Process process = pb.start();
        if (process.waitFor() == 0) {
            result = "";
        } else {
            result = Utils.streamToString(process.getErrorStream());
            result += "\n" + Utils.streamToString(process.getInputStream());
            Log.log(result);
        }

    } catch (Exception e) {
        e.printStackTrace();
        result = e.getLocalizedMessage();
    }

    return result;
}

From source file:gov.nih.nci.firebird.commons.selenium2.test.AbstractWebDriverTestRunner.java

private void catpureScreenShot(final Method method, File seleniumOutputDir) {
    String screenCaptureFilename = getTestClass().getName() + "." + method.getName() + ".png";
    try {/*  w  w w  .  jav a2s .c o  m*/
        File screenCaptureFile = new File(seleniumOutputDir, screenCaptureFilename);
        byte[] screenCaptureBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        FileUtils.writeByteArrayToFile(screenCaptureFile, screenCaptureBytes);
        System.err.println("Saved screenshot " + screenCaptureFilename);
    } catch (Throwable t) {
        System.err.println("Unable to save screenshot to " + screenCaptureFilename);
        t.printStackTrace();
    }
}

From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java

/**
 * Transform a png image into a jpeg image
 * // w w w. jav  a 2  s .c om
 * @param bytes
 * @return
 */
public static byte[] png2Jpeg(byte[] bytes) {
    try {
        File pngFile = File.createTempFile("upload", "png.tmp");
        FileUtils.writeByteArrayToFile(pngFile, bytes);
        SeekableStream s = new FileSeekableStream(pngFile);
        PNGDecodeParam param = new PNGDecodeParam();
        ImageDecoder dec = ImageCodec.createImageDecoder("png", s, param);
        return image2Jpeg(pngFile, dec);
    } catch (Exception e) {
        throw new RuntimeException("Error transforming png to jpeg", e);
    }
}

From source file:com.gemstone.gemfire.management.internal.configuration.SharedConfigurationEndToEndDUnitTest.java

public void createAsyncEventQueue(String queueName) {
    String queueCommandsJarName = "testEndToEndSC-QueueCommands.jar";
    final File jarFile = new File(queueCommandsJarName);

    try {/*from   w ww  .  jav a  2 s  . c  o  m*/
        ClassBuilder classBuilder = new ClassBuilder();
        byte[] jarBytes = classBuilder.createJarFromClassContent("com/qcdunit/QueueCommandsDUnitTestListener",
                "package com.qcdunit;" + "import java.util.List; import java.util.Properties;"
                        + "import com.gemstone.gemfire.internal.cache.xmlcache.Declarable2; import com.gemstone.gemfire.cache.asyncqueue.AsyncEvent;"
                        + "import com.gemstone.gemfire.cache.asyncqueue.AsyncEventListener;"
                        + "public class QueueCommandsDUnitTestListener implements Declarable2, AsyncEventListener {"
                        + "Properties props;"
                        + "public boolean processEvents(List<AsyncEvent> events) { return true; }"
                        + "public void close() {}"
                        + "public void init(final Properties props) {this.props = props;}"
                        + "public Properties getConfig() {return this.props;}}");

        FileUtils.writeByteArrayToFile(jarFile, jarBytes);
        CommandStringBuilder csb = new CommandStringBuilder(CliStrings.DEPLOY);
        csb.addOption(CliStrings.DEPLOY__JAR, queueCommandsJarName);
        executeAndVerifyCommand(csb.getCommandString());

        csb = new CommandStringBuilder(CliStrings.CREATE_ASYNC_EVENT_QUEUE);
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, queueName);
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER,
                "com.qcdunit.QueueCommandsDUnitTestListener");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE, "100");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL, "200");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS, "4");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION, "true");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS, "true");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY, "1000");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY, OrderPolicy.KEY.toString());
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT, "true");
        csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL, "true");

        executeAndVerifyCommand(csb.getCommandString());

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        FileUtils.deleteQuietly(jarFile);
    }
}