List of usage examples for java.io BufferedWriter BufferedWriter
public BufferedWriter(Writer out)
From source file:org.fao.fenix.wds.web.rest.faostat.GeoConverter.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from ww w. ja va 2 s . c o m*/ @Path("/{systemFrom}/{systemTo}/{code}") public Response convertCode(@PathParam("systemFrom") final String systemFrom, @PathParam("systemTo") final String systemTo, @PathParam("code") final String code) { // Initiate the stream StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { // Initiate utilities Writer writer = new BufferedWriter(new OutputStreamWriter(os)); Gson g = new Gson(); // compute result DatasourceBean db = datasourcePool.getDatasource(DATASOURCE.FENIX.name()); JDBCIterable it = new JDBCIterable(); try { // Query DB it.query(db, buildSQL(systemFrom, systemTo, code)); } catch (IllegalAccessException e) { WDSExceptionStreamWriter.streamException(os, ("Method 'convertCode' thrown an error: " + e.getMessage())); } catch (InstantiationException e) { WDSExceptionStreamWriter.streamException(os, ("Method 'convertCode' thrown an error: " + e.getMessage())); } catch (SQLException e) { WDSExceptionStreamWriter.streamException(os, ("Method 'convertCode' thrown an error: " + e.getMessage())); } catch (ClassNotFoundException e) { WDSExceptionStreamWriter.streamException(os, ("Method 'convertCode' thrown an error: " + e.getMessage())); } catch (Exception e) { WDSExceptionStreamWriter.streamException(os, ("Method 'getDomains' thrown an error: " + e.getMessage())); } // write the result of the query writer.write("["); while (it.hasNext()) { writer.write(g.toJson(it.next())); if (it.hasNext()) writer.write(","); } writer.write("]"); // Convert and write the output on the stream writer.flush(); } }; /* Stream result */ return Response.status(200).entity(stream).build(); }
From source file:org.envirocar.tools.TrackToCSV.java
public InputStream convert(InputStream in) throws IOException { FeatureCollection fc = new ObjectMapper().readValue(in, FeatureCollection.class); List<String> properties = new ArrayList<String>(); for (Feature feature : fc.getFeatures()) { for (String key : feature.getProperties().getPhenomenons().keySet()) { if (!properties.contains(key)) { properties.add(key);/* w w w . j a v a 2s.co m*/ } } } List<String> spaceTimeProperties = new ArrayList<String>(); spaceTimeProperties.add("longitude"); spaceTimeProperties.add("latitude"); spaceTimeProperties.add("time"); ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); bw.append(createCSVHeader(properties, spaceTimeProperties)); bw.newLine(); for (Feature feature : fc.getFeatures()) { for (int i = 0; i < properties.size(); i++) { String key = properties.get(i); Map<?, ?> value = (Map<?, ?>) feature.getProperties().getPhenomenons().get(key); bw.append(value != null ? value.get("value").toString() : Double.toString(Double.NaN)); bw.append(delimiter); } Point coord = (Point) feature.getGeometry(); bw.append(Double.toString(coord.getCoordinates().getLongitude())); bw.append(delimiter); bw.append(Double.toString(coord.getCoordinates().getLatitude())); bw.append(delimiter); bw.append(feature.getProperties().getTime()); bw.newLine(); } bw.flush(); bw.close(); return new ByteArrayInputStream(out.toByteArray()); }
From source file:com.sharksharding.resources.register.bean.RegisterDataSource.java
/** * bean/*from ww w . j av a2s .co m*/ * * @author gaoxianglong * * @param nodePathValue * zookeepervalue * * @param resourceType * * * @return void */ public static void register(String nodePathValue, String resourceType) { if (null == aContext) return; final String tmpdir = TmpManager.createTmp(); logger.debug("tmpdir-->" + tmpdir); try (BufferedWriter out = new BufferedWriter(new FileWriter(tmpdir))) { if (null != nodePathValue) { out.write(nodePathValue); out.flush(); FileSystemResource resource = new FileSystemResource(tmpdir); ConfigurableApplicationContext cfgContext = (ConfigurableApplicationContext) aContext; DefaultListableBeanFactory beanfactory = (DefaultListableBeanFactory) cfgContext.getBeanFactory(); /* * ?????ioc?,???bean, * loadBeanDefinitions() */ new XmlBeanDefinitionReader(beanfactory).loadBeanDefinitions(resource); final String defaultBeanName = "jdbcTemplate"; String[] beanNames = beanfactory.getBeanDefinitionNames(); for (String beanName : beanNames) { /* ??beanNamejdbcTemplateJdbcTemplate */ if (defaultBeanName.equals(beanName)) { GetJdbcTemplate.setJdbcTemplate((JdbcTemplate) beanfactory.getBean(defaultBeanName)); } else { /* bean */ beanfactory.getBean(beanName); } } } } catch (Exception e) { throw new RegisterBeanException(e.toString()); } finally { TmpManager.deleteTmp(tmpdir); } }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SelectIdentifiersListener.java
@Override public void handleEvent(Event event) { //write in a new file File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try {/*from www. ja va 2 s . c om*/ Vector<String> subjectIds = this.setSubjectsIdUI.getSubjectIds(); for (String s : subjectIds) { if (s.compareTo("") == 0) { this.setSubjectsIdUI.displayMessage("Subjects identifier columns have to be choosen"); return; } } FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n"); //subject identifier Vector<File> rawFiles = ((ClinicalData) this.dataType).getRawFiles(); for (int i = 0; i < rawFiles.size(); i++) { int columnNumber = FileHandler.getHeaderNumber(rawFiles.elementAt(i), subjectIds.elementAt(i)); if (columnNumber != -1) { out.write(rawFiles.elementAt(i).getName() + "\t\t" + columnNumber + "\tSUBJ_ID\t\t\n"); } } if (((ClinicalData) this.dataType).getCMF() == null) { out.close(); File fileDest = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns"); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); WorkPart.updateSteps(); } else { try { BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF())); String line = br.readLine(); while ((line = br.readLine()) != null) { String[] s = line.split("\t", -1); if (s[3].compareTo("SUBJ_ID") != 0) { out.write(line + "\n"); } } br.close(); } catch (Exception e) { this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } out.close(); try { String fileName = ((ClinicalData) this.dataType).getCMF().getName(); ((ClinicalData) this.dataType).getCMF().delete(); File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (IOException ioe) { this.setSubjectsIdUI.displayMessage("File errorrror: " + ioe.getLocalizedMessage()); return; } } } catch (Exception e) { this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setSubjectsIdUI.displayMessage("Column mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); UsedFilesPart.sendFilesChanged(dataType); }
From source file:SimpleFTP.java
/** * Connects to an FTP server and logs in with the supplied username and * password./*from w w w .ja va2 s . co m*/ */ public synchronized void connect(String host, int port, String user, String pass) throws IOException { if (socket != null) { throw new IOException("SimpleFTP is already connected. Disconnect first."); } socket = new Socket(host, port); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String response = readLine(); if (!response.startsWith("220 ")) { throw new IOException( "SimpleFTP received an unknown response when connecting to the FTP server: " + response); } sendLine("USER " + user); response = readLine(); if (!response.startsWith("331 ")) { throw new IOException("SimpleFTP received an unknown response after sending the user: " + response); } sendLine("PASS " + pass); response = readLine(); if (!response.startsWith("230 ")) { throw new IOException("SimpleFTP was unable to log in with the supplied password: " + response); } // Now logged in. }
From source file:com.github.jmabuin.blaspark.io.IO.java
public static void writeVectorToFileInHDFS(String file, DenseVector vector, Configuration conf) { try {/*from ww w . j a va 2 s. c om*/ FileSystem fs = FileSystem.get(conf); Path pt = new Path(file); //FileSystem fileSystem = FileSystem.get(context.getConfiguration()); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true))); bw.write("%%MatrixMarket matrix array real general"); bw.newLine(); bw.write(vector.size() + " 1"); bw.newLine(); for (int i = 0; i < vector.size(); i++) { bw.write(String.valueOf(vector.apply(i))); bw.newLine(); } bw.close(); //fs.close(); } catch (IOException e) { LOG.error("Error in " + IO.class.getName() + ": " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:com.splout.db.examples.PageCountsDataGenerator.java
public void generate(File namesFile, int days, File outFolder) throws IOException { if (outFolder.exists()) { FileUtils.deleteDirectory(outFolder); }//from w w w . j a v a 2s . c o m outFolder.mkdirs(); if (!namesFile.exists()) { throw new IllegalArgumentException("Provided names file doesn't exist (" + namesFile + ")"); } List<String> names = Files.readLines(namesFile, Charset.forName("UTF-8")); DateTime today = new DateTime(); DateTime someDaysBefore = today.minusDays(days); someDaysBefore = someDaysBefore.withMinuteOfHour(0); someDaysBefore = someDaysBefore.withSecondOfMinute(0); while (someDaysBefore.isBefore(today)) { for (int hour = 0; hour < 24; hour++) { someDaysBefore = someDaysBefore.withHourOfDay(hour); File currentFile = new File(outFolder, "pagecounts-" + format.print(someDaysBefore)); BufferedWriter writer = new BufferedWriter(new FileWriter(currentFile)); for (String name : names) { int pageviews = (int) (Math.random() * 10000) + 1; writer.write("en " + name + " " + pageviews + " 0" + "\n"); } writer.close(); } someDaysBefore = someDaysBefore.plusDays(1); } }
From source file:org.esupportail.nfctagdroid.requestasync.CsnHttpRequestAsync.java
protected String doInBackground(String... params) { CsnMessageBean nfcMsg = new CsnMessageBean(); nfcMsg.setNumeroId(LocalStorage.getValue("numeroId")); nfcMsg.setCsn(params[0]);//from w w w. j a v a 2s . c o m ObjectMapper mapper = new ObjectMapper(); String jsonInString = null; try { jsonInString = mapper.writeValueAsString(nfcMsg); URL url = new URL(NfcTacDroidActivity.ESUP_NFC_TAG_SERVER_URL + "/csn-ws"); log.info("Will call csn-ws on : " + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.connect(); Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(jsonInString); writer.close(); InputStream inputStream = conn.getInputStream(); String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); while ((line = br.readLine()) != null) { response += line; } conn.disconnect(); return response; } catch (Exception e) { throw new NfcTagDroidException(e); } }
From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java
public static JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception { final JSONObject json = new JSONObject(); json.put("pql", query); final long start = System.currentTimeMillis(); final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection(); conn.setDoOutput(true);//from w w w . j a v a 2s . c om final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); final String reqStr = json.toString(); System.out.println("reqStr = " + reqStr); writer.write(reqStr, 0, reqStr.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); final String res = sb.toString(); System.out.println("res = " + res); final JSONObject ret = new JSONObject(res); ret.put("totalTime", (stop - start)); return ret; }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetLabelsOntologyListener.java
@Override public void handleEvent(Event event) { // TODO Auto-generated method stub Vector<String> headers = this.setLabelsOntologyUI.getHeaders(); Vector<String> newLabels = this.setLabelsOntologyUI.getNewLabels(); Vector<String> codes = this.setLabelsOntologyUI.getCodes(); if (((ClinicalData) this.dataType).getCMF() == null) { this.setLabelsOntologyUI.displayMessage("Error: no column mapping file"); return;/*from w w w. ja v a 2s . c o m*/ } File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try { FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n"); try { BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF())); String line = br.readLine(); while ((line = br.readLine()) != null) { if (line.split("\t", -1)[3].compareTo("SUBJ_ID") == 0 || line.split("\t", -1)[3].compareTo("VISIT_NAME") == 0 || line.split("\t", -1)[3].compareTo("SITE_ID") == 0 || line.split("\t", -1)[3].compareTo("\\") == 0 || line.split("\t", -1)[3].compareTo("DATA_LABEL") == 0 || line.split("\t", -1)[3].compareTo("OMIT") == 0) { out.write(line + "\n"); } else { File rawFile = new File(this.dataType.getPath() + File.separator + line.split("\t", -1)[0]); String header = FileHandler.getColumnByNumber(rawFile, Integer.parseInt(line.split("\t", -1)[2])); String newLabel = newLabels.elementAt(headers.indexOf(rawFile.getName() + " - " + header)); if (newLabel.compareTo("") == 0) { newLabel = header; } out.write(line.split("\t", -1)[0] + "\t" + line.split("\t", -1)[1] + "\t" + line.split("\t", -1)[2] + "\t" + newLabel + "\t\t" + codes.elementAt(headers.indexOf(rawFile.getName() + " - " + header)) + "\n"); } } br.close(); } catch (Exception e) { this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } out.close(); String fileName = ((ClinicalData) this.dataType).getCMF().getName(); FileUtils.deleteQuietly(((ClinicalData) this.dataType).getCMF()); try { File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (Exception ioe) { this.setLabelsOntologyUI.displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setLabelsOntologyUI.displayMessage("Column mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); }