List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
From source file:at.lame.hellonzb.parser.NzbParser.java
/** * This method is called to save the currently loaded parser data * to a file (to be loaded later on)./*from ww w .j a v a 2 s . c o m*/ * * @param logger The central logger object * @param counter File(name) counter * @param filename File name to use * @param dlFiles The vector of DownloadFile to write * @return Success status (true or false) */ public synchronized static boolean saveParserData(MyLogger logger, int counter, String filename, Vector<DownloadFile> dlFiles) { String newline = System.getProperty("line.separator"); if (dlFiles.size() < 1) return true; try { String datadirPath = System.getProperty("user.home") + "/.HelloNzb/"; // create home directory File datadir = new File(datadirPath); if (datadir.exists()) { if (datadir.isFile()) { logger.msg("Can't create data directory: " + datadirPath, MyLogger.SEV_ERROR); return false; } } else datadir.mkdirs(); File file = new File(datadirPath, counter + "-" + filename + ".nzb"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); // XML header writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); writer.write(newline); // XML doctype writer.write("<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.0//EN\" " + "\"http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd\">"); writer.write(newline); // HelloNzb signature line writer.write("<!-- NZB generated by HelloNzb, the Binary Usenet tool -->"); writer.write(newline); // XML namespace writer.write("<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">"); writer.write(newline); writer.write(newline); // now write all files passed to this method for (DownloadFile dlFile : dlFiles) writeDlFileToXml(writer, dlFile); // end <nzb> element writer.write(newline); writer.write("</nzb>"); // flush and close file writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
From source file:crossbear.convergence.ConvergenceConnector.java
/** * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host. * //ww w .j av a 2s .c om * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear. * * @param notary * The notary to contact * @param hostPort * The Hostname and port of the server on which the information about the certificate observations is desired. * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ private static String contactNotary(ConvergenceNotary notary, String hostPort) throws IOException, KeyManagementException, NoSuchAlgorithmException { // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)") String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29"; // Build the url to connect to based on the Notary and the certificate's host URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+")); // Open a HttpsURLConnection for that url HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); /* * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary. */ SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) }, new java.security.SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); // Set the timeout during which the Notary has to reply conn.setConnectTimeout(3000); // POST the fake fingerprint to the Notary conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream(). InputStream is; if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ... is = conn.getInputStream(); } // Read the Notary's reply and store it String response = Message.inputStreamToString(is); // Close all opened streams wr.close(); // Return the Notary's reply return response; }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
/** * Does an HTTP post for a given form data string. * * @param data is the form data string.// w w w .j a va 2 s . com * @param url is the url to post to. * @return the return string from the server. * @throws java.io.IOException */ public static String postData(String data, URL url) throws IOException { String result = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { HttpHelpers.addCommonHeaders(conn); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); String line; BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn); while ((line = reader.readLine()) != null) { if (result == null) result = line; else result += line; } reader.close(); } catch (IOException ex) { Log.e(TAG, "Failed to read stream data", ex); String error = null; // TODO Am not yet sure if the section below should make it in the production release. // I mainly use it to get details of a failed http request. I get a FileNotFoundException // when actually the url is correct but an exception was thrown at the server and i use this // to get the server call stack for debugging purposes. try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); while ((line = reader.readLine()) != null) { if (error == null) error = line; else error += line; } reader.close(); } catch (Exception e) { Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex); } } return result; }
From source file:fr.simon.marquis.preferencesmanager.util.Utils.java
public static boolean savePreferences(PreferenceFile preferenceFile, String file, String packageName, Context ctx) {//from ww w. j a va 2 s.c o m Log.d(TAG, String.format("savePreferences(%s, %s)", file, packageName)); if (preferenceFile == null) { Log.e(TAG, "Error preferenceFile is null"); return false; } if (!preferenceFile.isValid()) { Log.e(TAG, "Error preferenceFile is not valid"); return false; } String preferences = preferenceFile.toXml(); if (TextUtils.isEmpty(preferences)) { Log.e(TAG, "Error preferences is empty"); return false; } File tmpFile = new File(ctx.getFilesDir(), TMP_FILE); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter( ctx.openFileOutput(TMP_FILE, Context.MODE_PRIVATE)); outputStreamWriter.write(preferences); outputStreamWriter.close(); } catch (IOException e) { Log.e(TAG, "Error writing temporary file", e); return false; } if (!RootTools.copyFile(tmpFile.getAbsolutePath(), file, true, false)) { Log.e(TAG, "Error copyFile from temporary file"); return false; } if (!fixUserAndGroupId(ctx, file, packageName)) { Log.e(TAG, "Error fixUserAndGroupId"); return false; } if (!tmpFile.delete()) { Log.e(TAG, "Error deleting temporary file"); } RootTools.killProcess(packageName); Log.d(TAG, "Preferences correctly updated"); return true; }
From source file:com.android.W3T.app.network.NetworkUtil.java
public static int attemptSendReceipt(String op, Receipt r) { // Here we may want to check the network status. checkNetwork();// ww w. j a va2s. c o m try { JSONObject jsonstr = new JSONObject(); if (op.equals(METHOD_SEND_RECEIPT)) { // Add your data JSONObject basicInfo = new JSONObject(); basicInfo.put("store_account", r.getEntry(ENTRY_STORE_ACC));// store name basicInfo.put("currency_mark", r.getEntry(ENTRY_CURRENCY)); basicInfo.put("store_define_id", r.getEntry(ENTRY_RECEIPT_ID)); basicInfo.put("source", r.getEntry(ENTRY_SOURCE)); basicInfo.put("tax", r.getEntry(ENTRY_TAX)); // tax basicInfo.put("total_cost", r.getEntry(ENTRY_TOTAL)); // total price basicInfo.put("user_account", UserProfile.getUsername()); JSONObject receipt = new JSONObject(); receipt.put("receipt", basicInfo); receipt.put("items", r.getItemsJsonArray()); receipt.put("opcode", op); receipt.put("acc", UserProfile.getUsername()); jsonstr.put("json", receipt); } URL url = new URL(RECEIPT_OP_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // Must put "json=" here for server to decoding the data String data = "json=" + jsonstr.toString(); out.write(data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String s = in.readLine(); System.out.println(s); if (Integer.valueOf(s) > 0) { return Integer.valueOf(s); } else return 0; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }
From source file:com.android.W3T.app.network.NetworkUtil.java
public static String attemptGetReceipt(String op, String id) { // Here we may want to check the network status. checkNetwork();//from www.j a v a 2s . c o m try { JSONObject jsonstr = new JSONObject(); JSONObject param = new JSONObject(); try { param.put("opcode", op); param.put("acc", UserProfile.getUsername()); if (op.equals(METHOD_RECEIVE_ALL)) { // Add your data param.put("limitStart", "0"); param.put("limitOffset", "7"); } else if (op.equals(METHOD_RECEIVE_RECEIPT_DETAIL)) { // Add your data JSONArray rid = new JSONArray(); rid.put(Integer.valueOf(id)); param.put("receiptIds", rid); } else if (op.equals(METHOD_RECEIVE_RECEIPT_ITEMS)) { // Add your data JSONArray rid = new JSONArray(); rid.put(Integer.valueOf(id)); param.put("receiptIds", rid); } jsonstr.put("json", param); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } URL url = new URL(RECEIPT_OP_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // Must put "json=" here for server to decoding the data String data = "json=" + jsonstr.toString(); out.write(data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String s = in.readLine(); System.out.println("get " + s); return s; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:Main.java
/** * Encode a path as required by the URL specification (<a href="http://www.ietf.org/rfc/rfc1738.txt"> * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according * to the <code>x-www-form-urlencoded</code> MIME format. * * @param path the path to encode/* www . j av a 2 s.c o m*/ * @return the encoded path */ public static String encodePath(String path) { // stolen from org.apache.catalina.servlets.DefaultServlet ;) /** * Note: Here, ' ' should be encoded as "%20" * and '/' shouldn't be encoded. */ int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer; try { writer = new OutputStreamWriter(buf, "UTF8"); } catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); } for (int i = 0; i < path.length(); i++) { int c = path.charAt(i); if (safeCharacters.get(c)) { rewrittenPath.append((char) c); } else { // convert to external encoding before hex conversion try { writer.write(c); writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); for (int j = 0; j < ba.length; j++) { // Converting each byte in the buffer byte toEncode = ba[j]; rewrittenPath.append('%'); int low = (toEncode & 0x0f); int high = ((toEncode & 0xf0) >> 4); rewrittenPath.append(hexadecimal[high]); rewrittenPath.append(hexadecimal[low]); } buf.reset(); } } return rewrittenPath.toString(); }
From source file:com.android.W3T.app.network.NetworkUtil.java
public static String attemptSearch(String op, int range, String[] terms) { // Here we may want to check the network status. checkNetwork();// w w w . j a va2 s . c o m try { JSONObject param = new JSONObject(); param.put("acc", UserProfile.getUsername()); param.put("opcode", "search"); param.put("mobile", true); JSONObject jsonstr = new JSONObject(); if (op == METHOD_KEY_SEARCH) { // Add your data // Add keys if there is any. if (terms != null) { JSONArray keys = new JSONArray(); int numTerm = terms.length; for (int i = 0; i < numTerm; i++) { keys.put(terms[i]); } param.put("keys", keys); } // Calculate the Search Range by last N days Calendar c = Calendar.getInstance(); if (range == -SEVEN_DAYS || range == -FOURTEEN_DAYS) { // 7 days or 14 days c.add(Calendar.DAY_OF_MONTH, range); } else if (range == -ONE_MONTH || range == -THREE_MONTHS) { // 1 month or 6 month c.add(Calendar.MONTH, range); } String timeStart = String.valueOf(c.get(Calendar.YEAR)); timeStart += ("-" + String.valueOf(c.get(Calendar.MONTH) + 1)); timeStart += ("-" + String.valueOf(c.get(Calendar.DAY_OF_MONTH))); Calendar current = Calendar.getInstance(); current.add(Calendar.DAY_OF_MONTH, 1); String timeEnd = String.valueOf(current.get(Calendar.YEAR)); timeEnd += ("-" + String.valueOf(current.get(Calendar.MONTH) + 1)); timeEnd += ("-" + String.valueOf(current.get(Calendar.DAY_OF_MONTH))); JSONObject timeRange = new JSONObject(); timeRange.put("start", timeStart); timeRange.put("end", timeEnd); param.put("timeRange", timeRange); jsonstr.put("json", param); } else if (op == METHOD_TAG_SEARCH) { } else if (op == METHOD_KEY_DATE_SEARCH) { if (terms.length > 2) { // Add keys if there is any. JSONArray keys = new JSONArray(); int numTerm = terms.length - 2; for (int i = 0; i < numTerm; i++) { keys.put(terms[i]); } param.put("keys", keys); } else if (terms.length < 2) { System.out.println("Wrong terms: no start or end date."); return null; } JSONObject timeRange = new JSONObject(); timeRange.put("start", terms[terms.length - 2]); timeRange.put("end", terms[terms.length - 1]); param.put("timeRange", timeRange); jsonstr.put("json", param); } URL url = new URL(RECEIPT_OP_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // Must put "json=" here for server to decoding the data String data = "json=" + jsonstr.toString(); out.write(data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); return in.readLine(); // String s = in.readLine(); // System.out.println(s); // return s; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:ch.ethz.epics.export.GoogleImageSitemap.java
/** * Creates a new google image sitemap. /*from w ww . jav a 2 s . c o m*/ * @return * @throws Exception */ public static void writeHeader(OutputStreamWriter out) throws Exception { String header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"; header += "<urlset xmlns=\"http://www.google.com/schemas/sitemap/0.9\"\n"; header += " xmlns:image=\"http://www.google.com/schemas/sitemap-images/1.0\">\n"; out.write(header); }
From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java
/** * * @param httpParam//from w w w.ja v a2 s . c om * @return */ public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) { String url = httpParam.getUrl(); Map<String, Object> parameters = httpParam.getParameters(); String sMethod = httpParam.getMethod(); String charSet = httpParam.getCharSet(); boolean sslVerify = httpParam.isSslVerify(); int maxResultSize = httpParam.getMaxResultSize(); Map<String, Object> headers = httpParam.getHeaders(); int readTimeout = httpParam.getReadTimeout(); int connectTimeout = httpParam.getConnectTimeout(); boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess(); boolean hostnameVerify = httpParam.isHostnameVerify(); TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore(); ClientKeyStore clientKeyStore = httpParam.getClientKeyStore(); if (url == null || url.trim().length() == 0) { throw new IllegalArgumentException("invalid url : " + url); } if (maxResultSize <= 0) { throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize); } Charset.forName(charSet); HttpURLConnection urlConn = null; URL destURL = null; String baseUrl = url.trim(); if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) { baseUrl = HTTP_PREFIX + baseUrl; } String method = null; if (sMethod != null) { method = sMethod.toUpperCase(); } if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) { throw new IllegalArgumentException("invalid http method : " + method); } int index = baseUrl.indexOf("?"); if (index > 0) { baseUrl = urlEncode(baseUrl, charSet); } else if (index == 0) { throw new IllegalArgumentException("invalid url : " + url); } String queryString = mapToQueryString(parameters, charSet); String targetUrl = ""; if (method.equals(HTTP_METHOD_POST)) { targetUrl = baseUrl; } else { if (index > 0) { targetUrl = baseUrl + "&" + queryString; } else { targetUrl = baseUrl + "?" + queryString; } } try { destURL = new URL(targetUrl); urlConn = (HttpURLConnection) destURL.openConnection(); setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore); boolean hasContentType = false; boolean hasUserAgent = false; for (String key : headers.keySet()) { if ("Content-Type".equalsIgnoreCase(key)) { hasContentType = true; } if ("user-agent".equalsIgnoreCase(key)) { hasUserAgent = true; } } if (!hasContentType) { headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet); } if (!hasUserAgent) { headers.put("user-agent", "PlatSystem"); } if (headers != null && !headers.isEmpty()) { for (Entry<String, Object> entry : headers.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> values = makeStringList(value); for (String v : values) { urlConn.addRequestProperty(key, v); } } } urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setConnectTimeout(connectTimeout); urlConn.setReadTimeout(readTimeout); if (method.equals(HTTP_METHOD_POST)) { String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString; if (postData != null && postData.trim().length() > 0) { OutputStream os = urlConn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, charSet); osw.write(postData); osw.flush(); osw.close(); } } int responseCode = urlConn.getResponseCode(); Map<String, List<String>> responseHeaders = urlConn.getHeaderFields(); String contentType = urlConn.getContentType(); SimpleHttpResult result = new SimpleHttpResult(responseCode); result.setHeaders(responseHeaders); result.setContentType(contentType); if (responseCode != 200 && ignoreContentIfUnsuccess) { return result; } InputStream is = urlConn.getInputStream(); byte[] temp = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int readBytes = is.read(temp); while (readBytes > 0) { baos.write(temp, 0, readBytes); readBytes = is.read(temp); } String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet); baos.close(); result.setContent(resultString); return result; } catch (Exception e) { logger.warn("connection error : " + e.getMessage()); return new SimpleHttpResult(e); } finally { if (urlConn != null) { urlConn.disconnect(); } } }