Java Examples for org.apache.commons.io.FileUtils

The following java examples will help you to understand the usage of org.apache.commons.io.FileUtils. These source code samples are taken from different open source projects.

Example 1
Project: sosies-generator-master  File: LineIteratorTestCase.java View source code
/** 
     * Test a missing File.
     */
@Test(timeout = 1000)
public void testMissingFile_add2085() throws Exception {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testMissingFile_add2085");
    File testFile = new File(FileBasedTestCase.getTestDirectory(), "dummy-missing-file.txt");
    LineIterator iterator = null;
    try {
        iterator = org.apache.commons.io.FileUtils.lineIterator(testFile, "UTF-8");
    } catch (FileNotFoundException expected) {
    } finally {
        LineIterator.closeQuietly(iterator);
        LineIterator.closeQuietly(iterator);
    }
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 2
Project: XMLVersioningFramework-master  File: FileManager.java View source code
/**
	 * 
	 * @param fullPath
	 * @deprecated use org.apache.commons.io.FileUtils.forceMkdir(File
	 *             directory) instead
	 */
public static void createFolder(String fullPath) {
    File directory = new File(fullPath);
    if (!directory.exists()) {
        try {
            FileUtils.forceMkdir(directory);
        } catch (IOException e) {
            System.out.println("Failed to create the directory: " + fullPath);
            e.printStackTrace();
        }
        boolean result = directory.exists();
        if (result) {
            System.out.println("Dir: " + fullPath + " created");
        } else {
            System.out.println("Failed to create the directory, check above for details.");
        }
    } else
        System.out.println("Dir: " + fullPath + " already exists, skipped creation");
}
Example 3
Project: dstream-master  File: BaseTezTests.java View source code
public static void clean(String applicationName) {
    try {
        File workDir = new File(System.getProperty("user.dir"));
        if (workDir.isDirectory()) {
            for (String sub : workDir.list()) {
                if (sub.startsWith(applicationName)) {
                    File file = new File(workDir, sub);
                    FileUtils.deleteDirectory(file);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 4
Project: jmeter-plugins-master  File: STSInstallerTest.java View source code
@Test
public void name() throws Exception {
    File self = new File(STSInstaller.class.getProtectionDomain().getCodeSource().getLocation().getFile());
    String home = self.getParentFile().getParentFile().getParent();
    File dest = new File(home + File.separator + "bin");
    dest.mkdirs();
    STSInstaller.main(new String[0]);
    FileUtils.deleteDirectory(dest);
}
Example 5
Project: strongbox-master  File: DirUtils.java View source code
public static void removeEmptyAncestors(String path, String stopAtPath) throws IOException {
    File dir = new File(path);
    if (stopAtPath != null && dir.getName().equals(stopAtPath)) {
        return;
    }
    String[] list = dir.list();
    if (list != null && list.length == 0) {
        org.apache.commons.io.FileUtils.deleteDirectory(dir);
        removeEmptyAncestors(dir.getParentFile().getAbsolutePath(), stopAtPath);
    }
}
Example 6
Project: thread-local-dns-master  File: SampleFileLoader.java View source code
public static String loadAsUrl(String name) throws Exception {
    InputStream sample = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
    File temp = File.createTempFile("webdrivertest", name.replaceAll("/", "--"));
    FileUtils.copyInputStreamToFile(sample, temp);
    temp.deleteOnExit();
    return temp.getAbsolutePath();
}
Example 7
Project: webarchive-commons-master  File: FileUtilsTest.java View source code
protected void setUp() throws Exception {
    super.setUp();
    this.srcDirFile = new File(getTmpDir(), srcDirName);
    FileUtils.ensureWriteableDirectory(srcDirFile);
    this.tgtDirFile = new File(getTmpDir(), tgtDirName);
    FileUtils.ensureWriteableDirectory(tgtDirFile);
    addFiles();
    zeroLengthLinesUnix = setUpLinesFile("zeroLengthLinesUnix", 0, 0, 400, IOUtils.LINE_SEPARATOR_UNIX);
    zeroLengthLinesWindows = setUpLinesFile("zeroLengthLinesUnix", 0, 0, 400, IOUtils.LINE_SEPARATOR_WINDOWS);
    smallLinesUnix = setUpLinesFile("smallLinesUnix", 0, 25, 400, IOUtils.LINE_SEPARATOR_UNIX);
    smallLinesWindows = setUpLinesFile("smallLinesWindows", 0, 25, 400, IOUtils.LINE_SEPARATOR_WINDOWS);
    largeLinesUnix = setUpLinesFile("largeLinesUnix", 128, 256, 5, IOUtils.LINE_SEPARATOR_UNIX);
    largeLinesWindows = setUpLinesFile("largeLinesWindows", 128, 256, 4096, IOUtils.LINE_SEPARATOR_WINDOWS);
    nakedLastLineUnix = setUpLinesFile("nakedLastLineUnix", 0, 50, 401, IOUtils.LINE_SEPARATOR_UNIX);
    org.apache.commons.io.FileUtils.writeStringToFile(nakedLastLineUnix, "a");
    nakedLastLineWindows = setUpLinesFile("nakedLastLineWindows", 0, 50, 401, IOUtils.LINE_SEPARATOR_WINDOWS);
    org.apache.commons.io.FileUtils.writeStringToFile(nakedLastLineWindows, "a");
}
Example 8
Project: carbon-commons-master  File: FileUtilities.java View source code
/**
     * Filter and clean files in the directory
     *
     * @param direcotry directory to clean
     */
public static void filterFiles(File direcotry) {
    if (direcotry.isDirectory()) {
        Collection<File> files = org.apache.commons.io.FileUtils.listFiles(direcotry, new String[] { ".svn" }, true);
        for (File file : files) {
            if (file.isDirectory()) {
                deleteFolderStructure(file);
            }
        }
    }
}
Example 9
Project: Canoo-WebTest-master  File: CountWebtestResultsTest.java View source code
public void testParseResultFile() {
    final URL url = getClass().getResource("CountWebtestResults_results.xml");
    assertNotNull(url);
    final File file = FileUtils.toFile(url);
    final CountWebtestResults task = new CountWebtestResults();
    task.setResultFile(file);
    task.readResults();
    assertEquals(1, task.getNbFailed());
    assertEquals(2, task.getNbSuccessful());
}
Example 10
Project: Carolina-Digital-Repository-master  File: DepositTestUtils.java View source code
public static String makeTestDir(File parent, String dirName, File zippedContent) {
    File workingDir = new File(parent, dirName);
    try {
        if (workingDir.exists()) {
            FileUtils.deleteDirectory(workingDir);
        }
        ZipFileUtil.unzipToDir(zippedContent, workingDir);
    } catch (IOException e) {
        throw new Error("Unable to unpack your deposit: " + zippedContent, e);
    }
    return workingDir.getAbsolutePath();
}
Example 11
Project: cassandra-unit-master  File: FileTmpHelper.java View source code
public static String copyClassPathDataSetToTmpDirectory(Class c, String initialClasspathDataSetLocation) throws IOException {
    InputStream dataSetInputStream = c.getResourceAsStream(initialClasspathDataSetLocation);
    String dataSetFileName = StringUtils.substringAfterLast(initialClasspathDataSetLocation, "/");
    String tmpPath = FileUtils.getTempDirectoryPath() + "/cassandra-unit/dataset/";
    String targetDataSetPathFileName = tmpPath + dataSetFileName;
    FileUtils.copyInputStreamToFile(dataSetInputStream, new File(targetDataSetPathFileName));
    return targetDataSetPathFileName;
}
Example 12
Project: constellio-master  File: GradleFileVersionParser.java View source code
private static String findVersion() {
    File appLayerBuildGradleFile = new File(new FoldersLocator().getConstellioWebappFolder(), "build.gradle");
    try {
        List<String> appLayerBuildGradleFileLines = FileUtils.readLines(appLayerBuildGradleFile);
        for (int i = 0; i < appLayerBuildGradleFileLines.size(); i++) {
            String line = appLayerBuildGradleFileLines.get(i);
            if (line.contains("version = ")) {
                int firstQuote = line.indexOf("'");
                int secondQuote;
                if (firstQuote == -1) {
                    firstQuote = line.indexOf("\"");
                    secondQuote = line.indexOf("\"", firstQuote + 1);
                } else {
                    secondQuote = line.indexOf("'", firstQuote + 1);
                }
                return line.substring(firstQuote + 1, secondQuote);
            }
        }
        return null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 13
Project: DexExtractor-master  File: ODex.java View source code
public static boolean dumpToSmalli(String bootPath, File dexFile) {
    // org.jf.baksmali.main aa;
    java.lang.String bootclass = "--bootclasspath";
    String odexdir = dexFile.getAbsolutePath() + "smali";
    try {
        FileUtils.deleteDirectory(new File(odexdir));
    } catch (IOException e) {
        e.printStackTrace();
    }
    File odexDir = new File(odexdir);
    odexDir.mkdirs();
    String[] args = new String[] { bootclass, bootPath, "-x", "--output", odexDir.getAbsolutePath(), dexFile.getAbsolutePath() };
    return false;
}
Example 14
Project: GATEinSpring-master  File: SettingsHashBuilder.java View source code
public int getHash(URL configFile, String query) {
    query = StringTransformations.stripMultiWS(query);
    try {
        String configString = FileUtils.readFileToString(Files.fileFromURL(configFile));
        configString = StringTransformations.stripMultiWS(configString);
        return (query + ";" + configString).hashCode();
    } catch (IOException e) {
        return query.hashCode();
    }
}
Example 15
Project: mule-in-action-2e-master  File: MediationFunctionalTestCase.java View source code
@Test
public void testCanProxyMessages() throws Exception {
    String order = FileUtils.readFileToString(new File("src/test/resources/order.xml"));
    Map properties = new HashMap();
    properties.put("Authorization", "Basic am9objpqb2hu");
    MuleMessage response = muleContext.getClient().send("http://localhost:8080", order, properties);
    assertNotNull(response);
    assertEquals("SUCCESS", response.getPayloadAsString());
}
Example 16
Project: SevenCommons-master  File: TempClassCleaner.java View source code
public static void main(String[] args) throws IOException {
    File[] dirs = new File("./eclipse/").listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith("CLASSLOADER_TEMP") || name.startsWith("sevencommonsdyn");
        }
    });
    for (File dir : dirs) {
        FileUtils.deleteDirectory(dir);
    }
}
Example 17
Project: speakeasy-plugin-master  File: TempHelp.java View source code
public static File getTempFile(String name) throws IOException {
    File base = new File("target");
    if (!base.exists()) {
        base = new File(System.getProperty("java.io.tmpdir"));
    }
    File tmp = new File(base, name);
    if (tmp.exists()) {
        if (tmp.isDirectory()) {
            FileUtils.cleanDirectory(tmp);
        }
        tmp.delete();
    }
    return tmp;
}
Example 18
Project: webtest-master  File: CountWebtestResultsTest.java View source code
public void testParseResultFile() {
    final URL url = getClass().getResource("CountWebtestResults_results.xml");
    assertNotNull(url);
    final File file = FileUtils.toFile(url);
    final CountWebtestResults task = new CountWebtestResults();
    task.setResultFile(file);
    task.readResults();
    assertEquals(1, task.getNbFailed());
    assertEquals(2, task.getNbSuccessful());
}
Example 19
Project: zstack-master  File: TestCompresser2.java View source code
@Test
public void test() throws IOException {
    String path = System.getProperty("file");
    String outpath = System.getProperty("out");
    File f = new File(path);
    File outFile = new File(outpath);
    String str = FileUtils.readFileToString(f);
    byte[] ret = Compresser.deflate(str.getBytes());
    System.out.println(String.format("before delfating: %s bytes", str.getBytes().length));
    System.out.println(String.format("after delfating: %s bytes", ret.length));
    byte[] outbyte = Compresser.inflate(ret);
    FileUtils.writeStringToFile(outFile, new String(outbyte));
}
Example 20
Project: EOISLauncher-master  File: LauncherWindow.java View source code
public void login() {
    label.setText("Logging In...");
    try {
        label.setText("");
        @SuppressWarnings("deprecation") String parameters = "user=" + URLEncoder.encode(textField.getText(), "UTF-8") + "&password=" + URLEncoder.encode(passwordField.getText(), "UTF-8") + "&version=" + 13;
        String result = CodeCore.excutePost("https://login.minecraft.net/", parameters);
        if (result == null) {
            label.setText("Cannot connect to Minecraft.net");
            offline = true;
            return;
        }
        if (!result.contains(":")) {
            if (result.trim().equals("Bad login")) {
                label.setText("Login failed");
            } else if (result.trim().equals("Old version")) {
                label.setText("Outdated launcher");
            } else {
                label.setText(result);
            }
            offline = true;
            return;
        }
        String[] values = result.split(":");
        System.out.println("Username: " + values[2]);
        System.out.println("Session ID: " + values[3]);
        String[] mc = new String[] { CodeCore.getWorkingDir(), values[2], values[3] };
        if (chckbxForceUpdate.isSelected()) {
            File mcjar = new File(CodeCore.getWorkingDir() + "/bin/minecraft.jar");
            File lwjgljar = new File(CodeCore.getWorkingDir() + "/bin/lwjgl.jar");
            File jinputjar = new File(CodeCore.getWorkingDir() + "/bin/jinput.jar");
            File natives = new File(CodeCore.getWorkingDir() + "/bin/natives.jar.lzma");
            File utiljar = new File(CodeCore.getWorkingDir() + "/bin/lwjgl_util.jar");
            File elementzip = new File(CodeCore.getWorkingDir() + "/bin/eois.zip");
            URL minecraft = new URL("http://s3.amazonaws.com/MinecraftDownload/minecraft.jar");
            URL lwjgl = new URL("http://s3.amazonaws.com/MinecraftDownload/lwjgl.jar");
            URL jinput = new URL("http://s3.amazonaws.com/MinecraftDownload/jinput.jar");
            URL lwjgl_util = new URL("http://s3.amazonaws.com/MinecraftDownload/lwjgl_util.jar");
            URL lnatives = new URL("http://s3.amazonaws.com/MinecraftDownload/linux_natives.jar.lzma");
            URL wnatives = new URL("http://s3.amazonaws.com/MinecraftDownload/windows_natives.jar.lzma");
            URL elements = new URL("http://dl.jphweb.com/emc/latest.zip");
            if (CodeCore.isLinux()) {
                org.apache.commons.io.FileUtils.copyURLToFile(lnatives, natives, 5000, 10000);
                String[] ex = new String[] { "d", CodeCore.getWorkingDir() + "/bin/natives.jar.lzma", CodeCore.getWorkingDir() + "/bin/linux_natives.jar" };
                LzmaAlone.main(ex);
            }
            if (CodeCore.isWin()) {
                org.apache.commons.io.FileUtils.copyURLToFile(wnatives, natives, 5000, 10000);
                String[] ex = new String[] { "d", CodeCore.getWorkingDir() + "/bin/natives.jar.lzma", CodeCore.getWorkingDir() + "/bin/windows_natives.jar" };
                LzmaAlone.main(ex);
            }
            org.apache.commons.io.FileUtils.copyURLToFile(minecraft, mcjar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(lwjgl, lwjgljar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(jinput, jinputjar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(lwjgl_util, utiljar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(elements, elementzip, 5000, 10000);
            MinecraftLauncher.init(mc);
        }
        if (exists && exists1 && exists2 && exists3) {
            MinecraftLauncher.init(mc);
        } else {
            File mcjar = new File(CodeCore.getWorkingDir() + "/bin/minecraft.jar");
            File lwjgljar = new File(CodeCore.getWorkingDir() + "/bin/lwjgl.jar");
            File jinputjar = new File(CodeCore.getWorkingDir() + "/bin/jinput.jar");
            File utiljar = new File(CodeCore.getWorkingDir() + "/bin/lwjgl_util.jar");
            File elementzip = new File(CodeCore.getWorkingDir() + "/bin/eois.zip");
            File natives = new File(CodeCore.getWorkingDir() + "/bin/natives.jar.lzma");
            URL minecraft = new URL("http://s3.amazonaws.com/MinecraftDownload/minecraft.jar");
            URL lwjgl = new URL("http://s3.amazonaws.com/MinecraftDownload/lwjgl.jar");
            URL jinput = new URL("http://s3.amazonaws.com/MinecraftDownload/jinput.jar");
            URL lwjgl_util = new URL("http://s3.amazonaws.com/MinecraftDownload/lwjgl_util.jar");
            URL elements = new URL("http://dl.jphweb.com/emc/latest.zip");
            URL lnatives = new URL("http://s3.amazonaws.com/MinecraftDownload/linux_natives.jar.lzma");
            URL wnatives = new URL("http://s3.amazonaws.com/MinecraftDownload/windows_natives.jar.lzma");
            if (CodeCore.isLinux()) {
                org.apache.commons.io.FileUtils.copyURLToFile(lnatives, natives, 5000, 10000);
                String[] ex = new String[] { "d", CodeCore.getWorkingDir() + "/bin/natives.jar.lzma", CodeCore.getWorkingDir() + "/bin/linux_natives.jar" };
                LzmaAlone.main(ex);
            }
            if (CodeCore.isWin()) {
                org.apache.commons.io.FileUtils.copyURLToFile(wnatives, natives, 5000, 10000);
                String[] ex = new String[] { "d", CodeCore.getWorkingDir() + "/bin/natives.jar.lzma", CodeCore.getWorkingDir() + "/bin/windows_natives.jar" };
                LzmaAlone.main(ex);
            }
            org.apache.commons.io.FileUtils.copyURLToFile(minecraft, mcjar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(lwjgl, lwjgljar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(jinput, jinputjar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(lwjgl_util, utiljar, 5000, 10000);
            org.apache.commons.io.FileUtils.copyURLToFile(elements, elementzip, 5000, 10000);
            MinecraftLauncher.init(mc);
        }
    } catch (Exception e1) {
    }
}
Example 21
Project: amza-master  File: UiServiceInitializer.java View source code
public UiService initialize(String cacheToken, UiServiceConfig config) {
    File soyPath = new File(System.getProperty("user.dir"), config.getPathToSoyResources());
    SoyFileSet.Builder soyFileSetBuilder = new SoyFileSet.Builder();
    FileUtils.listFiles(soyPath, null, true).forEach( file -> soyFileSetBuilder.add(file));
    SoyFileSet sfs = soyFileSetBuilder.build();
    SoyTofu tofu = sfs.compileToTofu();
    SoyRenderer renderer = new SoyRenderer(tofu, new SoyDataUtils());
    return new UiService(new UiChromeRegion<>(cacheToken, "soy.ui.chrome.chromeRegion", renderer, new UiHeaderRegion("soy.ui.chrome.headerRegion", renderer), new UiHomeRegion("soy.ui.page.homeRegion", renderer)));
}
Example 22
Project: bigpetstore-master  File: TestDocs.java View source code
@Test
public void testGraphViz() throws Exception {
    //test the graphviz file
    //by grepping out the constants.
    String graphviz = FileUtils.readFileToString(new File("arch.dot"));
    System.out.println(graphviz);
    org.junit.Assert.assertTrue(graphviz.contains(OUTPUTS.generated.name()));
    org.junit.Assert.assertTrue(graphviz.contains(OUTPUTS.cleaned.name()));
}
Example 23
Project: dddlib-master  File: FileImageAccessTest.java View source code
@Test
public void test() throws IOException {
    ImageAccess imageAccess = new FileImageAccess(director);
    String mediaId = imageAccess.saveImageFile(FileUtils.readFileToByteArray(new File(file)), "abc.jpg");
    assertTrue(mediaId != null);
    ImageFile imageFile = imageAccess.getImageFile(mediaId);
    assertTrue(imageFile.getContent() != null);
    assertTrue(imageFile.getFileName().equals("abc.jpg"));
}
Example 24
Project: fastcatsearch-master  File: CoreFileUtils.java View source code
public static void removeDirectoryCascade(File dirNumber) throws IOException {
    //FileUtils.deleteDirectory(dirNumber);
    try {
        FileUtils.forceDelete(dirNumber);
        File dir = dirNumber.getParentFile();
        String num = dirNumber.getName();
        int i = Integer.parseInt(num) + 1;
        while (i <= Integer.MAX_VALUE) {
            File f = new File(dir, Integer.toString(i));
            if (f.exists()) {
                //FileUtils.deleteDirectory(f);
                FileUtils.forceDelete(f);
                i++;
            } else {
                // 순차번호�므로 없으면 loop 탈출.
                break;
            }
        }
    } catch (FileNotFoundException ignore) {
    } catch (NumberFormatException ignore) {
    }
}
Example 25
Project: fpcms-master  File: HtmlFormatUtilTest.java View source code
@Test
public void test() throws FileNotFoundException, IOException {
    result = HtmlFormatUtil.htmlBeauty(StringUtils.repeat("中国人民银行,是个好银行。", 100));
    String expected = FileUtils.readFileToString(ResourceUtils.getFile("classpath:html_format_test.txt"));
    assertEquals(expected.replace("\r\n", "").replace("\n", "").trim(), result.replace("\n", "").trim());
}
Example 26
Project: geoserver-master  File: GMLGetCoverageTest.java View source code
@Test
public void testGMLExtension() throws Exception {
    final File xml = new File("./src/test/resources/requestGetCoverageGML.xml");
    final String request = FileUtils.readFileToString(xml);
    MockHttpServletResponse response = postAsServletResponse("wcs", request);
    assertEquals("application/gml+xml", response.getContentType());
    Document dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()));
//        print(dom);
// validate
//        checkValidationErrors(dom, WCS20_SCHEMA);
// check it is good
//        assertXpathEvaluatesTo("wcs__BlueMarble", "//wcs:CoverageDescription//wcs:CoverageId", dom);
//        assertXpathEvaluatesTo("3", "count(//wcs:CoverageDescription//gmlcov:rangeType//swe:DataRecord//swe:field)", dom);
}
Example 27
Project: hudson_plugins-master  File: RemoteListDir.java View source code
public Set<String> invoke(File workspace, VirtualChannel channel) throws IOException {
    Collection<File> list = FileUtils.listFiles(workspace, null, true);
    Set<String> set = new HashSet<String>();
    for (File file : list) {
        String relativePath = FolderDiff.getRelativeName(file.getAbsolutePath(), workspace.getAbsolutePath());
        set.add(relativePath);
    }
    return set;
}
Example 28
Project: jangaroo-tools-master  File: ExmlConfigPackageXsdGeneratorTest.java View source code
@Test
public void testGenerateXsdFile() throws Exception {
    setUp("ext.config", "/ext-as/", "/");
    String expected = FileUtils.readFileToString(new File(getClass().getResource("/ext-as/ext.config.xsd").toURI()));
    StringWriter output = new StringWriter();
    getConfigClassRegistry().generateXsd(output);
    //System.out.println(output.toString());
    expected = expected.replaceAll("\r\n", "\n");
    String actual = output.toString().replaceAll("\r\n", "\n");
    Assert.assertEquals(expected, actual);
}
Example 29
Project: java-libs-master  File: GenerateHypersensitivityTest.java View source code
public void testGenerateSimpleHypersensitivity() throws Exception {
    Archetype archetype = loadArchetype("openEHR-EHR-EVALUATION.hypersensitivity.v1.adl");
    assertNotNull(archetype);
    Object obj = generator.create(archetype, null, archetypeMap, GenerationStrategy.MAXIMUM);
    List<String> lines = dadlBinding.toDADL(obj);
    FileUtils.writeLines(new File("hypersensitivity_max.dadl"), lines);
    generator.create(archetype, null, archetypeMap, GenerationStrategy.MINIMUM);
    lines = dadlBinding.toDADL(obj);
    FileUtils.writeLines(new File("hypersensitivity_min.dadl"), lines);
}
Example 30
Project: javaonhorse-master  File: NewApp.java View source code
public void run() throws Exception {
    String home = System.getenv(HORSE__HOME);
    if (StringUtils.isEmpty(home)) {
        home = System.getProperty(HORSE__HOME);
    }
    if (StringUtils.isEmpty(home)) {
        throw new IllegalStateException("HORSE_HOME is not defined in your system!");
    }
    System.out.println("Created: " + this.appPath.getAbsolutePath());
    this.appPath.mkdirs();
    FileUtils.copyDirectory(new File(home + "/resources/newapp"), appPath);
}
Example 31
Project: jtwig-master  File: Issue313Test.java View source code
@Test
public void allowingForCurrentDirectoryRelativePaths() throws Exception {
    File parentDirectory = FileUtils.getTempDirectory();
    File subDirectory = new File(parentDirectory, "temp");
    subDirectory.mkdirs();
    File file1 = new File(parentDirectory, "file1.twig");
    File file2 = new File(subDirectory, "file2.twig");
    FileUtils.write(file1, "{% include './temp/file2.twig' %}");
    FileUtils.write(file2, "{{ var }}");
    String result = JtwigTemplate.fileTemplate(file1).render(JtwigModel.newModel().with("var", "Hi"));
    assertThat(result, is("Hi"));
}
Example 32
Project: jumbodb-master  File: JumboDBInitializer.java View source code
private void createRequiredFolders() {
    File dataPath = jumboConfiguration.getDataPath();
    File indexPath = jumboConfiguration.getIndexPath();
    try {
        if (!dataPath.exists()) {
            FileUtils.forceMkdir(dataPath);
        }
        if (!indexPath.exists()) {
            FileUtils.forceMkdir(indexPath);
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to create necessary directories");
    }
}
Example 33
Project: lzma-java-master  File: DecodingTest.java View source code
public void testDecodeFileWithoutEndOfStreamMarker() throws IOException {
    final InputStream compressedFileStream = FileUtils.openInputStream(new File("target/test-classes/hello.txt.lzma"));
    @SuppressWarnings("unchecked") final List<String> lines = IOUtils.readLines(new LzmaInputStream(compressedFileStream, new Decoder()));
    assertEquals(1, lines.size());
    assertEquals("Hello World !", lines.get(0));
}
Example 34
Project: molgenis_apps-legacy-master  File: XqtlGenerateMiniGUI.java View source code
/**
	 * 
	 * Experimental GUI, development mock-up.
	 * 
	 * Don't forget to add "modules/minigui" to the build path!
	 * 
	 */
public static void main(String[] args) throws Exception {
    try {
        File src = new File("apps/xqtl/org/molgenis/xqtl/minigui/MiniApplicationView.ftl");
        File dest = new File("../molgenis/src/org/molgenis/framework/ui/ApplicationView.ftl");
        FileUtils.copyFile(src, dest);
        new Molgenis("apps/xqtl/org/molgenis/xqtl/minigui/xqtl_minigui.properties").generate();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 35
Project: multi-module-maven-release-plugin-master  File: Photocopier.java View source code
public static File copyTestProjectToTemporaryLocation(String moduleName) throws IOException {
    File source = new File("test-projects", moduleName);
    if (!source.isDirectory()) {
        source = new File(FilenameUtils.separatorsToSystem("../test-projects/" + moduleName));
    }
    if (!source.isDirectory()) {
        throw new RuntimeException("Could not find module " + moduleName);
    }
    File target = folderForSampleProject(moduleName);
    FileUtils.copyDirectory(source, target);
    return target;
}
Example 36
Project: openxc-android-master  File: TestUtils.java View source code
public static URI copyToStorage(Context context, int resource, String filename) {
    URI uri = null;
    try {
        uri = new URI("file:///sdcard/com.openxc/" + filename);
    } catch (URISyntaxException e) {
        fail("Couldn't construct resource URIs: " + e);
    }
    try {
        FileUtils.copyInputStreamToFile(context.getResources().openRawResource(resource), new File(uri));
    } catch (IOException e) {
        fail("Couldn't copy trace files to SD card" + e);
    }
    return uri;
}
Example 37
Project: pbox-master  File: Sources.java View source code
public static List<String> getList() {
    List<String> sources = new ArrayList<>();
    String lines;
    try {
        lines = FileUtils.readFileToString(new File(Environment.getPboxHomeAsFile(), "sources.lst"));
        for (String line : lines.split("\\s+")) {
            if (StringUtils.isNoneBlank(line)) {
                sources.add(line);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Can't get sources.lst from PBOX_HOME [PBOX_HOME=" + Environment.getPboxHomeAsFile() + "].");
    }
    return Collections.unmodifiableList(sources);
}
Example 38
Project: RocooFix-master  File: SoFixApplication.java View source code
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    try {
        //删除之�的so
        SoFileUtil.getDataFileSoPatchForInstall(base).delete();
        //sdcard/libhello-jni-{cpu}.so  copy to getDataFileSoPath()
        //拷�sd� so到data目录
        FileUtils.copyFileToDirectory(new File(SoFileUtil.getSDCardSoPath(), SoFileUtil.getFullSoName("libhello-jni")), SoFileUtil.getDataFileSoPatchForInstall(base));
    } catch (IOException e) {
        e.printStackTrace();
    }
    //install data目录的so路径
    RocooSoFix.applyPatch(base, SoFileUtil.getDataFileSoPatchForInstall(base).getAbsolutePath());
}
Example 39
Project: saos-master  File: ContentFileTransactionContextFactoryTest.java View source code
//------------------------ TESTS --------------------------
@Test
public void createTransactionContext() throws IOException {
    // execute
    ContentFileTransactionContext context = contentFileTransactionContextFactory.createTransactionContext();
    // assert
    assertNotNull(context);
    assertEquals(new File(contentDirectoryPath), context.getContentDirectory());
    assertTrue(context.getDeletedTmpDirectory().exists());
    FileUtils.deleteDirectory(context.getDeletedTmpDirectory());
}
Example 40
Project: Stage-master  File: ConfigurationSourceExporter.java View source code
public static void main(String[] args) throws IOException {
    final String json = JsonUtils.toJson(new ConfigurationRegistry(StagemonitorPlugin.class).getConfigurationOptionsByCategory());
    System.out.println(json);
    File stagemonitorWidgetDevHtml = new File("stagemonitor-web/src/test/resources/stagemonitorWidgetDev.html");
    String content = FileUtils.readFileToString(stagemonitorWidgetDevHtml);
    content = content.replaceAll("configurationOptions .*", "configurationOptions = " + json.replace("$", "\\$").replace("\\\"", "\\\\\"") + ";");
    FileUtils.writeStringToFile(stagemonitorWidgetDevHtml, content);
}
Example 41
Project: stagemonitor-master  File: ConfigurationSourceExporter.java View source code
public static void main(String[] args) throws IOException {
    final String json = JsonUtils.toJson(new ConfigurationRegistry(StagemonitorPlugin.class).getConfigurationOptionsByCategory());
    System.out.println(json);
    File stagemonitorWidgetDevHtml = new File("stagemonitor-web/src/test/resources/stagemonitorWidgetDev.html");
    String content = FileUtils.readFileToString(stagemonitorWidgetDevHtml);
    content = content.replaceAll("configurationOptions .*", "configurationOptions = " + json.replace("$", "\\$").replace("\\\"", "\\\\\"") + ";");
    FileUtils.writeStringToFile(stagemonitorWidgetDevHtml, content);
}
Example 42
Project: tldgen-master  File: TldLibraryWriterTest.java View source code
@Test
public void writeTldTest() throws Exception {
    TldLibraryWriter writer = new TldLibraryWriter();
    writer.writeTLD(library, tldFolder);
    String expected = FileUtils.readFileToString(new File("src/test/resources/org/tldgen/writers/expected-output.tld"));
    String actual = FileUtils.readFileToString(new File(tldFolder + "/loom.tld"));
    assertEquals(expected, actual);
}
Example 43
Project: waitt-master  File: BundleCreator.java View source code
public IBundleCoverage createBundle(final ExecutionDataStore executionDataStore) throws IOException {
    final CoverageBuilder builder = new CoverageBuilder();
    final Analyzer analyzer = new Analyzer(executionDataStore, builder);
    final File classesDir = new File("target/classes");
    Collection<File> filesToAnalyze = FileUtils.listFiles(classesDir, new String[] { "class" }, true);
    for (final File file : filesToAnalyze) {
        analyzer.analyzeAll(file);
    }
    return builder.getBundle("project");
}
Example 44
Project: dwca-io-master  File: DwcaStreamWriterTest.java View source code
@Test
public void write() throws Exception {
    File dwca = FileUtils.createTempDir();
    Map<Term, Integer> mapping = ImmutableMap.of(DwcTerm.taxonID, 0, DwcTerm.scientificName, 1, DwcTerm.taxonRank, 2);
    try (DwcaStreamWriter dwcaWriter = new DwcaStreamWriter(dwca, DwcTerm.Taxon, DwcTerm.taxonID, true)) {
        Dataset d = new Dataset();
        d.setTitle("Abies of the Alps");
        d.setDescription("Abies of the Alps excl Switzerland.");
        dwcaWriter.setMetadata(d);
        dwcaWriter.write(DwcTerm.Taxon, 0, mapping, ImmutableList.<String[]>builder().add(new String[] { "tax-1", "Abies Mill.", "genus" }).add(new String[] { "tax-2", "Abies alba Mill.", "species" }).add(new String[] { "tax-3", "Piceae abies L.", "species" }).add(new String[] { "tax-4", "Piceae abies subsp. helvetica L.", "subspecies" }).build());
    } finally {
        org.apache.commons.io.FileUtils.deleteQuietly(dwca);
    }
}
Example 45
Project: tikione-steam-cleaner-master  File: Redist.java View source code
public double getSize() {
    long fsize;
    if (file.isFile()) {
        fsize = org.apache.commons.io.FileUtils.sizeOf(file);
    } else if (file.isDirectory()) {
        fsize = org.apache.commons.io.FileUtils.sizeOfDirectory(file);
    } else {
        fsize = 0;
    }
    double floatSize = fsize;
    floatSize /= (1024.0 * 1024.0);
    return floatSize;
}
Example 46
Project: wow-auctions-master  File: DownloadAuctionFileBatchlet.java View source code
private void downloadAuctionFile(AuctionFile auctionFile) {
    RealmFolder folder = woWBusiness.findRealmFolderById(auctionFile.getRealm().getId(), FolderType.valueOf(to));
    getLogger(this.getClass().getName()).log(Level.INFO, "Downloadig Auction file " + auctionFile.getUrl() + " to " + folder.getPath());
    try {
        File finalFile = getFile(folder.getPath() + "/" + auctionFile.getFileName());
        if (!finalFile.exists()) {
            FileUtils.copyURLToFile(new URL(auctionFile.getUrl()), finalFile);
        }
        auctionFile.setFileStatus(FileStatus.DOWNLOADED);
        woWBusiness.updateAuctionFile(auctionFile);
    } catch (FileNotFoundException e) {
        getLogger(this.getClass().getName()).log(Level.INFO, "Could not download Auction file " + auctionFile.getUrl() + " from " + auctionFile.getRealm().getName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 47
Project: ipt-master  File: VocabulariesManagerImplTest.java View source code
@Before
public void setup() throws ParserConfigurationException, SAXException, IOException, URISyntaxException {
    dataDir = mock(DataDir.class);
    appConfig = new AppConfig(dataDir);
    ConfigWarnings warnings = new ConfigWarnings();
    Injector injector = Guice.createInjector(new ServletModule(), new Struts2GuicePluginModule(), new IPTModule());
    SAXParserFactory saxf = injector.getInstance(SAXParserFactory.class);
    VocabularyFactory vocabularyFactory = new VocabularyFactory(saxf);
    // construct mock RegistryManager:
    // mock getVocabularies() response from Registry with local test resource (list of vocabularies from thesauri_sandbox.json)
    HttpUtil mockHttpUtil = mock(HttpUtil.class);
    HttpUtil.Response mockResponse = mock(HttpUtil.Response.class);
    mockResponse.content = IOUtils.toString(ExtensionManagerImplTest.class.getResourceAsStream("/responses/thesauri_sandbox.json"), "UTF-8");
    when(mockHttpUtil.get(anyString())).thenReturn(mockResponse);
    // create instance of RegistryManager
    RegistryManager mockRegistryManager = new RegistryManagerImpl(appConfig, dataDir, mockHttpUtil, saxf, warnings, mock(SimpleTextProvider.class), mock(RegistrationManager.class), mock(ResourceManager.class));
    assertTrue(TMP_DIR.isDirectory());
    // copy vocabulary file to temporary directory
    File newRanksVoc = FileUtils.getClasspathFile("thesauri/rank_2015-04-24.xml");
    File datasetTypeVoc = FileUtils.getClasspathFile("thesauri/dataset_type.xml");
    File languageVoc = FileUtils.getClasspathFile("thesauri/639-2.xml");
    File countryVoc = FileUtils.getClasspathFile("thesauri/3166-1.xml");
    File roleVoc = FileUtils.getClasspathFile("thesauri/agent_role.xml");
    File frequencyVoc = FileUtils.getClasspathFile("thesauri/update_frequency.xml");
    File methodsVoc = FileUtils.getClasspathFile("thesauri/preservation_method.xml");
    File subtypesVoc = FileUtils.getClasspathFile("thesauri/dataset_subtype.xml");
    org.apache.commons.io.FileUtils.copyFileToDirectory(newRanksVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(datasetTypeVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(languageVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(countryVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(roleVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(frequencyVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(methodsVoc, TMP_DIR);
    org.apache.commons.io.FileUtils.copyFileToDirectory(subtypesVoc, TMP_DIR);
    File tmpNewRankVoc = new File(TMP_DIR, "rank_2015-04-24.xml");
    assertTrue(tmpNewRankVoc.exists());
    File tmpDatasetTypeVoc = new File(TMP_DIR, "dataset_type.xml");
    File tmpLanguageVoc = new File(TMP_DIR, "639-2.xml");
    File tmpCountryVoc = new File(TMP_DIR, "3166-1.xml");
    File tmpRoleVoc = new File(TMP_DIR, "agent_role.xml");
    File tmpFrequencyVoc = new File(TMP_DIR, "update_frequency.xml");
    File tmpMethodVoc = new File(TMP_DIR, "preservation_method.xml");
    File tmpSubtypeVoc = new File(TMP_DIR, "dataset_subtype.xml");
    // mock returning temporary files when looked up by their 'safe' filenames
    when(dataDir.tmpFile("http_rs_gbif_org_sandbox_vocabulary_gbif_rank_2015-04-24_xml.xml")).thenReturn(tmpNewRankVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_gbif_dataset_type_xml.xml")).thenReturn(tmpDatasetTypeVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_iso_639-2_xml.xml")).thenReturn(tmpLanguageVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_iso_3166-1_alpha2_xml.xml")).thenReturn(tmpCountryVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_gbif_agent_role_xml.xml")).thenReturn(tmpRoleVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_eml_update_frequency_xml.xml")).thenReturn(tmpFrequencyVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_gbif_preservation_method_xml.xml")).thenReturn(tmpMethodVoc);
    when(dataDir.tmpFile("http_rs_gbif_org_vocabulary_gbif_dataset_subtype_xml.xml")).thenReturn(tmpSubtypeVoc);
    // mock returning newly created and installed vocabulary files
    File rankInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_gbif_rank.vocab");
    File datasetTypeInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_gbif_datasetType.vocab");
    File languageInstalled = new File(TMP_DIR, "http_iso_org_639-2.vocab");
    File countryInstalled = new File(TMP_DIR, "http_iso_org_iso3166-1_alpha2.vocab");
    File roleInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_gbif_agentRole.vocab");
    File frequencyInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_eml_updateFrequency.vocab");
    File methodInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_gbif_preservation_method.vocab");
    File subtypeInstalled = new File(TMP_DIR, "http_rs_gbif_org_vocabulary_gbif_datasetSubtype.vocab");
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_sandbox_vocabulary_gbif_rank_2015-04-24_xml.vocab")).thenReturn(rankInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_gbif_dataset_type_xml.vocab")).thenReturn(datasetTypeInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_iso_639-2_xml.vocab")).thenReturn(languageInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_iso_3166-1_alpha2_xml.vocab")).thenReturn(countryInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_gbif_agent_role_xml.vocab")).thenReturn(roleInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_eml_update_frequency_xml.vocab")).thenReturn(frequencyInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_gbif_preservation_method_xml.vocab")).thenReturn(methodInstalled);
    when(dataDir.configFile(VocabulariesManagerImpl.CONFIG_FOLDER + "/http_rs_gbif_org_vocabulary_gbif_dataset_subtype_xml.vocab")).thenReturn(subtypeInstalled);
    // Mock downloading vocabulary into tmpFile - we're cheating by handling the actual file already as if it
    // were downloaded already. Furthermore, mock download() response with StatusLine with 200 OK response code
    StatusLine sl = mock(StatusLine.class);
    when(sl.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    when(mockHttpUtil.download(any(URL.class), any(File.class))).thenReturn(sl);
    manager = new VocabulariesManagerImpl(appConfig, dataDir, vocabularyFactory, mockHttpUtil, mockRegistryManager, warnings, mock(SimpleTextProvider.class), mock(RegistrationManager.class));
}
Example 48
Project: jdal-master  File: Report.java View source code
/**
	 * @return a JasperReport
	 */
public JasperReport newJasperReport() {
    String suffix = FilenameUtils.getExtension(getFileName());
    String prefix = FilenameUtils.getBaseName(getFileName());
    JasperReport jasperReport = null;
    try {
        File file = File.createTempFile(prefix, "." + suffix);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, data);
        if ("zip".equalsIgnoreCase(suffix)) {
            String dir = System.getProperty("java.io.tmpdir") + "/" + prefix;
            ZipFileUtils.unzip(new ZipFile(file), dir);
            File dirFile = new File(dir);
            Iterator<File> iter = org.apache.commons.io.FileUtils.iterateFiles(dirFile, new String[] { "jrxml", "jasper" }, false);
            while (iter.hasNext()) {
                file = iter.next();
                break;
            }
        }
        // now file points to jrxml or jasper file
        suffix = FilenameUtils.getExtension(file.getName());
        FileInputStream reportStream = new FileInputStream(file);
        if ("jrxml".equalsIgnoreCase(suffix))
            jasperReport = JasperCompileManager.compileReport(reportStream);
        else if ("jasper".equalsIgnoreCase(suffix))
            jasperReport = (JasperReport) JRLoader.loadObject(reportStream);
    } catch (Exception e) {
        log.error(e);
    }
    return jasperReport;
}
Example 49
Project: actor-platform-master  File: DocIndexGenerator.java View source code
public static void generate(SchemeDefinition definition, String path) throws IOException {
    String indexTemplate = FileUtils.readFileToString(new File(path + "/index_template.html"));
    String body = "";
    String navigation = "";
    for (SchemeSection section : definition.getSections()) {
        navigation += "<li role=\"presentation\"><a href=\"#" + section.getPkg() + "\">" + section.getName() + "</a></li>";
        body += "<a name=\"" + section.getPkg() + "\"></a><h1 class=\"page-header\">" + section.getName() + "</h1>\n";
        body += section.getUniformedDocs();
        body += "<h3>Reference</h3>";
        body += ReferenceGenerator.generateSectionScheme("reference/", section);
    }
    String indexContent = indexTemplate.replace("{body_placeholder}", body).replace("{menu_placeholder}", navigation);
    FileUtils.writeStringToFile(new File(path + "/index.html"), indexContent);
}
Example 50
Project: allure-cli-master  File: BundleRemove.java View source code
/**
     * Remove the specified bundle from cache. The removed bundle can be cached
     * again using update or switch command.
     * <p/>
     * {@inheritDoc}
     */
@Override
protected void runUnsafe() throws IOException {
    if (isVersionNotInstalled(version)) {
        getLogger().warn(Messages.COMMAND_BUNDLE_REMOVE_BUNDLE_ABSENT, version);
        return;
    }
    Path bundlePath = getBundlesPath(version);
    getLogger().info(Messages.COMMAND_BUNDLE_REMOVE_BUNDLE_REMOVING, bundlePath.toAbsolutePath());
    FileUtils.deleteDirectory(bundlePath.toFile());
    getConfig().removeVersion(version);
    saveConfig();
    getLogger().info(Messages.COMMAND_BUNDLE_REMOVE_BUNDLE_REMOVED, version);
}
Example 51
Project: aluesarjat-master  File: LoaderDatasetsDump.java View source code
public static void main(String[] args) throws IOException {
    Properties properties = new Properties();
    InputStream in = LoaderDatasetsDump.class.getResourceAsStream("/loader.properties");
    if (in == null) {
        throw new IllegalArgumentException("Make sure classpath:/loader.properties is available");
    }
    properties.load(in);
    String dataDir = properties.getProperty("data.dir");
    // collect PX files
    Stack<File> unhandled = new Stack<File>();
    unhandled.push(new File(dataDir));
    StringBuilder builder = new StringBuilder();
    while (!unhandled.isEmpty()) {
        File file = unhandled.pop();
        if (file.isDirectory()) {
            if (file.listFiles() != null) {
                unhandled.addAll(Arrays.asList(file.listFiles()));
            }
        } else if (file.getName().endsWith(".px")) {
            builder.append(file.toURI().toURL().toString() + " \".\"\n");
        }
    }
    File file = new File("target/datasets.dump");
    FileUtils.writeStringToFile(file, builder.toString(), "UTF-8");
}
Example 52
Project: AnyMemo-master  File: AbstractExistingDBTest.java View source code
@Before
public void setUp() throws Exception {
    Context testContext = getContext();
    InputStream in = testContext.getResources().getAssets().open(AMEnv.DEFAULT_DB_NAME);
    File outFile = new File(TestHelper.SAMPLE_DB_PATH);
    outFile.delete();
    FileUtils.copyInputStreamToFile(in, outFile);
    in.close();
    helper = AnyMemoDBOpenHelperManager.getHelper(testContext, TestHelper.SAMPLE_DB_PATH);
}
Example 53
Project: arquillian-cube-master  File: VolumeCreator.java View source code
/**
     * Creates a new temporary folder with password file for VNC server.
     * The folder is relative to the root of the project.
     *
     * @param password
     *     value to generate password file.
     *
     * @return Path of generated file.
     */
public static final Path createTemporaryVolume(String password) {
    final File tmpFile = new File(".tmp" + System.currentTimeMillis());
    if (!tmpFile.mkdirs()) {
        throw new IllegalArgumentException("Temporary Folder for storing recordings could not be created.");
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            FileUtils.deleteQuietly(tmpFile);
        }
    });
    final Path temp = tmpFile.toPath();
    Path passwordFile = temp.resolve("password");
    try {
        Files.write(passwordFile, password.getBytes());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    return temp;
}
Example 54
Project: atlasframework-master  File: AvUtil.java View source code
/**
	 * This method fixes an error where the bg-color value was not set correctly and therefore the lobo html renderer
	 * failed to parse it
	 * 
	 * @return
	 */
public static boolean fixBrokenBgColor(File oldHtml) throws IOException {
    final String unfixed = IOUtil.readFileAsString(oldHtml);
    final String fixed = fixBrokenBgColor(unfixed);
    if (!fixed.equals(unfixed)) {
        // SVN friendyl only write the file if the is a change
        FileUtils.writeStringToFile(oldHtml, fixed);
        return true;
    }
    return false;
}
Example 55
Project: aws-sdk-first-steps-master  File: Ec2Utils.java View source code
public static void run(AmazonEC2 machines, String pathToScript, int count, String profileArn) throws IOException {
    machines.runInstances(new RunInstancesRequest().withImageId(// This used to be the official, Ireland running, 32 bit Amazon Machine Image. Or pick, for instance, [Ubuntu](http://cloud-images.ubuntu.com/locator/ec2/)
    "ami-c7c0d6b3").withInstanceType(// Smallest possible, cheapest. Be warned: Cc28xlarge can set you back 3.75$ per call per machine per hour... [Pricing](http://aws.amazon.com/fr/ec2/#pricing)
    InstanceType.T1Micro).withMaxCount(count).withMinCount(count).withInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate).withIamInstanceProfile(new IamInstanceProfileSpecification().withArn(profileArn)).withUserData(printBase64Binary(FileUtils.readFileToString(new File(pathToScript), "UTF-8").getBytes("UTF-8"))));
}
Example 56
Project: Bagginses-master  File: BagDescriptions.java View source code
public static void init() {
    File file = new File(Bagginses.path + "descriptions.json");
    if (!file.exists()) {
        URL inputUrl = Bagginses.class.getResource("/descriptions.json");
        try {
            System.out.println("Creating config file");
            file.createNewFile();
            FileUtils.copyURLToFile(inputUrl, file);
        } catch (IOException e) {
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        Gson gson = new GsonBuilder().create();
        descriptions = new ArrayList<BagInfo>(Arrays.asList(gson.fromJson(reader, BagInfo[].class)));
        reader.close();
    } catch (IOException e) {
    }
    for (BagInfo desc : descriptions) {
        ModItems.bags.get(desc.getColor()).setDesc(desc.getDescription());
    }
}
Example 57
Project: bior_pipeline-master  File: VEPFormatterTest.java View source code
/**
	 * Tests "happy" path where JSON has all fields.
	 * 
	 * @throws IOException
	 */
@Test
public void brca1Test() throws IOException {
    String json = FileUtils.readFileToString(new File("src/test/resources/treat/formatters/VEPFormatter.brca1.json"));
    String[] expectedValues = { "C", "ENSG00000012048", "ENST00000352993", "Transcript", "missense_variant", "768", "536", "179", "Y/C", "tAc/tGc", "BRCA1", "deleterious", "0.01", "probably_damaging", "0.999" };
    validateFormattedValues(mFormatter, json, expectedValues);
}
Example 58
Project: Canova-master  File: LineReaderTest.java View source code
@Test
public void testLineReader() throws Exception {
    File tmp = new File("tmp.txt");
    FileUtils.writeLines(tmp, Arrays.asList("1", "2", "3"));
    InputSplit split = new FileSplit(tmp);
    tmp.deleteOnExit();
    RecordReader reader = new LineRecordReader();
    reader.initialize(split);
    int count = 0;
    while (reader.hasNext()) {
        assertEquals(1, reader.next().size());
        count++;
    }
    assertEquals(3, count);
}
Example 59
Project: Captor-master  File: FileUtil.java View source code
//-------------------------------------------------------------------------
public static boolean cloneDir(File source, File destination) {
    destination = new File(destination, source.getName());
    if (!destination.mkdirs()) {
        return false;
    }
    File files[] = source.listFiles();
    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
            try {
                FileUtils.copyFileToDirectory(files[i], destination);
            } catch (IOException e) {
                String msgError = "Cannot clone directory.\nIOException.\n" + e;
                System.out.println(msgError);
                return false;
            }
        } else if (files[i].isDirectory()) {
            if (!cloneDir2(files[i], destination)) {
                return false;
            }
        }
    }
    return true;
}
Example 60
Project: carma-tishadow-bundle-update-master  File: ClearPendingUpdateTask.java View source code
/*
	 * (non-Javadoc)
	 * @see ma.car.tishadow.bundle.update.tasks.Task#execute(ma.car.tishadow.bundle.update.tasks.TaskContext)
	 */
@Override
public boolean execute(RequestProxy context) {
    Log.v(TAG, "Start clearing pending update ...");
    File backupDirectory = context.getBackupDirectory();
    Log.i(TAG, "Clearing pending updates from " + backupDirectory);
    try {
        FileUtils.deleteDirectory(backupDirectory);
        Log.d(TAG, "Clear pending update has been done.");
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Failed to delete '" + backupDirectory + "'.", e);
    }
    return false;
}
Example 61
Project: ci-eye-master  File: SettingsFile.java View source code
public List<String> readContent() {
    if (!file.canRead()) {
        return new ArrayList<String>();
    }
    try {
        final List<String> result = FileUtils.readLines(this.file);
        lastReadDate = new Date();
        return result;
    } catch (IOException e) {
        LOG.error("failed to read settings file", e);
    }
    return new ArrayList<String>();
}
Example 62
Project: cirilo-master  File: CantusConverter.java View source code
public void transform(String file) {
    try {
        PropertyConfigurator.configure(Cirilo.class.getResource("log4jcc.properties"));
        TEI t = new TEI();
        t.set(file, false);
        file = file.replaceAll("\\..*", ".xml");
        FileUtils.writeStringToFile(new File(file), t.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 63
Project: Client.Java-master  File: LDFTestUtils.java View source code
public static List<String> readFiles(String directoryPath) {
    List<String> fileContents = Lists.newArrayList();
    Iterator it = FileUtils.iterateFiles(new File(directoryPath), null, false);
    while (it.hasNext()) {
        File file = ((File) it.next());
        System.out.println(file.getName());
        try {
            fileContents.add(readFile(file.getPath(), Charset.defaultCharset()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return fileContents;
}
Example 64
Project: common-java-cookbook-master  File: FileDeleteExample.java View source code
public void start() {
    File file = new File("project.xml");
    String display = FileUtils.byteCountToDisplaySize(file.length());
    System.out.println("project.xml is " + display);
    System.out.println("Byte in KB: " + FileUtils.ONE_GB);
    display = FileUtils.byteCountToDisplaySize(12073741824l);
    System.out.println("size: " + display);
}
Example 65
Project: cucumber-contrib-master  File: AsciiDiagToHtmlPlugin.java View source code
@Override
protected void generateImage(File pngFile, NamedBlockNode named) throws Exception {
    File diagFile = new File(pngFile.getParentFile(), pngFile.getName() + ".txt");
    FileUtils.write(diagFile, named.getBody(), "UTF8");
    log.debug("About to generated ascii diagram (ditaa) as PNG files {}", pngFile.getAbsolutePath());
    CommandLineConverter.main(new String[] { //
    "-v", //
    "-encoding", //
    "UTF8", //
    diagFile.getAbsolutePath(), pngFile.getAbsolutePath() });
    log.info("Ascii diagram generated as PNG files {}", pngFile.getAbsolutePath());
}
Example 66
Project: dal-master  File: JavaDirectoryPreparerProcessor.java View source code
public void process(CodeGenContext codeGenCtx) throws Exception {
    JavaCodeGenContext ctx = (JavaCodeGenContext) codeGenCtx;
    File dir = new File(String.format("%s/%s/java", ctx.getGeneratePath(), ctx.getProjectId()));
    try {
        if (dir.exists() && ctx.isRegenerate())
            FileUtils.forceDelete(dir);
        File daoDir = new File(dir, "Dao");
        File entityDir = new File(dir, "Entity");
        File testDir = new File(dir, "Test");
        if (!daoDir.exists()) {
            FileUtils.forceMkdir(daoDir);
        }
        if (!entityDir.exists()) {
            FileUtils.forceMkdir(entityDir);
        }
        if (!testDir.exists()) {
            FileUtils.forceMkdir(testDir);
        }
    } catch (IOException e) {
        throw e;
    }
}
Example 67
Project: deploymentobjects-master  File: EntryPoint.java View source code
/**
	 * EntryPoint 
	 * Intended to be run from run.sh 
	 * @param args
	 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("file").withDescription("the file containing commands").hasArg().withArgName("file").isRequired().create("f"));
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (MissingOptionException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("run.sh", options, true);
        return;
    }
    String fileName = cmd.getOptionValue("file");
    String contents = FileUtils.readFileToString(new File(fileName));
    Program program = Program.factory(contents);
}
Example 68
Project: Diary-master  File: OldVersionHelper.java View source code
public static boolean Version17MoveTheDiaryIntoNewDir(Context context) throws Exception {
    FileManager rootFileManager = new FileManager(context, FileManager.ROOT_DIR);
    File[] dataFiles = rootFileManager.getDir().listFiles();
    boolean moveIntoNewDir = false;
    //router all dir first
    for (int i = 0; i < dataFiles.length; i++) {
        if (FileManager.isNumeric(dataFiles[i].getName()) && dataFiles[i].listFiles().length > 0) {
            moveIntoNewDir = true;
            break;
        }
    }
    //If the numeric dir is exist , move it
    if (moveIntoNewDir) {
        FileManager diaryFM = new FileManager(context, FileManager.DIARY_ROOT_DIR);
        File destDir = diaryFM.getDir();
        FileUtils.deleteDirectory(destDir);
        for (int i = 0; i < dataFiles.length; i++) {
            if (FileManager.isNumeric(dataFiles[i].getName())) {
                FileUtils.moveDirectoryToDirectory(dataFiles[i], new FileManager(context, FileManager.DIARY_ROOT_DIR).getDir(), true);
            }
        }
        //Remove the diary/temp/
        FileUtils.deleteDirectory(new File(diaryFM.getDirAbsolutePath() + "/temp"));
    }
    return moveIntoNewDir;
}
Example 69
Project: digidoc4j-master  File: TokenAlgorithmSupportTest.java View source code
@Test
public void oldEstonianIdCardCert_shouldReturnSha224() throws Exception {
    String certString = FileUtils.readFileToString(new File("testFiles/certs/esteid-pre2011-test-signing-certificate-37101010021.cer"));
    X509Certificate certificate = CertificatesForTests.getCertFromPEMFormat(certString);
    DigestAlgorithm digestAlgorithm = TokenAlgorithmSupport.determineSignatureDigestAlgorithm(certificate);
    Assert.assertEquals(DigestAlgorithm.SHA224, digestAlgorithm);
}
Example 70
Project: Doris-master  File: KyotocabinetStorageTest.java View source code
protected void setUp() throws Exception {
    try {
        FileUtils.forceDelete(new File(getConfig().getDatabasePath()));
    } catch (FileNotFoundException ignore) {
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    File f = new File(config.getDatabasePath());
    if (!f.exists()) {
        f.mkdir();
    }
}
Example 71
Project: EclipseCodeFormatter-master  File: CachedProviderTest.java View source code
@Before
public void setUp() throws Exception {
    tempFile = File.createTempFile("12311", "2");
    cachedProvider = new CachedProvider<String>(new ModifiableFile(tempFile.getPath())) {

        @Override
        protected String readFile(File file) {
            try {
                return FileUtils.readFileToString(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
}
Example 72
Project: editor-de-servicos-master  File: RepositorioConfigParaTeste.java View source code
@SneakyThrows
public void reset() {
    FileUtils.deleteDirectory(origin.toFile());
    FileUtils.deleteDirectory(localCloneRepositorio.toFile());
    Files.createDirectories(origin);
    Files.createDirectories(localCloneRepositorio);
    Git.init().setBare(true).setDirectory(origin.toFile()).call();
    origin.toFile().deleteOnExit();
    localCloneRepositorio.toFile().deleteOnExit();
}
Example 73
Project: Europeana-Cloud-master  File: TestReadOneProviderCommand.java View source code
@Override
public void execute(UISClient client, int threadNo, String... input) throws InvalidAttributesException {
    try {
        List<String> ids = FileUtils.readLines(new File("tests1IdRW"));
        Date now = new Date();
        System.out.println("Starting test at: " + now.toString());
        for (String id : ids) {
            String[] columns = id.split(" ");
            client.getCloudId(columns[1], columns[2]);
        }
        long end = new Date().getTime() - now.getTime();
        System.out.println("Reading " + ids.size() + " records took " + end + " ms");
        System.out.println("Average: " + (ids.size() / end) * 1000 + " records per second");
    } catch (IOExceptionCloudException |  e) {
        getLogger().error(e.getMessage());
    }
}
Example 74
Project: exist-service-master  File: TestExistManager.java View source code
@Override
public void afterPropertiesSet() {
    try {
        File tmpDir = SystemUtils.getJavaIoTmpDir();
        File file = new File(tmpDir.getAbsolutePath() + "/" + UUID.randomUUID().toString() + "/");
        if (!file.exists()) {
            file.mkdir();
        }
        FileUtils.cleanDirectory(file);
        System.setProperty("exist.home", file.getAbsolutePath());
        Resource confXml = new ClassPathResource("conf.xml");
        File confXmlFile = new File(file.getAbsolutePath() + "/conf.xml");
        confXmlFile.createNewFile();
        StringWriter writer = new StringWriter();
        IOUtils.copy(confXml.getInputStream(), writer);
        FileUtils.writeStringToFile(confXmlFile, writer.toString());
        this.setUri("xmldb:exist:///db/");
        System.setProperty("exist.initdb", "true");
        FileUtils.forceDeleteOnExit(file);
        this.setUserName("admin");
        this.setPassword("");
        super.afterPropertiesSet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 75
Project: fastjson-master  File: Alipay1206.java View source code
public void test_for_alipay() throws Exception {
    File file = new File("/Users/wenshao/Downloads/x.txt");
    String text = FileUtils.readFileToString(file);
    JSONObject root = JSON.parseObject(text);
    JSONObject resultObj = root.getJSONObject("resultObj");
    assertNotNull(resultObj);
    JSONArray conditionGroupItemList = resultObj.getJSONArray("conditionGroupItemList");
    assertNotNull(conditionGroupItemList);
    JSONObject conditionGroup = conditionGroupItemList.getJSONObject(0).getJSONObject("conditionGroup");
    assertNotNull(conditionGroup);
    JSONArray recordList = conditionGroup.getJSONArray("recordList");
    assertNotNull(recordList);
    JSONArray conditionItemList = recordList.getJSONObject(0).getJSONArray("conditionItemList");
    assertNotNull(conditionItemList);
    JSONObject condition = conditionItemList.getJSONObject(18).getJSONObject("condition");
    assertNotNull(condition);
    JSONArray conditionConstraint = condition.getJSONArray("conditionConstraint");
    assertNotNull(conditionConstraint);
    JSONObject constraintOptionalRecordMap = conditionConstraint.getJSONObject(0).getJSONObject("constraintOptionalRecordMap");
    assertNotNull(constraintOptionalRecordMap);
    System.out.println(constraintOptionalRecordMap);
}
Example 76
Project: geoserver-2.0.x-master  File: CoverageStoreFileUploadTest.java View source code
public void testWorldImageUploadZipped() throws Exception {
    URL zip = getClass().getResource("test-data/usa.zip");
    byte[] bytes = FileUtils.readFileToByteArray(DataUtilities.urlToFile(zip));
    MockHttpServletResponse response = putAsServletResponse("/rest/workspaces/gs/coveragestores/usa/file.worldimage", bytes, "application/zip");
    assertEquals(201, response.getStatusCode());
    String content = response.getOutputStreamContent();
    Document d = dom(new ByteArrayInputStream(content.getBytes()));
    assertEquals("coverageStore", d.getDocumentElement().getNodeName());
}
Example 77
Project: geoserver-old-master  File: CoverageStoreFileUploadTest.java View source code
public void testWorldImageUploadZipped() throws Exception {
    URL zip = getClass().getResource("test-data/usa.zip");
    byte[] bytes = FileUtils.readFileToByteArray(DataUtilities.urlToFile(zip));
    MockHttpServletResponse response = putAsServletResponse("/rest/workspaces/gs/coveragestores/usa/file.worldimage", bytes, "application/zip");
    assertEquals(201, response.getStatusCode());
    String content = response.getOutputStreamContent();
    Document d = dom(new ByteArrayInputStream(content.getBytes()));
    assertEquals("coverageStore", d.getDocumentElement().getNodeName());
}
Example 78
Project: geoserver_trunk-master  File: CoverageStoreFileUploadTest.java View source code
public void testWorldImageUploadZipped() throws Exception {
    URL zip = getClass().getResource("test-data/usa.zip");
    byte[] bytes = FileUtils.readFileToByteArray(DataUtilities.urlToFile(zip));
    MockHttpServletResponse response = putAsServletResponse("/rest/workspaces/gs/coveragestores/usa/file.worldimage", bytes, "application/zip");
    assertEquals(201, response.getStatusCode());
    String content = response.getOutputStreamContent();
    Document d = dom(new ByteArrayInputStream(content.getBytes()));
    assertEquals("coverageStore", d.getDocumentElement().getNodeName());
}
Example 79
Project: geosummly-master  File: SSEValidation.java View source code
public static void main(String[] args) {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("x=c(");
        List<String> lines = FileUtils.readLines(new File("datasets/milan/20140328/validation/clustering_correctness/SSEs.log"));
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(4);
        nf.setMinimumFractionDigits(4);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        for (int i = 0; i < lines.size(); i++) {
            String[] chunks = lines.get(i).split(",");
            //sb.append( nf.format(Double.parseDouble(chunks[1])) );
            sb.append((int) Math.floor(Double.parseDouble(chunks[1])));
            if (i < lines.size() - 1)
                sb.append(", ");
        }
        sb.append(");\n");
        sb.append("bins=seq(2060,2512,by=0.5);\n");
        sb.append("hist(x," + "breaks=bins," + "xlab=\"SSE\",ylab=\"count\"," + "main=\"Histogram of SSE for 500 random data sets\")");
        System.out.println(sb.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 80
Project: ginco-master  File: CliImporter.java View source code
/**
	 * SKOS import from file.
	 *
	 * @param inputFile
	 */
public void importSkos(String inputFile) {
    File inputF = new File(inputFile);
    File tempDir = new File("/tmp");
    try {
        Map<Thesaurus, Set<Alignment>> importResult = skosImportService.importSKOSFile(FileUtils.readFileToString(inputF), "tmpSkos.rdf", tempDir);
        Thesaurus thesaurus = importResult.keySet().iterator().next();
        thesaurusIndexerService.indexThesaurus(thesaurus);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 81
Project: gmm-eclipse-plugins-master  File: DragListener.java View source code
@Override
public void dragSetData(DragSourceEvent event) {
    if (FileTransfer.getInstance().isSupportedType(event.dataType)) {
        IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        TreeObject item = ((TreeObject) selection.getFirstElement());
        try {
            String data = GMMAPIRestClient.getInstance().GETProjectXMI(item.getCredential(), item.getProject().getProjectId());
            file = File.createTempFile(item.getName(), ".xmi");
            FileUtils.writeStringToFile(file, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    event.data = new String[] { file.getAbsolutePath() };
}
Example 82
Project: govu-master  File: ReadFile.java View source code
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
    try {
        return FileUtils.readFileToString(new File(renderer.getApp().getAbsolutePath() + "/" + args[0]), "UTF-8");
    } catch (FileNotFoundException ex) {
        cx.evaluateString(scope, "throw { error: \"fileNotFound\", msg: \"" + ex.getMessage() + "\" };", "<cmd>", 0, null);
    } catch (IOException ex) {
        cx.evaluateString(scope, "throw { error: \"ioError\", msg: \"" + ex.getMessage() + "\" };", "<cmd>", 0, null);
    }
    //To change body of generated methods, choose Tools | Templates.
    return super.call(cx, scope, thisObj, args);
}
Example 83
Project: grobid-master  File: TestChemicalNameParser.java View source code
//@Test
public void testChemicalNameParser() throws Exception {
    File textFile = new File(this.getResourceDir("./src/test/resources/").getAbsoluteFile() + "/patents/sample3.txt");
    if (!textFile.exists()) {
        throw new GrobidException("Cannot start test, because test resource folder is not correctly set.");
    }
    String text = FileUtils.readFileToString(textFile);
    List<ChemicalEntity> chemicalResults = engine.extractChemicalEntities(text);
    if (chemicalResults != null) {
        System.out.println(chemicalResults.size() + " extracted chemical entities");
        for (ChemicalEntity entity : chemicalResults) {
            System.out.println(entity.toString());
        }
    } else {
        System.out.println("no extracted chemical entities");
    }
}
Example 84
Project: hadoop-book-master  File: Synthetic2DClusteringPrep.java View source code
public static void write(File inputFile, Path outputPath) throws IOException {
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, outputPath, NullWritable.class, VectorWritable.class, SequenceFile.CompressionType.BLOCK, new DefaultCodec());
    try {
        for (String line : FileUtils.readLines(inputFile)) {
            String parts[] = StringUtils.split(line);
            writer.append(NullWritable.get(), new VectorWritable(new DenseVector(new double[] { Double.valueOf(parts[0]), Double.valueOf(parts[1]) })));
        }
    } finally {
        writer.close();
    }
}
Example 85
Project: head-master  File: TallyXMLOutputTest.java View source code
/**
     * failing on windows -suspect it could be a carraige return or something like that.
     */
@Ignore
@Test
public void testAccoutingDataOutPut() throws Exception {
    String fileName = "Mifos Accounting Export 2010-08-10 to 2010-08-10.xml";
    File file = MifosResourceUtil.getClassPathResourceAsResource("org/mifos/platform/accounting/tally/2010-08-10 to 2010-08-10").getFile();
    String expected = FileUtils.readFileToString(MifosResourceUtil.getClassPathResourceAsResource("org/mifos/platform/accounting/tally/" + fileName).getFile());
    List<AccountingDto> accountingData = cacheManager.accountingDataFromCache(file);
    String tallyOutput = TallyXMLGenerator.getTallyXML(accountingData, fileName);
    Assert.assertEquals(expected, tallyOutput);
}
Example 86
Project: heroku-maven-plugin-master  File: MavenWarApp.java View source code
@Override
protected void prepare(List<File> includedFiles, Map<String, String> processTypes) throws IOException {
    super.prepare(includedFiles, processTypes);
    File appTargetDir = new File(getAppDir(), "target");
    FileUtils.forceMkdir(appTargetDir);
    FileUtils.copyFile(new File(getTargetDir(), ListDependencies.FILENAME), new File(appTargetDir, ListDependencies.FILENAME));
    FileUtils.copyFile(new File(getRootDir(), "pom.xml"), new File(getAppDir(), "pom.xml"));
}
Example 87
Project: hiped2-master  File: Synthetic2DClusteringPrep.java View source code
public static void write(File inputFile, Path outputPath) throws IOException {
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, outputPath, NullWritable.class, VectorWritable.class, SequenceFile.CompressionType.BLOCK, new DefaultCodec());
    try {
        for (String line : FileUtils.readLines(inputFile)) {
            String parts[] = StringUtils.split(line);
            writer.append(NullWritable.get(), new VectorWritable(new DenseVector(new double[] { Double.valueOf(parts[0]), Double.valueOf(parts[1]) })));
        }
    } finally {
        writer.close();
    }
}
Example 88
Project: IDK-Server-Java-master  File: Translations.java View source code
public static void loadTranslations() throws IOException {
    defaultTranslations = new ConcurrentHashMap<>();
    Properties defaultTranslationsPropertiesFile = new Properties();
    defaultTranslationsPropertiesFile.load(Bootloader.class.getResourceAsStream("/translations.properties"));
    for (String key : defaultTranslationsPropertiesFile.stringPropertyNames()) {
        String value = defaultTranslationsPropertiesFile.getProperty(key);
        defaultTranslations.put(key, value);
    }
    File translationsFile = new File("translations.properties");
    if (!translationsFile.exists()) {
        FileUtils.copyURLToFile(Bootloader.class.getResource("/translations.properties"), translationsFile);
    }
    translations = new ConcurrentHashMap<>();
    Properties translationsPropertiesFile = new Properties();
    translationsPropertiesFile.load(new FileInputStream("translations.properties"));
    for (String key : translationsPropertiesFile.stringPropertyNames()) {
        String value = translationsPropertiesFile.getProperty(key);
        translations.put(key, value);
    }
}
Example 89
Project: iee-master  File: Iee.java View source code
public static void main(String[] args) {
    /*<Formula("id"="b8fe85ef-3938-412e-bfb6-c9f9b51424e6"):h=2+2<*/
    double h = (2) + (2);
    /*>>*/
    /*<Formula("id"="ab99f34f-040e-43d8-b363-d99bffc28179"):h=<*/
    new Runnable() {

        private double variable;

        private Runnable init(double var) {
            /*br*/
            variable = var;
            return this;
        }

        @Override
        public void run() {
            File file = new File("/home/aefimchuk/intl/runtime-EclipseApplication/test/pads/runtime/ab99f34f-040e-43d8-b363-d99bffc28179");
            try {
                FileUtils.writeStringToFile(file, "" + variable);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.init(h).run();
/*>>*/
}
Example 90
Project: iFramework-master  File: FileUtil.java View source code
/**
     * 根�路径创建文件
     * author:Lizhao
     * Date:15/12/31
     * version:1.0
     *
     * @param filePath
     *
     * @return
     */
public static File createFile(String filePath) {
    File file;
    try {
        file = new File(filePath);
        //确定返回的是抽象å??称路径
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            //创建文件夹
            FileUtils.forceMkdir(parentDir);
        }
    } catch (Exception e) {
        LOGGER.error("create file failure", e);
        throw new RuntimeException(e);
    }
    return file;
}
Example 91
Project: iis-master  File: ProjectDBBuilder.java View source code
// -------------------------- LOGIC -------------------------------------
@Override
public ProcessExecutionContext initializeProcess(Map<String, String> parameters) throws IOException {
    String targetDbLocation = System.getProperty("java.io.tmpdir") + File.separatorChar + "base_projects.db";
    File targetDbFile = new File(targetDbLocation);
    FileUtils.copyFile(new File("scripts/base_projects.db"), targetDbFile);
    targetDbFile.setWritable(true);
    return new ProcessExecutionContext(Runtime.getRuntime().exec("python scripts/madis/mexec.py -d " + targetDbLocation + " -f scripts/buildprojectdb.sql"), targetDbFile);
}
Example 92
Project: invio-master  File: ZipFingerprintsTask.java View source code
protected String getJsonString() throws IOException {
    final File fingerprintsFile = new File(indoorMap.getMapDirectory() + File.separator + "fingerprints" + File.separator + "fingerprints_data.json");
    if (fingerprintsFile.exists()) {
        final String result = FileUtils.readFileToString(fingerprintsFile, "UTF-8");
        return result;
    } else {
        throw new FileNotFoundException("ERROR: No fingerprints file found! " + "Was expected here: " + fingerprintsFile.getPath());
    }
}
Example 93
Project: ios-driver-master  File: ApplicationCrashDetails.java View source code
private String mostRecentCrashReport() {
    File crashFolder = new File(System.getProperty("user.home") + "/Library/Logs/DiagnosticReports/");
    Date now = new Date();
    Date cutoffDate = new Date(now.getTime() - 10000);
    Collection<File> files = FileUtils.listFiles(crashFolder, new AgeFileFilter(cutoffDate, false), null);
    StringBuilder sb = new StringBuilder();
    if (files.size() > 0) {
        sb.append("The crash report can be found:");
        for (File f : files) {
            sb.append("\n" + f.getAbsoluteFile());
        }
    }
    if (sb.toString().isEmpty()) {
        if (log.contains("Script was stopped by the user")) {
            sb.append("It appears like the Instruments process has crashed.");
        } else {
            sb.append("It appears like the Simulator process has crashed.");
        }
    }
    return sb.toString();
}
Example 94
Project: jabox-master  File: MavenSettingsManager.java View source code
private static void writeCustomSettings(final File file) throws IOException {
    DefaultConfiguration dc = ConfigXstreamDao.getConfig();
    InputStream is = MavenSettingsManager.class.getResourceAsStream("settings.xml");
    Map<String, String> values = new HashMap<String, String>();
    values.put("${repo.url}", dc.getRms().getRepositoryURL());
    values.put("${repo.username}", dc.getRms().getUsername());
    values.put("${repo.password}", dc.getRms().getPassword());
    String data = SettingsModifier.parseInputStream(is, values);
    FileUtils.writeStringToFile(file, data);
}
Example 95
Project: jar-nda-master  File: JarRenamer.java View source code
public static File remapWithConfig(File jarFile, String configure) {
    File configFile;
    try {
        configFile = File.createTempFile("remap", ".txt");
        configFile.deleteOnExit();
        FileUtils.writeStringToFile(configFile, configure, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return remapWithConfig(jarFile, configFile);
}
Example 96
Project: java-tdd-master  File: IpodTest.java View source code
@Test(groups = { "characterization" })
public void consoleOutput() throws IOException {
    PrintStream originalOut = System.out;
    try {
        System.setOut(new PrintStream("fixtures/ipod.out.actual"));
        Ipod.main(new String[] {});
        System.out.flush();
    } finally {
        System.setOut(originalOut);
    }
    String actual = FileUtils.readFileToString(new File("fixtures/ipod.out.actual"));
    String expected = FileUtils.readFileToString(new File("fixtures/ipod.out.expected"));
    assertEquals(expected, actual);
}
Example 97
Project: JAVMovieScraper-master  File: Trailer.java View source code
public void writeTrailerToFile(File fileNameToWrite) throws IOException {
    //we don't want to rewrite trailer if the file already exists since that can retrigger a pointlessly long download
    if (getTrailer() != null && getTrailer().length() > 0 && !fileNameToWrite.exists()) {
        System.out.println("Writing trailer: " + this.toString() + " into file " + fileNameToWrite);
        FileUtils.copyURLToFile(new URL(getTrailer()), fileNameToWrite, connectionTimeout, readTimeout);
    }
}
Example 98
Project: jboss-migration-master  File: ExternalMigratorsLoaderTest.java View source code
@Test
public void testLoadTestMigrator() throws Throwable {
    try {
        File workDir = new File("target/extMigrators/");
        FileUtils.forceMkdir(workDir);
        ClassUtils.copyResourceToDir(ExternalMigratorsLoaderTest.class, "res/TestMigrator.mig.xml", workDir);
        ClassUtils.copyResourceToDir(ExternalMigratorsLoaderTest.class, "res/TestJaxbBean.groovy", workDir);
        Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migs = new ExternalMigratorsLoader().loadMigrators(workDir, new IMigratorFilter.All(), new GlobalConfiguration());
        assertEquals("1 migrator loaded", 1, migs.size());
        DefinitionBasedMigrator mig = migs.values().iterator().next();
        assertEquals("1 migrator loaded", "MailExtMigrator", mig.getClass().getName());
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw ex;
    }
}
Example 99
Project: jbpmmigration-master  File: MigrationHelper.java View source code
/**
     * Migration from JPDL to BPMN2 format.
     *
     * @param jpdlFile
     *            File with process definition in JPDL.
     * @param bpmnFile
     *            File which should contain process definition in BPMN after
     *            migration.
     * @throws IllegalArgumentException
     *             if Jpdl or Bpmn2 definition file is not valid.
     */
public static void migration(File jpdlFile, File bpmnFile) {
    String jpdlStr;
    try {
        jpdlStr = FileUtils.readFileToString(jpdlFile);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    if (!JbpmMigration.validateJpdl(jpdlStr)) {
        throw new IllegalArgumentException("JPDL definition file is not valid");
    }
    String bpmnStr = JbpmMigration.transform(jpdlStr);
    try {
        FileUtils.writeStringToFile(bpmnFile, bpmnStr);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    if (!JbpmMigration.validateBpmn(bpmnStr)) {
        throw new IllegalArgumentException("BPMN2 definition file is not valid");
    }
}
Example 100
Project: jenkins-master  File: ScriptLoader.java View source code
public String call() throws IOException {
    File f = new File(script);
    if (f.exists())
        return FileUtils.readFileToString(f);
    URL url;
    try {
        url = new URL(script);
    } catch (MalformedURLException e) {
        throw new AbortException("Unable to find a script " + script);
    }
    InputStream s = url.openStream();
    try {
        return IOUtils.toString(s);
    } finally {
        s.close();
    }
}
Example 101
Project: JFTClient-master  File: LocalFileUtils.java View source code
/**
     * Copy file to directory<br/>
     * Copy file to file<br/>
     * Copy directory to directory
     *
     * @param src  source
     * @param dest destination
     * @return <code>true</code> if copied otherwise <code>false</code>
     */
public static boolean copy(File src, File dest) {
    try {
        if (dest.isDirectory()) {
            if (src.isFile()) {
                FileUtils.copyFileToDirectory(src, dest);
            } else {
                FileUtils.copyDirectoryToDirectory(src, dest);
            }
        } else {
            if (src.isFile()) {
                FileUtils.copyFile(src, dest);
            } else {
                logger.warn("cannot copy dir to file");
                return false;
            }
        }
    } catch (IOException e) {
        logger.warn("failed to copy", e);
        return false;
    }
    return true;
}