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:jproxy.DefaultSamplerCreator.java

/**
 * Compute sampler informations from Request Header
 * @param sampler {@link HTTPSamplerBase}
 * @param request {@link HttpRequestHdr}
 * @throws Exception when something fails
 *///from  w  w w .j ava  2s. c o  m
protected void computeFromPostBody(HTTPSamplerBase sampler, HttpRequestHdr request) throws Exception {
    // If it was a HTTP GET request, then all parameters in the URL
    // has been handled by the sampler.setPath above, so we just need
    // to do parse the rest of the request if it is not a GET request
    if ((!HTTPConstants.CONNECT.equals(request.getMethod()))
            && (!HTTPConstants.GET.equals(request.getMethod()))) {
        // Check if it was a multipart http post request
        final String contentType = request.getContentType();
        MultipartUrlConfig urlConfig = request.getMultipartConfig(contentType);
        String contentEncoding = sampler.getContentEncoding();
        // Get the post data using the content encoding of the request
        String postData = null;
        if (log.isDebugEnabled()) {
            if (!StringUtils.isEmpty(contentEncoding)) {
                log.debug("Using encoding " + contentEncoding + " for request body");
            } else {
                log.debug("No encoding found, using JRE default encoding for request body");
            }
        }

        if (!StringUtils.isEmpty(contentEncoding)) {
            postData = new String(request.getRawPostData(), contentEncoding);
        } else {
            // Use default encoding
            postData = new String(request.getRawPostData(), PostWriter.ENCODING);
        }

        if (urlConfig != null) {
            urlConfig.parseArguments(postData);
            // Tell the sampler to do a multipart post
            sampler.setDoMultipartPost(true);
            // Remove the header for content-type and content-length, since
            // those values will most likely be incorrect when the sampler
            // performs the multipart request, because the boundary string
            // will change
            request.getHeaderManager().removeHeaderNamed(HttpRequestHdr.CONTENT_TYPE);
            request.getHeaderManager().removeHeaderNamed(HttpRequestHdr.CONTENT_LENGTH);

            // Set the form data
            sampler.setArguments(urlConfig.getArguments());
            // Set the file uploads
            sampler.setHTTPFiles(urlConfig.getHTTPFileArgs().asArray());
            sampler.setDoBrowserCompatibleMultipart(true); // we are parsing browser input here
            // used when postData is pure xml (eg. an xml-rpc call) or for PUT
        } else if (postData.trim().startsWith("<?") || HTTPConstants.PUT.equals(sampler.getMethod())
                || isPotentialXml(postData)) {
            sampler.addNonEncodedArgument("", postData, "");
        } else if (contentType == null
                || (contentType.startsWith(HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED)
                        && !isBinaryContent(contentType))) {
            // It is the most common post request, with parameter name and values
            // We also assume this if no content type is present, to be most backwards compatible,
            // but maybe we should only parse arguments if the content type is as expected
            sampler.parseArguments(postData.trim(), contentEncoding); //standard name=value postData
        } else if (postData.length() > 0) {
            if (isBinaryContent(contentType)) {
                try {
                    File tempDir = new File(getBinaryDirectory());
                    File out = File.createTempFile(request.getMethod(), getBinaryFileSuffix(), tempDir);
                    FileUtils.writeByteArrayToFile(out, request.getRawPostData());
                    HTTPFileArg[] files = { new HTTPFileArg(out.getPath(), "", contentType) };
                    sampler.setHTTPFiles(files);
                } catch (IOException e) {
                    log.warn("Could not create binary file: " + e);
                }
            } else {
                // Just put the whole postbody as the value of a parameter
                sampler.addNonEncodedArgument("", postData, ""); //used when postData is pure xml (ex. an xml-rpc call)
            }
        }
    }
}

From source file:net.nicholaswilliams.java.licensing.TestFileLicenseProvider.java

@Test
public void testGetLicenseData05() throws IOException {
    File temp = new File("testGetLicenseData05.lic");
    FileUtils.writeByteArrayToFile(temp, Base64.encodeBase64("another get 05".getBytes()));

    this.provider = EasyMock.createMockBuilder(FileLicenseProvider.class).addMockedMethod("getLicenseFile")
            .createStrictMock();//from   ww w . j  a v a  2  s  .  com

    EasyMock.expect(this.provider.getLicenseFile("test05")).andReturn(new File("testGetLicenseData05.lic"));
    EasyMock.replay(this.provider);

    this.provider.setBase64Encoded(true);
    byte[] data = this.provider.getLicenseData("test05");

    assertNotNull("The data should not be null.", data);
    assertEquals("The data is not correct.", "another get 05", new String(data));

    FileUtils.forceDelete(temp);
}

From source file:de.metas.ui.web.letter.LetterRestController.java

private static File createFile(final byte[] pdfData) {
    final String pdfFilenamePrefix = Services.get(IMsgBL.class).getMsg(Env.getCtx(), Letters.MSG_Letter);
    try {//from   w w w  .j  a  v  a2  s  .c o m
        final File pdfFile = File.createTempFile(pdfFilenamePrefix, ".pdf");
        FileUtils.writeByteArrayToFile(pdfFile, pdfData);
        return pdfFile;
    } catch (IOException e) {
        throw AdempiereException.wrapIfNeeded(e);
    }
}

From source file:com.gorillalogic.monkeytalk.processor.command.tests.VerifyImageCommandTest.java

@Test
public void testWithFailedComparison() throws IOException {
    byte[] fff = Base64.decode(GOOD_SCREENSHOT_STRING);
    FileUtils.writeByteArrayToFile(new File(scriptDir, "GOODSCREENSHOT2.PNG"), fff);

    PlaybackResult result = doTestWithFailureResponse("Device * VerifyImage GOODSCREENSHOT2.PNG",
            " - expected and captured images do not match.");
    assertNull(result.getWarning());/*from ww w  . j a  va2s  .  co m*/
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpDir = new File("tmpDir");
    tmpDir.mkdir();/*ww w .ja  v a  2 s .co  m*/
    try {
        String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "extract", "-a",
                "RandomLSB", "-sf", "" + carrier.toPath(), "-xd", "" + tmpDir.toPath() };
        Process process = Runtime.getRuntime().exec(args);
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        byte b[] = new byte[inputStream.available()];
        inputStream.read(b, 0, b.length);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String originalCarrierPath = "";
    if (tmpDir.listFiles().length == 1) {
        File tmpMessage = tmpDir.listFiles()[0];
        byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpMessage);
        PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
        RestoredFile message = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
        message.originalFilePath = payloadSegment.getPayloadPath();
        originalCarrierPath = payloadSegment.getCarrierPath();
        FileUtils.writeByteArrayToFile(message, payloadSegment.getPayloadBytes());
        message.validateChecksum(payloadSegment.getPayloadChecksum());
        message.restorationNote = "Payload can be restored correctly.";
        message.wasPayload = true;
        restoredFiles.add(message);
    }
    FileUtils.forceDelete(tmpDir);
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    FileUtils.copyFile(carrier, copiedCarrier);
    copiedCarrier.wasCarrier = true;
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    copiedCarrier.originalFilePath = originalCarrierPath;
    restoredFiles.add(copiedCarrier); // The carrier can not be restored;
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:com.music.Generator.java

public static void main1(String[] args) throws Exception {
    // testing soundbanks
    Generator generator = new Generator();
    generator.configLocation = "c:/config/music";
    generator.maxConcurrentGenerations = 5;
    generator.init();/*from   ww w.  ja va  2  s.  c om*/
    byte[] midi = FileUtils.readFileToByteArray(new File("c:/tmp/classical.midi"));
    byte[] mp3 = generator.toMp3(midi);
    FileUtils.writeByteArrayToFile(new File("c:/tmp/aa" + System.currentTimeMillis() + ".mp3"), mp3);
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

@Override
public void export(final File file) throws IOException {
    final BufferedImage img = generateImage();
    if (img == null)
        return;//  w ww.  j a  va 2s.  com
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000000);
    ImageIO.write(img, "png", buffer);
    buffer.flush();

    if (Thread.currentThread().isInterrupted())
        return;

    FileUtils.writeByteArrayToFile(file, buffer.toByteArray());
}

From source file:com.gorillalogic.monkeytalk.processor.command.tests.VerifyImageCommandTest.java

@Test
public void testWithSuccessfulComparison() throws IOException {
    byte[] fff = Base64.decode(GOOD_SCREENSHOT_STRING);
    FileUtils.writeByteArrayToFile(new File(scriptDir, "GOODSCREENSHOT.PNG"), fff);

    String cmd = "Device * VerifyImage GOODSCREENSHOT.PNG";
    PlaybackResult result = doTestWithOkResponse(cmd, null);
    assertThat(result.getMessage(), is(""));
}

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

private void saveSettings() {
    if (swig() == null) {
        return;//from   w  ww.ja  v a 2s.co  m
    }

    try {
        byte[] data = saveState();
        FileUtils.writeByteArrayToFile(settingsFile(), data);
    } catch (Throwable e) {
        LOG.error("Error saving session state", e);
    }
}

From source file:com.emergya.persistenceGeo.service.impl.LayerAdminServiceImpl.java

protected LayerDto entityToDto(AbstractLayerEntity entity) {
    LayerDto dto = null;//from  www. j a  v a  2s  .c  om
    if (entity != null) {
        dto = new LayerDto();
        // Add own parameters
        dto.setId(entity.getId());
        dto.setName(entity.getName());
        dto.setOrder(entity.getOrder());
        dto.setServer_resource(entity.getServer_resource());
        dto.setPublicized(entity.getPublicized());
        dto.setEnabled(entity.getEnabled());
        dto.setPertenece_a_canal(entity.getIsChannel());
        dto.setCreateDate(entity.getCreateDate());
        dto.setUpdateDate(entity.getUpdateDate());

        //Layer type
        if (entity.getType() != null && entity.getType().getName() != null) {
            dto.setType(entity.getType().getName());
        }

        if (entity.getData() != null) {
            try {
                File file = com.emergya.persistenceGeo.utils.FileUtils.createFileTemp(entity.getName(),
                        entity.getType() != null ? entity.getType().getName() : "xml");
                FileUtils.writeByteArrayToFile(file, entity.getData());
                dto.setData(file);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // Add relational parameters
        // Add users
        AbstractUserEntity user = layerDao.findByLayer(entity.getId());
        if (user != null) {
            dto.setUser(user.getNombreCompleto());
        }
        // Add authority
        dto.setAuthId(entity.getAuth() != null ? entity.getAuth().getId() : null);
        // Add style
        Map<StyleDto, Map<RuleDto, Map<String, String>>> styles = new HashMap<StyleDto, Map<RuleDto, Map<String, String>>>();
        if (entity.getStyleList() != null) {
            for (Object style : entity.getStyleList()) {
                StyleDto styleDto = entityStyleToDto((AbstractStyleEntity) style);
                styles.put(styleDto, styleDto.getRules());
            }
        }
        dto.setStyles(styles);
        // Add folder
        dto.setFolderId(entity.getFolder() != null ? entity.getFolder().getId() : null);

        // Properties
        if (entity.getProperties() != null && entity.getProperties().size() > 0) {
            Map<String, String> properties = new HashMap<String, String>();
            List<AbstractLayerPropertyEntity> propertiesList = entity.getProperties();
            for (AbstractLayerPropertyEntity property : propertiesList) {
                properties.put(property.getName(), property.getValue());
            }
            dto.setProperties(properties);
        }
    }
    return dto;
}