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:io.siddhi.extension.io.file.FileSourceLineModeTestCase.java

@Test
public void siddhiIoFileTest4() throws InterruptedException {
    log.info("test SiddhiIoFile [mode=line] Test 4");
    String streams = "" + "@App:name('TestSiddhiApp')" + "@source(type='file', mode='line'," + "dir.uri='file:/"
            + dirUri + "/line/xml', " + "@map(type='xml'))"
            + "define stream FooStream (symbol string, price float, volume long); "
            + "define stream BarStream (symbol string, price float, volume long); ";
    String query = "" + "from FooStream " + "select * " + "insert into BarStream; ";

    SiddhiManager siddhiManager = new SiddhiManager();
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);
    siddhiAppRuntime.addCallback("BarStream", new StreamCallback() {

        @Override/*w  w w . j  av a2  s . c  o  m*/
        public void receive(Event[] events) {
            EventPrinter.print(events);
            int n = count.incrementAndGet();
            for (Event event : events) {
                switch (n) {
                case 1:
                    AssertJUnit.assertEquals(10000L, event.getData(2));
                    break;
                case 2:
                    AssertJUnit.assertEquals(10001L, event.getData(2));
                    break;
                case 3:
                    AssertJUnit.assertEquals(10002L, event.getData(2));
                    break;
                case 4:
                    AssertJUnit.assertEquals(10003L, event.getData(2));
                    break;
                case 5:
                    AssertJUnit.assertEquals(10004L, event.getData(2));
                    break;
                case 6:
                    AssertJUnit.assertEquals(1000L, event.getData(2));
                    break;
                case 7:
                    AssertJUnit.assertEquals(2000L, event.getData(2));
                    break;
                default:
                    AssertJUnit.fail("More events received than expected.");
                }
            }
        }
    });
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            siddhiAppRuntime.start();
        }
    });
    t1.start();
    SiddhiTestHelper.waitForEvents(waitTime, 5, count, timeout);
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            File file = new File(dirUri + "/line/xml/xml_line (3rd copy).txt");
            try {
                StringBuilder sb = new StringBuilder();
                sb.append("<events>").append("<event>").append("<symbol>").append("GOOGLE").append("</symbol>")
                        .append("<price>").append("100").append("</price>").append("<volume>").append("1000")
                        .append("</volume>").append("</event>").append("</events>\n");
                sb.append("<events>").append("<event>").append("<symbol>").append("YAHOO").append("</symbol>")
                        .append("<price>").append("200").append("</price>").append("<volume>").append("2000")
                        .append("</volume>").append("</event>").append("</events>");
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                bufferedWriter.write(sb.toString());
                bufferedWriter.newLine();
                bufferedWriter.flush();
                bufferedWriter.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    });
    t2.start();
    SiddhiTestHelper.waitForEvents(waitTime, 7, count, timeout);
    //assert event count
    AssertJUnit.assertEquals("Number of events", 7, count.get());
    siddhiAppRuntime.shutdown();
}

From source file:io.siddhi.extension.io.file.FileSourceLineModeTestCase.java

@Test
public void siddhiIoFileTest13() throws InterruptedException {
    log.info("test SiddhiIoFile [mode=line] Test 13");
    String streams = "" + "@App:name('TestSiddhiApp')" + "@source(type='file', mode='line',"
            + "file.uri='file:/" + dirUri + "/line/xml/xml_line.txt', " + "tailing='true', "
            + "@map(type='xml'))" + "define stream FooStream (symbol string, price float, volume long); "
            + "define stream BarStream (symbol string, price float, volume long); ";
    String query = "" + "from FooStream " + "select * " + "insert into BarStream; ";

    SiddhiManager siddhiManager = new SiddhiManager();
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);
    siddhiAppRuntime.addCallback("BarStream", new StreamCallback() {

        @Override//from w w w .  jav a 2  s.c  o  m
        public void receive(Event[] events) {
            EventPrinter.print(events);
            int n = count.incrementAndGet();
            for (Event event : events) {
                switch (n) {
                case 1:
                    AssertJUnit.assertEquals(10000L, event.getData(2));
                    break;
                case 2:
                    AssertJUnit.assertEquals(10001L, event.getData(2));
                    break;
                case 3:
                    AssertJUnit.assertEquals(10002L, event.getData(2));
                    break;
                case 4:
                    AssertJUnit.assertEquals(10003L, event.getData(2));
                    break;
                case 5:
                    AssertJUnit.assertEquals(10004L, event.getData(2));
                    break;
                case 6:
                    AssertJUnit.assertEquals(1000L, event.getData(2));
                    break;
                case 7:
                    AssertJUnit.assertEquals(2000L, event.getData(2));
                    break;
                default:
                    AssertJUnit.fail("More events received than expected.");
                }
            }
        }
    });
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            siddhiAppRuntime.start();
        }
    });
    t1.start();
    SiddhiTestHelper.waitForEvents(waitTime, 5, count, timeout);
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            File file = new File(dirUri + "/line/xml/xml_line.txt");
            try {
                StringBuilder sb = new StringBuilder();
                sb.append("<events>").append("<event>").append("<symbol>").append("GOOGLE").append("</symbol>")
                        .append("<price>").append("100").append("</price>").append("<volume>").append("1000")
                        .append("</volume>").append("</event>").append("</events>\n");
                sb.append("<events>").append("<event>").append("<symbol>").append("YAHOO").append("</symbol>")
                        .append("<price>").append("200").append("</price>").append("<volume>").append("2000")
                        .append("</volume>").append("</event>").append("</events>");
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                bufferedWriter.write(sb.toString());
                bufferedWriter.newLine();
                bufferedWriter.flush();
                bufferedWriter.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    });
    t2.start();
    SiddhiTestHelper.waitForEvents(waitTime, 7, count, timeout);
    //assert event count
    AssertJUnit.assertEquals("Number of events", 7, count.get());
    siddhiAppRuntime.shutdown();
}

From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java

/**
 * service/*from  ww w .  ja  v  a  2 s. c  o m*/
 *
 * @param beanName
 * @param serviceName
 * @throws IOException
 */
protected void buildService(String beanName, String serviceName) throws IOException {
    File serviceFile = new File(PATH_SERVICE, serviceName + ".java");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(serviceFile), "utf-8"));
    bw.write("package " + config.getServicePackage() + ";");
    bw.newLine();
    bw.newLine();
    bw.write("import " + config.getEntityPackage() + "." + beanName + ";");
    bw.newLine();
    String superService = config.getSuperService();
    bw.write("import " + superService + ";");
    bw.newLine();

    bw = buildClassComment(bw, beanName + " ???");
    bw.newLine();
    superService = superService.substring(superService.lastIndexOf(".") + 1);
    bw.write("public interface " + serviceName + " extends " + superService + "<" + beanName + "> {");
    bw.newLine();
    bw.newLine();

    // ----------serviceEnd----------
    bw.newLine();
    bw.write("}");
    bw.flush();
    bw.close();
}

From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java

/**
 * Mapper//from   w w w .  ja v a 2 s  .c o m
 *
 * @param beanName
 * @param mapperName
 * @throws IOException
 */
protected void buildMapper(String beanName, String mapperName) throws IOException {
    File mapperFile = new File(PATH_MAPPER, mapperName + ".java");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
    bw.write("package " + config.getMapperPackage() + ";");
    bw.newLine();
    bw.newLine();
    bw.write("import " + config.getEntityPackage() + "." + beanName + ";");
    bw.newLine();
    if (config.getConfigIdType() == ConfigIdType.STRING) {
        bw.write("import com.baomidou.mybatisplus.mapper.CommonMapper;");
    } else {
        bw.write("import com.baomidou.mybatisplus.mapper.AutoMapper;");
    }
    bw.newLine();

    bw = buildClassComment(bw, beanName + " ??");
    bw.newLine();
    if (config.getConfigIdType() == ConfigIdType.STRING) {
        bw.write("public interface " + mapperName + " extends CommonMapper<" + beanName + "> {");
    } else {
        bw.write("public interface " + mapperName + " extends AutoMapper<" + beanName + "> {");
    }
    bw.newLine();
    bw.newLine();

    // ----------mapperEnd----------
    bw.newLine();
    bw.write("}");
    bw.flush();
    bw.close();
}

From source file:playground.artemc.analysis.AnalysisControlerListener.java

private void writeWelfareAnalysis(IterationEndsEvent event) {

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

    try {//from www  .ja  v  a  2s .  c o  m
        BufferedWriter welfareWriter = new BufferedWriter(new FileWriter(welfareFile));
        welfareWriter.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");

        welfareWriter.newLine();
        for (Integer it : this.it2userBenefits_selected.keySet()) {
            welfareWriter.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));
            welfareWriter.newLine();

        }
        welfareWriter.close();
        log.info("Welfare analysis Output written to " + welfareFilePath);
    } 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);
    writeGraph("transitWalkTrips", "Number of Transit Walk Leg", it2transitWalkLegs);
    writeGraph("busVehicleTrips", "Number of Bus Vehicle Trips", it2busLegs);

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

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

From source file:playground.andreas.bln.ana.events2counts.PtCountCountComparisonKMLWriter.java

/**
 * Creates the CountsErrorGraph for all the data
 *
 * @param kmlFilename//  w  w w  . j av a  2 s.c  o  m
 *            the filename of the kml file
 * @param visible
 *            true if initially visible
 * @return the ScreenOverlay Feature
 */
private ScreenOverlayType createBiasErrorGraphBoard(String kmlFilename) {
    int index = kmlFilename.lastIndexOf(System.getProperty("file.separator"));
    if (index == -1) {
        index = kmlFilename.lastIndexOf('/');
    }
    String outdir;
    if (index == -1) {
        outdir = "";
    } else {
        outdir = kmlFilename.substring(0, index) + System.getProperty("file.separator");
    }
    // ------------------------------------------------------------------------------

    PtBiasErrorGraph epBoard = new PtBiasErrorGraph(this.boardCountComparisonFilter.getCountsForHour(null),
            this.iter, null, "error graph - boarding");
    epBoard.createChart(0);

    double[] meanErrorBoard = epBoard.getMeanRelError();
    double[] meanBiasBoard = epBoard.getMeanAbsBias();

    String fileBoard = outdir + "biasErrorGraphDataBoard.txt";
    log.info("writing chart data to " + new File(fileBoard).getAbsolutePath());
    try {
        BufferedWriter bwriter = IOUtils.getBufferedWriter(fileBoard);
        StringBuffer buffer = new StringBuffer(200);
        buffer.append("hour \t mean relative error \t mean absolute bias");
        bwriter.write(buffer.toString());
        bwriter.newLine();
        for (int i = 0; i < meanErrorBoard.length; i++) {
            buffer.delete(0, buffer.length());
            buffer.append(i + 1);
            buffer.append('\t');
            buffer.append(meanErrorBoard[i]);
            buffer.append('\t');
            buffer.append(meanBiasBoard[i]);
            bwriter.write(buffer.toString());
            bwriter.newLine();
        }
        bwriter.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String chartBoard = "errorGraphErrorBiasBoard.png";
    try {
        writeChartToKmz(chartBoard, epBoard.getChart());
        return createOverlayBottomRight(chartBoard, "Error Graph [Error/Bias]");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:playground.andreas.bln.ana.events2counts.PtCountCountComparisonKMLWriter.java

private ScreenOverlayType createBiasErrorGraphAlight(String kmlFilename) {
    int index = kmlFilename.lastIndexOf(System.getProperty("file.separator"));
    if (index == -1) {
        index = kmlFilename.lastIndexOf('/');
    }//from   w w  w  . ja v a  2s.  c o  m
    String outdir;
    if (index == -1) {
        outdir = "";
    } else {
        outdir = kmlFilename.substring(0, index) + System.getProperty("file.separator");
    }
    // ------------------------------------------------------------------------------
    PtBiasErrorGraph epAlight = new PtBiasErrorGraph(this.alightCountComparisonFilter.getCountsForHour(null),
            this.iter, null, "error graph - Alighting");
    epAlight.createChart(0);

    double[] meanErrorAlight = epAlight.getMeanRelError();
    double[] meanBiasAlight = epAlight.getMeanAbsBias();

    String fileAlight = outdir + "biasErrorGraphDataAlight.txt";
    log.info("writing chart data to " + new File(fileAlight).getAbsolutePath());
    try {
        BufferedWriter bwriter = IOUtils.getBufferedWriter(fileAlight);
        StringBuffer buffer = new StringBuffer(200);
        buffer.append("hour \t mean relative error \t mean absolute bias");
        bwriter.write(buffer.toString());
        bwriter.newLine();
        for (int i = 0; i < meanErrorAlight.length; i++) {
            buffer.delete(0, buffer.length());
            buffer.append(i + 1);
            buffer.append('\t');
            buffer.append(meanErrorAlight[i]);
            buffer.append('\t');
            buffer.append(meanBiasAlight[i]);
            bwriter.write(buffer.toString());
            bwriter.newLine();
        }
        bwriter.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String chartAlight = "errorGraphErrorBiasAlight.png";
    try {
        writeChartToKmz(chartAlight, epAlight.getChart());
        return createOverlayBottomRight(chartAlight, "Error Graph [Error/Bias]");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java

/**
 * service/* w  w  w.  ja  va2s  .  c  o  m*/
 *
 * @param beanName
 * @param serviceImplName
 * @param mapperName
 * @throws IOException
 */
protected void buildServiceImpl(String beanName, String serviceImplName, String serviceName, String mapperName)
        throws IOException {
    File serviceFile = new File(PATH_SERVICE_IMPL, serviceImplName + ".java");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(serviceFile), "utf-8"));
    bw.write("package " + config.getServiceImplPackage() + ";");
    bw.newLine();
    bw.newLine();
    bw.write("import org.springframework.stereotype.Service;");
    bw.newLine();
    bw.newLine();
    bw.write("import " + config.getMapperPackage() + "." + mapperName + ";");
    bw.newLine();
    bw.write("import " + config.getEntityPackage() + "." + beanName + ";");
    bw.newLine();
    bw.write("import " + config.getServicePackage() + "." + serviceName + ";");
    bw.newLine();

    String superServiceImpl = config.getSuperServiceImpl();
    bw.write("import " + superServiceImpl + ";");
    bw.newLine();

    bw = buildClassComment(bw, beanName + " ???");
    bw.newLine();
    bw.write("@Service");
    bw.newLine();
    superServiceImpl = superServiceImpl.substring(superServiceImpl.lastIndexOf(".") + 1);
    bw.write("public class " + serviceImplName + " extends " + superServiceImpl + "<" + mapperName + ", "
            + beanName + "> implements " + serviceName + " {");
    bw.newLine();
    bw.newLine();

    // ----------serviceEnd----------
    bw.newLine();
    bw.write("}");
    bw.flush();
    bw.close();
}

From source file:com.imaginary.home.controller.HomeController.java

private void saveCommands(List<CommandList> toSave) throws ControllerException {
    synchronized (commandQueue) {
        ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> cfg = new HashMap<String, Object>();

        for (CommandList cmdList : toSave) {
            ArrayList<Map<String, Object>> commands = new ArrayList<Map<String, Object>>();
            HashMap<String, Object> map = new HashMap<String, Object>();

            for (JSONObject cmd : cmdList) {
                try {
                    commands.add(toMap(cmd));
                } catch (JSONException e) {
                    throw new ControllerException(e);
                }//  ww  w . ja v  a  2 s.  co m
            }
            map.put("commands", commands);
            map.put("serviceId", cmdList.getServiceId());
            all.add(map);
        }
        cfg.put("commands", all);
        try {
            File f = new File(COMMAND_FILE);
            File backup = null;

            if (f.exists()) {
                backup = new File(COMMAND_FILE + "." + System.currentTimeMillis());
                if (!f.renameTo(backup)) {
                    throw new ControllerException("Unable to make backup of configuration file");
                }
                f = new File(COMMAND_FILE);
            }
            boolean success = false;
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

                writer.write((new JSONObject(cfg)).toString());
                writer.newLine();
                writer.flush();
                writer.close();
                success = true;
            } finally {
                if (!success && backup != null) {
                    //noinspection ResultOfMethodCallIgnored
                    backup.renameTo(f);
                }
            }
        } catch (IOException e) {
            throw new ControllerException("Unable to save command file: " + e.getMessage());
        }
    }
}

From source file:com.imaginary.home.controller.HomeController.java

private void saveConfiguration() throws ControllerException {
    ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
    HashMap<String, Object> cfg = new HashMap<String, Object>();

    cfg.put("name", name);
    for (HomeAutomationSystem sys : listSystems()) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("cname", sys.getClass().getName());
        json.put("id", sys.getId());
        json.put("authenticationProperties", sys.getAuthenticationProperties());
        json.put("customProperties", sys.getCustomProperties());
        all.add(json);//from   w w  w .  j  av a2s  .c  o m
    }
    cfg.put("systems", all);
    all = new ArrayList<Map<String, Object>>();
    for (CloudService service : cloudServices) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("id", service.getServiceId());
        json.put("name", service.getName());
        json.put("endpoint", service.getEndpoint());
        json.put("apiKeySecret", service.getApiKeySecret());
        if (service.getProxyHost() != null) {
            json.put("proxyHost", service.getProxyHost());
            json.put("proxyPort", service.getProxyPort());
        }
        all.add(json);
    }
    cfg.put("services", all);
    try {
        File f = new File(CONFIG_FILE);
        File backup = null;

        if (f.exists()) {
            backup = new File(CONFIG_FILE + "." + System.currentTimeMillis());
            if (!f.renameTo(backup)) {
                throw new ControllerException("Unable to make backup of configuration file");
            }
            f = new File(CONFIG_FILE);
        }
        boolean success = false;
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

            writer.write((new JSONObject(cfg)).toString());
            writer.newLine();
            writer.flush();
            writer.close();
            success = true;
        } finally {
            if (!success && backup != null) {
                //noinspection ResultOfMethodCallIgnored
                backup.renameTo(f);
            }
        }
    } catch (IOException e) {
        throw new ControllerException("Unable to save configuration: " + e.getMessage());
    }
}