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

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

Introduction

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

Prototype

public static void writeLines(File file, Collection lines) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:controllers.FileHandler.java

/**
 * brief: writes file with list of TraceMessages
 * @param file          - file to write in
 * @param listMessages  - data to write in file
 *///  w  ww.j  a  va  2 s. c o  m
public static void WriteTraceMessagesToFile(File file, ArrayList<TraceMessage> listMessages) {
    try {
        FileUtils.writeLines(file, listMessages);
    } catch (IOException ex) {
        Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        return;
    }
}

From source file:cz.cas.lib.proarc.common.process.GenericExternalProcessTest.java

@Test
public void testGetResultParameters() throws Exception {
    File confFile = temp.newFile("props.cfg");
    FileUtils.writeLines(confFile,
            Arrays.asList("processor.test.param.mime=image/jpeg", "processor.test.onExits=0, >10, 2\\,3, *",
                    "processor.test.onExit.0.param.file=ERR_0\\:$${input.file.name}",
                    "processor.test.onExit.>10.param.file=ERR_>10\\:$${input.file.name}",
                    "processor.test.onExit.>10.stop=false",
                    "processor.test.onExit.2,3.param.file=ERR_2\\,3\\:$${input.file.name}",
                    "processor.test.onExit.*.param.file=ERR_*\\:$${input.file.name}",
                    "processor.test.onSkip.param.file=SKIPPED\\:$${input.file.name}"));
    PropertiesConfiguration pconf = new PropertiesConfiguration(confFile);
    String processorId = "processor.test";
    Configuration conf = pconf.subset(processorId);
    conf.setProperty("id", processorId);
    GenericExternalProcess gep = new GenericExternalProcess(conf);
    gep.addInputFile(confFile);//  w  ww.j  a va  2  s.  co  m
    ProcessResult result = ProcessResult.getResultParameters(conf, gep.getParameters().getMap(), false, 0,
            null);
    assertEquals("image/jpeg", result.getParameters().get(processorId + ".param.mime"));
    assertEquals("ERR_0:props", result.getParameters().get(processorId + ".param.file"));
    assertEquals(Integer.valueOf(0), result.getExit().getExitCode());
    assertFalse(result.getExit().isStop());
    assertFalse(result.getExit().isSkip());

    result = ProcessResult.getResultParameters(conf, gep.getParameters().getMap(), false, 3, null);
    assertEquals("image/jpeg", result.getParameters().get(processorId + ".param.mime"));
    assertEquals("ERR_2,3:props", result.getParameters().get(processorId + ".param.file"));
    assertEquals(Integer.valueOf(3), result.getExit().getExitCode());
    assertTrue(result.getExit().isStop());
    assertFalse(result.getExit().isSkip());

    result = ProcessResult.getResultParameters(conf, gep.getParameters().getMap(), false, 11, null);
    assertEquals("image/jpeg", result.getParameters().get(processorId + ".param.mime"));
    assertEquals("ERR_>10:props", result.getParameters().get(processorId + ".param.file"));
    assertEquals(Integer.valueOf(11), result.getExit().getExitCode());
    assertFalse(result.getExit().isStop());
    assertFalse(result.getExit().isSkip());

    result = ProcessResult.getResultParameters(conf, gep.getParameters().getMap(), false, -1, null);
    assertEquals("image/jpeg", result.getParameters().get(processorId + ".param.mime"));
    assertEquals("ERR_*:props", result.getParameters().get(processorId + ".param.file"));
    assertEquals(Integer.valueOf(-1), result.getExit().getExitCode());
    assertTrue(result.getExit().isStop());
    assertFalse(result.getExit().isSkip());

    result = ProcessResult.getResultParameters(conf, gep.getParameters().getMap(), true, 0, null);
    assertEquals("image/jpeg", result.getParameters().get(processorId + ".param.mime"));
    assertEquals("SKIPPED:props", result.getParameters().get(processorId + ".param.file"));
    assertFalse(result.getExit().isStop());
    assertTrue(result.getExit().isSkip());
}

From source file:io.druid.indexer.DeterminePartitionsJobTest.java

public DeterminePartitionsJobTest(boolean assumeGrouped, Long targetPartitionSize, String interval,
        int expectedNumOfSegments, int[] expectedNumOfShardsForEachSegment,
        String[][][] expectedStartEndForEachShard, List<String> data) throws IOException {
    this.expectedNumOfSegments = expectedNumOfSegments;
    this.expectedNumOfShardsForEachSegment = expectedNumOfShardsForEachSegment;
    this.expectedStartEndForEachShard = expectedStartEndForEachShard;

    dataFile = File.createTempFile("test_website_data", "tmp");
    dataFile.deleteOnExit();/*ww  w .jav a2s. c  o m*/
    tmpDir = Files.createTempDir();
    tmpDir.deleteOnExit();

    FileUtils.writeLines(dataFile, data);

    config = new HadoopDruidIndexerConfig(new HadoopIngestionSpec(
            new DataSchema("website", HadoopDruidIndexerConfig.jsonMapper.convertValue(
                    new StringInputRowParser(
                            new CSVParseSpec(new TimestampSpec("timestamp", "yyyyMMddHH", null),
                                    new DimensionsSpec(ImmutableList.of("host", "country"), null, null), null,
                                    ImmutableList.of("timestamp", "host", "country", "visited_num"))),
                    Map.class),
                    new AggregatorFactory[] { new LongSumAggregatorFactory("visited_num", "visited_num") },
                    new UniformGranularitySpec(Granularity.DAY, QueryGranularity.NONE,
                            ImmutableList.of(new Interval(interval))),
                    HadoopDruidIndexerConfig.jsonMapper),
            new HadoopIOConfig(
                    ImmutableMap.<String, Object>of("paths", dataFile.getCanonicalPath(), "type", "static"),
                    null, tmpDir.getCanonicalPath()),
            new HadoopTuningConfig(tmpDir.getCanonicalPath(), null,
                    new SingleDimensionPartitionsSpec(null, targetPartitionSize, null, assumeGrouped), null,
                    null, null, false, false, false, false, null, false, false, false, null, null, false)));
}

From source file:jenkins.security.stapler.StaticRoutingDecisionProvider.java

/**
 * Saves the configuration info to the disk.
 *///from ww w  . j  av a 2 s.  co  m
public synchronized void save() {
    if (BulkChange.contains(this)) {
        return;
    }

    File file = getConfigFile();
    try {
        List<String> allSignatures = new ArrayList<>(whitelistSignaturesFromUserControlledList);
        blacklistSignaturesFromUserControlledList.stream().map(signature -> "!" + signature)
                .forEach(allSignatures::add);

        FileUtils.writeLines(file, allSignatures);
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to save " + file.getAbsolutePath(), e);
    }
}

From source file:avantssar.aslanpp.testing.Tester.java

public static void doTest(TranslationReport rep, ITestTask task, File sourceBaseDir, File targetBaseDir,
        ASLanPPConnectorImpl translator, TesterCommandLineOptions options, PrintStream err) {
    String relativePath = FilenameUtils.normalize(task.getASLanPP().getAbsolutePath())
            .substring(FilenameUtils.normalizeNoEndSeparator(sourceBaseDir.getAbsolutePath()).length() + 1);
    File aslanPPinput = new File(
            FilenameUtils.concat(FilenameUtils.normalize(targetBaseDir.getAbsolutePath()), relativePath));

    try {//www  . j  a  v  a 2s.  c  om
        FileUtils.copyFile(task.getASLanPP(), aslanPPinput, true);
        File aslanPPcheck1 = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.aslan++");
        File aslanPPcheck1det = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.detailed.aslan++");
        File aslanPPcheck1err = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.errors.aslan++");
        File aslanPPcheck1warn = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.warnings.aslan++");
        File aslanPPcheck2 = null;
        File aslanPPcheck2det = null;
        File aslanPPcheck2err = null;
        File aslanPPcheck2warn = null;
        File aslanFile = new File(FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".aslan");
        File errorsFile = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".errors.txt");
        File warningsFile = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".warnings.txt");

        // Load the file and write it back to another file.
        // Then again load it back and write it to another file.
        // The files should have the same content.
        String fileName = aslanPPinput.getAbsolutePath();
        String aslanppSpec = FileUtils.readFileToString(task.getASLanPP());
        TranslatorOptions optPP = new TranslatorOptions();
        optPP.setPrettyPrint(true);
        TranslatorOptions optPPdet = new TranslatorOptions();
        optPPdet.setPreprocess(true);
        // EntityManager.getInstance().purge();
        TranslatorOutput firstLoad = translator.translate(optPP, fileName, aslanppSpec);
        FileUtils.writeStringToFile(aslanPPcheck1, firstLoad.getSpecification());
        FileUtils.writeLines(aslanPPcheck1err, firstLoad.getErrors());
        aslanPPcheck1err = deleteIfZero(aslanPPcheck1err);
        FileUtils.writeLines(aslanPPcheck1warn, firstLoad.getWarnings());
        aslanPPcheck1warn = deleteIfZero(aslanPPcheck1warn);
        // EntityManager.getInstance().purge();
        TranslatorOutput firstLoadDet = translator.translate(optPPdet, fileName, aslanppSpec);
        // TODO should use translate_main, since result will be empty
        FileUtils.writeStringToFile(aslanPPcheck1det, firstLoadDet.getSpecification());
        if (firstLoad.getSpecification() != null) {
            aslanPPcheck2 = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.aslan++");
            aslanPPcheck2det = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.detailed.aslan++");
            aslanPPcheck2err = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.errors.aslan++");
            aslanPPcheck2warn = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.warnings.aslan++");
            // EntityManager.getInstance().purge();
            TranslatorOutput secondLoad = translator.translate(optPP, null, firstLoad.getSpecification());
            FileUtils.writeStringToFile(aslanPPcheck2, secondLoad.getSpecification());
            FileUtils.writeLines(aslanPPcheck2err, secondLoad.getErrors());
            aslanPPcheck2err = deleteIfZero(aslanPPcheck2err);
            FileUtils.writeLines(aslanPPcheck2warn, secondLoad.getWarnings());
            aslanPPcheck2warn = deleteIfZero(aslanPPcheck2warn);
            // EntityManager.getInstance().purge();
            TranslatorOutput secondLoadDet = translator.translate(optPPdet, null, firstLoad.getSpecification());
            FileUtils.writeStringToFile(aslanPPcheck2det, secondLoadDet.getSpecification());
        }

        // EntityManager.getInstance().purge();
        TranslatorOutput result = translator.translate(options, fileName, aslanppSpec);
        FileUtils.writeStringToFile(aslanFile, result.getSpecification());
        FileUtils.writeLines(errorsFile, result.getErrors());
        FileUtils.writeLines(warningsFile, result.getWarnings());

        File expASLan = null;
        if (task.getExpectedASLan() != null) {
            expASLan = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".expected.aslan");
            FileUtils.copyFile(task.getExpectedASLan(), expASLan, true);
        }

        TranslationInstance ti = rep.newInstance(aslanPPinput, deleteIfZero(aslanPPcheck1),
                deleteIfZero(aslanPPcheck1det), deleteIfZero(aslanPPcheck2), deleteIfZero(aslanPPcheck2det),
                result.getErrors().size(), deleteIfZero(errorsFile), result.getWarnings().size(),
                deleteIfZero(warningsFile), deleteIfZero(expASLan), deleteIfZero(aslanFile),
                task.getExpectedVerdict());
        if (ti.hasTranslation()) {
            if (bm != null && bm.getBackendRunners().size() > 0) {
                for (final IBackendRunner runner : bm.getBackendRunners()) {
                    try {
                        List<String> pars = task.getBackendParameters(runner.getName());
                        pool.execute(new BackendTask(runner.spawn(), pars, aslanFile, ti));
                    } catch (BackendRunnerInstantiationException bex) {
                        Debug.logger.error("Failed to spawn backend " + runner.getName() + ".", bex);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println("Exception while testing file '" + task.getASLanPP().getAbsolutePath() + "': "
                + e.getMessage());
        Debug.logger.error("Failed to test file '" + aslanPPinput + "'.", e);
    }
}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

private void appendSitemapIndex(String sitemap) throws IOException {
    File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME);
    if (!sitemapIndexFile.exists()) {
        //if a new sitemap file
        List<String> lines = new ArrayList<String>();
        lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        lines.add("</sitemapindex>");
        FileUtils.writeLines(sitemapIndexFile, lines);
    }//from  w w w  . j a va2 s. c o  m

    RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw");
    FileChannel channel = rfile.getChannel();

    //this new content will append to end of file before XML end tag
    StringBuilder lines = new StringBuilder();
    lines.append("   <sitemap>\n");
    lines.append("     <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n");
    lines.append("     <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n");
    lines.append("   </sitemap>\n");
    //the last tag will be overwrite, so append it again to new content. 
    lines.append(SITEMAP_INDEX_TAIL_FLAG);
    byte[] content = lines.toString().getBytes();

    ByteBuffer byteBuf = ByteBuffer.allocate(512);
    // seek first
    int len = 0, headIdx = 0;
    long tailIdx = channel.size() - 512;
    tailIdx = tailIdx < 0 ? 0 : tailIdx;

    long headPos = -1;
    StringBuilder header = new StringBuilder();
    while ((len = channel.read(byteBuf, tailIdx)) > 0) {
        byteBuf.rewind();
        byte[] dst = new byte[len];
        byteBuf.get(dst, 0, len);
        header.append(new String(dst, "UTF8"));
        headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG);
        if (headIdx != -1) {
            headPos = channel.size() - header.substring(headIdx).getBytes().length;
            break;
        }
    }
    FileLock lock = channel.tryLock(headPos, content.length, false);
    try {
        channel.write(ByteBuffer.wrap(content), headPos);
    } finally {
        lock.release();
    }

    channel.force(false);
    rfile.close();

}

From source file:it.drwolf.ridire.index.cwb.scripts.VRTFilesBuilder.java

@Asynchronous
public void buildFilesFromFiles(VRTFilesBuilderData vrtFilesBuilderData) {
    String origDir = vrtFilesBuilderData.getOrigDir();
    Collection<File> files = FileUtils.listFiles(new File(origDir), new String[] { "pos" }, true);
    System.out.println("Files to be processed: " + files.size());
    File destDir = new File(vrtFilesBuilderData.getDestDir());
    destDir.mkdir();/*from  ww  w. ja  va 2s  .c  o  m*/
    int i = 0;
    for (File f : files) {
        ++i;
        List<String> lines = null;
        try {
            lines = FileUtils.readLines(f);
            List<String> newLines = new ArrayList<String>();
            for (String l : lines) {
                newLines.add(l.replaceAll(":", ""));
            }
            String header = this.getHeaderFromFile(i, f);
            newLines.add(0, header);
            newLines.add("</text>");
            File vrtFile = new File(destDir, FilenameUtils.getBaseName(f.getName()) + ".vrt");
            FileUtils.writeLines(vrtFile, newLines);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (i % 100 == 0) {
            System.out.println("Processed files: " + i);
        }
    }
}

From source file:com.daphne.es.maintain.icon.web.controller.IconController.java

/**
 * ?  ? ??/*from   ww  w .j a  v  a  2 s.c  o  m*/
 *
 * @param request
 * @return
 */
@RequestMapping(value = "/genCssFile")
@ResponseBody
public String genIconCssFile(HttpServletRequest request) {

    this.permissionList.assertHasEditPermission();

    String uploadFileTemplate = ".%1$s{background:url(%2$s/%3$s);width:%4$spx;height:%5$spx;display:inline-block;vertical-align: middle;%6$s}";
    String cssSpriteTemplate = ".%1$s{background:url(%2$s/%3$s) no-repeat -%4$spx -%5$spx;width:%6$spx;height:%7$spx;display:inline-block;vertical-align: middle;%8$s}";

    ServletContext sc = request.getServletContext();
    String ctx = sc.getContextPath();

    List<String> cssList = Lists.newArrayList();

    Searchable searchable = Searchable.newSearchable().addSearchParam("type_in",
            new IconType[] { IconType.upload_file, IconType.css_sprite });

    List<Icon> iconList = baseService.findAllWithNoPageNoSort(searchable);

    for (Icon icon : iconList) {

        if (icon.getType() == IconType.upload_file) {
            cssList.add(String.format(uploadFileTemplate, icon.getIdentity(), ctx, icon.getImgSrc(),
                    icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

        if (icon.getType() == IconType.css_sprite) {
            cssList.add(String.format(cssSpriteTemplate, icon.getIdentity(), ctx, icon.getSpriteSrc(),
                    icon.getLeft(), icon.getTop(), icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

    }

    try {

        ServletContextResource resource = new ServletContextResource(sc, iconClassFile);
        FileUtils.writeLines(resource.getFile(), cssList);
    } catch (Exception e) {
        LogUtils.logError("gen icon error", e);
        return "?" + e.getMessage();
    }

    return "??";
}

From source file:com.chaschev.install.InstallMojo.java

private static File writeClasspath(Artifact artifact, List<ArtifactResult> dependencies, File installToDir)
        throws IOException {
    final String jarPath = getJarByClass(Runner.class).getAbsolutePath();

    final String installerUserHome = getInstallerHomeDir(jarPath);

    ArrayList<File> classPathFiles = newArrayList(transform(dependencies, new Function<ArtifactResult, File>() {
        @Override//from   w w w.j  a  v a2 s.c o m
        public File apply(ArtifactResult artifactResult) {
            return artifactResult.getArtifact().getFile();
        }
    }));

    classPathFiles.add(getJarByClass(Runner.class));

    File file = new File(installToDir, artifact.getGroupId() + "." + artifact.getArtifactId());
    FileUtils.writeLines(file, transform(classPathFiles, new Function<File, String>() {
        @Override
        public String apply(File file) {
            if (IS_OS_UNIX) {
                return file.getAbsolutePath().replace(installerUserHome, "$HOME");
            } else {
                return file.getAbsolutePath();
            }
        }
    }));

    return file;
}

From source file:edu.illinois.cs.cogcomp.nlp.corpusreaders.CoNLLNerReader.java

/**
 * Converts a list of annotated TextAnnotation into CoNLL format. Must have NER_CONLL view. This
 * writes each TextAnnotation to it's own file, using the sentence view as a guide for
 * sentences. This will requires that each TextAnnotation have a non-null ID, which will be the
 * name of the conll file for that TextAnnotation.
 * // w  w w . j a va2s .  com
 * @param tas
 * @param outpath
 * @throws IOException
 */
public static void TaToConll(List<TextAnnotation> tas, String outpath) throws IOException {

    for (TextAnnotation ta : tas) {
        List<String> talines = new ArrayList<>();

        View sentview = ta.getView(ViewNames.SENTENCE);
        View nerview = ta.getView(ViewNames.NER_CONLL);
        for (int i = 0; i < ta.getTokens().length; i++) {

            // Default "outside" label in NER_CONLL
            String label = "O";

            List<Constituent> constituents = nerview.getConstituentsCoveringToken(i);

            // should be just one constituent
            if (constituents.size() > 0) {
                Constituent c = constituents.get(0);
                if (c.getStartSpan() == i) {
                    label = "B-" + c.getLabel();
                } else {
                    label = "I-" + c.getLabel();
                }

                if (constituents.size() > 1) {
                    logger.error("More than one label -- selecting the first.");
                    logger.error("Constituents: " + constituents);
                }
            }
            talines.add(conllline(label, i, ta.getToken(i)));
            List<Constituent> sents = sentview.getConstituentsCoveringToken(i);
            if (sents.size() > 0) {
                Constituent sent = sents.get(0);

                int end = sent.getEndSpan();
                if (i == end - 1) {
                    talines.add("");
                }

                if (sents.size() > 1) {
                    logger.error("More than one sentence constituent for this token -- selecting the first.");
                    logger.error("Sentences: " + sents);
                }
            }
        }

        FileUtils.writeLines(Paths.get(outpath, ta.getId()).toFile(), talines);
    }

}