List of usage examples for java.io BufferedWriter flush
public void flush() throws IOException
From source file:ml.shifu.shifu.util.CommonUtils.java
public static void writeFeatureImportance(String fiPath, Map<Integer, MutablePair<String, Double>> importances) throws IOException { ShifuFileUtils.createFileIfNotExists(fiPath, SourceType.LOCAL); BufferedWriter writer = null; log.info("Writing feature importances to file {}", fiPath); try {/* www . j av a 2s . c om*/ writer = ShifuFileUtils.getWriter(fiPath, SourceType.LOCAL); writer.write("column_id\t\tcolumn_name\t\timportance"); writer.newLine(); for (Map.Entry<Integer, MutablePair<String, Double>> entry : importances.entrySet()) { String content = entry.getKey() + "\t\t" + entry.getValue().getKey() + "\t\t" + entry.getValue().getValue(); writer.write(content); writer.newLine(); } writer.flush(); } finally { IOUtils.closeQuietly(writer); } }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
public boolean logout(String server_url) { if (isEmpty(server_url)) { Logd(TAG, "revokSite no server url"); return false; }/*from w ww .ja v a 2 s .c om*/ if (!server_url.endsWith("/")) server_url += "/"; // get end session endpoint String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url); if (isEmpty(end_session_endpoint)) { Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url); return false; } // set up connection HttpURLConnection huc = getHUC(end_session_endpoint); huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("Logout", "url: " + end_session_endpoint); Logd("Logout", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "Logout response: " + responseCode); // if 200 - OK if (responseCode == 200) { return true; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
String refreshToken(String refresh_token) { // android.os.Debug.waitForDebugger(); // check initialization if (mOcp == null || isEmpty(mOcp.m_server_url)) return null; // nothing to do if (isEmpty(refresh_token)) return null; String postUrl = mOcp.m_server_url + "token"; // set up connection HttpURLConnection huc = getHUC(postUrl); huc.setDoOutput(true);/*from w w w . j a v a 2 s . c o m*/ huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7); nameValuePairs.add(new BasicNameValuePair("client_id", mOcp.m_client_id)); nameValuePairs.add(new BasicNameValuePair("client_secret", mOcp.m_client_secret)); nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token)); if (!isEmpty(mOcp.m_scope)) nameValuePairs.add(new BasicNameValuePair("scope", mOcp.m_scope)); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("refreshToken", "url: " + postUrl); Logd("refreshToken", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "refreshToken response: " + responseCode); // if 200 - OK, read the json string if (responseCode == 200) { sysout("refresh_token - code " + responseCode); InputStream is = huc.getInputStream(); String result = convertStreamToString(is); is.close(); huc.disconnect(); Logd("refreshToken", "result: " + result); sysout("refresh_token - content: " + result); return result; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:json_to_xml_1.java
public int execute(String args[]) throws ProgramTerminationException { this.getInfoMessages().clear(); if (args.length < 2) { throw constructTermination("messageArgumentsMissing", null, getI10nString("messageArgumentsMissingUsage") + "\n\tjson_to_xml_1 " + getI10nString("messageParameterList") + "\n"); }//from ww w . ja v a2 s .co m File resultInfoFile = new File(args[1]); try { resultInfoFile = resultInfoFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } if (resultInfoFile.exists() == true) { if (resultInfoFile.isFile() == true) { if (resultInfoFile.canWrite() != true) { throw constructTermination("messageResultInfoFileIsntWritable", null, null, resultInfoFile.getAbsolutePath()); } } else { throw constructTermination("messageResultInfoPathIsntAFile", null, null, resultInfoFile.getAbsolutePath()); } } json_to_xml_1.resultInfoFile = resultInfoFile; File jobFile = new File(args[0]); try { jobFile = jobFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } if (jobFile.exists() != true) { throw constructTermination("messageJobFileDoesntExist", null, null, jobFile.getAbsolutePath()); } if (jobFile.isFile() != true) { throw constructTermination("messageJobPathIsntAFile", null, null, jobFile.getAbsolutePath()); } if (jobFile.canRead() != true) { throw constructTermination("messageJobFileIsntReadable", null, null, jobFile.getAbsolutePath()); } System.out.println("json_to_xml_1: " + getI10nStringFormatted("messageCallDetails", jobFile.getAbsolutePath(), resultInfoFile.getAbsolutePath())); File inputFile = null; File outputFile = null; try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); InputStream in = new FileInputStream(jobFile); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); while (eventReader.hasNext() == true) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement() == true) { String tagName = event.asStartElement().getName().getLocalPart(); if (tagName.equals("json-input-file") == true) { StartElement inputFileElement = event.asStartElement(); Attribute pathAttribute = inputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String inputFilePath = pathAttribute.getValue(); if (inputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } inputFile = new File(inputFilePath); if (inputFile.isAbsolute() != true) { inputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + inputFilePath); } try { inputFile = inputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.exists() != true) { throw constructTermination("messageInputFileDoesntExist", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.isFile() != true) { throw constructTermination("messageInputPathIsntAFile", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.canRead() != true) { throw constructTermination("messageInputFileIsntReadable", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } } else if (tagName.equals("xml-output-file") == true) { StartElement outputFileElement = event.asStartElement(); Attribute pathAttribute = outputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String outputFilePath = pathAttribute.getValue(); if (outputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } outputFile = new File(outputFilePath); if (outputFile.isAbsolute() != true) { outputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + outputFilePath); } try { outputFile = outputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (outputFile.exists() == true) { if (outputFile.isFile() == true) { if (outputFile.canWrite() != true) { throw constructTermination("messageOutputFileIsntWritable", null, null, outputFile.getAbsolutePath()); } } else { throw constructTermination("messageOutputPathIsntAFile", null, null, outputFile.getAbsolutePath()); } } } } } } catch (XMLStreamException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (SecurityException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } if (inputFile == null) { throw constructTermination("messageJobFileNoInputFile", null, null, jobFile.getAbsolutePath()); } if (outputFile == null) { throw constructTermination("messageJobFileNoOutputFile", null, null, jobFile.getAbsolutePath()); } StringBuilder stringBuilder = new StringBuilder(); try { JSONObject json = new JSONObject(new JSONTokener(new BufferedReader(new FileReader(inputFile)))); stringBuilder.append(XML.toString(json)); } catch (Exception ex) { throw constructTermination("messageConversionError", ex, null, inputFile.getAbsolutePath()); } try { BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write( "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n"); writer.write(stringBuilder.toString()); writer.flush(); writer.close(); } catch (FileNotFoundException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (UnsupportedEncodingException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } return 0; }
From source file:com.hypersocket.client.hosts.HostsFileManager.java
private void writeFile(File file, boolean outputAliases) throws IOException { // Load the latest content first in case user added entries loadFile(false);//w w w. ja v a 2s.c om FileOutputStream out = new FileOutputStream(file); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); try { for (String host : content) { if (StringUtils.isBlank(host)) { continue; } writer.write(host); writer.write(System.getProperty("line.separator")); } if (outputAliases) { writer.write(BEGIN); writer.write(System.getProperty("line.separator")); writer.write("# WARNING: These are dynamic hosts added by a Hypersocket product"); writer.write(System.getProperty("line.separator")); for (Map.Entry<String, String> host : staticAlias.entrySet()) { writer.write(host.getValue() + " " + host.getKey()); writer.write(System.getProperty("line.separator")); } for (Map.Entry<String, String> host : hostsToLoopbackAlias.entrySet()) { writer.write(host.getValue() + " " + host.getKey()); writer.write(System.getProperty("line.separator")); } } writer.flush(); } finally { writer.close(); } }
From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java
public static void outputConfusionMatrix(TransducerEvaluator eval, File fileConfusionMatrix) throws IOException { BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileConfusionMatrix), "UTF-8")); ArrayList<String> labelNames = ((PerClassEvaluator) eval).getLabelNames(); int numLabels = labelNames.size(); HashMap<String, Integer> labelNameToIndexMap = new HashMap<String, Integer>(); for (int i = 0; i < numLabels; i++) { labelNameToIndexMap.put(labelNames.get(i), i); }/*from ww w . ja v a 2 s .c o m*/ ArrayList<String> goldLabels = ((PerClassEvaluator) eval).getGoldLabels(); ArrayList<String> predictedLabels = ((PerClassEvaluator) eval).getPredictedLabels(); Integer[][] confusionMatrix = new Integer[numLabels][numLabels]; //initialize to 0 for (int i = 0; i < confusionMatrix.length; i++) { for (int j = 0; j < confusionMatrix.length; j++) { confusionMatrix[i][j] = 0; } } for (int i = 0; i < goldLabels.size(); i++) { confusionMatrix[labelNameToIndexMap.get(goldLabels.get(i))][labelNameToIndexMap .get(predictedLabels.get(i))]++; } String[][] confusionMatrixString = new String[numLabels + 1][numLabels + 1]; confusionMatrixString[0][0] = " "; for (int i = 1; i < numLabels + 1; i++) { confusionMatrixString[i][0] = labelNames.get(i - 1) + "_actual"; confusionMatrixString[0][i] = labelNames.get(i - 1) + "_predicted"; } for (int i = 1; i < numLabels + 1; i++) { for (int j = 1; j < numLabels + 1; j++) { confusionMatrixString[i][j] = confusionMatrix[i - 1][j - 1].toString(); } } for (String[] element : confusionMatrixString) { bw.write(StringUtils.join(element, ",")); bw.write("\n"); bw.flush(); } bw.close(); }
From source file:de.micromata.genome.util.collections.OrderedProperties.java
/** * Store0./* w w w . j av a2 s .com*/ * * @param bw the bw * @param comments the comments * @param escUnicode the esc unicode * @param replacer the replacer * @throws RuntimeIOException the runtime io exception */ private void store0(BufferedWriter bw, String comments, boolean escUnicode, KeyValueReplacer replacer) throws RuntimeIOException { if (comments != null) { PropertiesReadWriter.writeComments(bw, comments); } try { bw.write("#" + new Date().toString()); bw.newLine(); for (Map.Entry<String, String> me : entrySet()) { String key = me.getKey(); String val = me.getValue(); if (replacer != null) { Pair<String, String> p = replacer.replace(Pair.make(key, val), this); if (p == null) { continue; } key = p.getKey(); val = p.getValue(); } key = PropertiesReadWriter.saveConvert(key, true, escUnicode, true); /* * No need to escape embedded and trailing spaces for value, hence pass false to flag. */ val = PropertiesReadWriter.saveConvert(val, false, escUnicode, false); bw.write(key + "=" + val); bw.newLine(); } bw.flush(); } catch (IOException ex) { throw new RuntimeIOException(ex); } }
From source file:gtu._work.ui.SqlCreaterUI.java
private void executeBtnPreformed() { try {/*from w w w . j a va 2 s .co 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); } }
From source file:com.egt.ejb.toolkit.ToolKitSessionBean.java
private void copyfile(File sourceFile, File targetFile, Map replacements) { if (sourceFile.getName().endsWith(".")) { } else if (sourceFile.getName().endsWith(".gif")) { } else if (sourceFile.getName().endsWith(".jpg")) { } else {//from w w w . j av a 2s. co m // Bitacora.trace(this.getClass(), "copyfile-source", sourceFile.getAbsolutePath(), sourceFile.getName()); // Bitacora.trace(this.getClass(), "copyfile-target", targetFile.getAbsolutePath(), targetFile.getName()); try { FileOutputStream fos; try (FileInputStream fis = new FileInputStream(sourceFile)) { InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); fos = new FileOutputStream(targetFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); int escapeRule = getEscapeRule(sourceFile.getName()); String line; while ((line = br.readLine()) != null) { line = replaceStrings(line, replacements, escapeRule); bw.write(line); bw.newLine(); bw.flush(); } } fos.close(); } catch (FileNotFoundException ex) { // System.out.println(ThrowableUtils.getString(ex)); Bitacora.logFatal(ThrowableUtils.getString(ex)); } catch (IOException ex) { // System.out.println(ThrowableUtils.getString(ex)); Bitacora.logFatal(ThrowableUtils.getString(ex)); } } }
From source file:com.trackplus.ddl.DataReader.java
public static void writeDataToSql(DatabaseInfo databaseInfo, String dirName) throws DDLException { LOGGER.info("Exporting SQL data from \"" + databaseInfo.getUrl() + "\" ..."); Map<String, String> info = new TreeMap<String, String>(); java.util.Date d1 = new java.util.Date(); info.put("start", d1.toString()); info.put("driver", databaseInfo.getDriver()); info.put("url", databaseInfo.getUrl()); info.put("user", databaseInfo.getUser()); info.put("user", databaseInfo.getUser()); info.put("usePassword", Boolean.toString(databaseInfo.getPassword() != null)); String databaseType = MetaDataBL.getDatabaseType(databaseInfo.getUrl()); info.put(DATABASE_TYPE, databaseType); Connection connection = getConnection(databaseInfo); //log the database meta data information's logDatabaseMetaDataInfo(databaseInfo, connection); String[] versions = MetaDataBL.getVersions(connection); info.put(SYSTEM_VERSION, versions[0]); info.put(DB_VERSION, versions[1]);//from ww w. j a va 2 s . co m StringValueConverter stringValueConverter = new GenericStringValueConverter(); BufferedWriter writer = createBufferedWriter(dirName + File.separator + FILE_NAME_DATA); BufferedWriter writerUpdate = createBufferedWriter(dirName + File.separator + FILE_NAME_DATA_UPDATE); BufferedWriter writerClean = createBufferedWriter(dirName + File.separator + FILE_NAME_DATA_CLEAN); BufferedWriter writerUpdateClean = createBufferedWriter( dirName + File.separator + FILE_NAME_DATA_UPDATE_CLEAN); BufferedWriter writerBlob = createBufferedWriter(dirName + File.separator + FILE_NAME_BLOB); int idx = 0; String[] tableNames = MetaDataBL.getTableNames(); for (String tableName : tableNames) { LOGGER.debug("Processing table: " + tableName + "...."); int count = getTableData(writer, writerClean, writerUpdate, writerUpdateClean, connection, tableName, stringValueConverter); info.put("_" + tableName, count + ""); LOGGER.debug("Records exported:" + count + "\n"); idx = idx + count; } LOGGER.debug("Processing blob data ...."); int count = getBlobTableData(writerBlob, connection); LOGGER.debug(" Blob record exported:" + count + "\n"); info.put("table_BLOB", count + ""); idx = idx + count; try { char dataSeparator = (char) ASCII_DATA_SEPARATOR; writerBlob.write(dataSeparator); writerBlob.newLine(); writerBlob.newLine(); writerBlob.write("--TMSPROJECTEXCHANGE"); writerBlob.newLine(); } catch (IOException e) { LOGGER.error("Error on close blob stream file :" + e.getMessage()); throw new DDLException(e.getMessage(), e); } LOGGER.debug("Processing clob data ...."); count = getClobTableData(writerBlob, connection); LOGGER.debug(" Clob record exported:" + count + "\n"); info.put("table_TMSPROJECTEXCHANGE", count + ""); idx = idx + count; info.put("allData", idx + ""); try { writer.flush(); writer.close(); writerClean.flush(); writerClean.close(); writerUpdate.flush(); writerUpdate.close(); writerUpdateClean.flush(); writerUpdateClean.close(); writerBlob.flush(); writerBlob.close(); } catch (IOException e) { LOGGER.error("Error on close stream file: " + e.getMessage()); throw new DDLException(e.getMessage(), e); } try { connection.close(); } catch (SQLException e) { throw new DDLException(e.getMessage(), e); } java.util.Date d2 = new java.util.Date(); long timeSpend = d2.getTime() - d1.getTime(); info.put("timeSpend", Long.toString(timeSpend)); writeInfoToFile(info, dirName + File.separator + FILE_NAME_INFO); LOGGER.info("Data generated. All records found: " + idx + ". Time spend: " + timeSpend + " ms!"); }