Example usage for org.apache.commons.io FileUtils readFileToByteArray

List of usage examples for org.apache.commons.io FileUtils readFileToByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToByteArray.

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

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. ja v  a2s  .c om*/
        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: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  ww .  j  av  a2 s .c  om*/

    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:com.zacwolf.commons.crypto.Crypter_Blowfish.java

public Crypter_Blowfish(final File keyfile) throws NoSuchAlgorithmException, IOException {
    this(FileUtils.readFileToByteArray(keyfile));
}

From source file:gov.nih.nci.nbia.wadosupport.WADOSupportDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED)
public WADOSupportDTO getWADOSupportDTO(String study, String series, String image, String user) {
    WADOSupportDTO returnValue = new WADOSupportDTO();
    log.info("Study-" + study + " series-" + series + " image-" + image);
    try {/*  ww w  .  j a va  2s  .  c om*/
        List<Object[]> images = this.getHibernateTemplate().getSessionFactory().getCurrentSession()
                .createSQLQuery(WADO_QUERY).setParameter("study", study).setParameter("series", series)
                .setParameter("image", image).list();
        if (images.size() == 0) {
            log.info("image not found");
            return null; //nothing to do
        }
        List<SiteData> authorizedSites;
        UserObject uo = userTable.get(user);
        if (uo != null) {
            authorizedSites = uo.getAuthorizedSites();
            if (authorizedSites == null) {
                AuthorizationManager manager = new AuthorizationManager(user);
                authorizedSites = manager.getAuthorizedSites();
                uo.setAuthorizedSites(authorizedSites);
            }
        } else {
            AuthorizationManager manager = new AuthorizationManager(user);
            authorizedSites = manager.getAuthorizedSites();
            uo = new UserObject();
            uo.setAuthorizedSites(authorizedSites);
            userTable.put(user, uo);
        }
        returnValue.setCollection((String) images.get(0)[0]);
        returnValue.setSite((String) images.get(0)[1]);
        boolean isAuthorized = false;
        for (SiteData siteData : authorizedSites) {
            if (siteData.getCollection().equals(returnValue.getCollection())) {
                if (siteData.getSiteName().equals(returnValue.getSite())) {
                    isAuthorized = true;
                    break;
                }
            }
        }
        if (!isAuthorized) {
            System.out.println("User: " + user + " not authorized");
            return null; //not authorized
        }
        String filePath = (String) images.get(0)[2];
        File imageFile = new File(filePath);
        if (!imageFile.exists()) {
            log.error("File " + filePath + " does not exist");
            return null;
        }
        returnValue.setImage(FileUtils.readFileToByteArray(imageFile));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    return returnValue;
}

From source file:it.drwolf.ridire.filters.TmpResourcesFilter.java

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain arg2)
        throws IOException, ServletException {
    String filename = req.getParameter("filename");
    String encoding = req.getParameter("encoding");
    String tempDir = System.getProperty("java.io.tmpdir");
    String freqList = req.getParameter("freqList");
    String tsvList = req.getParameter("tsvList");
    if (filename != null && encoding != null && filename.indexOf(tempDir) != -1) {
        try {/*  www .ja  v  a 2s. c  o m*/
            Lifecycle.beginCall();
            if (resp instanceof HttpServletResponse) {
                HttpServletResponse response = (HttpServletResponse) resp;
                response.setContentType("text/html");
                response.setCharacterEncoding(encoding);
                response.setHeader("Expires", "0");
                response.setHeader("Date", new Date().toString());
                response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                response.setHeader("Pragma", "public");
                File file = new File(filename);
                if (file.exists() && file.canRead()) {
                    String ret = FileUtils.readFileToString(file, encoding);
                    response.getWriter().write(ret);
                    response.getWriter().flush();
                    response.getWriter().close();
                }
                // FacesContext.getCurrentInstance().responseComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Lifecycle.endCall();
        }
    } else if (freqList != null && freqList.trim().length() > 0
            || tsvList != null && tsvList.trim().length() > 0) {
        try {
            Lifecycle.beginCall();
            String contentType = "application/vnd.oasis.opendocument.spreadsheet";
            File file = null;
            if (freqList != null) {
                file = new File(TmpResourcesFilter.LF_DIR + freqList + ".ods");
                if (freqList.equals("RIDIRE_LF")) {
                    file = new File(TmpResourcesFilter.LF_DIR + freqList + ".zip");
                    contentType = "application/zip";
                }
            } else {
                String zipFileName = tsvList.replaceAll("\\s\\(TSV\\)", "");
                file = new File(TmpResourcesFilter.LF_DIR + zipFileName + ".zip");
                contentType = "application/zip";
            }
            if (file.exists() && file.canRead()) {
                if (resp instanceof HttpServletResponse) {
                    HttpServletResponse response = (HttpServletResponse) resp;
                    response.setContentType(contentType);
                    response.setHeader("Expires", "0");
                    if (freqList != null) {
                        if (freqList.equals("RIDIRE_LF")) {
                            response.addHeader("Content-disposition",
                                    "attachment; filename=\"" + freqList + ".zip\"");
                        } else {
                            response.addHeader("Content-disposition",
                                    "attachment; filename=\"" + freqList + ".ods\"");
                        }
                    } else if (tsvList != null) {
                        response.addHeader("Content-disposition",
                                "attachment; filename=\"" + tsvList + ".zip\"");
                    }
                    response.setHeader("Date", new Date().toString());
                    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                    response.setHeader("Pragma", "public");
                    byte[] lf = FileUtils.readFileToByteArray(file);
                    response.getOutputStream().write(lf);
                    response.getOutputStream().flush();
                    response.getOutputStream().close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Lifecycle.endCall();
        }
    } else {
        Map<String, String[]> pMap = req.getParameterMap();
        final Map<String, String[]> additionalParams = new HashMap<String, String[]>();
        for (String key : pMap.keySet()) {
            // if (key.equals("forma") || key.equals("lemma")
            // || key.equals("pos") || key.equals("phrase")
            // || key.startsWith("pattern")) {
            String[] values = pMap.get(key);
            if (values != null && values.length == 1) {
                byte[] bytes = values[0].getBytes("ISO-8859-1");
                additionalParams.put(key, new String[] { new String(bytes, "UTF-8") });
            }
            // }
        }
        HttpServletRequest httpServletRequest = new PrettyFacesWrappedRequest((HttpServletRequest) req,
                additionalParams);
        arg2.doFilter(httpServletRequest, resp);
    }
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Create a zip file from list of files to a temp directory. They will be added at the root of zip file
 * @param files//from  w  w  w . ja va  2 s . co  m
 * @return the zipped file
 * @throws IOException
 */
public static File createZipArchiveFromFiles(List<File> files) throws IOException {
    final File zipArchive = File.createTempFile("temp_zip_", ".zip");
    try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipArchive))) {
        for (File f : files) {
            if (!f.exists()) {
                logger.warn(String.format("File %s does not exist", f.getName()));
                continue;
            }
            ZipEntry e = new ZipEntry(f.getName());
            out.putNextEntry(e);
            IOUtils.write(FileUtils.readFileToByteArray(f), out);
            out.closeEntry();
        }
    }
    return zipArchive;
}

From source file:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyfile/*from   ww  w . ja v a2s.  c o m*/
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public Crypter_AES(final File keyfile) throws NoSuchAlgorithmException, IOException {
    this(FileUtils.readFileToByteArray(keyfile));
}

From source file:de.undercouch.gradle.tasks.download.DownloadTaskPluginTest.java

/**
 * Tests if a single file can be downloaded
 * @throws Exception if anything goes wrong
 *//*  w  w  w .j  ava 2  s.c  o  m*/
@Test
public void downloadSingleFile() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    byte[] dstContents = FileUtils.readFileToByteArray(dst);
    assertArrayEquals(contents, dstContents);
}

From source file:be.fedict.eid.dss.portal.control.bean.UploadBean.java

@Override
public void listener(UploadEvent event) throws Exception {
    this.log.debug("listener");
    UploadItem item = event.getUploadItem();
    this.log.debug("filename: #0", item.getFileName());
    this.filename = item.getFileName();
    this.log.debug("content type: #0", item.getContentType());
    String extension = FilenameUtils.getExtension(this.filename).toLowerCase();
    this.contentType = supportedFileExtensions.get(extension);
    if (null == this.contentType) {
        /*//from  ww w. j  a  v  a  2  s  .  c  o  m
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(this.filename);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(item.getData(), zipOutputStream);
        zipOutputStream.close();
        this.filename = FilenameUtils.getBaseName(this.filename) + ".zip";
        this.document = outputStream.toByteArray();
        this.contentType = "application/zip";
        return;
    }
    this.log.debug("file size: #0", item.getFileSize());
    this.log.debug("data bytes available: #0", (null != item.getData()));
    if (null != item.getData()) {
        this.document = item.getData();
        return;
    }
    File file = item.getFile();
    if (null != file) {
        this.log.debug("tmp file: #0", file.getAbsolutePath());
        this.document = FileUtils.readFileToByteArray(file);
    }
}

From source file:com.offbynull.coroutines.antplugin.InstrumentTask.java

private void instrumentPath(Instrumenter instrumenter) throws IOException {
    for (File inputFile : FileUtils.listFiles(sourceDirectory, new String[] { "class" }, true)) {
        Path relativePath = sourceDirectory.toPath().relativize(inputFile.toPath());
        Path outputFilePath = targetDirectory.toPath().resolve(relativePath);
        File outputFile = outputFilePath.toFile();

        log("Instrumenting " + inputFile, Project.MSG_INFO);
        byte[] input = FileUtils.readFileToByteArray(inputFile);
        byte[] output = instrumenter.instrument(input);
        log("File size changed from " + input.length + " to " + output.length, Project.MSG_DEBUG);
        FileUtils.writeByteArrayToFile(outputFile, output);
    }/*  www  .  j av  a  2 s .  com*/
}