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.bonitasoft.console.common.server.page.ChildFirstClassLoader.java

protected void addResources(final Map<String, byte[]> resources) {
    if (resources != null) {
        for (final Map.Entry<String, byte[]> resource : resources.entrySet()) {
            if (resource.getKey().matches(".*\\.jar")) {
                final byte[] data = resource.getValue();
                try {
                    final File file = File.createTempFile(resource.getKey(), null, temporaryFolder);
                    file.deleteOnExit();
                    FileUtils.writeByteArrayToFile(file, data);
                    final String path = file.getAbsolutePath();
                    final URL url = new File(path).toURI().toURL();
                    urls.add(url);/*from w w w. ja v a 2  s . c  o m*/
                } catch (final MalformedURLException e) {
                    e.printStackTrace();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            } else {
                nonJarResources.put(resource.getKey(), resource.getValue());
            }
        }
    }
}

From source file:org.bonitasoft.console.common.server.page.CustomPageChildFirstClassLoader.java

private void addOtherDependencies() {
    final Map<String, byte[]> customPageDependencies = customPageDependenciesResolver
            .resolveCustomPageDependencies();
    for (final Map.Entry<String, byte[]> resource : customPageDependencies.entrySet()) {
        if (resource.getKey().matches(".*\\.jar")
                && !bdmDependenciesResolver.isABDMDependency(resource.getKey())) {
            final byte[] data = resource.getValue();
            try {
                final File file = File.createTempFile(resource.getKey(), null,
                        customPageDependenciesResolver.getTempFolder());
                file.deleteOnExit();/*  ww  w  .  j  a v  a  2s  .  c om*/
                FileUtils.writeByteArrayToFile(file, data);
                addURL(new File(file.getAbsolutePath()).toURI().toURL());
            } catch (final IOException e) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING,
                            String.format("Failed to add file %s in classpath", resource.getKey()), e);
                }
            }
        } else {
            nonJarResources.put(resource.getKey(), resource.getValue());
        }
    }
}

From source file:org.bonitasoft.console.common.server.page.CustomPageService.java

protected void retrievePageZipContent(final APISession apiSession,
        final PageResourceProvider pageResourceProvider) throws BonitaException, IOException {
    final PageAPI pageAPI = getPageAPI(apiSession);
    // retrieve page zip content from engine and cache it
    final Page page = pageResourceProvider.getPage(pageAPI);
    final byte[] pageContent = pageAPI.getPageContent(page.getId());
    FileUtils.writeByteArrayToFile(pageResourceProvider.getTempPageFile(), pageContent);
    UnzipUtil.unzip(pageResourceProvider.getTempPageFile(), pageResourceProvider.getPageDirectory().getPath(),
            true);//  w ww.  ja  v a  2  s. c o m
    final File timestampFile = getPageFile(pageResourceProvider.getPageDirectory(), LASTUPDATE_FILENAME);
    long lastUpdateTimestamp = 0L;
    if (page.getLastModificationDate() != null) {
        lastUpdateTimestamp = page.getLastModificationDate().getTime();
    }
    FileUtils.writeStringToFile(timestampFile, String.valueOf(lastUpdateTimestamp), false);
}

From source file:org.bonitasoft.console.common.server.preferences.properties.ConfigurationFilesManager.java

public void setPlatformConfigurations(Map<String, byte[]> configurationFiles) throws IOException {
    platformConfigurations = new HashMap<>(configurationFiles.size());
    for (Map.Entry<String, byte[]> entry : configurationFiles.entrySet()) {
        if (entry.getKey().endsWith(".properties")) {
            platformConfigurations.put(entry.getKey(), getProperties(entry.getValue()));
        } else {/*from  w  ww .  j  a va  2 s  .co  m*/
            File file = new File(WebBonitaConstantsUtils.getInstance().getTempFolder(), entry.getKey());
            FileUtils.writeByteArrayToFile(file, entry.getValue());
            platformConfigurationFiles.put(entry.getKey(), file);
        }
    }
}

From source file:org.bonitasoft.console.common.server.preferences.properties.ConfigurationFilesManager.java

public void setTenantConfigurations(Map<String, byte[]> configurationFiles, long tenantId) throws IOException {
    Map<String, Properties> tenantProperties = new HashMap<>();
    Map<String, File> tenantFiles = new HashMap<>();
    for (Map.Entry<String, byte[]> entry : configurationFiles.entrySet()) {
        if (entry.getKey().endsWith(".properties")) {
            tenantProperties.put(entry.getKey(), getProperties(entry.getValue()));
        } else {/*  w  ww.  j a  v  a 2  s .co m*/
            File file = new File(WebBonitaConstantsUtils.getInstance(tenantId).getTempFolder(), entry.getKey());
            FileUtils.writeByteArrayToFile(file, entry.getValue());
            tenantFiles.put(entry.getKey(), file);
        }
    }
    tenantsConfigurations.put(tenantId, tenantProperties);
    tenantsConfigurationFiles.put(tenantId, tenantFiles);
}

From source file:org.bonitasoft.console.common.server.preferences.properties.ConfigurationFilesManager.java

public void setTenantConfiguration(String fileName, byte[] content, long tenantId) throws IOException {
    if (fileName.endsWith(".properties")) {
        Map<String, Properties> tenantConfiguration = tenantsConfigurations.get(tenantId);
        if (tenantConfiguration != null) {
            tenantConfiguration.put(fileName, getProperties(content));
        }/*w ww.j a v  a  2 s . co m*/
    } else {
        Map<String, File> tenantConfigurationFiles = tenantsConfigurationFiles.get(tenantId);
        if (tenantConfigurationFiles != null) {
            File file = new File(WebBonitaConstantsUtils.getInstance(tenantId).getTempFolder(), fileName);
            FileUtils.writeByteArrayToFile(file, content);
            tenantConfigurationFiles.put(fileName, file);
        }
    }
}

From source file:org.bonitasoft.engine.business.data.ClassloaderRefresher.java

/**
 * @param clientZipContent/*from w  w w. j a v a  2  s  . c o m*/
 * @param contextClassLoader
 * @param modelClass
 * @param fsFolderToPutJars
 * @return the newly created classloader with newly loaded class, if found.
 * @throws java.io.IOException
 * @throws java.net.MalformedURLException
 */
public ClassLoader loadClientModelInClassloader(final byte[] clientZipContent,
        final ClassLoader contextClassLoader, final String modelClass, final File fsFolderToPutJars)
        throws IOException, MalformedURLException {
    final Map<String, byte[]> ressources = IOUtils.unzip(clientZipContent);
    final List<URL> urls = new ArrayList<URL>();
    for (final Entry<String, byte[]> e : ressources.entrySet()) {
        final File file = new File(fsFolderToPutJars, e.getKey());
        if (file.getName().endsWith(".jar")) {
            if (file.getName().contains("model")) {
                try {
                    contextClassLoader.loadClass(modelClass);
                } catch (final ClassNotFoundException e1) {
                    FileUtils.writeByteArrayToFile(file, e.getValue());
                    urls.add(file.toURI().toURL());
                }
            }
            if (file.getName().contains("dao")) {
                try {
                    contextClassLoader.loadClass(modelClass + "DAO");
                } catch (final ClassNotFoundException e1) {
                    FileUtils.writeByteArrayToFile(file, e.getValue());
                    urls.add(file.toURI().toURL());
                }
            }
            if (file.getName().contains("javassist")) {
                try {
                    contextClassLoader.loadClass("javassist.util.proxy.MethodFilter");
                } catch (final ClassNotFoundException e1) {
                    FileUtils.writeByteArrayToFile(file, e.getValue());
                    urls.add(file.toURI().toURL());
                }
            }
        }
    }
    ClassLoader classLoaderWithBDM = contextClassLoader;
    if (!urls.isEmpty()) {
        classLoaderWithBDM = new URLClassLoader(urls.toArray(new URL[urls.size()]), contextClassLoader);
    }
    return classLoaderWithBDM;
}

From source file:org.bonitasoft.engine.home.BonitaHomeServerTest.java

@Test
public void should_getPropertiesFromClassPath_get_properties_of_all_files_from_classpath() throws Exception {
    //given//from  www  .  j a  va2s.co m
    File jar1 = temporaryFolder.newFile("myJar1.jar");
    FileUtils.writeByteArrayToFile(jar1, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile1.properties", "prop1=value1".getBytes())));
    File jar2 = temporaryFolder.newFile("myJar2.jar");
    FileUtils.writeByteArrayToFile(jar2, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile2.properties", "prop2=value2".getBytes())));
    File jar3 = temporaryFolder.newFile("myJar3.jar");
    FileUtils.writeByteArrayToFile(jar3, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile3.properties", "prop3=value3".getBytes())));
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader urlClassLoader = new URLClassLoader(
            new URL[] { jar1.toURI().toURL(), jar2.toURI().toURL(), jar3.toURI().toURL() }, contextClassLoader);
    try {
        Thread.currentThread().setContextClassLoader(urlClassLoader);
        //when
        Properties propertiesFromClassPath = bonitaHomeServer.getPropertiesFromClassPath(
                "myPropertiesFile1.properties", "myPropertiesFile2.properties",
                "anUnexistingProperty.properties");
        //then
        assertThat(propertiesFromClassPath).containsOnly(entry("prop1", "value1"), entry("prop2", "value2"));
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.bonitasoft.platform.setup.PlatformSetupIT.java

@Test
public void push_method_should_clean_previous_config() throws Exception {
    //given//w w w  .ja  v a  2  s .c  o  m
    List<FullBonitaConfiguration> configurations = new ArrayList<>();
    final Path initPath = temporaryFolder.newFolder("init").toPath();
    final Path pushPath = temporaryFolder.newFolder("push").toPath();
    final Path checkPath = temporaryFolder.newFolder("check").toPath();
    final Path licensesPath = temporaryFolder.newFolder("lic").toPath();

    FileUtils.writeByteArrayToFile(
            initPath.resolve(PLATFORM_CONF_FOLDER_NAME).resolve("initial")
                    .resolve(PLATFORM_ENGINE.name().toLowerCase()).resolve("initial.properties").toFile(),
            "key1=value1".getBytes());

    FileUtils.writeByteArrayToFile(pushPath.resolve(PLATFORM_CONF_FOLDER_NAME).resolve("current")
            .resolve(TENANT_TEMPLATE_PORTAL.name().toLowerCase()).resolve("current.properties").toFile(),
            "key2=value2".getBytes());

    System.setProperty(BONITA_SETUP_FOLDER, initPath.toString());
    configurationFolderUtil.buildSqlFolder(initPath.toFile().toPath(), dbVendor);
    platformSetup.init();

    //when
    System.setProperty(BONITA_SETUP_FOLDER, pushPath.toString());
    platformSetup.forcePush();

    //then
    platformSetup.pull(checkPath, licensesPath);
    Files.walkFileTree(checkPath, new AllConfigurationResourceVisitor(configurations));
    assertThat(configurations).as("should remove all files").hasSize(1).extracting("resourceName")
            .containsOnly("current.properties");
}

From source file:org.broadinstitute.gatk.utils.help.GATKDoclet.java

/**
 * @param rootDoc/*  ww w.j a  va  2s .  com*/
 */
private void processDocs(RootDoc rootDoc) {
    // setup the global access to the root
    this.rootDoc = rootDoc;

    try {
        // print the Version number
        FileUtils.writeByteArrayToFile(new File(destinationDir + "/current.version.txt"),
                getSimpleVersion(absoluteVersion).getBytes());

        /* ------------------------------------------------------------------- */
        /* You should do this ONLY ONCE in the whole application life-cycle:   */

        Configuration cfg = new Configuration();
        // Specify the data source where the template files come from.
        cfg.setDirectoryForTemplateLoading(settingsDir);
        // Specify how templates will see the data-model. This is an advanced topic...
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        myWorkUnits = computeWorkUnits();

        List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
        Set<String> seenDocumentationFeatures = new HashSet<String>();
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for (GATKDocWorkUnit workUnit : myWorkUnits) {
            data.add(workUnit.indexDataMap());
            if (!seenDocumentationFeatures.contains(workUnit.annotation.groupName())) {
                groups.add(toMap(workUnit.annotation));
                seenDocumentationFeatures.add(workUnit.annotation.groupName());
            }
        }

        for (GATKDocWorkUnit workUnit : myWorkUnits) {
            processDocWorkUnit(cfg, workUnit, groups, data);
        }

        processIndex(cfg, new ArrayList<GATKDocWorkUnit>(myWorkUnits));

        File forumKeyFile = new File(forumKeyPath);
        if (forumKeyFile.exists()) {
            String forumKey = null;
            // Read in a one-line file so we can do a for loop
            for (String line : new XReadLines(forumKeyFile))
                forumKey = line;
            updateForum(myWorkUnits, forumKey);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}