Example usage for java.io BufferedWriter newLine

List of usage examples for java.io BufferedWriter newLine

Introduction

In this page you can find the example usage for java.io BufferedWriter newLine.

Prototype

public void newLine() throws IOException 

Source Link

Document

Writes a line separator.

Usage

From source file:com.codesourcery.installer.actions.EnvironmentAction.java

/**
 * Handles Linux path environment.//  w w  w  .ja  v  a 2 s  .  c o  m
 * 
 * @param product Product
 * @param mode Mode
 * @param monitor Progress monitor
 * @throws CoreException on failure
 */
private void runLinux(IInstallProduct product, IInstallMode mode, IProgressMonitor monitor)
        throws CoreException {
    // Path to .profile
    String homeDir = System.getProperty("user.home");
    if (homeDir == null)
        Installer.fail("Failed to get user home directory.");
    IPath homePath = new Path(homeDir);

    // Check for profile
    String profileFilename = null;
    File profileFile = null;
    for (String name : PROFILE_FILENAMES) {
        IPath profilePath = homePath.append(name);
        profileFile = profilePath.toFile();
        if (profileFile.exists()) {
            profileFilename = name;
            break;
        } else {
            Installer.log(name + " not found, skipping.");
        }
    }
    if (profileFilename == null) {
        // Create a new profile.
        profileFilename = PROFILE_FILENAMES[PROFILE_DEFAULT_INDEX];
        IPath newProfilePath = homePath.append(profileFilename);
        try {
            profileFile = newProfilePath.toFile();
            profileFile.createNewFile();
        } catch (IOException e) {
            Installer.log("Could not create profile " + newProfilePath);
            return;
        }
    }

    // Do not modify read-only profile
    if (!profileFile.canWrite()) {
        Installer.log("Profile was not modified because it is read-only.");
        return;
    }

    // File date suffix
    SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyDDDHHmmss");
    String fileDateDesc = fileDateFormat.format(new Date());
    // Backup file path
    String backupName = profileFilename + fileDateDesc;
    IPath backupPath = homePath.append(backupName);
    File backupFile = backupPath.toFile();

    String line;
    // Install
    if (mode.isInstall()) {
        // Date description
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
        String dateDesc = dateFormat.format(new Date());

        // Make backup of .profile
        try {
            org.apache.commons.io.FileUtils.copyFile(profileFile, backupFile);
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToBackupProfile, e);
        }

        // Write path extensions
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(profileFile, true));
            writer.newLine();
            // Write product block start
            writer.append(getProfileMarker(product, true));
            writer.newLine();
            writer.append("# Do NOT modify these lines; they are used to uninstall.");
            writer.newLine();
            line = MessageFormat.format("# New environment added by {0} on {1}.",
                    new Object[] { product.getName(), dateDesc });
            writer.append(line);
            writer.newLine();
            line = MessageFormat.format("# The unmodified version of this file is saved in {0}.",
                    backupPath.toOSString());
            writer.append(line);
            writer.newLine();

            monitor.setTaskName("Setting environment variables...");
            for (EnvironmentVariable environmentVariable : environmentVariables) {
                monitor.setTaskName(
                        NLS.bind(InstallMessages.SettingEnvironment, environmentVariable.getName()));
                StringBuilder buffer = new StringBuilder();
                buffer.append(environmentVariable.getName());
                buffer.append('=');
                // Append variable
                if (environmentVariable.getOperation() == EnvironmentOperation.APPEND) {
                    buffer.append("${");
                    buffer.append(environmentVariable.getName());
                    buffer.append("}");
                    buffer.append(environmentVariable.getDelimiter());
                }
                boolean path = "PATH".equals(environmentVariable.getName());
                if (path)
                    buffer.append('\"');
                buffer.append(environmentVariable.getValue());
                if (path)
                    buffer.append('\"');
                if (environmentVariable.getOperation() == EnvironmentOperation.PREPEND) {
                    buffer.append(environmentVariable.getDelimiter());
                    buffer.append("${");
                    buffer.append(environmentVariable.getName());
                    buffer.append("}");
                }
                writer.append(buffer.toString());
                writer.newLine();
                writer.append("export ");
                writer.append(environmentVariable.getName());
                writer.newLine();
            }

            // Write product block end
            writer.append(getProfileMarker(product, false));
            writer.newLine();

        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }
    // Uninstall
    else {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        boolean inProductBlock = false;
        try {
            reader = new BufferedReader(new FileReader(profileFile));
            writer = new BufferedWriter(new FileWriter(backupFile));
            while ((line = reader.readLine()) != null) {
                // Start of product path block
                if (line.startsWith(getProfileMarker(product, true))) {
                    inProductBlock = true;
                }
                // End of product path block
                else if (line.startsWith(getProfileMarker(product, false))) {
                    inProductBlock = false;
                }
                // If not in product path block, copy lines
                else if (!inProductBlock) {
                    writer.write(line);
                    writer.newLine();
                }
            }
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }

        // Copy new profile
        try {
            org.apache.commons.io.FileUtils.copyFile(backupFile, profileFile);
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        }

        backupFile.delete();
    }
}

From source file:org.matsim.analysis.IterationStopWatch.java

/**
 * Writes the gathered data tab-separated into a text file.
 *
 * @param filename The name of a file where to write the gathered data.
 *//* w ww .j a v a2 s. co  m*/
public void writeTextFile(final String filename) {

    try {
        BufferedWriter writer = IOUtils.getBufferedWriter(filename + ".txt");

        // print header
        writer.write("Iteration");
        for (String identifier : this.identifiers) {
            writer.write('\t');
            writer.write(identifier);
        }
        writer.write('\t');
        for (String identifier : this.operations) {
            writer.write('\t');
            writer.write(identifier);
        }
        writer.newLine();

        // print data
        for (Map.Entry<Integer, Map<String, Long>> entry : this.iterations.entrySet()) {
            Integer iteration = entry.getKey();
            Map<String, Long> data = entry.getValue();
            // iteration
            writer.write(iteration.toString());
            // identifiers
            for (String identifier : this.identifiers) {
                Long time = data.get(identifier);
                writer.write('\t');
                writer.write(formatMilliTime(time));
            }
            // blank separator
            writer.write('\t');
            // durations of operations
            for (String identifier : this.operations) {
                Long startTime = data.get("BEGIN " + identifier);
                Long endTime = data.get("END " + identifier);
                writer.write('\t');
                if (startTime != null && endTime != null) {
                    double diff = (endTime.longValue() - startTime.longValue()) / 1000.0;
                    writer.write(Time.writeTime(diff));
                }
            }

            // finish
            writer.newLine();
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.emc.vipr.sync.CasMigrationTest.java

@Test
public void testVerify() throws Exception {
    FPPool sourcePool = new FPPool(connectString1);
    FPPool destPool = new FPPool(connectString2);

    // create random data (capture summary for comparison)
    StringWriter sourceSummary = new StringWriter();
    List<String> clipIds = createTestClips(sourcePool, 10240, 500, sourceSummary);

    try {/*www .j a  v a  2  s. c  o m*/
        // write clip file
        File clipFile = File.createTempFile("clip", "lst");
        clipFile.deleteOnExit();
        BufferedWriter writer = new BufferedWriter(new FileWriter(clipFile));
        for (String clipId : clipIds) {
            writer.write(clipId);
            writer.newLine();
        }
        writer.close();

        // test sync with verify
        ViPRSync sync = createViPRSync(connectString1, connectString2, 20, true);
        ((CasSource) sync.getSource()).setClipIdFile(clipFile.getAbsolutePath());
        sync.setVerify(true);

        sync.run();
        System.out.println(sync.getStatsString());

        Assert.assertEquals(0, sync.getFailedCount());

        // test verify only
        sync = createViPRSync(connectString1, connectString2, 20, true);
        sync.setVerifyOnly(true);

        sync.run();
        System.out.println(sync.getStatsString());

        Assert.assertEquals(0, sync.getFailedCount());

        // delete clips from target
        delete(destPool, clipIds);

        // test sync+verify with failures
        sync = createViPRSync(connectString1, connectString2, 20, true);
        ((CasSource) sync.getSource()).setClipIdFile(clipFile.getAbsolutePath());
        ByteAlteringFilter filter = new ByteAlteringFilter();
        sync.setFilters(Arrays.asList((SyncFilter) filter));
        sync.setVerify(true);

        sync.run();
        System.out.println(sync.getStatsString());

        Assert.assertEquals(filter.getModifiedObjects(), sync.getFailedCount());
    } finally {
        // delete clips from both
        delete(sourcePool, clipIds);
        delete(destPool, clipIds);
    }
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

@Test
public void testVerify() throws Exception {
    FPPool sourcePool = new FPPool(connectString1);
    FPPool destPool = new FPPool(connectString2);

    // create random data (capture summary for comparison)
    StringWriter sourceSummary = new StringWriter();
    List<String> clipIds = createTestClips(sourcePool, 10240, 500, sourceSummary);

    try {/*from   ww w.  jav  a  2s .c  om*/
        // write clip file
        File clipFile = File.createTempFile("clip", "lst");
        clipFile.deleteOnExit();
        BufferedWriter writer = new BufferedWriter(new FileWriter(clipFile));
        for (String clipId : clipIds) {
            writer.write(clipId);
            writer.newLine();
        }
        writer.close();

        // test sync with verify
        EcsSync sync = createEcsSync(connectString1, connectString2, CAS_THREADS, true);
        ((CasSource) sync.getSource()).setClipIdFile(clipFile.getAbsolutePath());
        sync.setVerify(true);

        run(sync);

        Assert.assertEquals(0, sync.getObjectsFailed());

        // test verify only
        sync = createEcsSync(connectString1, connectString2, CAS_THREADS, true);
        sync.setVerifyOnly(true);

        run(sync);

        Assert.assertEquals(0, sync.getObjectsFailed());

        // delete clips from target
        delete(destPool, clipIds);

        // test sync+verify with failures
        sync = createEcsSync(connectString1, connectString2, CAS_THREADS, true);
        ((CasSource) sync.getSource()).setClipIdFile(clipFile.getAbsolutePath());
        ByteAlteringFilter filter = new ByteAlteringFilter();
        sync.setFilters(Collections.singletonList((SyncFilter) filter));
        sync.setVerify(true);

        run(sync);

        Assert.assertEquals(filter.getModifiedObjects(), sync.getObjectsFailed());
    } finally {
        // delete clips from both
        delete(sourcePool, clipIds);
        delete(destPool, clipIds);
    }
}

From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java

public Set<String> getAllLeaves(ConceptGraph cg, BufferedWriter w) throws IOException {
    Set<String> leafSet = new HashSet<String>();
    for (Map.Entry<String, ConcRel> con : cg.getConceptMap().entrySet()) {
        if (con.getValue().isLeaf()) {
            leafSet.add(con.getValue().getConceptID());
        }//from   w  w  w .  ja va2s .com
    }
    if (w != null) {
        w.write(Integer.toString(leafSet.size()));
        w.write("\t");
        w.write(leafSet.toString());
        w.newLine();
    }
    return leafSet;
}

From source file:org.apache.hadoop.hive.ant.QTestGenTask.java

public void execute() throws BuildException {
    if (getTemplatePath().equals("")) {
        throw new BuildException("No templatePath attribute specified");
    }//from   w w w.j  a v  a  2 s . c  o m

    if (template == null) {
        throw new BuildException("No template attribute specified");
    }

    if (outputDirectory == null) {
        throw new BuildException("No outputDirectory specified");
    }

    if (queryDirectory == null && queryFile == null) {
        throw new BuildException("No queryDirectory or queryFile specified");
    }

    if (logDirectory == null) {
        throw new BuildException("No logDirectory specified");
    }

    if (className == null) {
        throw new BuildException("No className specified");
    }

    Set<String> includeOnly = null;
    if (includeQueryFile != null && !includeQueryFile.isEmpty()) {
        includeOnly = Sets.<String>newHashSet(TEST_SPLITTER.split(includeQueryFile));
    }

    List<File> qFiles;
    HashMap<String, String> qFilesMap = new HashMap<String, String>();
    File hiveRootDir = null;
    File queryDir = null;
    File outDir = null;
    File resultsDir = null;
    File logDir = null;

    try {

        System.out.println("Starting Generation of: " + className);
        System.out.println("Include Files: " + includeQueryFile);
        System.out.println("Excluded Files: " + excludeQueryFile);
        System.out.println("Query Files: " + queryFile);
        System.out.println("Query Files Regex: " + queryFileRegex);

        // queryDirectory should not be null
        queryDir = new File(queryDirectory);

        // dedup file list
        Set<File> testFiles = new HashSet<File>();
        if (queryFile != null && !queryFile.equals("")) {
            // The user may have passed a list of files - comma separated
            for (String qFile : TEST_SPLITTER.split(queryFile)) {
                if (null != queryDir) {
                    testFiles.add(new File(queryDir, qFile));
                } else {
                    testFiles.add(new File(qFile));
                }
            }
        } else if (queryFileRegex != null && !queryFileRegex.equals("")) {
            for (String regex : TEST_SPLITTER.split(queryFileRegex)) {
                testFiles.addAll(Arrays.asList(queryDir.listFiles(new QFileRegexFilter(regex))));
            }
        } else if (runDisabled != null && runDisabled.equals("true")) {
            testFiles.addAll(Arrays.asList(queryDir.listFiles(new DisabledQFileFilter(includeOnly))));
        } else {
            testFiles.addAll(Arrays.asList(queryDir.listFiles(new QFileFilter(includeOnly))));
        }

        if (excludeQueryFile != null && !excludeQueryFile.equals("")) {
            // Exclude specified query files, comma separated
            for (String qFile : TEST_SPLITTER.split(excludeQueryFile)) {
                if (null != queryDir) {
                    testFiles.remove(new File(queryDir, qFile));
                } else {
                    testFiles.remove(new File(qFile));
                }
            }
        }

        hiveRootDir = new File(hiveRootDirectory);
        if (!hiveRootDir.exists()) {
            throw new BuildException(
                    "Hive Root Directory " + hiveRootDir.getCanonicalPath() + " does not exist");
        }

        qFiles = new ArrayList<File>(testFiles);
        Collections.sort(qFiles);
        for (File qFile : qFiles) {
            qFilesMap.put(qFile.getName(), relativePath(hiveRootDir, qFile));
        }

        // Make sure the output directory exists, if it doesn't then create it.
        outDir = new File(outputDirectory);
        if (!outDir.exists()) {
            outDir.mkdirs();
        }

        logDir = new File(logDirectory);
        if (!logDir.exists()) {
            throw new BuildException("Log Directory " + logDir.getCanonicalPath() + " does not exist");
        }

        if (resultsDirectory != null) {
            resultsDir = new File(resultsDirectory);
            if (!resultsDir.exists()) {
                throw new BuildException(
                        "Results Directory " + resultsDir.getCanonicalPath() + " does not exist");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException(e);
    }

    VelocityEngine ve = new VelocityEngine();

    try {
        ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, getTemplatePath());
        if (logFile != null) {
            File lf = new File(logFile);
            if (lf.exists()) {
                System.out.println("Log file already exists: " + lf.getCanonicalPath());
                if (!lf.delete()) {
                    System.out.println("Could not delete log file " + lf.getCanonicalPath());
                    logFile = createAlternativeFile(lf);
                }
            }

            ve.setProperty(RuntimeConstants.RUNTIME_LOG, logFile);
        }

        ve.init();
        Template t = ve.getTemplate(template);

        if (clusterMode == null) {
            clusterMode = "";
        }
        if (hadoopVersion == null) {
            hadoopVersion = "";
        }

        File qFileNames = new File(outputDirectory, className + "QFileNames.txt");
        String qFileNamesFile = qFileNames.toURI().getPath();

        if (qFileNames.exists()) {
            System.out.println("Query file names containing file already exists: " + qFileNamesFile);
            if (!qFileNames.delete()) {
                System.out.println(
                        "Could not delete query file names containing file " + qFileNames.getCanonicalPath());
                qFileNamesFile = createAlternativeFile(qFileNames);
            } else if (!qFileNames.createNewFile()) {
                System.out.println("Could not create query file names containing file " + qFileNamesFile);
                qFileNamesFile = createAlternativeFile(qFileNames);
            }
        }
        FileWriter fw = new FileWriter(qFileNames.getCanonicalFile());
        BufferedWriter bw = new BufferedWriter(fw);

        for (File qFile : qFiles) {
            bw.write(qFile.getName());
            bw.newLine();
        }
        bw.close();

        // For each of the qFiles generate the test
        System.out.println("hiveRootDir = " + hiveRootDir);
        VelocityContext ctx = new VelocityContext();
        ctx.put("className", className);
        ctx.put("hiveRootDir", escapePath(hiveRootDir.getCanonicalPath()));
        System.out.println("hiveRootDir = " + hiveRootDir);
        System.out.println("queryDir = " + queryDir);
        String strQueryDir = relativePath(hiveRootDir, queryDir);
        System.out.println("queryDir = " + strQueryDir);
        ctx.put("queryDir", strQueryDir);
        ctx.put("qfiles", qFiles);
        ctx.put("qFileNamesFile", qFileNamesFile);
        ctx.put("qfilesMap", qFilesMap);
        if (resultsDir != null) {
            ctx.put("resultsDir", relativePath(hiveRootDir, resultsDir));
        }
        ctx.put("logDir", relativePath(hiveRootDir, logDir));
        ctx.put("clusterMode", clusterMode);
        if (hiveConfDir == null || hiveConfDir.isEmpty()) {
            ctx.put("hiveConfDir", "");
        } else {
            System.out.println("hiveConfDir = " + hiveConfDir);
            hiveConfDir = relativePath(hiveRootDir, new File(hiveConfDir));
            System.out.println("hiveConfDir = " + hiveConfDir);
            if (!(new File(hiveRootDir, hiveConfDir)).isDirectory()) {
                throw new BuildException("hiveConfDir is not dir " + new File(hiveRootDir, hiveConfDir));
            }
            ctx.put("hiveConfDir", hiveConfDir);
        }
        ctx.put("hadoopVersion", hadoopVersion);
        ctx.put("initScript", initScript);
        ctx.put("cleanupScript", cleanupScript);

        File outFile = new File(outDir, className + ".java");
        FileWriter writer = new FileWriter(outFile);
        t.merge(ctx, writer);
        writer.close();

        System.out.println("Generated " + outFile.getCanonicalPath() + " from template " + template);
    } catch (BuildException e) {
        throw e;
    } catch (MethodInvocationException e) {
        throw new BuildException("Exception thrown by '" + e.getReferenceName() + "." + e.getMethodName() + "'",
                e.getWrappedThrowable());
    } catch (ParseErrorException e) {
        throw new BuildException("Velocity syntax error", e);
    } catch (ResourceNotFoundException e) {
        throw new BuildException("Resource not found", e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException("Generation failed", e);
    }
}

From source file:org.matsim.contrib.analysis.vsp.traveltimedistance.TravelTimeValidationRunner.java

private void writeTravelTimeValidation(String folder, List<CarTrip> trips) {
    BufferedWriter bw = IOUtils.getBufferedWriter(folder + "/validated_trips.csv");
    XYSeriesCollection times = new XYSeriesCollection();
    XYSeriesCollection distances = new XYSeriesCollection();

    XYSeries distancess = new XYSeries("distances", true, true);
    XYSeries timess = new XYSeries("times", true, true);
    times.addSeries(timess);/* w ww  . j  a va  2 s. co  m*/
    distances.addSeries(distancess);
    try {
        bw.append(
                "agent;departureTime;fromX;fromY;toX;toY;traveltimeActual;traveltimeValidated;traveledDistance;validatedDistance");
        for (CarTrip trip : trips) {
            if (trip.getValidatedTravelTime() != null) {
                bw.newLine();
                bw.append(trip.toString());
                timess.add(trip.getActualTravelTime(), trip.getValidatedTravelTime());
                distancess.add(trip.getTravelledDistance(), trip.getValidatedTravelDistance());
            }
        }

        bw.flush();
        bw.close();
        final JFreeChart chart2 = ChartFactory.createScatterPlot("Travel Times", "Simulated travel time [s]",
                "Validated travel time [s]", times);
        final JFreeChart chart = ChartFactory.createScatterPlot("Travel Distances",
                "Simulated travel distance [m]", "Validated travel distance [m]", distances);

        NumberAxis yAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getRangeAxis();
        NumberAxis xAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getDomainAxis();
        NumberAxis yAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getRangeAxis();
        NumberAxis xAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getDomainAxis();
        yAxisd.setUpperBound(xAxisd.getUpperBound());
        yAxis.setUpperBound(xAxis.getUpperBound());
        yAxis.setTickUnit(new NumberTickUnit(500));
        xAxis.setTickUnit(new NumberTickUnit(500));

        XYAnnotation diagonal = new XYLineAnnotation(xAxis.getRange().getLowerBound(),
                yAxis.getRange().getLowerBound(), xAxis.getRange().getUpperBound(),
                yAxis.getRange().getUpperBound());
        ((XYPlot) chart2.getPlot()).addAnnotation(diagonal);

        XYAnnotation diagonald = new XYLineAnnotation(xAxisd.getRange().getLowerBound(),
                yAxisd.getRange().getLowerBound(), xAxisd.getRange().getUpperBound(),
                yAxisd.getRange().getUpperBound());
        ((XYPlot) chart.getPlot()).addAnnotation(diagonald);

        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveltimes" + ".png"), chart2,
                1500, 1500);
        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveldistances.png"), chart,
                1500, 1500);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:playground.ikaddoura.analysis.welfare.WelfareAnalysisControlerListener.java

private void writeAnalysis(IterationEndsEvent event) {

    UserBenefitsCalculator userBenefitsCalculator_logsum = new UserBenefitsCalculator(this.scenario.getConfig(),
            WelfareMeasure.LOGSUM, true);
    this.it2userBenefits_logsum.put(event.getIteration(), userBenefitsCalculator_logsum
            .calculateUtility_money(event.getControler().getScenario().getPopulation()));
    this.it2invalidPersons_logsum.put(event.getIteration(),
            userBenefitsCalculator_logsum.getPersonsWithoutValidPlanCnt());
    this.it2invalidPlans_logsum.put(event.getIteration(), userBenefitsCalculator_logsum.getInvalidPlans());

    UserBenefitsCalculator userBenefitsCalculator_selected = new UserBenefitsCalculator(
            this.scenario.getConfig(), WelfareMeasure.SELECTED, true);
    this.it2userBenefits_selected.put(event.getIteration(), userBenefitsCalculator_selected
            .calculateUtility_money(event.getControler().getScenario().getPopulation()));
    this.it2invalidPersons_selected.put(event.getIteration(),
            userBenefitsCalculator_selected.getPersonsWithoutValidPlanCnt());
    this.it2invalidPlans_selected.put(event.getIteration(), userBenefitsCalculator_selected.getInvalidPlans());

    double tollSum = this.moneyHandler.getSumOfMonetaryAmounts();
    this.it2tollSum.put(event.getIteration(), (-1) * tollSum);
    this.it2stuckEvents.put(event.getIteration(), this.tripAnalysisHandler.getAgentStuckEvents());
    this.it2totalTravelTimeAllModes.put(event.getIteration(),
            this.tripAnalysisHandler.getTotalTravelTimeAllModes());
    this.it2totalTravelTimeCarMode.put(event.getIteration(),
            this.tripAnalysisHandler.getTotalTravelTimeCarMode());
    this.it2carLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getCarLegs());
    this.it2ptLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getPtLegs());
    this.it2walkLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getWalkLegs());

    String fileName = this.scenario.getConfig().controler().getOutputDirectory() + "/welfareAnalysis.csv";
    File file = new File(fileName);

    try {//from  w w w  .j ava  2s. c om
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write("Iteration;"
                + "User Benefits (LogSum);Number of Invalid Persons (LogSum);Number of Invalid Plans (LogSum);"
                + "User Benefits (Selected);Number of Invalid Persons (Selected);Number of Invalid Plans (Selected);"
                + "Total Monetary Payments;Welfare (LogSum);Welfare (Selected);Total Travel Time All Modes (sec);Total Travel Time Car Mode (sec);Avg Travel Time Per Car Trip (sec);Number of Agent Stuck Events;"
                + "Car Trips;Pt Trips;Walk Trips");
        bw.newLine();
        for (Integer it : this.it2userBenefits_selected.keySet()) {
            bw.write(it + ";" + this.it2userBenefits_logsum.get(it) + ";"
                    + this.it2invalidPersons_logsum.get(it) + ";" + this.it2invalidPlans_logsum.get(it) + ";"
                    + this.it2userBenefits_selected.get(it) + ";" + this.it2invalidPersons_selected.get(it)
                    + ";" + this.it2invalidPlans_selected.get(it) + ";" + this.it2tollSum.get(it) + ";"
                    + (this.it2userBenefits_logsum.get(it) + this.it2tollSum.get(it)) + ";"
                    + (this.it2userBenefits_selected.get(it) + this.it2tollSum.get(it)) + ";"
                    + this.it2totalTravelTimeAllModes.get(it) + ";" + this.it2totalTravelTimeCarMode.get(it)
                    + ";" + (this.it2totalTravelTimeCarMode.get(it) / this.it2carLegs.get(it)) + ";"
                    + this.it2stuckEvents.get(it) + ";" + this.it2carLegs.get(it) + ";" + this.it2ptLegs.get(it)
                    + ";" + this.it2walkLegs.get(it));
            bw.newLine();
        }

        bw.close();
        log.info("Output written to " + fileName);

    } catch (IOException e) {
        e.printStackTrace();
    }

    // ##################################################

    writeGraph("userBenefits_selected", "Monetary Units", it2userBenefits_selected);
    writeGraph("userBenefits_logsum", "Monetary Units", it2userBenefits_logsum);
    writeGraph("tollSum", "Monetary Units", it2tollSum);
    writeGraph("totalTravelTimeAllModes", "Seconds", it2totalTravelTimeAllModes);
    writeGraph("totalTravelTimeCarMode", "Seconds", it2totalTravelTimeCarMode);
    writeGraph("carTrips", "Number of Car Trips", it2carLegs);
    writeGraph("ptTrips", "Number of Pt Trips", it2ptLegs);
    writeGraph("walkTrips", "Number of Walk Trips", it2walkLegs);

    writeGraphSum("welfare_logsum", "Monetary Units", it2userBenefits_logsum, it2tollSum);
    writeGraphSum("welfare_selected", "Monetary Units", it2userBenefits_selected, it2tollSum);

    writeGraphDiv("avgTripTravelTimeCar", "Seconds", it2totalTravelTimeCarMode, it2carLegs);
}

From source file:sandbox.sfwatergit.analysis.modules.welfare.WelfareAnalysisControlerListener.java

private void writeAnalysis(IterationEndsEvent event) {

    UserBenefitsCalculator userBenefitsCalculator_logsum = new UserBenefitsCalculator(this.scenario.getConfig(),
            WelfareMeasure.LOGSUM, true);
    this.it2userBenefits_logsum.put(event.getIteration(), userBenefitsCalculator_logsum
            .calculateUtility_money(event.getServices().getScenario().getPopulation()));
    this.it2invalidPersons_logsum.put(event.getIteration(),
            userBenefitsCalculator_logsum.getPersonsWithoutValidPlanCnt());
    this.it2invalidPlans_logsum.put(event.getIteration(), userBenefitsCalculator_logsum.getInvalidPlans());

    UserBenefitsCalculator userBenefitsCalculator_selected = new UserBenefitsCalculator(
            this.scenario.getConfig(), WelfareMeasure.SELECTED, true);
    this.it2userBenefits_selected.put(event.getIteration(), userBenefitsCalculator_selected
            .calculateUtility_money(event.getServices().getScenario().getPopulation()));
    this.it2invalidPersons_selected.put(event.getIteration(),
            userBenefitsCalculator_selected.getPersonsWithoutValidPlanCnt());
    this.it2invalidPlans_selected.put(event.getIteration(), userBenefitsCalculator_selected.getInvalidPlans());

    double tollSum = this.moneyHandler.getSumOfMonetaryAmounts();
    this.it2tollSum.put(event.getIteration(), (-1) * tollSum);
    this.it2stuckEvents.put(event.getIteration(), this.tripAnalysisHandler.getAgentStuckEvents());
    this.it2totalTravelTimeAllModes.put(event.getIteration(),
            this.tripAnalysisHandler.getTotalTravelTimeAllModes());
    this.it2totalTravelTimeCarMode.put(event.getIteration(),
            this.tripAnalysisHandler.getTotalTravelTimeCarMode());
    this.it2carLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getCarLegs());
    this.it2ptLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getPtLegs());
    this.it2walkLegs.put(event.getIteration(), (double) this.tripAnalysisHandler.getWalkLegs());

    String fileName = this.scenario.getConfig().controler().getOutputDirectory() + "/welfareAnalysis.csv";
    File file = new File(fileName);

    try {/*from w w  w.  j a v  a 2s .  c  o  m*/
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write("Iteration;"
                + "User Benefits (LogSum);Number of Invalid Persons (LogSum);Number of Invalid Plans (LogSum);"
                + "User Benefits (Selected);Number of Invalid Persons (Selected);Number of Invalid Plans (Selected);"
                + "Total Monetary Payments;Welfare (LogSum);Welfare (Selected);Total Travel Time All Modes (sec);Total Travel Time Car Mode (sec);Avg Travel Time Per Car Trip (sec);Number of Player Stuck Events;"
                + "Car Trips;Pt Trips;Walk Trips");
        bw.newLine();
        for (Integer it : this.it2userBenefits_selected.keySet()) {
            bw.write(it + ";" + this.it2userBenefits_logsum.get(it) + ";"
                    + this.it2invalidPersons_logsum.get(it) + ";" + this.it2invalidPlans_logsum.get(it) + ";"
                    + this.it2userBenefits_selected.get(it) + ";" + this.it2invalidPersons_selected.get(it)
                    + ";" + this.it2invalidPlans_selected.get(it) + ";" + this.it2tollSum.get(it) + ";"
                    + (this.it2userBenefits_logsum.get(it) + this.it2tollSum.get(it)) + ";"
                    + (this.it2userBenefits_selected.get(it) + this.it2tollSum.get(it)) + ";"
                    + this.it2totalTravelTimeAllModes.get(it) + ";" + this.it2totalTravelTimeCarMode.get(it)
                    + ";" + (this.it2totalTravelTimeCarMode.get(it) / this.it2carLegs.get(it)) + ";"
                    + this.it2stuckEvents.get(it) + ";" + this.it2carLegs.get(it) + ";" + this.it2ptLegs.get(it)
                    + ";" + this.it2walkLegs.get(it));
            bw.newLine();
        }

        bw.close();
        log.info("Output written to " + fileName);

    } catch (IOException e) {
        e.printStackTrace();
    }

    // ##################################################

    writeGraph("userBenefits_selected", "Monetary Units", it2userBenefits_selected);
    writeGraph("userBenefits_logsum", "Monetary Units", it2userBenefits_logsum);
    writeGraph("tollSum", "Monetary Units", it2tollSum);
    writeGraph("totalTravelTimeAllModes", "Seconds", it2totalTravelTimeAllModes);
    writeGraph("totalTravelTimeCarMode", "Seconds", it2totalTravelTimeCarMode);
    writeGraph("carTrips", "Number of Car Trips", it2carLegs);
    writeGraph("ptTrips", "Number of Pt Trips", it2ptLegs);
    writeGraph("walkTrips", "Number of Walk Trips", it2walkLegs);

    writeGraphSum("welfare_logsum", "Monetary Units", it2userBenefits_logsum, it2tollSum);
    writeGraphSum("welfare_selected", "Monetary Units", it2userBenefits_selected, it2tollSum);

    writeGraphDiv("avgTripTravelTimeCar", "Seconds", it2totalTravelTimeCarMode, it2carLegs);
}

From source file:eu.cloud4soa.tests.TestReqSec_Deploy.java

private void writeOnFileDeployedApplicationsUriId() {
    BufferedWriter bufferedWriter = null;
    try {/*from  w  ww  . jav  a2 s  .  c  o m*/
        String userHome = System.getProperty("user.home");
        File testFile = new File(userHome + File.separator + "TestsC4S" + File.separator + "testReqSec_Deploy_"
                + numberTests + ".txt");
        bufferedWriter = new BufferedWriter(new FileWriter(testFile));
        Collection<String> values = applicationInstances.values();
        for (String applicationInstanceUriId : values) {
            bufferedWriter.write(applicationInstanceUriId);
            bufferedWriter.newLine();
        }
    } catch (IOException ex) {
        Logger.getLogger(TestReqSec_Deploy.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            bufferedWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(TestReqSec_Deploy.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}