List of usage examples for java.io BufferedWriter append
public Writer append(CharSequence csq) throws IOException
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Reads the appname file generated from tcpdump and appends the application * version next to each application ./*from ww w . jav a2 s. co m*/ * * @throws IOException */ private void writAppVersions() throws IOException { BufferedReader appNamesFileReader = null; BufferedWriter appNmesFileWriter = null; try { final String strTraceFolderName = mApp.getTcpDumpTraceFolderName(); Log.i(TAG, "Trace folder name is: " + strTraceFolderName); final File appNameFile = new File(mApp.getTcpDumpTraceFolderName() + APP_NAME_FILE); appNamesFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(appNameFile))); String processName = null; final List<String> appNamesWithVersions = new ArrayList<String>(); while ((processName = appNamesFileReader.readLine()) != null) { String versionNum = null; try { versionNum = getPackageManager().getPackageInfo(processName, 0).versionName; appNamesWithVersions.add(processName + " " + versionNum); } catch (NameNotFoundException e) { appNamesWithVersions.add(processName); Log.e(TAG, "Package name can not be found; unable to get version number."); } catch (Exception e) { Log.e(TAG, "Unable to get version number "); } } appNmesFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(appNameFile))); final String eol = System.getProperty("line.separator"); for (String appNemeVersion : appNamesWithVersions) { appNmesFileWriter.append(appNemeVersion + eol); } } catch (IOException e) { Log.e(TAG, "Error occured while writing the version number for the applications"); } finally { if (appNamesFileReader != null) { appNamesFileReader.close(); } if (appNmesFileWriter != null) { appNmesFileWriter.close(); } } }
From source file:otn.mobile.bl.TrackServicesHandler.java
public OtnServiceTrackResponse addTracks(OtnServiceTrackRequest request) { //*********************** Variables *************************** OtnServiceTrackResponse response = new OtnServiceTrackResponse(); User users;/* ww w . j a v a 2 s . c o m*/ TransportType transport_type = null; Weather weather; WeatherType weather_type; Apps app = null; Source source = null; Track track = new Track(); Track subTracks; TrackRating track_rating; TrackRatingType track_rating_type; ArrayList<OtnServiceSubTracksResponse> trackList = new ArrayList<OtnServiceSubTracksResponse>(); ArrayList<OtnServiceWeatherRatings> weatherListparams = null; ArrayList<OtnServiceGeometryPoints> geometryPointsListparams = null; byte[] trackFileCsv = null; //************************* Action **************************** System.out.println("------------Start---------------"); try { //**********************find user***************************** users = em.find(User.class, request.getUserId()); if (users != null) { System.out.println("====================================="); System.out.println("user id " + users.getUserId()); } else { System.out.println("====================================="); System.out.println("user not found"); em.getTransaction().begin(); users = new User(); users.setUserId(request.getUserId()); em.persist(users); em.flush(); em.getTransaction().commit(); em.clear(); System.out.println("user created"); } //***********************find transportID****************************** if (request.getTransportId() != 0) { transport_type = em.find(TransportType.class, request.getTransportId()); if (transport_type != null) { System.out.println("====================================="); System.out.println("transport id " + transport_type.getTransportTypeId()); track.setTransportTypeId(transport_type); } else { response.setMessage("transport type id does not exist"); response.setResponseCode(1); return response; } } //***********************find weatherID****************************** // if (request.getWeatherId() != 0) { // weather = em.find(WeatherType.class, request.getWeatherId()); // // if (weather != null) { // System.out.println("====================================="); // System.out.println("weather id " + weather.getWeatherId()); // // } else { // response.setMessage("weather condition id does not exist"); // response.setResponseCode(1); // return response; // } // } //***********************find app name****************************** if (request.getAppId() != 0) { app = em.find(Apps.class, request.getAppId()); if (app != null) { System.out.println("====================================="); System.out.println("app id " + app.getName()); track.setAppId(app); } else { response.setMessage("application does not exist"); response.setResponseCode(1); return response; } } //***********************find sourceId****************************** if (request.getSourceId() != 0) { source = em.find(Source.class, request.getSourceId()); if (source != null) { System.out.println("====================================="); System.out.println("source id " + source.getName()); track.setRouteSourceId(source); } else { response.setMessage("source type id does not exist"); response.setResponseCode(1); return response; } } //***************Create track record**************************** em.getTransaction().begin(); if (request.getName() != null) { track.setName(request.getName()); } else { track.setName(""); } track.setDescription(request.getDescription()); if (request.getPicture() != null) { track.setPicture(request.getPicture()); } track.setDistance(request.getDistance()); track.setDuration(request.getDuration()); track.setSpeed(request.getSpeed()); track.setElevation(request.getElevation()); if (request.getTrackFileCsv() != null) { // String csvFile = new String(request.getTrackFileCsv()); trackFileCsv = Base64.encodeBase64(request.getTrackFileCsv()); track.setTrackFileCsv(trackFileCsv); } track.setRouteKlm(request.getRoute_kml()); track.setLatStart(request.getLat_start()); track.setLongStart(request.getLon_start()); track.setLatEnd(request.getLat_end()); track.setLongEnd(request.getLon_end()); track.setCreationDate(new Date()); track.setDatetimeStart(request.getDatetime_start()); track.setDatetimeEnd(request.getDatetime_end()); track.setUserId(users); track.setIsPublic(request.isIs_public()); track.setStartAddress(request.getStart_address()); track.setEndAddress(request.getEnd_address()); if (request.getTrackRatings().size() > 0) { OtnServiceTrackResponse rate_response = checkTrackRateAndType(request.getTrackRatings()); if (rate_response.getResponseCode() == 0) { em.persist(track); em.flush(); em.getTransaction().commit(); em.clear(); for (OtnServicePoiRatings trackRatingList : request.getTrackRatings()) { em.getTransaction().begin(); track_rating = new TrackRating(); track_rating_type = em.find(TrackRatingType.class, trackRatingList.getRatingTypeId()); track_rating.setTrackId(track); track_rating.setTrackRatingTypeId(track_rating_type); track_rating.setRate(trackRatingList.getRate()); track_rating.setUserId(users); em.persist(track_rating); em.flush(); em.getTransaction().commit(); em.clear(); response.setMessage("success"); response.setResponseCode(0); } } else { response.setMessage(rate_response.getMessage()); response.setResponseCode(rate_response.getResponseCode()); return response; } } else { em.persist(track); em.flush(); em.getTransaction().commit(); em.clear(); response.setMessage("success"); response.setResponseCode(0); } //***********************find weatherID****************************** if (request.getWeatherList().size() > 0) { if (track.getTrackId() == 0) { em.persist(track); em.flush(); em.getTransaction().commit(); em.clear(); } weatherListparams = new ArrayList<OtnServiceWeatherRatings>(); for (OtnServiceWeatherRatings weatherList : request.getWeatherList()) { em.getTransaction().begin(); weather = new Weather(); weather_type = em.find(WeatherType.class, weatherList.getWeatherTypeId()); if (weather_type == null) { response.setMessage("weather id does not exist"); response.setResponseCode(1); return response; } weather.setTrackId(track); weather.setWeatherTypeId(weather_type); em.persist(weather); em.flush(); em.getTransaction().commit(); em.clear(); response.setMessage("success"); response.setResponseCode(0); weatherListparams.add(new OtnServiceWeatherRatings(weather_type.getWeatherId())); } response.setWeatherList(weatherListparams); } //***********************insert geometry points****************************** // insert startPoint List<OtnServiceGeometryPoints> startPointsList = new ArrayList<OtnServiceGeometryPoints>(); OtnServiceGeometryPoints startPoints = new OtnServiceGeometryPoints(); startPoints.setLatitude(request.getLat_start()); startPoints.setLongitude(request.getLon_start()); startPointsList.add(startPoints); // insert endPoint List<OtnServiceGeometryPoints> endPointsList = new ArrayList<OtnServiceGeometryPoints>(); OtnServiceGeometryPoints endPoints = new OtnServiceGeometryPoints(); endPoints.setLatitude(request.getLat_end()); endPoints.setLongitude(request.getLon_end()); endPointsList.add(endPoints); /** * decode csv String */ if (request.getTrackFileCsv() != null) { String trackFilecsvDecode = new String(request.getTrackFileCsv()); /** * write file to folder */ String urlfile = Base_url + System.currentTimeMillis() + ".csv"; BufferedWriter writer = new BufferedWriter(new FileWriter(urlfile)); writer.append(trackFilecsvDecode); writer.close(); // System.out.println("csv " + trackFilecsvDecode); // set delimeter CSVFormat format = CSVFormat.newFormat(';').withHeader(); //parse csv format String // log.info("1 "); CSVParser parser = new CSVParser(new StringReader(trackFilecsvDecode), format); List<OtnServiceGeometryPoints> geomPoints = new ArrayList<OtnServiceGeometryPoints>(); //parse records (in the example 2 records) List timestamp = new ArrayList<String>(); for (CSVRecord record : parser) { timestamp.add(record.get("Timestamp")); // System.out.println("latitude " + record.get("Latitude")); // System.out.println("Longitude " + record.get("Longitude")); // System.out.println("Timestamp " + record.get("Timestamp")); // log.info("2"); geomPoints.add(new OtnServiceGeometryPoints(Double.parseDouble(record.get("Latitude")), Double.parseDouble(record.get("Longitude")))); } // System.out.println("number " + total_records); // System.out.println("first time" + timestamp.get(0)); // System.out.println("end time" + timestamp.get(timestamp.size() - 1)); String start_date = timestamp.get(0).toString(); String end_date = timestamp.get(timestamp.size() - 1).toString(); parser.close(); // log.info("3"); // if (request.getGeometryPoints() != null) { // geomPoints = request.getGeometryPoints(); // // } insertGeometryPoints(track.getTrackId(), geomPoints, startPointsList, endPointsList, start_date, end_date, urlfile); } response.setName(track.getName()); response.setTrackId(track.getTrackId()); response.setDescription(track.getDescription()); response.setDistance(track.getDistance()); response.setDuration(track.getDuration()); if (transport_type != null) { response.setTransportName(transport_type.getName()); } response.setSpeed(track.getSpeed()); response.setElevation(track.getElevation()); response.setLat_start(track.getLatStart()); response.setLon_start(track.getLongStart()); response.setLat_end(track.getLatEnd()); response.setLon_end(track.getLongEnd()); response.setDatetime_start(track.getDatetimeStart()); response.setDatetime_end(track.getDatetimeEnd()); response.setUserId(users.getUserId()); response.setIs_public(track.getIsPublic()); response.setRoute_kml(track.getRouteKlm()); response.setTrackFileCsv(Base64.decodeBase64(track.getTrackFileCsv())); if (app != null) { response.setAppName(app.getName()); } response.setStart_address(track.getStartAddress()); response.setEnd_address(track.getEndAddress()); // if (weather != null) { // response.setWeatherCondition(weather.getCondition()); // } if (source != null) { response.setSourceName(source.getName()); } return response; // } } catch (Exception e) { e.printStackTrace(); response.setMessage("failure"); response.setResponseCode(2); } finally { return response; } }
From source file:org.ramadda.geodata.cdmdata.GridPointOutputHandler.java
/** * _more_//from w w w.j a v a 2 s. co m * * @param request _more_ * @param entry _more_ * @param gds _more_ * @param varNames _more_ * @param llp _more_ * @param dates _more_ * @param allDates _more_ * * @return _more_ * * @throws Exception _more_ */ private Result processPointRequest(Request request, Entry entry, GridDataset gds, List<String> varNames, LatLonPointImpl llp, CalendarDate[] dates, List<CalendarDate> allDates) throws Exception { double levelVal = request.get(ARG_LEVEL, Double.NaN); String format = request.getString(CdmConstants.ARG_FORMAT, SupportedFormat.NETCDF3.toString()); boolean doingJson = format.equals(FORMAT_JSON); if (doingJson) { format = FORMAT_CSV; request.setCORSHeaderOnResponse(); } SupportedFormat sf = getSupportedFormat(format); NcssParamsBean pdrb = new NcssParamsBean(); GridAsPointDataset gapds = NcssRequestUtils.buildGridAsPointDataset(gds, varNames); pdrb.setVar(varNames); // accept uses the response type pdrb.setAccept((format.equalsIgnoreCase(FORMAT_TIMESERIES_CHART) || format.equalsIgnoreCase(FORMAT_TIMESERIES_IMAGE)) ? SupportedFormat.CSV_STREAM.getResponseContentType() : sf.getResponseContentType()); //pdrb.setPoint(true); pdrb.setLatitude(llp.getLatitude()); pdrb.setLongitude(llp.getLongitude()); if (dates[0] != null) { pdrb.setTime_start(dates[0].toString()); if (dates[1] != null) { pdrb.setTime_end(dates[1].toString()); } else { pdrb.setTime(pdrb.getTime_start()); } } else { // dates weren't specified dates[0] = allDates.get(0); dates[1] = allDates.get(allDates.size() - 1); pdrb.setTemporal("all"); } if (levelVal == levelVal) { pdrb.setVertCoord(levelVal); } Map<String, List<String>> groupVars = groupVarsByVertLevels(gds, pdrb); String suffix = SUFFIX_NC; if (sf.equals(SupportedFormat.NETCDF4)) { suffix = SUFFIX_NC4; } else if (pdrb.getAccept().equals(SupportedFormat.CSV_STREAM.getResponseContentType()) || format.equals(FORMAT_TIMESERIES_CHART_DATA) || format.equals(FORMAT_TIMESERIES_IMAGE)) { suffix = SUFFIX_CSV; } else if (pdrb.getAccept().equals(SupportedFormat.XML_STREAM.getResponseContentType())) { suffix = SUFFIX_XML; } String baseName = IOUtil.stripExtension(entry.getName()); if (format.equalsIgnoreCase(FORMAT_TIMESERIES_CHART)) { request.put(CdmConstants.ARG_FORMAT, FORMAT_JSON); request.put(ARG_LATITUDE, "_LATITUDEMACRO_"); request.put(ARG_LONGITUDE, "_LONGITUDEMACRO_"); StringBuffer html = new StringBuffer(); getPageHandler().entrySectionOpen(request, entry, html, "Time Series", true); html.append(getWikiManager().getStandardChartDisplay(request, entry)); getPageHandler().entrySectionClose(request, entry, html); return new Result("Point as Grid Time Series", html); } File tmpFile = getStorageManager().getTmpFile(request, "pointsubset" + suffix); OutputStream outStream = getStorageManager().getUncheckedFileOutputStream(tmpFile); DiskCache2 dc = getCdmManager().getDiskCache2(); PointDataStream pds = PointDataStream.factory(sf, outStream, dc); List<CalendarDate> wantedDates = NcssRequestUtils.wantedDates(gapds, CalendarDateRange.of(dates[0], dates[1]), 0); boolean allWritten = false; allWritten = pds.stream(gds, llp, wantedDates, groupVars, pdrb.getVertCoord()); File f = null; if (allWritten) { outStream.close(); f = tmpFile; if (doingJson) { File jsonFile = getRepository().getStorageManager().getTmpFile(request, "subset.json"); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile))); List<RecordField> fields = new ArrayList<RecordField>(); for (int i = 0; i < varNames.size(); i++) { String var = (String) varNames.get(i); RecordField recordField = new RecordField(var, var, var, i, ""); recordField.setChartable(true); fields.add(recordField); } RecordField.addJsonHeader(bw, entry.getName(), fields, false, false, false); String line = null; int cnt = 0; boolean hasVertical = (pdrb.getVertCoord() != null); // System.err.println ("has vert:" + hasVertical); // System.err.println ("vars:" + varNames.size() +" " + varNames); while ((line = br.readLine()) != null) { cnt++; List<String> toks = StringUtil.split(line, ",", true, true); if (cnt == 1) { // System.err.println ("line:" + line); //time/lat/lon maybeZ vars if (toks.size() == 3 + 1 + varNames.size()) { hasVertical = true; } continue; } if (cnt > 2) { bw.append(","); } bw.append("\n"); bw.append(Json.mapOpen()); // date lat lon alt value(s) // 2009-11-10T00:00:00Z,34.6,-101.1,100.0,207.89999389648438 CalendarDate date = CalendarDate.parseISOformat(toks.get(0), toks.get(0)); double lat = Double.parseDouble(toks.get(1)); double lon = Double.parseDouble(toks.get(2)); double alt = (hasVertical ? Double.parseDouble(toks.get(3)) : Double.NaN); Json.addGeolocation(bw, lat, lon, alt); bw.append(","); bw.append(Json.attr(Json.FIELD_DATE, date.getMillis())); bw.append(","); bw.append(Json.mapKey(Json.FIELD_VALUES)); int startIdx = (hasVertical ? 4 : 3); List<String> values = new ArrayList(); for (int i = startIdx; i < toks.size(); i++) { double v = Double.parseDouble(toks.get(i)); values.add(Json.formatNumber(v)); } bw.append(Json.list(values)); bw.append(Json.mapClose()); } RecordField.addJsonFooter(bw); bw.close(); f = jsonFile; } } else { //Something went wrong... System.err.println("something went wrong"); } if (doingPublish(request)) { return getEntryManager().processEntryPublish(request, f, (Entry) entry.clone(), entry, "point series of"); } Result result = null; if (format.equalsIgnoreCase(FORMAT_TIMESERIES_IMAGE)) { result = outputTimeSeriesImage(request, entry, f); } else { result = new Result(getStorageManager().getFileInputStream(f), pdrb.getAccept()); //Set return filename sets the Content-Disposition http header so the browser saves the file //with the correct name and suffix result.setReturnFilename(baseName + "_pointsubset" + suffix); } return result; }
From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java
@SuppressLint("SdCardPath") final public void saveHistoryList(final ArrayList<SyncHistoryItem> hl) { // Log.v("","save hist started"); if (hl == null) return;/* ww w.ja v a 2 s. c om*/ try { String dir = mGp.internalRootDirectory + "/" + APPLICATION_TAG; File lf = new File(dir); lf.mkdirs(); lf = new File(dir + "/history.txt"); FileWriter fw = new FileWriter(lf); BufferedWriter bw = new BufferedWriter(fw, 4096 * 16); int max = 500; StringBuilder sb_buf = new StringBuilder(1024 * 2); SyncHistoryItem shli = null; // String cpy_str, del_str, ign_str; final ArrayList<SyncHistoryItem> del_list = new ArrayList<SyncHistoryItem>(); for (int i = 0; i < hl.size(); i++) { // Log.v("","i="+i+", n="+hl.get(i).sync_prof); if (!hl.get(i).sync_prof.equals("")) { shli = hl.get(i); if (i < max) { // cpy_str=array2String(sb_buf,shli.sync_copied_file); // del_str=array2String(sb_buf,shli.sync_deleted_file); // ign_str=array2String(sb_buf,shli.sync_ignored_file); String lfp = ""; if (shli.isLogFileAvailable) lfp = shli.sync_log_file_path; sb_buf.setLength(0); sb_buf.append(shli.sync_date).append("\u0001").append(shli.sync_time).append("\u0001") .append(shli.sync_elapsed_time).append("\u0001").append(shli.sync_prof) .append("\u0001").append(shli.sync_status).append("\u0001") .append(shli.sync_test_mode ? "1" : "0").append("\u0001") .append(shli.sync_result_no_of_copied).append("\u0001") .append(shli.sync_result_no_of_deleted).append("\u0001") .append(shli.sync_result_no_of_ignored).append("\u0001").append(shli.sync_req) .append("\u0001").append(shli.sync_error_text.replaceAll("\n", "\u0002")) .append("\u0001").append(shli.sync_result_no_of_retry).append("\u0001") //retry count .append(" ").append("\u0001") //Dummy .append(" ").append("\u0001") //Dummy .append(lfp).append("\u0001").append(shli.sync_result_file_path).append("\n"); bw.append(sb_buf.toString()); } else { del_list.add(shli); if (!shli.sync_result_file_path.equals("")) { File tlf = new File(shli.sync_result_file_path); if (tlf.exists()) tlf.delete(); } } } } bw.close(); } catch (IOException e) { e.printStackTrace(); } // Log.v("","save hist ended"); }
From source file:com.github.rinde.rinsim.scenario.generator.NHPoissonProcessTest.java
@Ignore @Test/*ww w .j av a2 s.c om*/ public void test() throws IOException { final int numSamples = 100; final long lengthOfScenario = 4 * 60 * 60 * 1000; final double period = 30 * 60 * 1000; final int[] orders = new int[] { 10, 20, 30, 40, 50, 75, 100, 150, 200, 500 }; final List<Point> dataPoints = newArrayList(); final RandomGenerator rng = new MersenneTwister(123); final List<Double> relHeights = newArrayList(); for (int i = 0; i < 10; i++) { relHeights.add(-.999 + i * .001); } for (int i = 0; i < 100; i++) { relHeights.add(-.99 + i * .05); } // for (int i = 0; i < 50; i++) { // relHeights.add(3.99 + (i * .5)); // } Files.createParentDirs(new File("files/test/times/relheight-dynamism.txt")); final BufferedWriter writer = Files.newWriter(new File("files/test/times/relheight-dynamism.txt"), Charsets.UTF_8); for (int k = 0; k < orders.length; k++) { for (int i = 0; i < relHeights.size(); i++) { final double d = relHeights.get(i); final double relHeight = d;// -.99 + (j * .05); // final double period = 3600d; final double ordersPerPeriod = orders[k] / (lengthOfScenario / period); final IntensityFunction intensity = IntensityFunctions.sineIntensity().height(d).period(period) .area(ordersPerPeriod).build(); System.out.printf("%1d relative height: %1.3f%n", i, relHeight); // final List<Double> sineTimes = FluentIterable // .from( // ContiguousSet.create(Range.closedOpen(0L, lengthOfScenario), // DiscreteDomain.longs())) // .transform(Conversion.LONG_TO_DOUBLE) // .transform(intensity) // .toList(); // Analysis // .writeLoads( // sineTimes, // new File( // "files/test/times/sine/sine-" // + Strings.padStart(Integer.toString(i), 2, '0') // + ".intens")); final TimeSeriesGenerator generator = TimeSeries.nonHomogenousPoisson(lengthOfScenario, intensity); double max = 0; double sum = 0; final StandardDeviation sd = new StandardDeviation(); final List<Double> dynamismValues = newArrayList(); for (int j = 0; j < numSamples; j++) { List<Double> times = generator.generate(rng.nextLong()); while (times.size() < 2) { times = generator.generate(rng.nextLong()); } final double dyn = Metrics.measureDynamism(times, lengthOfScenario); dynamismValues.add(dyn); sd.increment(dyn); sum += dyn; max = Math.max(max, dyn); // if (j < 3) { // // System.out.printf("%1.3f%% %d%n", dyn * 100, times.size()); // Analysis.writeTimes( // lengthOfScenario, // times, // new File( // "files/test/times/orders" // + Strings.padStart(Integer.toString(i), 2, '0') + "_" // + j // + "-" + (dyn * 100) // + ".times")); // } } try { writer.append(Double.toString(relHeight)); writer.append(" "); writer.append(Integer.toString(orders[k])); writer.append(" "); writer.append(Joiner.on(" ").join(dynamismValues).toString()); writer.append("\n"); } catch (final IOException e) { checkState(false); } System.out.printf(" > dyn %1.3f+-%1.3f%n", +(sum / numSamples), sd.getResult()); dataPoints.add(new Point(relHeight, sum / numSamples)); } } writer.close(); // Analysis.writeLocationList(dataPoints, new File( // "files/test/times/intensity-analysis.txt")); }
From source file:org.kaaproject.kaa.server.control.cli.ControlApiCommandProcessor.java
/** * Store entity info to file.//w w w . j a v a 2s. c o m * * @param file * the target file to store object id * @param info * the entity info * @param errorWriter * the error writer to output store errors */ private void storeInfo(String file, String info, PrintWriter errorWriter) { try { File f = new File(file); f.getParentFile().mkdirs(); BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.append(info); writer.flush(); writer.close(); } catch (Exception e) { LOG.error("Unable to write Object Id to specified file '{}'! Error: {}", file, e.getMessage()); } }
From source file:org.kaaproject.kaa.server.control.cli.ControlApiCommandProcessor.java
/** * Store entities object ids to file.// ww w .ja v a 2s .co m * * @param file * the target file to store object ids * @param objects * the entities object ids * @param errorWriter * the error writer to output store errors */ private void storeObjectIds(String file, List<? extends HasId> objects, PrintWriter errorWriter) { try { File f = new File(file); f.getParentFile().mkdirs(); BufferedWriter writer = new BufferedWriter(new FileWriter(f)); for (int i = 0; i < objects.size(); i++) { if (i > 0) { writer.newLine(); } writer.append(objects.get(i).getId()); } writer.flush(); writer.close(); } catch (Exception e) { LOG.error("Unable to write Object Ids to specified file '{}'! Error: {}", file, e.getMessage()); } }
From source file:com.termmed.statistics.Processor.java
/** * Prints the report.//ww w . ja va 2 s.c o m * * @param bw the bw * @param detail the detail * @param listDescriptors * @throws Exception the exception */ private void printReport(BufferedWriter bw, OutputDetailFile detail, List<HierarchicalConfiguration> listDescriptors) throws Exception { SQLStatementExecutor executor = new SQLStatementExecutor(connection); AdditionalList[] additionalList = null; if (listDescriptors != null) { additionalList = getAdditionalList(listDescriptors); } Integer ixSctIdInReport = detail.getSctIdIndex(); if (ixSctIdInReport == null) { ixSctIdInReport = 1; } List<IReportListener> dependentReports = null; if (enableListeners) { ReportListeners reportListenersDescriptors = detail.getReportListeners(); if (reportListenersDescriptors != null) { dependentReports = initListeners(reportListenersDescriptors, detail); } } for (StoredProcedure sProc : detail.getStoredProcedure()) { executor.executeStoredProcedure(sProc, ImportManager.params, null); ResultSet rs = executor.getResultSet(); if (rs != null) { ResultSetMetaData meta = rs.getMetaData(); String fieldValue; String sctId = ""; String line; while (rs.next()) { line = ""; for (int i = 0; i < meta.getColumnCount(); i++) { if (rs.getObject(i + 1) != null) { fieldValue = rs.getObject(i + 1).toString().replaceAll(",", ",").trim(); if (ixSctIdInReport.intValue() == i) { sctId = fieldValue; } } else { fieldValue = ""; if (ixSctIdInReport.intValue() == i) { sctId = "0"; } } line += fieldValue; // bw.append(fieldValue); if (i + 1 < meta.getColumnCount()) { line += ","; // bw.append(","); } else { if (additionalList != null && detail.getCreateInterestConceptList()) { for (int ix = 0; i < additionalList.length; ix++) { line += ","; // bw.append(","); if (additionalList[ix].getIds().contains(sctId)) { line += "1"; // bw.append("1"); } else { line += "0"; // bw.append("0"); } } } bw.append(line); bw.append("\r\n"); if (dependentReports != null) { for (IReportListener dependentReport : dependentReports) { dependentReport.actionPerform(line); } } } } } meta = null; rs.close(); } } executor = null; if (dependentReports != null) { for (IReportListener dependentReport : dependentReports) { dependentReport.finalizeListener(); } } }
From source file:com.actelion.research.table.view.JVisualization.java
public String getStatisticalValues() { if (mChartType == cChartTypeScatterPlot) return "Incompatible chart type."; String[][] categoryList = new String[6][]; int[] categoryColumn = new int[6]; int categoryColumnCount = 0; if (isSplitView()) { for (int i = 0; i < 2; i++) { if (mSplittingColumn[i] != cColumnUnassigned) { categoryColumn[categoryColumnCount] = mSplittingColumn[i]; categoryList[categoryColumnCount] = mTableModel.getCategoryList(mSplittingColumn[i]); categoryColumnCount++;/*from w w w . j av a 2s .c o m*/ } } } for (int axis = 0; axis < mDimensions; axis++) { if (mIsCategoryAxis[axis]) { categoryColumn[categoryColumnCount] = mAxisIndex[axis]; categoryList[categoryColumnCount] = new String[mCategoryVisibleCount[axis]]; if (mAxisIndex[axis] == cColumnUnassigned) { // box/whisker plot with unassigned category axis categoryList[categoryColumnCount][0] = "<All Rows>"; } else { String[] list = mTableModel.getCategoryList(categoryColumn[categoryColumnCount]); for (int j = 0; j < mCategoryVisibleCount[axis]; j++) categoryList[categoryColumnCount][j] = list[mCategoryMin[axis] + j]; } categoryColumnCount++; } } if (isCaseSeparationDone()) { categoryColumn[categoryColumnCount] = mCaseSeparationColumn; categoryList[categoryColumnCount] = mTableModel.getCategoryList(mCaseSeparationColumn); categoryColumnCount++; } boolean includePValue = false; boolean includeFoldChange = false; int pValueColumn = getPValueColumn(); int referenceCategoryIndex = -1; if (pValueColumn != cColumnUnassigned) { referenceCategoryIndex = getCategoryIndex(pValueColumn, mPValueRefCategory); if (referenceCategoryIndex != -1) { includePValue = mBoxplotShowPValue; includeFoldChange = mBoxplotShowFoldChange; } } StringWriter stringWriter = new StringWriter(1024); BufferedWriter writer = new BufferedWriter(stringWriter); try { // construct the title line for (int i = 0; i < categoryColumnCount; i++) { String columnTitle = (categoryColumn[i] == -1) ? "Category" : mTableModel.getColumnTitleWithSpecialType(categoryColumn[i]); writer.append(columnTitle + "\t"); } if (mChartType != cChartTypeBoxPlot) writer.append("Rows in Category"); if ((mChartType == cChartTypeBars || mChartType == cChartTypePies) && mChartMode != cChartModeCount) { String name = mTableModel.getColumnTitleWithSpecialType(mChartColumn); writer.append((mChartMode == cChartModePercent) ? "\tPercent of Rows" : (mChartMode == cChartModeMean) ? "\tMean of " + name : (mChartMode == cChartModeMean) ? "\tSum of " + name : (mChartMode == cChartModeMin) ? "\tMinimum of " + name : (mChartMode == cChartModeMax) ? "\tMaximum of " + name : ""); } if (mChartType == cChartTypeBoxPlot || mChartType == cChartTypeWhiskerPlot) { if (mChartType == cChartTypeBoxPlot) { writer.append("Total Count"); writer.append("\tOutlier Count"); } writer.append("\tMean Value"); writer.append("\t1st Quartile"); writer.append("\tMedian"); writer.append("\t3rd Quartile"); writer.append("\tLower Adjacent Limit"); writer.append("\tUpper Adjacent Limit"); /* if (includeFoldChange || includePValue) don't use additional column writer.append("\tIs Reference Group"); */ if (includeFoldChange) writer.append( mTableModel.isLogarithmicViewMode(mAxisIndex[((BoxPlotViewInfo) mChartInfo).barAxis]) ? "\tlog2(Fold Change)" : "\tFold Change"); if (includePValue) writer.append("\tp-Value"); } writer.newLine(); int[] categoryIndex = new int[6]; while (categoryIndex[0] < categoryList[0].length) { int columnIndex = 0; int hv = 0; if (isSplitView()) { if (mSplittingColumn[0] != cColumnUnassigned) hv += categoryIndex[columnIndex++]; if (mSplittingColumn[1] != cColumnUnassigned) hv += categoryIndex[columnIndex++] * categoryList[0].length; } int cat = 0; for (int axis = 0; axis < mDimensions; axis++) if (mIsCategoryAxis[axis]) cat += categoryIndex[columnIndex++] * mCombinedCategoryCount[axis]; if (isCaseSeparationDone()) cat += categoryIndex[columnIndex++]; if (mChartInfo.pointsInCategory[hv][cat] != 0) { for (int i = 0; i < categoryColumnCount; i++) { writer.append(categoryList[i][categoryIndex[i]]); if ((includeFoldChange || includePValue) && pValueColumn == categoryColumn[i] && mPValueRefCategory.equals(categoryList[i][categoryIndex[i]])) writer.append(" (ref)"); writer.append("\t"); } if (mChartType != cChartTypeBoxPlot) writer.append("" + mChartInfo.pointsInCategory[hv][cat]); if ((mChartType == cChartTypeBars || mChartType == cChartTypePies) && mChartMode != cChartModeCount) writer.append("\t" + formatValue(mChartInfo.barValue[hv][cat], mChartColumn)); if (mChartType == cChartTypeBoxPlot || mChartType == cChartTypeWhiskerPlot) { BoxPlotViewInfo vi = (BoxPlotViewInfo) mChartInfo; if (mChartType == cChartTypeBoxPlot) { writer.append("" + (mChartInfo.pointsInCategory[hv][cat] + vi.outlierCount[hv][cat])); writer.append("\t" + vi.outlierCount[hv][cat]); } int column = mAxisIndex[((BoxPlotViewInfo) mChartInfo).barAxis]; writer.append("\t" + formatValue(vi.barValue[hv][cat], column)); writer.append("\t" + formatValue(vi.boxQ1[hv][cat], column)); writer.append("\t" + formatValue(vi.median[hv][cat], column)); writer.append("\t" + formatValue(vi.boxQ3[hv][cat], column)); writer.append("\t" + formatValue(vi.boxLAV[hv][cat], column)); writer.append("\t" + formatValue(vi.boxUAV[hv][cat], column)); /* if (includeFoldChange || includePValue) { don't use additional column int refHV = getReferenceHV(hv, pValueColumn, referenceCategoryIndex); int refCat = getReferenceCat(cat, pValueColumn, referenceCategoryIndex, new int[1+mDimensions]); writer.append("\t"+((hv==refHV && cat==refCat) ? "yes" : "no")); } */ if (includeFoldChange) { writer.append("\t"); if (!Float.isNaN(vi.foldChange[hv][cat])) writer.append(new DecimalFormat("#.#####").format(vi.foldChange[hv][cat])); } if (includePValue) { writer.append("\t"); if (!Float.isNaN(vi.pValue[hv][cat])) writer.append(new DecimalFormat("#.#####").format(vi.pValue[hv][cat])); } } writer.newLine(); } // update category indices for next row for (int i = categoryColumnCount - 1; i >= 0; i--) { if (++categoryIndex[i] < categoryList[i].length || i == 0) break; categoryIndex[i] = 0; } } writer.close(); } catch (IOException ioe) { } return stringWriter.toString(); }
From source file:MSUmpire.LCMSPeakStructure.LCMSPeakDIAMS2.java
private void PrepareMGF_UnfragmentIon() throws IOException { String mgffile4 = FilenameUtils.getFullPath(ParentmzXMLName) + GetQ3Name() + ".mgf.temp"; // FileWriter mgfWriter4 = new FileWriter(mgffile4, true); final BufferedWriter mgfWriter4 = DIAPack.get_file(DIAPack.OutputFile.Mgf_Q3, mgffile4); // FileWriter mapwriter3 = new FileWriter(FilenameUtils.getFullPath(ParentmzXMLName) + FilenameUtils.getBaseName(ParentmzXMLName) + ".ScanClusterMapping_Q3", true); final BufferedWriter mapwriter3 = DIAPack.get_file(DIAPack.OutputFile.ScanClusterMapping_Q3, FilenameUtils.getFullPath(ParentmzXMLName) + FilenameUtils.getBaseName(ParentmzXMLName) + ".ScanClusterMapping_Q3"); ArrayList<PseudoMSMSProcessing> ScanList = new ArrayList<>(); ExecutorService executorPool = Executors.newFixedThreadPool(NoCPUs); for (PeakCluster ms2cluster : PeakClusters) { ArrayList<PrecursorFragmentPairEdge> frags = UnFragIonClu2Cur.get(ms2cluster.Index); if (frags != null && DIA_MZ_Range.getX() <= ms2cluster.TargetMz() && DIA_MZ_Range.getY() >= ms2cluster.TargetMz()) { // if (DIA_MZ_Range.getX() <= ms2cluster.TargetMz() && DIA_MZ_Range.getY() >= ms2cluster.TargetMz() && UnFragIonClu2Cur.containsKey(ms2cluster.Index)) { // ArrayList<PrecursorFragmentPairEdge> frags = UnFragIonClu2Cur.get(ms2cluster.Index); ms2cluster.GroupedFragmentPeaks.addAll(frags); PseudoMSMSProcessing mSMSProcessing = new PseudoMSMSProcessing(ms2cluster, parameter); executorPool.execute(mSMSProcessing); ScanList.add(mSMSProcessing); }//from w w w. j a va2 s. c o m } executorPool.shutdown(); try { executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { Logger.getRootLogger().info("interrupted.."); } for (PseudoMSMSProcessing mSMSProcessing : ScanList) { if (MatchedFragmentMap.size() > 0) { mSMSProcessing.RemoveMatchedFrag(MatchedFragmentMap); } XYPointCollection Scan = mSMSProcessing.GetScan(); if (Scan != null && Scan.PointCount() > parameter.MinFrag) { parentDIA.Q3Scan++; // StringBuilder mgfString = new StringBuilder(); // mgfString.append("BEGIN IONS\n"); // mgfString.append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n"); // mgfString.append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n"); // mgfString.append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n"); // mgfString.append("TITLE=").append(GetQ3Name()).append(".").append(parentDIA.Q3Scan).append(".").append(parentDIA.Q3Scan).append(".").append(mSMSProcessing.Precursorcluster.Charge).append("\n"); // //mgfString.append("TITLE=" + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n"); // //mgfString.append("TITLE=" GetQ3Name() + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n"); // // for (int i = 0; i < Scan.PointCount(); i++) { // mgfString.append(Scan.Data.get(i).getX()).append(" ").append(Scan.Data.get(i).getY()).append("\n"); // } // mgfString.append("END IONS\n\n"); // mgfWriter4.write(mgfString.toString()); mgfWriter4.append("BEGIN IONS\n") .append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n") .append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n") .append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n") .append("TITLE=").append(GetQ3Name()).append(".").append(Integer.toString(parentDIA.Q3Scan)) .append(".").append(Integer.toString(parentDIA.Q3Scan)).append(".") .append(Integer.toString(mSMSProcessing.Precursorcluster.Charge)).append("\n"); //mgfWriter4.append("TITLE=" + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n"); //mgfWriter4.append("TITLE=" GetQ3Name() + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n"); for (int i = 0; i < Scan.PointCount(); i++) { mgfWriter4.append(Float.toString(Scan.Data.get(i).getX())).append(" ") .append(Float.toString(Scan.Data.get(i).getY())).append("\n"); } mgfWriter4.append("END IONS\n\n"); mapwriter3.write( parentDIA.Q3Scan + ";" + WindowID + ";" + mSMSProcessing.Precursorcluster.Index + "\n"); } mSMSProcessing.Precursorcluster.GroupedFragmentPeaks.clear(); } // mgfWriter4.close(); // mapwriter3.close(); }