List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);//from w w w.j a va 2 s .c om final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); }
From source file:biblivre3.cataloging.bibliographic.BiblioBO.java
private MemoryFileDTO createFile(final Collection<RecordDTO> records) { final MemoryFileDTO file = new MemoryFileDTO(); file.setFileName(new Date().getTime() + ".mrc"); try {//from w ww . j av a 2 s .co m final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8"); for (RecordDTO dto : records) { writer.write(dto.getIso2709()); writer.write(ApplicationConstants.LINE_BREAK); } writer.flush(); writer.close(); file.setFileData(baos.toByteArray()); } catch (Exception e) { log.error(e.getMessage(), e); } return file; }
From source file:MegaHandler.java
private String api_request(String data) { HttpURLConnection connection = null; try {/*from w w w .ja v a 2s . co m*/ String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number; if (sid != null) urlString += "&sid=" + sid; URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); //use post method connection.setDoOutput(true); //we will send stuff connection.setDoInput(true); //we want feedback connection.setUseCaches(false); //no caches connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); try { OutputStreamWriter wr = new OutputStreamWriter(out); wr.write("[" + data + "]"); //data is JSON object containing the api commands wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the output stream if (out != null) out.close(); } InputStream in = connection.getInputStream(); StringBuffer response = new StringBuffer(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); //close the reader } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the input stream if (in != null) in.close(); } return response.toString().substring(1, response.toString().length() - 1); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:de.baumann.hhsmoodle.activities.Activity_count.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); toDo_title = sharedPref.getString("count_title", ""); String count_title = sharedPref.getString("count_content", ""); toDo_icon = sharedPref.getString("count_icon", ""); toDo_create = sharedPref.getString("count_create", ""); String todo_attachment = sharedPref.getString("count_attachment", ""); if (!sharedPref.getString("count_seqno", "").isEmpty()) { toDo_seqno = Integer.parseInt(sharedPref.getString("count_seqno", "")); }//w w w . j a v a 2 s . com setContentView(R.layout.activity_count); setTitle(toDo_title); final EditText etNewItem = (EditText) findViewById(R.id.etNewItem); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String itemText = etNewItem.getText().toString(); if (itemText.isEmpty()) { Snackbar.make(lvItems, R.string.todo_enter, Snackbar.LENGTH_LONG).show(); } else { itemsTitle.add(0, itemText); itemsCount.add(0, "0"); etNewItem.setText(""); writeItemsTitle(); writeItemsCount(); lvItems.post(new Runnable() { public void run() { lvItems.setSelection(lvItems.getCount() - 1); } }); adapter.notifyDataSetChanged(); } } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); helper_main.onStart(Activity_count.this); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } try { FileOutputStream fOut = new FileOutputStream(newFileTitle()); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(count_title); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } try { FileOutputStream fOut = new FileOutputStream(newFileCount()); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(todo_attachment); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } lvItems = (ListView) findViewById(R.id.lvItems); itemsTitle = new ArrayList<>(); readItemsTitle(); readItemsCount(); adapter = new CustomListAdapter(Activity_count.this, itemsTitle, itemsCount) { @NonNull @Override public View getView(final int position, View convertView, @NonNull ViewGroup parent) { View v = super.getView(position, convertView, parent); ImageButton ib_plus = (ImageButton) v.findViewById(R.id.but_plus); ImageButton ib_minus = (ImageButton) v.findViewById(R.id.but_minus); TextView tv = (TextView) v.findViewById(R.id.count_count); int count = Integer.parseInt(itemsCount.get(position)); if (count < 0) { tv.setTextColor(ContextCompat.getColor(Activity_count.this, R.color.color_red)); } else if (count > 0) { tv.setTextColor(ContextCompat.getColor(Activity_count.this, R.color.color_green)); } else if (count == 0) { tv.setTextColor(ContextCompat.getColor(Activity_count.this, R.color.color_grey)); } ib_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { int a = Integer.parseInt(itemsCount.get(position)) + 1; String plus = String.valueOf(a); itemsCount.remove(position); itemsCount.add(position, plus); // Refresh the adapter adapter.notifyDataSetChanged(); // Return true consumes the long click event (marks it handled) writeItemsTitle(); writeItemsCount(); } }); ib_minus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { int a = Integer.parseInt(itemsCount.get(position)) - 1; String minus = String.valueOf(a); itemsCount.remove(position); itemsCount.add(position, minus); // Refresh the adapter adapter.notifyDataSetChanged(); // Return true consumes the long click event (marks it handled) writeItemsTitle(); writeItemsCount(); } }); return v; } }; lvItems.setAdapter(adapter); lvItems.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick(android.widget.AdapterView<?> parent, View view, final int position, long id) { final String title = itemsTitle.get(position); final String count = itemsCount.get(position); AlertDialog.Builder builder = new AlertDialog.Builder(Activity_count.this); View dialogView = View.inflate(Activity_count.this, R.layout.dialog_edit_text_singleline_count, null); final EditText edit_title = (EditText) dialogView.findViewById(R.id.pass_title); edit_title.setText(title); 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 inputTag = edit_title.getText().toString().trim(); // Remove the item within array at position itemsTitle.remove(position); itemsCount.remove(position); itemsTitle.add(position, inputTag); itemsCount.add(position, count); // Refresh the adapter adapter.notifyDataSetChanged(); // Return true consumes the long click event (marks it handled) writeItemsTitle(); writeItemsCount(); } }); builder.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); final AlertDialog dialog2 = builder.create(); // Display the custom alert dialog on interface dialog2.show(); helper_main.showKeyboard(Activity_count.this, edit_title); } }); lvItems.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(android.widget.AdapterView<?> parent, View view, final int position, long id) { final String title = itemsTitle.get(position); final String count = itemsCount.get(position); // Remove the item within array at position itemsTitle.remove(position); itemsCount.remove(position); // Refresh the adapter adapter.notifyDataSetChanged(); // Return true consumes the long click event (marks it handled) writeItemsTitle(); writeItemsCount(); Snackbar snackbar = Snackbar.make(lvItems, R.string.todo_removed, Snackbar.LENGTH_LONG) .setAction(R.string.todo_removed_back, new View.OnClickListener() { @Override public void onClick(View view) { itemsTitle.add(position, title); itemsCount.add(position, count); // Refresh the adapter adapter.notifyDataSetChanged(); // Return true consumes the long click event (marks it handled) writeItemsTitle(); writeItemsCount(); } }); snackbar.show(); return true; } }); }
From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java
/** * Post data//from w ww . ja v a 2 s. c om * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; OutputStream outStream = null; try { outStream = conn.getOutputStream(); writer = new OutputStreamWriter(outStream, "UTF-8"); writer.write(data); writer.flush(); } finally { if (outStream != null) { try { outStream.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:org.spiffyui.server.AuthServlet.java
private void doLogout(HttpServletRequest request, HttpServletResponse response, String token, String tsUrl) throws ServletException, IOException { if (token == null || tsUrl == null) { returnError(response, "Logout requires a token and a token server URL", RESTAuthConstants.INVALID_LOGOUT_REQUEST); return;//from w ww .java2 s . co m } LOGGER.info("Making logout request for " + token + " to server " + tsUrl); try { validateURI(request, tsUrl); } catch (IllegalArgumentException iae) { returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL); return; } HttpClient httpclient = new DefaultHttpClient(); URI.create(tsUrl); URL url = new URL(tsUrl); LOGGER.info("url: " + url); if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("https")) { setupClientSSL(httpclient, url.getPort()); } HttpDelete httpdel = new HttpDelete(tsUrl + "/" + URLEncoder.encode(token, "UTF-8")); httpdel.setHeader("Accept", "application/json"); httpdel.setHeader("Accept-Charset", "UTF-8"); httpdel.setHeader("Authorization", request.getHeader("Authorization")); httpdel.setHeader("TS-URL", request.getHeader("TS-URL")); // Execute the request HttpResponse authResponse = httpclient.execute(httpdel); int status = authResponse.getStatusLine().getStatusCode(); if (status == 404) { LOGGER.info("The authentication server " + tsUrl + " was not found."); returnError(response, "The token server URL was not found", RESTAuthConstants.NOTFOUND_TS_URL); return; } // Get hold of the response entity HttpEntity entity = authResponse.getEntity(); StringBuffer authResponseData = new StringBuffer(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response authResponseData.append(reader.readLine()); } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. httpdel.abort(); LOGGER.throwing(AuthServlet.class.getName(), "doLogout", ex); throw ex; } finally { // Closing the input stream will trigger connection release if (reader != null) { reader.close(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } //Now we write the response back to our client. response.setStatus(status); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); out.write(authResponseData.toString()); out.flush(); out.close(); }
From source file:GCS_Auth.java
public GCS_Auth(String client_id, String key) { String SCOPE = "https://www.googleapis.com/auth/shoppingapi"; SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent"; try {/*from ww w. ja v a2 s. c o m*/ String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; long now = System.currentTimeMillis() / 1000L; long exp = now + 3600; String iss = client_id; String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now + "}"; String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); byte[] jwt_data = jwt.getBytes("UTF8"); Signature sig = Signature.getInstance("SHA256WithRSA"); KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), "notasecret".toCharArray()); sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray())); sig.update(jwt_data); byte[] signatureBytes = sig.sign(); String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); String data = "grant_type=assertion"; data += "&" + "assertion_type" + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8"); data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8"); URLConnection conn = null; try { URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { InputStream error = ((HttpURLConnection) conn).getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Error: " + ex + "\n " + sb.toString()); } //System.out.println(access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }
From source file:com.rapleaf.api.personalization.RapleafApi.java
protected String bulkJsonResponse(String urlStr, String list) throws Exception { URL url = new URL(urlStr); HttpURLConnection handle = (HttpURLConnection) url.openConnection(); handle.setRequestProperty("User-Agent", getUserAgent()); handle.setRequestProperty("Content-Type", "application/json"); handle.setConnectTimeout(timeout);/*w w w. j av a 2s .c o m*/ handle.setReadTimeout(bulkTimeout); handle.setDoOutput(true); handle.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(handle.getOutputStream()); wr.write(list); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(handle.getInputStream())); String line = rd.readLine(); StringBuilder sb = new StringBuilder(); while (line != null) { sb.append(line); line = rd.readLine(); } wr.close(); rd.close(); int responseCode = handle.getResponseCode(); if (responseCode < 200 || responseCode > 299) { throw new Exception("Error Code " + responseCode + ": " + sb.toString()); } return sb.toString(); }
From source file:com.ibm.BestSellerServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//* w w w. ja v a2s . c o m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/json"); response.setCharacterEncoding("UTF-8"); OutputStream stream = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8"); String listName = request.getParameter("list"); String date = request.getParameter("date"); logger.debug("Requested list {} and requested date {}", listName, date); NewYorkTimes times = new NewYorkTimes(listName, date); try { BestSellerList bestSellers = times.getList(); ObjectMapper mapper = new ObjectMapper(); String listContents = mapper.writeValueAsString(bestSellers.getBooks()); logger.debug("Booklist is {}", listContents); writer.write(listContents); writer.flush(); writer.close(); } catch (Exception e) { logger.error("New York times list unavailable"); throw new IOException("Could not get book list from ny times"); } }
From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java
/** * Get the request token/* w w w. j a v a 2 s . c o m*/ * * @param callbackUrl * HTTP callback URL for handling the user authorization * @return * @throws Exception */ public Map<String, String> getRequestToken(String callbackUrl) throws Exception { Log.d(LOG_TAG, "getRequestToken"); URLConnection urlConnection = getUrlConnection(API_URL_BASE + REQUEST_TOKEN_PATH, true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); Request request = new Request(POST); request.addParameter(OAUTH_CONSUMER_KEY, consumerKey); request.addParameter(OAUTH_CALLBACK, callbackUrl); request.sign(API_URL_BASE + REQUEST_TOKEN_PATH, consumerSecret, null); outputStreamWriter.write(request.toString()); outputStreamWriter.close(); return readParams(urlConnection.getInputStream()); }