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:org.openmrs.module.clinicalsummary.web.controller.utils.ExtendedDataGeneralController.java

@RequestMapping(method = RequestMethod.POST)
public void processRequest(final @RequestParam(required = true, value = "data") MultipartFile data,
        final @RequestParam(required = true, value = "conceptNames") String conceptNames,
        final HttpServletResponse response) throws IOException {

    List<Concept> concepts = new ArrayList<Concept>();
    for (String conceptName : StringUtils.splitPreserveAllTokens(conceptNames, ",")) {
        Concept concept = Context.getConceptService().getConcept(conceptName);
        if (concept != null)
            concepts.add(concept);/*  w  w w. jav  a 2 s .  co  m*/
    }

    PatientService patientService = Context.getPatientService();
    PatientSetService patientSetService = Context.getPatientSetService();

    File identifierData = File.createTempFile(STUDY_DATA, INPUT_PREFIX);
    OutputStream identifierDataStream = new BufferedOutputStream(new FileOutputStream(identifierData));
    FileCopyUtils.copy(data.getInputStream(), identifierDataStream);

    File extendedData = File.createTempFile(STUDY_DATA, OUTPUT_PREFIX);
    BufferedWriter writer = new BufferedWriter(new FileWriter(extendedData));

    String line;
    BufferedReader reader = new BufferedReader(new FileReader(identifierData));
    while ((line = reader.readLine()) != null) {
        Patient patient = null;
        if (isDigit(StringUtils.trim(line)))
            patient = patientService.getPatient(NumberUtils.toInt(line));
        else {
            Cohort cohort = patientSetService.convertPatientIdentifier(Arrays.asList(line));
            for (Integer patientId : cohort.getMemberIds()) {
                Patient cohortPatient = patientService.getPatient(patientId);
                if (cohortPatient != null && !cohortPatient.isVoided())
                    patient = cohortPatient;
            }
        }

        if (patient != null) {
            ExtendedData extended = new ExtendedData(patient, null);
            extended.setEncounters(searchEncounters(patient));
            for (Concept concept : concepts)
                extended.addObservations(concept, searchObservations(patient, concept));
            writer.write(extended.generatePatientData());
            writer.newLine();

            ResultCacheInstance.getInstance().clearCache(patient);
        } else {
            writer.write("Unresolved patient id or patient identifier for " + line);
            writer.newLine();
        }
    }
    reader.close();
    writer.close();

    InputStream inputStream = new BufferedInputStream(new FileInputStream(extendedData));

    response.setHeader("Content-Disposition", "attachment; filename=" + data.getName());
    response.setContentType("text/plain");
    FileCopyUtils.copy(inputStream, response.getOutputStream());
}

From source file:mase.stat.MasterTournament.java

private void logResults(List<PersistentSolution>[] solutions, List<EvaluationResult[]>[] subpopEvals,
        String outPath) throws Exception {
    // Log results
    File log = new File(outPath + "comp" + name + ".stat");
    BufferedWriter bfw = new BufferedWriter(new FileWriter(log));
    float[] bestFar = new float[] { Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY };
    for (int g = 0; g < subpopEvals[0].size(); g++) {
        bfw.write(g + "");
        for (int s = 0; s < 2; s++) {
            EvaluationResult[] er = subpopEvals[s].get(g);
            // assumes fitness evaluation is in first index
            float fit = (Float) (((CompoundEvaluationResult) er[0]).getEvaluation(s).value());
            // assumes behaviour evaluation is in second index
            BehaviourResult br = null;/*  ww  w.  j a v a2 s.  c o m*/
            if (er[1] instanceof CompoundEvaluationResult) {
                br = (BehaviourResult) ((CompoundEvaluationResult) er[1]).getEvaluation(s);
            } else {
                br = (BehaviourResult) er[1];
            }
            bestFar[s] = Math.max(bestFar[s], fit);
            bfw.write(" " + fit + " " + bestFar[s] + " " + br.toString());
        }
        bfw.newLine();
    }
    bfw.close();

    // Persist the most interesting challenge
    PersistentSolution best0 = solutions[0].get(bestIndex(subpopEvals[0], 0));
    PersistentSolution best1 = solutions[1].get(bestIndex(subpopEvals[1], 1));
    HeterogeneousGroupController hc0 = (HeterogeneousGroupController) best0.getController();
    HeterogeneousGroupController hc1 = (HeterogeneousGroupController) best1.getController();
    HeterogeneousGroupController newC = new HeterogeneousGroupController(
            new AgentController[] { hc0.getAgentControllers(2)[0], hc1.getAgentControllers(2)[1] });
    CompoundEvaluationResult ser = new CompoundEvaluationResult(new FitnessResult(bestFar[0]),
            new FitnessResult(bestFar[1]));
    PersistentSolution sol = new PersistentSolution();
    sol.setController(newC);
    sol.setEvalResults(new EvaluationResult[] { ser });
    File superBest = new File(outPath + "challenge" + name + ".xml");
    SolutionPersistence.writeSolution(sol, superBest);
}

From source file:analytics.storage.store2csv.java

@Override
public void storeRepositoryData(String repoName, int noRecords, float avgFSize, float storageReq,
        float informativeness, String schema) {
    // TODO Auto-generated method stub

    ConfigureLogger conf = new ConfigureLogger();

    String sFileName = repoName + "_GeneralInfo" + ".csv";

    Properties props = new Properties();
    try {/*from  www  .  ja  v  a 2  s  . c  om*/
        props.load(new FileInputStream("configure.properties"));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        System.exit(-1);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        System.exit(-1);
    }
    ;
    File anls = new File(props.getProperty(AnalyticsConstants.resultsPath) + "Analysis_Results");

    if (!anls.exists())
        anls.mkdir();

    File dir = new File(anls, repoName);
    if (!dir.exists())
        dir.mkdir();

    File file = new File(dir, sFileName);

    Logger logger = conf.getLogger("generalInfo", anls + File.separator + "repoGeneralInfo.log");

    StringBuffer logString = new StringBuffer();

    this.setGeneralDataFilePath(file.getAbsolutePath());
    FileWriter writer;
    BufferedWriter bw = null;
    try {
        writer = new FileWriter(file);
        bw = new BufferedWriter(writer);
        // create header
        bw.append("Repository Name");
        bw.append(",");
        bw.append("Number of records");
        bw.append(",");
        bw.append("Average file size(bytes)");
        bw.append(",");
        bw.append("Approximate Storage requirements(bytes)");
        bw.append(",");
        bw.append("Repository Informativeness(bits)");
        bw.append(",");
        bw.append("Metadata schema namespace");
        bw.newLine();

        // insert data
        bw.append(repoName);
        logString.append(repoName);
        bw.append(",");
        bw.append(String.valueOf(noRecords));
        logString.append(" " + String.valueOf(noRecords));
        bw.append(",");
        bw.append(String.valueOf(avgFSize));
        logString.append(" " + String.valueOf(avgFSize));
        bw.append(",");
        bw.append(String.valueOf(storageReq));
        logString.append(" " + String.valueOf(storageReq));

        bw.append(",");
        bw.append(String.valueOf(informativeness));
        logString.append(" " + String.valueOf(informativeness));
        bw.append(",");
        bw.append(schema);
        logString.append(" " + schema);
        bw.close();

        logger.info(logString.toString());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

From source file:com.github.geequery.codegen.ast.JavaUnit.java

public void writeTo(BufferedWriter bw) throws IOException {
    prepareImports();// w  w w. j ava2  s . com
    if (StringUtils.isNotEmpty(packageName)) {
        bw.write("package ");
        bw.write(packageName);
        bw.write(COMMA);
        bw.newLine();
        bw.newLine();
    }
    if (addNotModifiedTag) {
        this.addImport(NotModified.class);
    }
    for (String cls : this.imports.values()) {
        if (StringUtils.isNotBlank(cls)) {
            bw.write("import ");
            bw.write(cls);
            bw.write(COMMA);
        }
        bw.newLine();
    }
    if (!this.importsStatic.isEmpty()) {
        for (String cls : this.importsStatic.values()) {
            bw.write("import static ");
            bw.write(cls);
            bw.write(COMMA);
            bw.newLine();
        }
        bw.newLine();
    }

    if (rawLinesBeforeTypeDef != null) {
        bw.write(rawLinesBeforeTypeDef.toCode(this));
    }

    if (comments != null && comments.size() > 0) {
        bw.write("/**\r\n");
        for (String s : comments) {
            bw.write(" * ");
            bw.write(s);
            bw.newLine();
        }
        bw.write(" */\r\n");
    }

    if (addNotModifiedTag) {
        bw.write("@NotModified\r\n");
    }
    if (annotations != null) {
        for (String s : annotations) {
            bw.write(s);
            bw.write("\r\n");
        }
    }
    if (this.isInterface) {
        bw.write("public interface " + this.unitName);
    } else {
        StringBuilder sb = new StringBuilder(64);
        appendModifier(sb, this.modifiers, false);
        sb.append("class " + this.unitName);
        bw.write(sb.toString());
    }
    if (typeParameters != null && typeParameters.length > 0) {
        bw.write("<");
        for (int n = 0; n < typeParameters.length; n++) {
            if (n > 0)
                bw.write(',');
            bw.write(typeParameters[n]);
        }
        bw.write(">");
    }
    if (this.extendsClass != null) {
        bw.write(" extends ");
        bw.write(this.getJavaClassName(extendsClass));
    }
    if (this.implementsInterface != null && implementsInterface.length > 0) {
        for (int i = 0; i < implementsInterface.length; i++) {
            implementsInterface[i] = this.getJavaClassName(implementsInterface[i]);
        }
        bw.write(" implements ");
        bw.write(StringUtils.join(implementsInterface, ","));
    }
    bw.write("{");
    bw.newLine();
    bw.newLine();
    // Fields
    if (fields.size() > 0) {
        for (JavaElement str : fields.values()) {
            if ((str instanceof JavaField) && ((JavaField) str).isStatic()) {
                String code = str.toCode(this);
                bw.write("\t");
                bw.write(code);
            }
        }
        bw.newLine();
        for (JavaElement str : fields.values()) {
            if ((str instanceof JavaField) && ((JavaField) str).isStatic()) {
            } else {
                String code = str.toCode(this);
                bw.write("\t");
                bw.write(code);
                bw.newLine();
            }
        }
    }
    // 
    if (!methods.isEmpty()) {
        for (JavaElement method : methods.values()) {
            bw.write("\t");
            bw.write(method.toCode(this));
            bw.newLine();
        }
    }

    if (!content.isEmpty()) {
        bw.newLine();
        // 
        for (String str : content) {
            // bw.write("\t");
            bw.write(str);
            bw.newLine();
        }
    }
    if (rawBlocks != null) {
        bw.newLine();
        for (JavaElement block : rawBlocks) {
            bw.write(block.toCode(this));
            bw.newLine();
        }
    }
    bw.write("}");
    bw.flush();
}

From source file:Evaluator.PerQueryRelDocs.java

public void storeKDE(String fileName) throws IOException {
    FileWriter fw = new FileWriter(new File(fileName));
    BufferedWriter bw = new BufferedWriter(fw);
    Iterator it = KDEValues.keySet().iterator();
    bw.write("#" + qrelno);
    bw.newLine();
    while (it.hasNext()) {
        String st = (String) it.next();
        bw.write(st + " " + KDEValues.get(st));
        bw.newLine();//w ww.j av a  2 s .  c o m

    }
    bw.close();
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

void appendLog(String fileName, String text, boolean clearFile) {
    File logFile = new File("sdcard/" + fileName);
    if (!logFile.exists()) {
        try {//  ww w  .j  a  v  a2s .  c  o  m
            logFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        if (clearFile) {
            logFile.delete();
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        //BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        buf.append(text);
        buf.newLine();
        buf.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:Evaluator.PerQueryRelDocs.java

public void writeCentroid(HashMap<String, Double> termMap, String fileName) throws IOException {
    FileWriter fw = new FileWriter(new File(fileName), true);
    BufferedWriter bw = new BufferedWriter(fw);
    Iterator it = termMap.keySet().iterator();
    ArrayList ar = new ArrayList();
    bw.write("#" + qrelno);
    bw.newLine();
    while (it.hasNext()) {
        String st = (String) it.next();
        bw.write(st + " " + termMap.get(st));
        bw.newLine();/*from   w  ww .  j  a  va  2 s . com*/
    }
    bw.close();
    fw.close();
}

From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java

public void writeData(OutputStream out, ServerRequest sr) throws DataAccessException {
    try {//  w w  w .j  a v a 2 s  . co  m
        TableServerRequest request = (TableServerRequest) sr;

        File inf = getDataFile(request);
        if (inf != null && inf.canRead()) {
            int rows = IpacTableUtil.getMetaInfo(inf).getRowCount();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            BufferedReader reader = new BufferedReader(new FileReader(inf), IpacTableUtil.FILE_IO_BUFFER_SIZE);

            prepareAttributes(rows, writer, sr);
            String s = reader.readLine();
            while (s != null) {
                if (!(s.startsWith("\\col.") || s.startsWith("\\Loading"))) { // ignore ALL system-use headers
                    if (s.startsWith("|") && getOutputColumnsMap() != null)
                        for (String key : getOutputColumnsMap().keySet()) {
                            s = s.replaceAll(key, getOutputColumnsMap().get(key));
                        }
                    writer.write(s);
                    writer.newLine();
                }
                s = reader.readLine();
            }
            writer.flush();
        } else {
            throw new DataAccessException("Data not accessible.  Check server log for errors.");
        }
    } catch (Exception e) {
        throw new DataAccessException(e);
    }
}

From source file:gtu._work.ui.SqlCreaterUI.java

private void executeBtnPreformed() {
    try {//w  w w .  j  a  v a  2 s .  c o m
        logArea.setText("");
        File srcFile = JCommonUtil.filePathCheck(excelFilePathText.getText(), "?", false);
        if (srcFile == null) {
            return;
        }
        if (!srcFile.getName().endsWith(".xlsx")) {
            JCommonUtil._jOptionPane_showMessageDialog_error("excel");
            return;
        }
        if (StringUtils.isBlank(sqlArea.getText())) {
            return;
        }
        File saveFile = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
        if (saveFile == null) {
            JCommonUtil._jOptionPane_showMessageDialog_error("?");
            return;
        }

        String sqlText = sqlArea.getText();

        StringBuffer sb = new StringBuffer();
        Map<Integer, String> refMap = new HashMap<Integer, String>();
        Pattern sqlPattern = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
        Matcher matcher = sqlPattern.matcher(sqlText);
        while (matcher.find()) {
            String val = StringUtils.trim(matcher.group(1)).toUpperCase();
            refMap.put(ExcelUtil.cellEnglishToPos(val), val);
            matcher.appendReplacement(sb, "\\$\\{" + val + "\\}");
        }
        matcher.appendTail(sb);
        appendLog(refMap.toString());

        sqlText = sb.toString();
        sqlArea.setText(sqlText);

        Configuration cfg = new Configuration();
        StringTemplateLoader stringTemplatge = new StringTemplateLoader();
        stringTemplatge.putTemplate("aaa", sqlText);
        cfg.setTemplateLoader(stringTemplatge);
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("aaa");

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(saveFile), "utf8"));

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(bis);
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
            Row row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            Map<String, Object> root = new HashMap<String, Object>();
            for (int index : refMap.keySet()) {
                root.put(refMap.get(index), formatCellType(row.getCell(index)));
            }
            appendLog(root.toString());

            StringWriter out = new StringWriter();
            temp.process(root, out);
            out.flush();
            String writeStr = out.getBuffer().toString();
            appendLog(writeStr);

            writer.write(writeStr);
            writer.newLine();
        }
        bis.close();

        writer.flush();
        writer.close();

        JCommonUtil._jOptionPane_showMessageDialog_info("? : \n" + saveFile);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}