List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:com.galactogolf.genericobjectmodel.levelloader.LevelSet.java
private void saveToFile(File f) throws LevelSavingException { OutputStream output;/*from ww w . ja v a 2s . c o m*/ try { output = new FileOutputStream(f); } catch (FileNotFoundException e) { Log.e("File saving error", e.getMessage()); throw new LevelSavingException(e.getMessage()); } OutputStreamWriter writer = new OutputStreamWriter(output); String data; try { data = JSONSerializer.toJSON(this).toString(2); } catch (JSONException e) { Log.e("File saving error", e.getMessage()); throw new LevelSavingException(e.getMessage()); } try { writer.write(data); writer.flush(); writer.close(); output.close(); } catch (IOException e) { Log.e("Exception", e.getMessage()); } }
From source file:com.github.pemapmodder.pocketminegui.gui.startup.installer.cards.ServerSetupCard.java
@SuppressWarnings("unchecked") public ServerSetupCard(InstallServerActivity activity) { JButton serverPropertiesButton = new JButton("General server properties"); serverPropertiesButton.addActionListener(e -> new ServerOptionsActivity("Server properties editor", activity, new HashMap<>(SERVER_PROPERTIES_MAP), new HashMap<>(SERVER_PROPERTIES_DESC_MAP)) { @Override/*from w w w . j av a 2 s . c om*/ protected void onResult(Map<String, Object> opts) { try { OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(new File(activity.getSelectedHome(), "server.properties"))); writer.append("#Properties Config file\r\n").append("#Generated by PocketMine-GUI\r\n"); for (Map.Entry<String, Object> entry : opts.entrySet()) { writer.append(entry.getKey()).append('=').append(entry.getValue().toString()) .append("\r\n"); } writer.close(); } catch (IOException e1) { e1.printStackTrace(); } } }.init()); JButton pocketmineOpts = new JButton("PocketMine-specific settings"); pocketmineOpts.addActionListener(e -> new ServerOptionsActivity("PocketMine settings editor", activity, new HashMap<>(POCKETMINE_YML_MAP), new HashMap<>(POCKETMINE_YML_DESC_MAP)) { @Override protected void onResult(Map<String, Object> opts) { Yaml yaml = new Yaml(); try { Writer writer = new OutputStreamWriter( new FileOutputStream(new File(activity.getSelectedHome(), "pocketmine.yml"))); yaml.dump(convertPlainToNested(opts), writer); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } } }.init()); add(serverPropertiesButton); add(pocketmineOpts); }
From source file:de.baumann.hhsmoodle.data_random.Random_Fragment.java
private void setRandomList() { if (isFABOpen) { closeFABMenu();//from www .j av a 2 s . c om } //display data final int layoutstyle = R.layout.list_item_notes; int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes }; String[] column = new String[] { "random_title", "random_content", "random_creation" }; final Cursor row = db.fetchAllData(); SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) { @Override public View getView(final int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes); iv_icon.setVisibility(View.GONE); return v; } }; lv.setAdapter(adapter); //onClick function lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) { if (isFABOpen) { closeFABMenu(); } Cursor row2 = (Cursor) lv.getItemAtPosition(position); final String random_content = row2.getString(row2.getColumnIndexOrThrow("random_content")); final String random_title = row2.getString(row2.getColumnIndexOrThrow("random_title")); if (random_content.isEmpty()) { Snackbar.make(lv, getActivity().getString(R.string.number_enterData), Snackbar.LENGTH_LONG) .show(); } else { getActivity().setTitle(random_title); lv.setVisibility(View.GONE); lvItems.setVisibility(View.VISIBLE); try { FileOutputStream fOut = new FileOutputStream(newFile()); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(random_content); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } items = new ArrayList<>(); readItems(); setAdapter(1000); fab.setVisibility(View.GONE); fab_dice.setVisibility(View.VISIBLE); } } }); lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (isFABOpen) { closeFABMenu(); } Cursor row2 = (Cursor) lv.getItemAtPosition(position); final String _id = row2.getString(row2.getColumnIndexOrThrow("_id")); final String random_title = row2.getString(row2.getColumnIndexOrThrow("random_title")); final String random_content = row2.getString(row2.getColumnIndexOrThrow("random_content")); final String random_icon = row2.getString(row2.getColumnIndexOrThrow("random_icon")); final String random_attachment = row2.getString(row2.getColumnIndexOrThrow("random_attachment")); final String random_creation = row2.getString(row2.getColumnIndexOrThrow("random_creation")); final CharSequence[] options = { getString(R.string.number_edit_entry), getString(R.string.bookmark_remove_bookmark) }; new android.app.AlertDialog.Builder(getActivity()) .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals(getString(R.string.number_edit_entry))) { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder( getActivity()); View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_entry, null); final EditText edit_title = (EditText) dialogView .findViewById(R.id.note_title_input); edit_title.setHint(R.string.title_hint); edit_title.setText(random_title); final EditText edit_cont = (EditText) dialogView .findViewById(R.id.note_text_input); edit_cont.setHint(R.string.text_hint); edit_cont.setText(random_content); builder.setView(dialogView); builder.setTitle(R.string.number_edit_entry); builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputTitle = edit_title.getText().toString().trim(); String inputCont = edit_cont.getText().toString().trim(); db.update(Integer.parseInt(_id), inputTitle, inputCont, random_icon, random_attachment, random_creation); setRandomList(); Snackbar.make(lv, R.string.bookmark_added, Snackbar.LENGTH_SHORT).show(); } }); builder.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); final android.app.AlertDialog dialog2 = builder.create(); // Display the custom alert dialog on interface dialog2.show(); helper_main.showKeyboard(getActivity(), edit_title); } if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) { Snackbar snackbar = Snackbar .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { db.delete(Integer.parseInt(_id)); setRandomList(); } }); snackbar.show(); } } }).show(); return true; } }); }
From source file:org.kite9.diagram.server.AbstractKite9Controller.java
protected void sendErrorFormBack(OutputStream os, String formName) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(os); osw.write("form=" + formName); osw.close(); }
From source file:com.annuletconsulting.homecommand.node.AsyncSend.java
@Override public Loader<String> onCreateLoader(int id, Bundle args) { AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) { @Override//w w w. j a v a2 s . c o m public String loadInBackground() { StringBuffer instr = new StringBuffer(); try { Socket connection = new Socket(ipAddr, port); BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); osw.write(formatJSON(command.toUpperCase())); osw.write(13); osw.flush(); BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); InputStreamReader isr = new InputStreamReader(bis, "US-ASCII"); int c; while ((c = isr.read()) != 13) instr.append((char) c); isr.close(); bis.close(); osw.close(); bos.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } return instr.toString(); } }; return loader; }
From source file:com.google.wave.api.AbstractRobotServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { this.req = req; // RobotMessageBundleImpl events = deserializeEvents(req); // /*from w w w .j a va2 s.c o m*/ // // Log All Events // for (Event event : events.getEvents()) { // log(event.getType().toString() + " [" + // event.getWavelet().getWaveId() + " " + // event.getWavelet().getWaveletId()); // try { // log(" " + event.getBlip().getBlipId() + "] [" + // event.getBlip().getDocument().getText().replace("\n", "\\n") + "]"); // } catch(NullPointerException npx) { // log("] [null]"); // } // } // processEvents(events); // events.getOperations().setVersion(getVersion()); // serializeOperations(events.getOperations(), resp); String events = getRequestBody(req); log("Events: " + events); JSONSerializer serializer = getJSONSerializer(); EventMessageBundle eventsBundle = null; String proxyingFor = ""; try { JSONObject jsonObject = new JSONObject(events); proxyingFor = jsonObject.getString("proxyingFor"); } catch (JSONException jsonx) { jsonx.printStackTrace(); } log(proxyingFor); String port = ""; try { port = new JSONObject(proxyingFor).getString("port"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } String data = "events=" + URLEncoder.encode(events, "UTF-8"); // Send the request log("port = " + port); URL url = new URL("http://jem.thewe.net/" + port + "/wave"); URLConnection conn = url.openConnection(); log("no timeout"); //conn.setReadTimeout(10000); //conn.setConnectTimeout(10000); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); // write parameters log("Sending: " + data); writer.write(data); writer.flush(); // Get the response StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); log("Answer: " + answer.toString()); serializeOperations(answer.toString(), resp); }
From source file:com.webarch.common.io.xml.XMLEditor.java
public boolean save(File outPutFile, Document document, boolean lineAble) { boolean flag = true; XMLWriter writer = null;/*from w ww. j a v a2 s. co m*/ OutputStreamWriter outputStream = null; try { outputStream = new OutputStreamWriter(new FileOutputStream(outPutFile), DAFAULT_CHARSET); final OutputFormat format = OutputFormat.createCompactFormat();//? format.setNewlines(lineAble); writer = new XMLWriter(outputStream, format); writer.write(document); writer.flush(); outputStream.close(); writer.close(); } catch (Exception ex) { log.error("?xml", ex); flag = false; } finally { try { if (null != writer) { writer.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.error("?xml:", e); } } return flag; }
From source file:com.hqme.cm.cache.StreamingServer.java
public void stopServer() { UntenCacheService.debugLog(sTag, "stopServer"); isStopping = true;/*w w w. j a va 2 s . c o m*/ try { URL term = new URL("http://localhost:" + serverPortNumber + "/"); URLConnection conn = term.openConnection(); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("GET /favicon.ico HTTP/1.1"); out.close(); } catch (Throwable fault) { // UntenCacheService.debugLog(sTag, "stopServer", fault); } }
From source file:graphene.rest.ws.impl.ExportGraphRSImpl.java
@Override public Response exportGraphAsJSON(@QueryParam("fileName") final String fileName, @QueryParam("fileExt") final String fileExt, @QueryParam("username") final String username, @QueryParam("timeStamp") final String timeStamp, // this is the // client // timestamp in // millisecs as a string final String graphJSONdata) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(outputStream); // DEBUG//w w w . j ava 2s. c o m logger.debug("exportGraphAsJSON: fileName = " + fileName + ", fileExt = " + fileExt + ", graphJSONdata length = " + graphJSONdata.length()); try { writer.write(graphJSONdata); } catch (final IOException e) { logger.error("exportGraphAsJSON: Exception writing JSON"); logger.error(e.getMessage()); } try { writer.close(); outputStream.flush(); outputStream.close(); } catch (final java.io.IOException ioe) { logger.error("exportGraphAsJSON: I/O Exception when attempting to close output. Details " + ioe.getMessage()); } // Create the file on the Web Server File file = null; ServletContext servletContext = null; try { servletContext = globals.getServletContext(); } catch (final Exception se) { logger.error("exportGraphAsJSON: ServletContext is null."); } String path = null; final String serverfileName = "GraphExport" + "_" + username + "_" + timeStamp + "_" + fileName + fileExt; if (servletContext != null) { path = servletContext.getRealPath("/"); } // TODO - get the path from the servlerContext or the request param // TODO the file should be placed under the webserver's dir if (path == null) { // TODO - handle case if the Server is Linux instead of Windows path = "C:/Windows/Temp"; // Temp hack } // DEBUG logger.debug("exportGraphAsJSON: file path = " + path); try { file = new File(path, serverfileName); // file.mkdirs(); final FileOutputStream fout = new FileOutputStream(file); fout.write(outputStream.toByteArray()); fout.close(); String finalPath = file.toURI().toString(); finalPath = finalPath.replace("file:/", ""); // remove leading // DEBUG // logger.debug("exportGraphAsJSON: file toURI = " + finalPath); final ResponseBuilder response = Response.ok(finalPath); response.type("text/plain"); final Response responseOut = response.build(); return responseOut; } catch (final Exception fe) { logger.error( "exportGraphAsJSON: Failed to create file for export. Details: " + fe.getLocalizedMessage()); } return null; }
From source file:de.dentrassi.pm.maven.internal.MavenRepositoryChannelAggregator.java
private void makePrefixes(final OutputStream stream, final Set<String> groupIds) throws IOException { final OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8); writer.write("## repository-prefixes/2.0" + NL); writer.write("#" + NL); writer.write("# Generated by Package Drone " + VersionInformation.VERSION + NL); final String[] groups = groupIds.toArray(new String[groupIds.size()]); Arrays.sort(groups);/*from w ww . ja v a 2 s. co m*/ for (final String groupId : groups) { writer.write("/"); writer.write(groupId.replace(".", "/")); writer.write(NL); } writer.close(); }