List of usage examples for java.io BufferedWriter flush
public void flush() throws IOException
From source file:musite.io.xml.ProteinResidueAnnotationWriter.java
public void write(OutputStream os, Map<String, MultiMap<Integer, Map<String, Object>>> residueAnnotations) throws IOException { if (os == null || residueAnnotations == null) return;// www . j a v a2 s .c om String prefix = StringUtils.repeat("\t", getIndent()); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bufWriter = new BufferedWriter(osw); for (Map.Entry<String, MultiMap<Integer, Map<String, Object>>> entry : residueAnnotations.entrySet()) { String type = entry.getKey(); bufWriter.write(prefix + "<" + type + ">\n"); writeMultiMap(os, bufWriter, entry.getValue(), prefix + "\t"); bufWriter.write(prefix + "</" + type + ">\n"); } bufWriter.flush(); osw.flush(); }
From source file:de.minestar.sixteenblocks.Threads.JSONThread.java
@SuppressWarnings("unchecked") @Override//www . j ava 2 s .c o m public void run() { // Create sync thread to use notthreadsafe methods Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), new Runnable() { @Override public void run() { BufferedWriter bWriter = null; try { JSONObject json = new JSONObject(); json.put("ConnectedUsers", Bukkit.getOnlinePlayers().length); json.put("Skins", aManager.getUsedAreaCount()); json.put("Slots", Core.getAllowedMaxPlayer()); bWriter = new BufferedWriter(new FileWriter(JSONFile)); bWriter.write(json.toJSONString()); bWriter.flush(); bWriter.close(); } catch (Exception e) { ConsoleUtils.printException(e, Core.NAME, "Can't save JSON"); } finally { try { if (bWriter != null) bWriter.close(); } catch (Exception e2) { // IGNORE SECOND EXCEPTION } } } }); }
From source file:edu.umd.cs.eclipse.courseProjectManager.EclipseLaunchEventLog.java
private void log(String event) throws IOException { BufferedWriter writer = null; try {/*from ww w . jav a2s. c o m*/ writer = new BufferedWriter(new FileWriter(getLogFile(), true)); writer.write(event + "\n"); writer.flush(); writer.close(); } finally { try { if (writer != null) writer.close(); } catch (IOException ignore) { // ignore } try { file.refreshLocal(1, null); } catch (CoreException ignore) { // ignore } } }
From source file:mamo.vanillaVotifier.VotifierServer.java
public synchronized void start() throws IOException { if (isRunning()) { throw new IllegalStateException("Server is already running!"); }/*from w ww . j a va 2s .com*/ notifyListeners(new ServerStartingEvent()); serverSocket = new ServerSocket(); serverSocket.bind(votifier.getConfig().getInetSocketAddress()); running = true; notifyListeners(new ServerStartedEvent()); new Thread(new Runnable() { @Override public void run() { ExecutorService executorService = Executors.newSingleThreadExecutor(); while (isRunning()) { try { final Socket socket = serverSocket.accept(); executorService.execute(new Runnable() { @Override public void run() { try { notifyListeners(new ConnectionEstablishedEvent(socket)); socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("VOTIFIER 2.9\n"); writer.flush(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch. byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair() .getPublic()).getModulus().bitLength() / Byte.SIZE]; in.read(request); // IOException: handled by try/catch. notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request))); request = RsaUtils .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate()) .doFinal(request); // IllegalBlockSizeException: can't happen. String requestString = new String(request); notifyListeners(new DecryptedInputReceivedEvent(socket, requestString)); String[] requestArray = requestString.split("\n"); if ((requestArray.length == 5 || requestArray.length == 6) && requestArray[0].equals("VOTE")) { notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1], requestArray[2], requestArray[3], requestArray[4]))); for (VoteAction voteAction : votifier.getConfig().getVoteActions()) { String[] params = new String[4]; try { for (int i = 0; i < params.length; i++) { params[i] = SubstitutionUtils.applyRegexReplacements( requestArray[i + 1], voteAction.getRegexReplacements()); } } catch (PatternSyntaxException e) { notifyListeners(new RegularExpressionPatternErrorException(e)); params = new String[] { requestArray[1], requestArray[2], requestArray[3], requestArray[4] }; } if (voteAction.getCommandSender() instanceof RconCommandSender) { RconCommandSender commandSender = (RconCommandSender) voteAction .getCommandSender(); StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor( new SimpleEntry<String, Object>("service-name", params[0]), new SimpleEntry<String, Object>("user-name", params[1]), new SimpleEntry<String, Object>("address", params[2]), new SimpleEntry<String, Object>("timestamp", params[3])); for (String command : voteAction.getCommands()) { String theCommand = substitutor.replace(command); notifyListeners(new SendingRconCommandEvent( commandSender.getRconConnection(), theCommand)); try { notifyListeners(new RconCommandResponseEvent( commandSender.getRconConnection(), commandSender .sendCommand(theCommand).getPayload())); } catch (Exception e) { notifyListeners(new RconExceptionEvent( commandSender.getRconConnection(), e)); } } } if (voteAction.getCommandSender() instanceof ShellCommandSender) { ShellCommandSender commandSender = (ShellCommandSender) voteAction .getCommandSender(); HashMap<String, String> environment = new HashMap<String, String>(); environment.put("voteServiceName", params[0]); environment.put("voteUserName", params[1]); environment.put("voteAddress", params[2]); environment.put("voteTimestamp", params[3]); for (String command : voteAction.getCommands()) { notifyListeners(new SendingShellCommandEvent(command)); try { commandSender.sendCommand(command, environment); notifyListeners(new ShellCommandSentEvent()); } catch (Exception e) { notifyListeners(new ShellCommandExceptionEvent(e)); } } } } } else { notifyListeners(new InvalidRequestEvent(socket, requestString)); } } catch (SocketTimeoutException e) { notifyListeners(new ReadTimedOutExceptionEvent(socket, e)); } catch (BadPaddingException e) { notifyListeners(new DecryptInputExceptionEvent(socket, e)); } catch (Exception e) { notifyListeners(new CommunicationExceptionEvent(socket, e)); } try { socket.close(); notifyListeners(new ConnectionClosedEvent(socket)); } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close. notifyListeners(new ConnectionCloseExceptionEvent(socket, e)); } } }); } catch (Exception e) { if (running) { // Show errors only while running, to hide error while stopping. notifyListeners(new ConnectionEstablishExceptionEvent(e)); } } } executorService.shutdown(); if (!executorService.isTerminated()) { notifyListeners(new ServerAwaitingTaskCompletionEvent()); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (Exception e) { // InterruptedException: can't happen. } } notifyListeners(new ServerStoppedEvent()); } }).start(); }
From source file:foam.starwisp.NetworkManager.java
private void Post(String u, String type, String data, String CallbackName) { try {/*from w w w.j a v a 2 s . c om*/ Log.i("starwisp", "posting: " + u); URL url = new URL(u); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); con.setReadTimeout(100000 /* milliseconds */); con.setConnectTimeout(150000 /* milliseconds */); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("data", data)); OutputStream os = con.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); // Starts the query con.connect(); m_RequestHandler.sendMessage( Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName))); } catch (Exception e) { Log.i("starwisp", e.toString()); e.printStackTrace(); } }
From source file:fr.mcc.ginco.rest.services.ExportRestService.java
/** * Returns a XML file that contains exported branch (the concept given in parameter + all its children), in Ginco export format * @param conceptId/*from w ww.j a v a 2 s .co m*/ * @return */ @GET @Path("/getGincoBranchExport") @Produces(MediaType.TEXT_PLAIN) public Response getGincoBranchExport(@QueryParam("conceptId") String conceptId) { ThesaurusConcept targetConcept = thesaurusConceptService.getThesaurusConceptById(conceptId); File temp; BufferedWriter out = null; try { temp = File.createTempFile("GINCO ", XML_EXTENSION); temp.deleteOnExit(); out = new BufferedWriter(new FileWriter(temp)); String result = gincoBranchExportService.getBranchExport(targetConcept); out.write(result); out.flush(); out.close(); } catch (IOException e) { throw new BusinessException("Cannot create temp file!", "cannot-create-file", e); } return new FileResponse(temp, XML_EXTENSION, "GINCO Branch " + thesaurusConceptService.getConceptTitle(targetConcept)).toResponse(); }
From source file:fr.mcc.ginco.rest.services.ExportRestService.java
/** * Returns a XML file that contains exported thesaurus and all related objects, in Ginco export format * @param thesaurusId//from w ww. jav a2s .c o m * @return */ @GET @Path("/getGincoThesaurusExport") @Produces(MediaType.TEXT_PLAIN) public Response getGincoThesaurusExport(@QueryParam(THESAURUS_ID_PARAMETER) String thesaurusId) { Thesaurus targetThesaurus = thesaurusService.getThesaurusById(thesaurusId); File temp; BufferedWriter out = null; try { temp = File.createTempFile("GINCO ", XML_EXTENSION); temp.deleteOnExit(); out = new BufferedWriter(new FileWriter(temp)); String result = gincoThesaurusExportService.getThesaurusExport(targetThesaurus); out.write(result); out.flush(); out.close(); } catch (IOException e) { throw new BusinessException("Cannot create temp file!", "cannot-create-file", e); } return new FileResponse(temp, XML_EXTENSION, "GINCO " + targetThesaurus.getTitle()).toResponse(); }
From source file:net.sourceforge.eclipsetrader.ats.Repository.java
protected void saveDocument(Document document, String path, String name) { try {//from ww w . j a v a2s . com TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", new Integer(4)); } catch (Exception e) { } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); File file = new File(Platform.getLocation().toFile(), path); file.mkdirs(); file = new File(file, name); BufferedWriter out = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { log.error(e.toString(), e); } }
From source file:ai.grakn.migration.base.io.MigrationCLI.java
public void writeToSout(Stream<InsertQuery> queries) { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); queries.map(InsertQuery::toString).forEach((str) -> { try {/*from w w w .ja v a 2 s . co m*/ writer.write(str); writer.write("\n"); } catch (IOException e) { die("Problem writing"); } }); try { writer.flush(); } catch (IOException e) { e.printStackTrace(); } }
From source file:jatoo.exec.InputStreamExhausterWithDumpStream.java
public final void exhaust() { BufferedReader processInputStreamReader = null; BufferedWriter dumpOutputStreamWriter = null; try {/*from w ww. j a va2 s . c o m*/ processInputStreamReader = new BufferedReader(new InputStreamReader(processInputStream)); dumpOutputStreamWriter = new BufferedWriter(new OutputStreamWriter(dumpOutputStream)); String line = null; while ((line = processInputStreamReader.readLine()) != null) { dumpOutputStreamWriter.write(line); dumpOutputStreamWriter.newLine(); dumpOutputStreamWriter.flush(); } } catch (IOException e) { LOGGER.error("error exhausting the stream", e); } finally { if (closeDumpOutputStream && dumpOutputStreamWriter != null) { try { dumpOutputStreamWriter.close(); } catch (IOException e) { LOGGER.error("error closing the dump stream", e); } } } }