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:apiserver.model.Document.java

/**
 * Convert the internal file byte[] array back into a generic File to return.
 * @return//from   w  ww. ja  v  a  2s  . c  o  m
 * @throws IOException
 */
public File getFile() throws IOException {
    if (this.file != null && this.file instanceof File && ((File) file).exists()) {
        //return (File)this.file;
    }

    FileOutputStream outputStream = null;

    String filePath = null;
    if (getId() != null) {
        filePath = System.getProperty("java.io.tmpdir") + "/" + getId() + "." + getFileName().split("\\.")[1];
    } else {
        filePath = System.getProperty("java.io.tmpdir") + "/" + getFileName();
    }

    file = new File(filePath);
    FileUtils.writeByteArrayToFile((File) file, getFileBytes());

    //((File)file).deleteOnExit();
    return (File) this.file;
}

From source file:com.floragunn.searchguard.service.SearchGuardService.java

@Inject
public SearchGuardService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    try {/*from   w w w.j a v a 2s  .c o  m*/
        method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
        method.setAccessible(true);
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    try {
        searchServiceSetCallbackMethod = SearchService.class.getDeclaredMethod("setCallback",
                SearchContextCallback.class);
        searchServiceSetCallbackMethod.invoke(searchService,
                new ConfigurableSearchContextCallback(settings, auditListener));
    } catch (final Exception e) {
        log.error(e.toString(), e);
        //throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final String keyPath = settings.get(ConfigConstants.SEARCHGUARD_KEY_PATH, ".");
    SecretKey sc = null;
    try {

        final File keyFile = new File(keyPath, "searchguard_node_key.key");

        if (keyFile.exists()) {
            log.debug("Loaded key from {}", keyFile.getAbsolutePath());
            sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
        } else {

            final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
            final KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128, secRandom);
            final SecretKey secretKey = kg.generateKey();
            final byte[] enckey = secretKey.getEncoded();

            if (enckey == null || enckey.length != 16) {
                throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
            }
            FileUtils.writeByteArrayToFile(keyFile, enckey);
            sc = secretKey;
            log.info("New key written to {}, make sure all nodes have this key", keyFile.getAbsolutePath());
        }

    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/

    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    SearchGuardService.secretKey = sc;
}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}//from   www .  j a v  a  2 s. c om
 */
public void downloadMageTabFileSetToDir(CaArrayEntityReference experimentRef, File dir)
        throws InvalidReferenceException, DataTransferException, IOException {
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Could not create temporary directory " + dir.getAbsolutePath());
    }

    MageTabFileSet mtset = exportMageTab(experimentRef);
    File idf = new File(dir, mtset.getIdf().getMetadata().getName());
    FileUtils.writeByteArrayToFile(idf, mtset.getIdf().getContents());
    File sdrf = new File(dir, mtset.getSdrf().getMetadata().getName());
    FileUtils.writeByteArrayToFile(sdrf, mtset.getSdrf().getContents());
    for (gov.nih.nci.caarray.external.v1_0.data.File dataFile : mtset.getDataFiles()) {
        File dataFileOnDisk = new File(dir, dataFile.getMetadata().getName());
        downloadFileContentsToFile(dataFile.getReference(), false, dataFileOnDisk);
    }
}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from  w w w.ja  v  a  2s  .c  o  m

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}

From source file:nc.noumea.mairie.appock.services.impl.CommandeServiceServiceImpl.java

private void creeFichierCoteServeur(BonLivraison bonLivraison) throws IOException {
    if (bonLivraison.getContenu() == null) {
        return;/*from  ww w . j av a2 s.co  m*/
    }

    FileUtils.writeByteArrayToFile(getFileBonLivraison(bonLivraison), bonLivraison.getContenu());
}

From source file:com.mirth.connect.connectors.dimse.DICOMDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    DICOMDispatcherProperties dicomDispatcherProperties = (DICOMDispatcherProperties) connectorProperties;

    String info = "Host: " + dicomDispatcherProperties.getHost();
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING, info));

    String responseData = null;//w  w w.ja  v  a  2 s . c  om
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;

    File tempFile = null;
    MirthDcmSnd dcmSnd = new MirthDcmSnd(configuration);

    try {
        tempFile = File.createTempFile("temp", "tmp");

        FileUtils.writeByteArrayToFile(tempFile, getAttachmentHandlerProvider()
                .reAttachMessage(dicomDispatcherProperties.getTemplate(), connectorMessage, null, true));

        dcmSnd.setCalledAET("DCMRCV");
        dcmSnd.setRemoteHost(dicomDispatcherProperties.getHost());
        dcmSnd.setRemotePort(NumberUtils.toInt(dicomDispatcherProperties.getPort()));

        if ((dicomDispatcherProperties.getApplicationEntity() != null)
                && !dicomDispatcherProperties.getApplicationEntity().equals("")) {
            dcmSnd.setCalledAET(dicomDispatcherProperties.getApplicationEntity());
        }

        if ((dicomDispatcherProperties.getLocalApplicationEntity() != null)
                && !dicomDispatcherProperties.getLocalApplicationEntity().equals("")) {
            dcmSnd.setCalling(dicomDispatcherProperties.getLocalApplicationEntity());
        }

        if ((dicomDispatcherProperties.getLocalHost() != null)
                && !dicomDispatcherProperties.getLocalHost().equals("")) {
            dcmSnd.setLocalHost(dicomDispatcherProperties.getLocalHost());
            dcmSnd.setLocalPort(NumberUtils.toInt(dicomDispatcherProperties.getLocalPort()));
        }

        dcmSnd.addFile(tempFile);

        //TODO Allow variables
        int value = NumberUtils.toInt(dicomDispatcherProperties.getAcceptTo());
        if (value != 5)
            dcmSnd.setAcceptTimeout(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getAsync());
        if (value > 0)
            dcmSnd.setMaxOpsInvoked(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getBufSize());
        if (value != 1)
            dcmSnd.setTranscoderBufferSize(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getConnectTo());
        if (value > 0)
            dcmSnd.setConnectTimeout(value);
        if (dicomDispatcherProperties.getPriority().equals("med"))
            dcmSnd.setPriority(0);
        else if (dicomDispatcherProperties.getPriority().equals("low"))
            dcmSnd.setPriority(1);
        else if (dicomDispatcherProperties.getPriority().equals("high"))
            dcmSnd.setPriority(2);
        if (dicomDispatcherProperties.getUsername() != null
                && !dicomDispatcherProperties.getUsername().equals("")) {
            String username = dicomDispatcherProperties.getUsername();
            UserIdentity userId;
            if (dicomDispatcherProperties.getPasscode() != null
                    && !dicomDispatcherProperties.getPasscode().equals("")) {
                String passcode = dicomDispatcherProperties.getPasscode();
                userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
            } else {
                userId = new UserIdentity.Username(username);
            }
            userId.setPositiveResponseRequested(dicomDispatcherProperties.isUidnegrsp());
            dcmSnd.setUserIdentity(userId);
        }
        dcmSnd.setPackPDV(dicomDispatcherProperties.isPdv1());

        value = NumberUtils.toInt(dicomDispatcherProperties.getRcvpdulen());
        if (value != 16)
            dcmSnd.setMaxPDULengthReceive(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getReaper());
        if (value != 10)
            dcmSnd.setAssociationReaperPeriod(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getReleaseTo());
        if (value != 5)
            dcmSnd.setReleaseTimeout(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getRspTo());
        if (value != 60)
            dcmSnd.setDimseRspTimeout(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getShutdownDelay());
        if (value != 1000)
            dcmSnd.setShutdownDelay(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getSndpdulen());
        if (value != 16)
            dcmSnd.setMaxPDULengthSend(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getSoCloseDelay());
        if (value != 50)
            dcmSnd.setSocketCloseDelay(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getSorcvbuf());
        if (value > 0)
            dcmSnd.setReceiveBufferSize(value);

        value = NumberUtils.toInt(dicomDispatcherProperties.getSosndbuf());
        if (value > 0)
            dcmSnd.setSendBufferSize(value);

        dcmSnd.setStorageCommitment(dicomDispatcherProperties.isStgcmt());
        dcmSnd.setTcpNoDelay(!dicomDispatcherProperties.isTcpDelay());

        configuration.configureDcmSnd(dcmSnd, this, dicomDispatcherProperties);

        dcmSnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(dicomDispatcherProperties.isTs1());
        dcmSnd.configureTransferCapability();
        dcmSnd.start();

        dcmSnd.open();
        dcmSnd.send();

        if (dcmSnd.isStorageCommitment() && !dcmSnd.commit()) {
            logger.error("Failed to send Storage Commitment request.");
        }

        dcmSnd.close();

        responseStatusMessage = "DICOM message successfully sent";
        responseStatus = Status.SENT;
    } catch (Exception e) {
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse(e.getMessage(), e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), e.getMessage(),
                null);
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), e.getMessage(), null));
    } finally {
        dcmSnd.stop();

        if (tempFile != null) {
            tempFile.delete();
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError);
}

From source file:controllers.SceneController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file,
        @RequestParam(value = "sceneId", required = true) Long sceneId, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*ww w  . java  2  s  .  c  o m*/
        File newFile = new File("/usr/local/etc/sceneParamsList");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            sceneService.updateFromXml(newFile, sceneId);
            ras.addFlashAttribute("error", sceneService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("sceneId", sceneId);
    return "redirect:/Scene/show";
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCloneReadSaveRequest.java

@Override
void save() throws IOException {
    try {//from  w ww  .  j  a va2  s  .c  o  m
        GitClient git = cloneRepo();
        try {
            git.checkoutBranch(sourceBranch, "origin/" + sourceBranch);
        } catch (Exception e) {
            throw new RuntimeException("Branch not found: " + sourceBranch);
        }
        if (!sourceBranch.equals(branch)) {
            //git.branch(branch);
            git.checkoutBranch(branch, "origin/" + sourceBranch);
        }
        File f = new File(repositoryPath, filePath);
        // commit will fail if the contents hasn't changed
        if (!f.exists() || !Arrays.equals(FileUtils.readFileToByteArray(f), contents)) {
            FileUtils.writeByteArrayToFile(f, contents);
            git.add(filePath);
            git.commit(commitMessage);
        }
        git.push().ref(branch).to(new URIish(gitSource.getRemote())).execute();
    } catch (InterruptedException | GitException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to save " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}

From source file:algorithm.F5Steganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpPayload = new File("tmp");
    tmpPayload.delete(); // F5 won't override existing files!
    restore("" + tmpPayload.toPath(), "" + carrier.toPath());
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    copiedCarrier.wasCarrier = true;/*from   ww  w  .j a va  2 s .  c o  m*/
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    FileUtils.copyFile(carrier, copiedCarrier);
    byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpPayload);
    PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
    RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
    FileUtils.writeByteArrayToFile(restoredPayload, payloadSegment.getPayloadBytes());
    restoredPayload.validateChecksum(payloadSegment.getPayloadChecksum());
    restoredPayload.restorationNote = "Payload can be restored correctly.";
    restoredPayload.wasPayload = true;
    restoredPayload.originalFilePath = payloadSegment.getPayloadPath();
    copiedCarrier.originalFilePath = payloadSegment.getCarrierPath();
    restoredFiles.add(restoredPayload);
    FileUtils.forceDelete(tmpPayload);
    restoredFiles.add(copiedCarrier);// 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.haulmont.yarg.formatters.impl.doc.connector.OfficeResourceProvider.java

protected File createTempFile(byte[] bytes) {
    try {//from  w w  w.  j av a2  s  .  c  o  m
        String tempFileName = String.format("document%d", counter.incrementAndGet());
        String tempFileExt = ".tmp";
        if (StringUtils.isNotBlank(officeIntegration.getTemporaryDirPath())) {
            Path tempDir = Paths.get(officeIntegration.getTemporaryDirPath());
            tempDir.toFile().mkdirs();

            temporaryFile = Files.createTempFile(tempDir, tempFileName, tempFileExt).toFile();
        } else {
            temporaryFile = File.createTempFile(tempFileName, tempFileExt);
        }
        FileUtils.writeByteArrayToFile(temporaryFile, bytes);
        return temporaryFile;
    } catch (java.io.IOException e) {
        throw new ReportFormattingException("Could not create temporary file for pdf conversion", e);
    }
}