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:org.apache.torque.generator.control.existingtargetstrategy.AppendToTargetFileStrategy.java

/**
 * Processes the results of the generation.
 *
 * @param outputDirKey the key for the output directory
 *        into which the generated file should be written,
 *        null for the default output directory.
 * @param outputPath the path to which the output should be written,
 *        relative to the output base directory.
 * @param encoding The character encoding of the generated file,
 *        or null for the platform default encoding.
 * @param generationResult the result of the generation, not null.
 * @param unitConfiguration the configuration of the current configuration
 *        unit, not null./* w w w  . j  a  va 2  s .co  m*/
 * @throws GeneratorException on an error.
 */
public void afterGeneration(String outputDirKey, String outputPath, String encoding,
        OutletResult generationResult, UnitConfiguration unitConfiguration) throws GeneratorException {
    File outputFile = ControllerHelper.getOutputFile(outputDirKey, outputPath, unitConfiguration);
    try {
        if (generationResult.isStringResult()) {
            String originalContent = "";
            if (outputFile.exists()) {
                originalContent = FileUtils.readFileToString(outputFile, encoding);
            }
            FileUtils.writeStringToFile(outputFile, originalContent + generationResult.getStringResult(),
                    encoding);
        } else {
            byte[] originalContent = new byte[] {};
            if (outputFile.exists()) {
                originalContent = FileUtils.readFileToByteArray(outputFile);
            }
            byte[] result = new byte[originalContent.length + generationResult.getByteArrayResult().length];
            System.arraycopy(originalContent, 0, result, 0, originalContent.length);
            System.arraycopy(generationResult.getByteArrayResult(), 0, result, originalContent.length,
                    generationResult.getByteArrayResult().length);

            FileUtils.writeByteArrayToFile(outputFile, result);
        }
    } catch (IOException e) {
        throw new ControllerException("Could not write file \"" + outputFile.getAbsolutePath() + "\"", e);
    }
}

From source file:org.apache.torque.generator.control.existingtargetstrategy.ReplaceTargetFileStrategy.java

/**
 * Processes the results of the generation.
 *
 * @param outputDirKey the key for the output directory
 *        into which the generated file should be written,
 *        null for the default output directory.
 * @param outputPath the path to which the output should be written,
 *        relative to the output base directory.
 * @param encoding The character encoding of the generated file,
 *        or null for the platform default encoding.
 * @param generationResult the result of the generation, not null.
 * @param unitConfiguration the configuration of the current configuration
 *        unit, not null./*w w w  . jav  a  2  s  .c  o m*/
 * @throws GeneratorException on an error.
 */
public void afterGeneration(String outputDirKey, String outputPath, String encoding,
        OutletResult generationResult, UnitConfiguration unitConfiguration) throws GeneratorException {
    File outputFile = ControllerHelper.getOutputFile(outputDirKey, outputPath, unitConfiguration);
    try {
        if (generationResult.isStringResult()) {
            FileUtils.writeStringToFile(outputFile, generationResult.getStringResult(), encoding);
        } else {
            FileUtils.writeByteArrayToFile(outputFile, generationResult.getByteArrayResult());
        }
    } catch (IOException e) {
        throw new ControllerException("Could not write file \"" + outputFile.getAbsolutePath() + "\"", e);
    }
}

From source file:org.apache.wookie.tests.helpers.WidgetUploader.java

/**
 * Upload a widget from a file at a given URL
 * @param url/*from   w ww.  ja  v  a 2s  .co  m*/
 * @return
 * @throws IOException
 */
public static String uploadWidget(String url) throws IOException {
    HttpClient httpclient = new HttpClient();
    GetMethod get = new GetMethod(url);
    int status = httpclient.executeMethod(get);
    if (status != 200) {
        fail("problem with download:" + url);
    }
    File file = File.createTempFile("w3c", ".wgt");
    FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(get.getResponseBodyAsStream()));
    get.releaseConnection();
    return uploadWidget(file);
}

From source file:org.apache.wookie.w3c.W3CWidgetFactory.java

/**
 * Download widget from given URL/*  w  w w.j  a v  a  2  s . co m*/
 * @param url the URL to download
 * @param ignoreContentType if set to true, will ignore invalid content types (not application/widget)
 * @return the File downloaded
 * @throws InvalidContentTypeException 
 * @throws HttpException
 * @throws IOException
 */
private File download(URL url, boolean ignoreContentType)
        throws InvalidContentTypeException, HttpException, IOException {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url.toString());
    client.executeMethod(method);
    String type = method.getResponseHeader("Content-Type").getValue();
    if (!ignoreContentType && !type.startsWith(WIDGET_CONTENT_TYPE))
        throw new InvalidContentTypeException("Problem downloading widget: expected a content type of "
                + WIDGET_CONTENT_TYPE + " but received:" + type);
    File file = File.createTempFile("wookie", null);
    FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(method.getResponseBodyAsStream()));
    method.releaseConnection();
    return file;
}

From source file:org.atomserver.core.filestore.FileBasedContentStorage.java

private void writeTestFile(File dir) {
    File testFile = null;//from  www  .  j ava  2s  .  co m
    try {
        testFile = File.createTempFile("testFS", ".txt", dir);
        successfulAvailabiltyFileWrite = false;
        FileUtils.writeByteArrayToFile(testFile, testBytes);
        FileUtils.forceDelete(testFile);
        successfulAvailabiltyFileWrite = true;
    } catch (IOException e) {
        String msg = "An IOException occured while writing the testFile; " + String.valueOf(testFile);
        log.error(msg);
        throw new AtomServerException(msg, e);
    }
}

From source file:org.automagic.mojo.UpdateDepsToUpperBoundMojo.java

public void execute() throws MojoExecutionException {

    if (skip) {/*from  w  ww.j  a  v a2  s . co m*/
        lineBreak();
        getLog().info("--- Skipped!");
        return;
    }

    PomSpy pomSpy = new PomSpyImpl(project, repository, factory, metadataSource, collector, treeBuilder,
            useParent);
    DependenciesFilter filter = new DependenciesFilterImpl(toList(include), toList(exclude));
    DependenciesDoctor doctor = new DependenciesDoctor(pomSpy, honorTopDependencies, filter);

    Optional<List<TransitiveDependency>> antidote = doctor.getAntidote();

    if (!antidote.isPresent()) {
        lineBreak();
        getLog().info("--- Everything is fine!");
        return;
    }

    PomWriter pomWriter = new PomWriterImpl(project, indentSize, indentWithTabs, addComments);
    PomEditor pomEditor = new PomEditor(pomSpy, pomWriter);

    Result result = pomEditor.updateDependencies(antidote.get());

    lineBreak();
    getLog().info("--- Updating dependencies:");
    for (TransitiveDependency dep : result.getModifiedDependencies()) {
        getLog().info(dep.getDependencyNode().toNodeString().trim());
    }
    for (TransitiveDependency dep : result.getNewDependencies()) {
        getLog().info(dep.getDependencyNode().toNodeString().trim());
    }

    if (dryRun) {
        lineBreak();
        getLog().info("--- Finished dry run!");
        return;
    }

    try {
        if (result.isProjectModified()) {
            lineBreak();
            getLog().info("--- Saving changes in pom.xml file:");
            getLog().info(project.getFile().getPath());
            byte[] bytes = pomWriter.saveChanges(!pomSpy.hasXmlDeclaration());
            FileUtils.writeByteArrayToFile(project.getFile(), bytes);
        }
        if (result.isParentProjectModified()) {
            lineBreak();
            getLog().info("--- Saving changes in parent pom.xml file:");
            getLog().info(project.getParent().getFile().getPath());
            byte[] bytes = pomWriter.getParentWriter().saveChanges(!pomSpy.hasXmlDeclaration());
            FileUtils.writeByteArrayToFile(project.getParent().getFile(), bytes);
        }
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("%nError writing in the pom.xml file"), e);
    }
}

From source file:org.ayound.js.debug.resource.JsResourceManager.java

private static void writeGzip2File(File file, InputStream inputStream) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // Transfer bytes from the compressed stream to the output stream
    byte[] buf;/*from w  w w  .ja v a  2s  .co  m*/
    try {
        inputStream = new GZIPInputStream(inputStream);
        buf = new byte[1024];
        int len;
        while ((len = inputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        FileUtils.writeByteArrayToFile(file, out.toByteArray());
        // Close the file and stream
        inputStream.close();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bimserver.emf.SharedJsonDeserializer.java

@SuppressWarnings("rawtypes")
public IfcModelInterface read(InputStream in, IfcModelInterface model, boolean checkWaitingList)
        throws DeserializeException {
    if (model.getPackageMetaData().getSchemaDefinition() == null) {
        throw new DeserializeException("No SchemaDefinition available");
    }// w w w  . j  a v a  2  s .  com
    WaitingList<Long> waitingList = new WaitingList<Long>();
    final boolean log = false;
    if (log) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            IOUtils.copy(in, baos);
            File file = new File("debug.json");
            System.out.println(file.getAbsolutePath());
            FileUtils.writeByteArrayToFile(file, baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        in = new ByteArrayInputStream(baos.toByteArray());
    }
    JsonReader jsonReader = new JsonReader(new InputStreamReader(in, Charsets.UTF_8));
    int nrObjects = 0;
    try {
        JsonToken peek = jsonReader.peek();
        if (peek != null && peek == JsonToken.BEGIN_OBJECT) {
            jsonReader.beginObject();
            peek = jsonReader.peek();
            while (peek == JsonToken.NAME) {
                String nextName = jsonReader.nextName();
                if (nextName.equals("objects")) {
                    jsonReader.beginArray();
                    while (jsonReader.hasNext()) {
                        nrObjects++;
                        processObject(model, waitingList, jsonReader, null);
                    }
                    jsonReader.endArray();
                } else if (nextName.equals("header")) {
                    IfcHeader ifcHeader = (IfcHeader) processObject(model, waitingList, jsonReader,
                            StorePackage.eINSTANCE.getIfcHeader());
                    model.getModelMetaData().setIfcHeader(ifcHeader);
                }
                peek = jsonReader.peek();
            }
            jsonReader.endObject();
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (IfcModelInterfaceException e) {
        LOGGER.error("", e);
    } finally {
        LOGGER.info("# Objects: " + nrObjects);
        try {
            jsonReader.close();
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }
    boolean checkUnique = false;
    if (checkUnique) {
        for (IdEObject idEObject : model.getValues()) {
            for (EStructuralFeature eStructuralFeature : idEObject.eClass().getEAllStructuralFeatures()) {
                Object value = idEObject.eGet(eStructuralFeature);
                if (eStructuralFeature instanceof EReference) {
                    if (eStructuralFeature.isMany()) {
                        List list = (List) value;
                        if (eStructuralFeature.isUnique()) {
                            Set<Object> t = new HashSet<>();
                            for (Object v : list) {
                                if (t.contains(v)) {
                                    //                           LOGGER.error("NOT UNIQUE " + idEObject.eClass().getName() + "." + eStructuralFeature.getName());
                                }
                                t.add(v);
                            }
                        }
                    }
                }
            }
        }
    }
    if (checkWaitingList && waitingList.size() > 0) {
        try {
            waitingList.dumpIfNotEmpty();
        } catch (BimServerClientException e) {
            e.printStackTrace();
        }
        throw new DeserializeException("Waitinglist should be empty (" + waitingList.size() + ")");
    }
    return model;
}

From source file:org.bimserver.geometry.GeometryRunner.java

private synchronized void writeDebugFile(byte[] bytes, boolean error,
        Map<Integer, HashMapVirtualObject> notFoundObjects) throws FileNotFoundException, IOException {
    boolean debug = true;
    if (debug) {/*from  ww  w. j  a  v a  2 s  .c  o  m*/
        Path debugPath = this.streamingGeometryGenerator.bimServer.getHomeDir().resolve("debug");
        if (!Files.exists(debugPath)) {
            Files.createDirectories(debugPath);
        }

        Path folder = debugPath.resolve(this.streamingGeometryGenerator.getDebugIdentifier());
        if (!Files.exists(folder)) {
            Files.createDirectories(folder);
        }

        String basefilenamename = "all";
        if (eClass != null) {
            basefilenamename = eClass.getName();
        }
        if (error) {
            basefilenamename += "-error";
        }

        Path file = folder.resolve(basefilenamename + "-" + job.getId() + ".ifc");
        job.getReport().addDebugFile(file.toString(), job.getId());

        //         if (notFoundObjects != null) {
        //            StringBuilder sb = new StringBuilder();
        //            for (Integer expressId : notFoundObjects.keySet()) {
        //               sb.append(notFoundObjects.get(expressId) + ": " + expressId + "\r\n");
        //            }
        //            FileUtils.writeStringToFile(Paths.get(file.toAbsolutePath().toString() + ".txt").toFile(), sb.toString());
        //         }

        //         StreamingGeometryGenerator.LOGGER.info("Writing debug file to " + file.toAbsolutePath().toString());
        FileUtils.writeByteArrayToFile(file.toFile(), bytes);
    }
}

From source file:org.bimserver.shared.reflector.RealtimeReflectorFactoryBuilder.java

private void writeClassFile(CtClass ctClass) throws IOException, CannotCompileException {
    if (generatedClassesDir != null) {
        File dir = new File(generatedClassesDir, ctClass.getPackageName().replace(".", "/"));
        FileUtils.forceMkdir(dir);//w  w  w.j a v  a  2 s  .c o  m
        FileUtils.writeByteArrayToFile(new File(dir, ctClass.getSimpleName() + ".class"), ctClass.toBytecode());
    }
}