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:net.mindengine.oculus.frontend.web.controllers.trm.customize.UploadProjectController.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/* w  w  w .j  ava2 s .  co  m*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    TrmUploadProject uploadProject = (TrmUploadProject) command;
    if ("Current Version".equals(uploadProject.getVersion())) {
        uploadProject.setVersion("current");
    }

    if (uploadProject.getZippedFile() == null || uploadProject.getZippedFile().length == 0) {
        errors.reject("trm.uploadproject.error.file.empty");
        Map model = errors.getModel();
        model.put("uploadProject", uploadProject);
        return new ModelAndView(getFormView(), model);
    }

    Project project = projectDAO.getProject(Long.parseLong(request.getParameter("projectId")));
    if (project == null)
        throw new UnexistentResource("Project with id " + request.getParameter("projectId") + " doesn't exist");
    ClientServerRemoteInterface server = config.lookupGridServer();

    /*
     * Uploading project to server
     */
    User user = getUser(request);
    String fileName = UUID.randomUUID().toString().replace("-", "");
    File tmpFile = File.createTempFile(fileName, ".tmp");
    FileUtils.writeByteArrayToFile(tmpFile, uploadProject.getZippedFile());
    server.uploadProject(project.getPath(), uploadProject.getVersion(), tmpFile, user.getName());

    return new ModelAndView(getSuccessView());
}

From source file:net.osten.watermap.batch.FetchPCTWaypointsJob.java

/**
 * Fetch the PCT waypoint files and save in output directory.
 *
 * @see javax.batch.api.Batchlet#process()
 * @return FAILED if the files cannot be downloaded or can't be written to disk; COMPLETED otherwise
 *///  ww w .j ava  2  s. c  o m
@Override
public String process() throws Exception {
    outputDir = new File(config.getString("output_dir"));

    if (!outputDir.isDirectory()) {
        log.log(Level.WARNING, "Output directory [{0}] is not a directory.", outputDir);
        return BatchStatus.FAILED.toString();
    } else if (!outputDir.canWrite()) {
        log.log(Level.WARNING, "Output directory [{0}] is not writable.", outputDir);
        return BatchStatus.FAILED.toString();
    }

    for (String url : URLS) {
        log.log(Level.FINE, "Fetching PCT waypoints from {0}", new Object[] { url });

        byte[] response = Request.Get(context.getProperties().getProperty(url)).execute().returnContent()
                .asBytes();
        File outputFile = new File(outputDir.getAbsolutePath() + File.separator + url + "_state_gps.zip");
        FileUtils.writeByteArrayToFile(outputFile, response);

        if (outputFile.exists()) {
            unZipIt(outputFile, outputDir);
        }
    }

    return BatchStatus.COMPLETED.toString();
}

From source file:com.mirth.connect.connectors.file.filesystems.test.FileConnectionTest.java

@Test
public void testReadFile() throws IOException {
    // The string to write
    String testString = new String("This is just a test string");
    byte[] byteTest = testString.getBytes(Charset.defaultCharset());

    File testFile = new File(someFolder, "readFile" + System.currentTimeMillis() + ".dat");

    // write the file
    FileUtils.writeByteArrayToFile(testFile, byteTest);

    InputStream in = null;/*from   www . ja v a  2s  .c om*/
    try {
        in = fc.readFile(testFile.getName(), someFolder.getAbsolutePath());
    } catch (FileConnectorException e) {
        fail("Threw a FileConnectorException");
    }

    // Read the file data
    byte[] tempRead = new byte[byteTest.length];
    in.read(tempRead);
    in.close();

    // check to make sure it is the same
    assertArrayEquals(byteTest, tempRead);

}

From source file:com.xiaoaitouch.mom.net.ShortFileRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *///from  ww  w .  j av a  2  s.  com
private Response<File> doParse(NetworkResponse response) {
    byte[] data = response.data;
    File file = null;
    if (data != null) {
        file = new File(mRootDir, getFilenameForKey(getUrl()));
        // simple verify the file is available.
        if (file != null && file.exists() && file.length() == data.length) {
            return Response.success(file, HttpHeaderParser.parseCacheHeaders(response, new DefaultExpire()));
        } else {
            try {
                FileUtils.writeByteArrayToFile(file, data);
                return Response.success(file,
                        HttpHeaderParser.parseCacheHeaders(response, new DefaultExpire()));
            } catch (IOException e) {
                e.printStackTrace();

                return Response.error(new ParseError(e));
            }
        }
    }

    return Response.error(new ParseError(response));
}

From source file:algorithm.TextInformationFrame.java

@Override
public List<RestoredFile> restore(File encapsulatedData) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    String restoredCarrierName = getRestoredCarrierName(encapsulatedData);
    byte[] encapsulatedBytes = FileUtils.readFileToByteArray(encapsulatedData);
    String carrierChecksum = "";
    String carrierPath = "";
    while (true) {
        PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(encapsulatedBytes);
        if (payloadSegment == null) {
            RestoredFile carrier = new RestoredFile(restoredCarrierName);
            FileUtils.writeByteArrayToFile(carrier, encapsulatedBytes);
            carrier.validateChecksum(carrierChecksum);
            carrier.wasCarrier = true;/*from   w  ww. ja v a  2 s. c o  m*/
            carrier.algorithm = this;
            carrier.relatedFiles.addAll(restoredFiles);
            carrier.originalFilePath = carrierPath;
            for (RestoredFile file : restoredFiles) {
                file.relatedFiles.add(carrier);
                file.algorithm = this;
            }
            restoredFiles.add(carrier);
            return restoredFiles;
        } else {
            RestoredFile payload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
            FileUtils.writeByteArrayToFile(payload, payloadSegment.getPayloadBytes());
            payload.validateChecksum(payloadSegment.getPayloadChecksum());
            payload.wasPayload = true;
            payload.originalFilePath = payloadSegment.getPayloadPath();
            payload.relatedFiles.addAll(restoredFiles);
            for (RestoredFile file : restoredFiles) {
                file.relatedFiles.add(payload);
            }
            restoredFiles.add(payload);
            encapsulatedBytes = PayloadSegment.removeLeastPayloadSegment(encapsulatedBytes);
            carrierChecksum = payloadSegment.getCarrierChecksum();
            carrierPath = payloadSegment.getCarrierPath();
        }
    }
}

From source file:com.leclercb.commons.api.license.LicenseManager.java

public void writeLicense(License license, File file) throws Exception {
    byte[] message = license.licenseToString().getBytes("UTF-8");
    byte[] signature = this.encryptionManager.sign(message);
    byte[] data = ArrayUtils.addAll(signature, message);

    Base64 base64 = new Base64(40);
    FileUtils.writeByteArrayToFile(file, base64.encode(data));
}

From source file:com.comcast.video.dawg.show.plugins.RemotePluginManager.java

/**
 * Stores a jar and finds all the plugin classes in that jar
 * @param jarBase64 The base64 string representing the jar
 * @throws IOException//from   w  w  w .  ja  va  2s  . c o m
 */
public void storePlugin(String jarBase64) throws IOException {
    byte[] jarBytes = Base64.decodeBase64(jarBase64);
    File file = File.createTempFile("plugin", ".jar", new File(config.getPluginDir()));
    FileUtils.writeByteArrayToFile(file, jarBytes);
    storePlugin(file);
}

From source file:hudson.model.ItemGroupMixInTest.java

/**
 * This test unit makes sure that if part of the config.xml file is
 * deleted it will still load everything else inside the folder.
 * The test unit expects an IOException is thrown, and the one failed
 * job fails to load.//from  w w  w.j  av  a  2  s  .  co  m
 */
@Issue("JENKINS-22811")
@Test
public void xmlFileFailsToLoad() throws Exception {
    MockFolder folder = r.createFolder("folder");
    assertNotNull(folder);

    AbstractProject project = folder.createProject(FreeStyleProject.class, "job1");
    AbstractProject project2 = folder.createProject(FreeStyleProject.class, "job2");
    AbstractProject project3 = folder.createProject(FreeStyleProject.class, "job3");

    File configFile = project.getConfigFile().getFile();

    List<String> lines = FileUtils.readLines(configFile).subList(0, 5);
    configFile.delete();

    // Remove half of the config.xml file to make "invalid" or fail to load
    FileUtils.writeByteArrayToFile(configFile, lines.toString().getBytes());
    for (int i = lines.size() / 2; i < lines.size(); i++) {
        FileUtils.writeStringToFile(configFile, lines.get(i), true);
    }

    // Reload Jenkins.
    r.jenkins.reload();

    // Folder
    assertNotNull("Folder failed to load.", r.jenkins.getItemByFullName("folder"));
    assertNull("Job should have failed to load.", r.jenkins.getItemByFullName("folder/job1"));
    assertNotNull("Other job in folder should have loaded.", r.jenkins.getItemByFullName("folder/job2"));
    assertNotNull("Other job in folder should have loaded.", r.jenkins.getItemByFullName("folder/job3"));
}

From source file:com.xiaoqq.practise.threadmonitor.Agent.java

public byte[] transform(ClassLoader classLoader, String className, Class clazz,
        java.security.ProtectionDomain domain, byte[] bytes) {
    try {//from   w ww .  ja  v a 2s .c  om
        if (inIgnoreList(className)) {
            return bytes;
        }
        ClassReader cr = new ClassReader(bytes);
        ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
        /*ClassVisitor thCV = new ThreadImplementationClassVisitor(Opcodes.ASM5, cw, classLoader);
        ClassVisitor cv = new MonitoringClassVisitor(Opcodes.ASM5, thCV, classLoader);  */
        ClassVisitor cv = new LookupRelationShipClassVisitor(Opcodes.ASM5, cw, classLoader);
        cr.accept(cv, ClassReader.EXPAND_FRAMES);

        byte[] transformedBytes = cw.toByteArray();

        //TODO: remove it
        try {
            FileUtils.writeByteArrayToFile(
                    new File("d:\\workspace\\tmp\\generatedclasses\\" + className + "_gen.class"),
                    transformedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return transformedBytes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.disney.opa.fhb.util.FacilityUtil.java

/**
 * This method is to save the file to disk
 * /*from w  w  w. j  a v a  2s . c om*/
 * @param document
 * @throws Exception
 */
public void saveFacilityDocumentOnServer(Document document) throws Exception {
    String fileNameOnServer = getFacilityDocumentFileNameOnServer(document);
    String serverPath = getFacilityDocumentServerPath(fileNameOnServer);
    FileUtils.writeByteArrayToFile(new File(serverPath), document.getFile());
    document.setFileNameOnServer(fileNameOnServer);
    document.setServerPath(serverPath);
}