List of usage examples for java.util Formatter close
public void close()
From source file:org.kalypso.kalypsomodel1d2d.sim.SwanResultProcessor.java
private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) { final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile); if (lShiftPosition == null) return;/*from w w w . ja v a 2 s . c om*/ try { // FIXME: why?! should never happen...! if (swanResOutTabFile.isContentOpen()) swanResOutTabFile.close(); final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent() .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$ swanResOutTabFile.moveTo(swanResOutTabFileBackUp); final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream(); final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US); final BufferedReader lInDataStream = new BufferedReader( new InputStreamReader(swanResOutTabFileBackUp.getContent().getInputStream())); while (lInDataStream.ready()) { final String lStrTmpLine = lInDataStream.readLine().trim(); if (lStrTmpLine.startsWith("%")) //$NON-NLS-1$ { lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$ continue; } final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$ int lIntTokenCounter = 0; String lStrNewLine = ""; //$NON-NLS-1$ while (lStrTokenizer.hasMoreTokens()) { final String lStrToken = lStrTokenizer.nextToken(); if (lIntTokenCounter == 1) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX()); } else if (lIntTokenCounter == 2) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY()); } else { lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$ } lIntTokenCounter++; } lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$ } // FIXME: not closed in a save way! lFormatter.close(); lInDataStream.close(); lOutStream.close(); } catch (final Exception e) { // FIXME: this is no way to handle an error ! } }
From source file:net.sourceforge.fenixedu.domain.candidacyProcess.IndividualCandidacy.java
public void exportValues(final StringBuilder result) { Formatter formatter = new Formatter(result); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.candidacy"), getCandidacyExecutionInterval().getName()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.state"), getState().getLocalizedName()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.whenCreated"), getWhenCreated().toString("yyy-MM-dd")); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.candidacyDate"), getCandidacyDate().toString()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.responsible"), StringUtils.isEmpty(getResponsible()) ? StringUtils.EMPTY : getResponsible()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.notes"), StringUtils.isEmpty(getNotes()) ? StringUtils.EMPTY : getNotes()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.observations"), StringUtils.isEmpty(getObservations()) ? StringUtils.EMPTY : getObservations()); for (final Formation formation : getFormationsSet()) { formation.exportValues(result);/*w w w . ja va2s. c om*/ } formatter.close(); }
From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java
/** * Store cluster similarities in the database. * * @param sims the similarities to store * @param type the type of similarity/*from w w w . j a v a2 s .co m*/ */ private void storeClusterSimilarities(List<ClusterSimilarity> sims, ClusterSimilarityCalculator.SIM_TYPE type) { String format = "%d\t%d\t%f\t\'%s\'\t\'%s\'\n"; StringBuffer databuf = new StringBuffer(); Formatter formatter = new Formatter(databuf); if (sims.size() > 0) { String tabletype = ""; switch (type) { case IP: tabletype = "ip"; break; case DOMAINNAME: tabletype = "domainname"; break; } String tabDateStr = dateFormatTable.format(sims.get(0).getADate()); String copyQuery = "COPY cluster_" + tabletype + "_similarity_" + tabDateStr + " (cluster_id, candidate_cluster_id, " + "similarity, log_date, candidate_log_date ) FROM stdin;"; for (ClusterSimilarity s : sims) { formatter.format(format, s.getAClusterId(), s.getBClusterId(), s.getSim(), dateFormatStr.format(s.getADate()), dateFormatStr.format(s.getBDate())); } this.executeCopyIn(copyQuery, new StringReader(databuf.toString())); } formatter.close(); }
From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.logger.impl.DatabaseLoggerImpl.java
private static void writeDotNode(OutputStream gvoss, OutputStream gvos, Node node, String indent) throws IllegalFormatException, FormatterClosedException, IOException { StringBuilder sbSimple = new StringBuilder(); StringBuilder sbFull = new StringBuilder(); Formatter formatterSimple = null; Formatter formatterFull = null; try {/* ww w . j a va2s. c o m*/ formatterSimple = new Formatter(sbSimple); formatterFull = new Formatter(sbFull); Sender sender = node.getSender(); String senderIP = (sender == null) ? "" : "" + sender.getIp().getHostAddress() + ":" + sender.getPort(); String senderColor = (sender == null) ? colorFullNotOk : colorFullOk; Long nodeId = node.getId(); String nodeIP = node.getMainIp().getHostAddress().toString(); PositionUpdateMsg nodePU = node.getPositionUpdateMsg(); PositionUpdate nodePUMsg = (nodePU == null) ? null : nodePU.getPositionUpdateMsg(); String nodeSimpleColor = (nodePUMsg == null) ? colorSimpleNotOk : colorSimpleOk; String nodeColor = (nodePUMsg == null) ? colorFullNotOk : colorFullOk; String nodeShape = node.getClusterNodes().isEmpty() ? shapeNormal : shapeClusterLeader; String nodeName = getNodeNameOrIp(node); String url = (sender == null) ? "" : ", URL=\"http://" + sender.getIp().getHostAddress() + "\""; formatterSimple.format(dotNodeTemplateSimple, indent, nodeId, nodeShape, nodeSimpleColor, nodeName, url); if ((nodePUMsg == null) || (nodePUMsg.getPositionUpdateNodeIdType() == 4) || (nodePUMsg.getPositionUpdateNodeIdType() == 6)) { /* use IP variant */ formatterFull.format(dotNodeTemplateFullIp, indent, nodeId, nodeColor, nodeName, senderColor, senderIP, url); } else { /* use named variant */ formatterFull.format(dotNodeTemplateFull, indent, nodeId, nodeColor, nodeName, colorFullOk, nodeIP, senderColor, senderIP, url); } /* now write graph */ ClusterLeaderMsg nodeCL = node.getClusterLeaderMsg(); if (nodeCL != null) { formatterSimple.format("%s%s -> %s%n", indent, nodeId, nodeCL.getClusterLeaderNode().getId()); formatterFull.format("%s%s -> %s%n", indent, nodeId, nodeCL.getClusterLeaderNode().getId()); } gvoss.write(sbSimple.toString().getBytes(Constants.CHARSET_DEFAULT)); gvos.write(sbFull.toString().getBytes(Constants.CHARSET_DEFAULT)); } finally { if (formatterSimple != null) { formatterSimple.close(); formatterSimple = null; } if (formatterFull != null) { formatterFull.close(); formatterFull = null; } } }
From source file:org.mule.modules.box.BoxConnector.java
private String hash(InputStream content) { byte[] bytes = null; try {//from www. j a v a 2 s . c o m bytes = IOUtils.toByteArray(content); } catch (IOException e) { throw new RuntimeException("Error generating sha1 for content", e); } Formatter formatter = new Formatter(); try { for (byte b : bytes) { formatter.format("%02x", b); } return formatter.toString(); } finally { formatter.close(); } }
From source file:org.kalypso.kalypsomodel1d2d.sim.ResultManager.java
private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) { final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile); if (lShiftPosition == null) { return;//from ww w . j av a 2 s . com } try { if (swanResOutTabFile.isContentOpen()) { swanResOutTabFile.close(); } final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent() .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$ swanResOutTabFile.moveTo(swanResOutTabFileBackUp); // int lIntLinesCounter = 0; final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream(); final DataInputStream lInDataStream = new DataInputStream( swanResOutTabFileBackUp.getContent().getInputStream()); BufferedReader streamReader = new BufferedReader(new InputStreamReader(lInDataStream)); final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US); while (lInDataStream.available() != 0) { final String lStrTmpLine = streamReader.readLine().trim(); // ++lIntLinesCounter; if (lStrTmpLine.startsWith("%")) { //$NON-NLS-1$ lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$ continue; } final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$ int lIntTokenCounter = 0; String lStrNewLine = ""; //$NON-NLS-1$ while (lStrTokenizer.hasMoreTokens()) { final String lStrToken = lStrTokenizer.nextToken(); if (lIntTokenCounter == 1) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX()); } else if (lIntTokenCounter == 2) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY()); } else { lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$ } lIntTokenCounter++; } lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$ } lFormatter.close(); lInDataStream.close(); lOutStream.close(); } catch (final Exception e) { return; } return; }
From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java
/** * Calculates the cluster novelty feature for each cluster generated * on a specific run date.// w ww . j ava2 s .c om * * @param log_date the run date * @param window the number of days previous to use in feature calculation * @return a table of values where the keys are cluster ids and the values * are the feature values * @throws SQLException if there is an error calculating the feature values */ public Map<Integer, Double> calculateNoveltyFeature(Date log_date, int window) throws SQLException { HashMap<Integer, Double> retval = new HashMap<Integer, Double>(); ArrayList<Date> prevDates = getPrevDates(log_date, window); if (prevDates.size() > 0) { StringBuffer querybuf = new StringBuffer(); Formatter formatter = new Formatter(querybuf); String curdatestr = df.format(log_date); formatter.format(properties.getProperty(NOVELTY_QUERY1_1KEY), curdatestr, curdatestr, curdatestr, curdatestr); for (Date prevDate : prevDates) { formatter.format(" " + properties.getProperty(NOVELTY_QUERY1_2KEY) + " ", df.format(prevDate)); } formatter.format(properties.getProperty(NOVELTY_QUERY1_3KEY), curdatestr, curdatestr); ResultSet rs2 = null; Hashtable<Integer, Hashtable<String, Long>> new_resolved_ips = new Hashtable<Integer, Hashtable<String, Long>>(); try { rs2 = dbi.executeQueryWithResult(querybuf.toString()); while (rs2.next()) { int cluster_id = rs2.getInt(2); if (!new_resolved_ips.containsKey(cluster_id)) { new_resolved_ips.put(cluster_id, new Hashtable<String, Long>()); } String secondLevelDomainName = rs2.getString(1); long newips = rs2.getLong(3); Hashtable<String, Long> clustertable = new_resolved_ips.get(cluster_id); clustertable.put(secondLevelDomainName, newips); } } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } finally { if (rs2 != null && !rs2.isClosed()) { rs2.close(); } formatter.close(); } Hashtable<String, List<Integer>> numDays = new Hashtable<String, List<Integer>>(); for (Date prevDate : prevDates) { String prevDateStr = df.format(prevDate); querybuf = new StringBuffer(); formatter = new Formatter(querybuf); formatter.format(properties.getProperty(NOVELTY_QUERY2KEY), curdatestr, prevDateStr, curdatestr, prevDateStr); ResultSet rs3 = null; try { rs3 = dbi.executeQueryWithResult(querybuf.toString()); while (rs3.next()) { String sldn = rs3.getString(1); if (!numDays.containsKey(sldn)) { numDays.put(sldn, new ArrayList<Integer>()); } Date pd = rs3.getDate(2); DateTime start = new DateTime(pd.getTime()); DateTime end = new DateTime(log_date.getTime()); Days d = Days.daysBetween(start, end); int diffDays = d.getDays(); numDays.get(sldn).add(diffDays); } } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } finally { if (rs3 != null && !rs3.isClosed()) { rs3.close(); } formatter.close(); } } Hashtable<Integer, List<Float>> clusterValues = new Hashtable<Integer, List<Float>>(); for (int clusterID : new_resolved_ips.keySet()) { clusterValues.put(clusterID, new ArrayList<Float>()); Hashtable<String, Long> sldnValues = new_resolved_ips.get(clusterID); for (String sldn : sldnValues.keySet()) { if (numDays.keySet().contains(sldn)) { long newIPCount = sldnValues.get(sldn); float f = ((float) newIPCount) / Collections.max(numDays.get(sldn)); clusterValues.get(clusterID).add(f); } } } for (int clusterID : clusterValues.keySet()) { if (clusterValues.get(clusterID) == null) { //I dont think it is possible for this to ever be true retval.put(clusterID, null); } else { double sum = 0; for (double d : clusterValues.get(clusterID)) { sum += d; } double val = 0; if (clusterValues.get(clusterID).size() > 0) { val = sum / clusterValues.get(clusterID).size(); } retval.put(clusterID, val); } } } return retval; }
From source file:org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.java
private void prepareSteuerpoly() throws SimulationException { final File steuerFile = new File(m_tmpDir, "steuerpoly.ini"); //$NON-NLS-1$ try {// w w w.j a v a2 s .co m final double startStation = m_calculation.getStartStation().doubleValue(); final double endStation = m_calculation.getStartStation().doubleValue(); /* Polynomial Parameters */ final PolynomeProperties pps = m_calculation.getPolynomeProperties(); final int polynomialDeegree = pps.getDeegree(); final boolean ignoreOutlier = pps.getIgnoreOutlier(); final boolean isTripleForAll = pps.getTripleForAll(); final BigDecimal alphaLimit = pps.getAlphaLimit(); final TripleMode tripleMode = pps.getTripleMode(); final boolean autoSlopeDetection = tripleMode == TripleMode.slopeChange; final BigDecimal runoffSlope = pps.getRunoffSlope(); final BigDecimal areaSlope = pps.getAreaSlope(); final BigDecimal alphaSlope = pps.getAlphaSlope(); final BigDecimal weightSplinePoint = pps.getWeightSplinePoint(); // Programming Language C (PRC) locale in order to format with decimal '.' final Formatter formatter = new Formatter(steuerFile, Charset.defaultCharset().name(), Locale.PRC); formatter.format("Steuerdatei fuer die Polynomfunktionen je Profil%n"); //$NON-NLS-1$ formatter.format("-------------------------------------------------%n"); //$NON-NLS-1$ formatter.format("02 Lngsschnitt(Pfad) 01Eingang\\%s%n", QLANG_FILE_NAME); //$NON-NLS-1$ formatter.format("03 PolyGrad(2,3,4) %d%n", polynomialDeegree); //$NON-NLS-1$ formatter.format("04 DreiTeil(J/N) %1s%n", isTripleForAll ? "J" : "N"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ formatter.format("05 PolyReduce(J/N) J%n"); //$NON-NLS-1$ formatter.format("06 ProfIntervall(J/N) N%n"); //$NON-NLS-1$ formatter.format("07 StartProf(0000.0000) %.4f%n", startStation); //$NON-NLS-1$ formatter.format("08 EndProf(0000.0000) %.4f%n", endStation); //$NON-NLS-1$ formatter.format("09 AusgabeJeFunktion(J/N) J%n"); //$NON-NLS-1$ formatter.format("10 AusgabeWspWerte(J/N) J%n"); //$NON-NLS-1$ formatter.format("11 AusgabeKontrolle(J/N) J%n"); //$NON-NLS-1$ formatter.format("12 AusgabeFile(Pfad) 02Ausgang\\%n"); //$NON-NLS-1$ formatter.format("13 Ausreisser(J/N) %1s%n", ignoreOutlier ? "J" : "N"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ formatter.format("14 Impulsstrom(00.0000) %.4f%n", alphaLimit); //$NON-NLS-1$ formatter.format("15 AutoSteigung(J/N) %1s%n", autoSlopeDetection ? "J" : "N"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ formatter.format("16 Q_Steigung(00.0000) %.4f%n", runoffSlope); //$NON-NLS-1$ formatter.format("17 A_Steigung(00.0000) %.4f%n", areaSlope); //$NON-NLS-1$ formatter.format("18 Alp_Steigung(00.0000) %.4f%n", alphaSlope); //$NON-NLS-1$ formatter.format("19 WichtungSplinePkt(0000.00) %.2f%n", weightSplinePoint); //$NON-NLS-1$ formatter.close(); FormatterUtils.checkIoException(formatter); } catch (final IOException e) { throw new SimulationException( Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.16"), e); //$NON-NLS-1$ } finally { } }
From source file:com.diablominer.DiabloMiner.NetworkState.JSONRPCNetworkState.java
boolean doSendWorkMessage(WorkState workState) throws IOException { StringBuilder dataOutput = new StringBuilder(8 * 32 + 1); Formatter dataFormatter = new Formatter(dataOutput); int[] data = workState.getData(); dataFormatter.format(//from ww w. ja va 2 s . co m "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x" + "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", Integer.reverseBytes(data[0]), Integer.reverseBytes(data[1]), Integer.reverseBytes(data[2]), Integer.reverseBytes(data[3]), Integer.reverseBytes(data[4]), Integer.reverseBytes(data[5]), Integer.reverseBytes(data[6]), Integer.reverseBytes(data[7]), Integer.reverseBytes(data[8]), Integer.reverseBytes(data[9]), Integer.reverseBytes(data[10]), Integer.reverseBytes(data[11]), Integer.reverseBytes(data[12]), Integer.reverseBytes(data[13]), Integer.reverseBytes(data[14]), Integer.reverseBytes(data[15]), Integer.reverseBytes(data[16]), Integer.reverseBytes(data[17]), Integer.reverseBytes(data[18]), Integer.reverseBytes(data[19]), Integer.reverseBytes(data[20]), Integer.reverseBytes(data[21]), Integer.reverseBytes(data[22]), Integer.reverseBytes(data[23]), Integer.reverseBytes(data[24]), Integer.reverseBytes(data[25]), Integer.reverseBytes(data[26]), Integer.reverseBytes(data[27]), Integer.reverseBytes(data[28]), Integer.reverseBytes(data[29]), Integer.reverseBytes(data[30]), Integer.reverseBytes(data[31])); ObjectNode sendWorkMessage = mapper.createObjectNode(); sendWorkMessage.put("method", "getwork"); ArrayNode params = sendWorkMessage.putArray("params"); params.add(dataOutput.toString()); sendWorkMessage.put("id", 1); JsonNode responseMessage = doJSONRPCCall(false, sendWorkMessage); boolean accepted; dataFormatter.close(); try { accepted = responseMessage.getBooleanValue(); } catch (Exception e) { throw new IOException("Bitcoin returned unparsable JSON"); } return accepted; }
From source file:org.kalypso.kalypsomodel1d2d.conv.SWANAdditionalDataConverter.java
private void writeCurrentSeriesFile(final Date pDate, final FileObject modelCurrentFileSerie) { Formatter lFormatterCurrent = null; // put first the Y component of current into buffer to write it out after X-component according to SWAN formating // rules/* ww w .j ava2s . co m*/ final StringBuffer lStrBuffY = new StringBuffer(); try { final List<INodeResult> lListActResults = m_resultsSimpleHandler.getResultsForDate(pDate); lFormatterCurrent = new Formatter(modelCurrentFileSerie.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); if (lListActResults == null) { // TODO: debug output... return; } final double lDoubleExclNr = Double.parseDouble(ISimulation1D2DConstants.SIM_SWAN_EXCLUSION_NUMBER); for (final INodeResult lResultAct : lListActResults) { if (lDoubleExclNr != lResultAct.getWaterlevel()) { try { final List<Double> lListDoubleVelocity = lResultAct.getVelocity();// AbsoluteVelocity(); lFormatterCurrent.format("%.2f\n", lListDoubleVelocity.get(0)); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%.2f\n", lListDoubleVelocity.get(1))); //$NON-NLS-1$ } catch (final Exception e) { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } else { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } lFormatterCurrent.format("%s\n", lStrBuffY.toString()); //$NON-NLS-1$ FormatterUtils.checkIoException(lFormatterCurrent); } catch (final Exception e) { e.printStackTrace(); } finally { if (lFormatterCurrent != null) { // REMARK: do not check io-exception here, else other exception would be hidden by this on lFormatterCurrent.close(); } } }