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.jgrades.lic.api.crypto.encrypt.LicenceSaver.java

public void saveSignature(byte[] signatureBytes) throws IOException {
    String signatureFilePath = licenceFile.getAbsolutePath() + SIGNATURE_FILE_EXTENSION;
    FileUtils.writeByteArrayToFile(new File(signatureFilePath), signatureBytes);
}

From source file:org.jgrades.rest.client.lic.LicenceManagerServiceClient.java

private FileSystemResource getResource(MultipartFile multipartFile) throws IOException {
    String resourcePath = tempDir + "/" + multipartFile.getName();
    File file = new File(resourcePath);
    FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
    return new FileSystemResource(file.getAbsolutePath());
}

From source file:org.jgrades.rest.lic.LicenceManagerService.java

@Override
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Licence uploadAndInstall(@RequestParam("licence") MultipartFile licence,
        @RequestParam("signature") MultipartFile signature) throws IOException {
    LOGGER.info("Licence installation service invoked");
    checkFilesExisting(licence, signature);

    filesNameResolver.init();//from  www .  j  a  v a  2  s  . c  o m
    File licenceFile = filesNameResolver.getLicenceFile();
    File signatureFile = filesNameResolver.getSignatureFile();

    String licenceFilePath = licenceFile.getAbsolutePath();
    String signatureFilePath = signatureFile.getAbsolutePath();

    LOGGER.info("Saving received licence file to {}", licenceFilePath);
    FileUtils.writeByteArrayToFile(licenceFile, licence.getBytes());

    LOGGER.info("Saving received signature file to {}", signatureFilePath);
    FileUtils.writeByteArrayToFile(signatureFile, signature.getBytes());

    try {
        return licenceManagingService.installLicence(licenceFilePath, signatureFilePath);
    } catch (LicenceException ex) {
        LOGGER.error("Problem during installation licence: {} and signature: {}", licenceFilePath,
                signatureFilePath, ex);
        LOGGER.error("Due to exception during installation saved file will be removed: {} , {}",
                licenceFilePath, signatureFilePath);
        FileUtils.deleteQuietly(licenceFile);
        FileUtils.deleteQuietly(signatureFile);
        throw ex;
    }
}

From source file:org.jspare.sample.svc.controller.TestController.java

@Method(Type.POST)
@Mapping("formUpload")
public void upload() throws IOException {

    DataPart bodyDataPart = request.getParameter("file");
    InputStream is = bodyDataPart.getEntityAs(InputStream.class);
    String fileName = bodyDataPart.getName();

    byte[] image = IOUtils.toByteArray(is);
    FileUtils.writeByteArrayToFile(new File(fileName), image);
    success(image);//ww w  .  j a v  a 2s. c  om
}

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aConnector//from w w  w  .j  av  a  2 s .c  o  m
 * @param aToken
 * @param aResponse
 * @param aServer
 * @param aPlugInNS
 */
public void addAttachment(WebSocketConnector aConnector, Token aToken, Token aResponse, TokenServer aServer,
        String aPlugInNS) {
    String lId = aToken.getString("id");
    String lFilename = aToken.getString("filename");
    String lData = aToken.getString("data");
    String lEncoding = aToken.getString("encoding", "base64");
    String lMsg;

    Token lMailStoreToken = mMailStore.getMail(lId);
    if (null == lMailStoreToken) {
        lMsg = "No mail with id '" + lId + "' found.";
        if (mLog.isDebugEnabled()) {
            mLog.debug(lMsg);
        }
        aResponse.setInteger("code", -1);
        aResponse.setString("msg", lMsg);
        // send error response to requester
        aServer.sendToken(aConnector, aResponse);
        return;
    }

    byte[] lBA = null;
    try {
        if ("base64".equals(lEncoding)) {
            int lIdx = lData.indexOf(',');
            if (lIdx >= 0) {
                lData = lData.substring(lIdx + 1);
            }
            lBA = Base64.decodeBase64(lData);
        } else {
            lBA = lData.getBytes("UTF-8");
        }
    } catch (UnsupportedEncodingException lEx) {
        mLog.error(lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage());
    }

    String lBaseDir;
    String lUsername = aServer.getUsername(aConnector);
    lBaseDir = mSettings.getMailRoot();
    if (lUsername != null) {
        lBaseDir = FilenameUtils
                .getFullPath(JWebSocketConfig.expandEnvVarsAndProps(lBaseDir).replace("{username}", lUsername));
    }

    // complete the response token
    String lFullPath = lBaseDir + lFilename;
    File lFile = new File(lFullPath);
    try {
        // prevent two threads at a time writing to the same file
        synchronized (this) {
            // force create folder if not yet exists
            File lDir = new File(FilenameUtils.getFullPath(lFullPath));
            FileUtils.forceMkdir(lDir);
            if (lBA != null) {
                FileUtils.writeByteArrayToFile(lFile, lBA);
            } else {
                FileUtils.writeStringToFile(lFile, lData, "UTF-8");
            }
        }
        List<Object> lAttachments = lMailStoreToken.getList("attachments");
        if (null == lAttachments) {
            lAttachments = new FastList<Object>();
            lMailStoreToken.setList("attachments", lAttachments);
        }
        lAttachments.add(lFile.getAbsolutePath());

        mMailStore.storeMail(lMailStoreToken);

        Token lSplitToken = archiveAttachments(aConnector, aToken, lMailStoreToken, lBaseDir, aServer,
                aPlugInNS);

    } catch (IOException lEx) {
        aResponse.setInteger("code", -1);
        lMsg = lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage();
        aResponse.setString("msg", lMsg);
        mLog.error(lMsg);
    }
}

From source file:org.kaaproject.kaa.server.appenders.file.appender.FileSystemLogEventServiceImpl.java

private File prepareScriptFile(String resourceName) throws IOException {

    File scriptFile = File.createTempFile(resourceName, ".sh");
    byte[] data = org.kaaproject.kaa.server.common.utils.FileUtils.readResourceBytes(resourceName);
    FileUtils.writeByteArrayToFile(scriptFile, data);

    executeCommand(null, "sudo", "chmod", "+x", scriptFile.getAbsolutePath());

    return scriptFile;
}

From source file:org.kalypso.service.wps.utils.simulation.WPSSimulationDataProvider.java

public static Object parseComplexValue(final ComplexValueType complexValue) throws SimulationException {
    final String mimeType = complexValue.getFormat();
    final List<Object> content = complexValue.getContent();
    if (content.size() == 0)
        return null;

    final Object firstContent = content.get(0);
    final String textContent;
    if (firstContent instanceof String) {
        textContent = (String) firstContent;
    } else if (firstContent instanceof Element) {
        final DOMSource domSource = new DOMSource((Element) firstContent);
        final TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;//  w w  w.j  a va 2  s  . co  m
        try {
            transformer = factory.newTransformer();
            final StringWriter writer = new StringWriter();
            transformer.transform(domSource, new StreamResult(writer));
            textContent = writer.toString();
        } catch (final Exception e) {
            throw new SimulationException(
                    Messages.getString("org.kalypso.service.wps.utils.simulation.WPSSimulationDataProvider.2"), //$NON-NLS-1$
                    e);
        }
    } else {
        throw new SimulationException(
                Messages.getString("org.kalypso.service.wps.utils.simulation.WPSSimulationDataProvider.2")); //$NON-NLS-1$
    }

    // distinguish by mime type, default to binary
    if (TYPE_GML.equals(mimeType)) {
        final StringReader reader = new StringReader(textContent);
        final InputSource inputSource = new InputSource(reader);

        try {
            final String schema = complexValue.getSchema();
            if (schema == null || schema.isEmpty()) {
                return GmlSerializer.createGMLWorkspace(inputSource, null, null, null);
            }

            final URL schemaLocationHint = new URL(schema);
            return GmlSerializer.createGMLWorkspace(inputSource, schemaLocationHint, null, null);
        } catch (final Exception e) {
            throw new SimulationException(
                    Messages.getString("org.kalypso.service.wps.utils.simulation.WPSSimulationDataProvider.2"), //$NON-NLS-1$
                    e);
        }
    } else {
        try {
            // parse as hexBinary
            // TODO: why not base64 encoded byte[]?
            final byte[] bytes = DatatypeConverter.parseHexBinary(textContent);

            final File file = FileUtilities.createNewUniqueFile("complexValue_", FileUtilities.TMP_DIR); //$NON-NLS-1$
            FileUtils.writeByteArrayToFile(file, bytes);

            return file.toURI().toURL();
        } catch (final IOException e) {
            throw new SimulationException(
                    Messages.getString("org.kalypso.service.wps.utils.simulation.WPSSimulationDataProvider.3"), //$NON-NLS-1$
                    e);
        }
    }
}

From source file:org.kawanfw.file.api.util.client.JarReader.java

/**
 * @param args// www.j a v a2s . com
 */
public static void main(String[] args) throws Exception {

    InputStream in = new FileInputStream("I:\\_dev_awake\\awake-file-3.0\\dist\\awake-file-3.0.jar");

    byte[] b = extractClassFileBytecode(in, "org.kawanfw.file.api.util.client.PathUtil");
    System.out.println("b.length: " + b.length);
    FileUtils.writeByteArrayToFile(new File("c:\\temp\\the.class"), b);

}

From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.impl.UploadedDocumentStorageImpl.java

@Override
public void uploadContentChunk(DocumentUploadChunk chunk) throws Exception {
    File docFolder = resolveDocStorage(chunk.getDocumentId());

    File chunkFile = docFolder.toPath().resolve(PARTS_FOLDER).resolve(resolveChunkFileName(chunk)).toFile();

    FileUtils.writeByteArrayToFile(chunkFile, Base64.getDecoder().decode(chunk.getContent()));

    chunk.clearContent();//from   w w w  .j  a  va2s. co m
}

From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.impl.UploadedDocumentStorageImpl.java

@Override
public void uploadContent(String id, byte[] content) {
    File file = rootFolder.resolve(id).toFile();

    try {//w  w  w  .j  ava 2 s.  c  o m
        FileUtils.writeByteArrayToFile(file, content);
    } catch (IOException ex) {
        logger.warn("Cannot upload content for document {}: {}", id, ex);
    }

    uploadedFiles.put(id, file);
}