List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:com.geotrackin.gpslogger.senders.gdocs.GDocsHelper.java
private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null;/* w w w. j a v a 2 s.co m*/ HttpURLConnection conn = null; String createFileUrl = "https://www.googleapis.com/drive/v2/files"; String createFilePayload = " {\n" + " \"title\": \"" + fileName + "\",\n" + " \"mimeType\": \"" + mimeType + "\",\n" + " \"parents\": [\n" + " {\n" + " \"id\": \"" + parentFolderId + "\"\n" + " }\n" + " ]\n" + " }"; try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(createFileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(createFilePayload); wr.flush(); wr.close(); fileId = null; String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); tracer.debug("File created with ID " + fileId + " of type " + mimeType); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:org.atricore.idbus.capabilities.josso.test.JOSSO11WebSSORouteTest.java
private String executePost(String targetURL, String urlParameters) { URL url;/*w ww . java 2s. c o m*/ HttpURLConnection connection = null; try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.openymsg.network.HTTPConnectionHandler.java
/** * The only time Yahoo can actually send us any packets is when we send it some. Yahoo encodes its packets in a POST * body - the format is the same binary representation used for direct connections (with one or two extra codes). * /*from w ww . ja v a 2s . c om*/ * After posting a packet, the connection will receive a HTTP response who's payload consists of four bytes followed * by zero or more packets. The first byte of the four is a count of packets encoded in the following body. * * Each incoming packet is transfered to a queue, where receivePacket() takes them off - thus preserving the effect * that input and output packets are being received independently, as with other connection handlers. As * readPacket() can throw an exception, these are caught and transfered onto the queue too, then rethrown by * receivePacket() . */ @Override synchronized void sendPacket(PacketBodyBuffer body, ServiceType service, long status, long sessionID) throws IOException, IllegalStateException { if (!connected) throw new IllegalStateException("Not logged in"); if (filterOutput(body, service)) return; byte[] b = body.getBuffer(); Socket soc = new Socket(proxyHost, proxyPort); PushbackInputStream pbis = new PushbackInputStream(soc.getInputStream()); DataOutputStream dos = new DataOutputStream(soc.getOutputStream()); // HTTP header dos.writeBytes(HTTP_HEADER_POST); dos.writeBytes("Content-length: " + (b.length + NetworkConstants.YMSG9_HEADER_SIZE) + NetworkConstants.END); dos.writeBytes(HTTP_HEADER_AGENT); dos.writeBytes(HTTP_HEADER_HOST); if (HTTP_HEADER_PROXY_AUTH != null) dos.writeBytes(HTTP_HEADER_PROXY_AUTH); if (cookie != null) dos.writeBytes("Cookie: " + cookie + NetworkConstants.END); dos.writeBytes(NetworkConstants.END); // YMSG9 header dos.write(NetworkConstants.MAGIC, 0, 4); dos.write(NetworkConstants.VERSION_HTTP, 0, 4); dos.writeShort(b.length & 0xffff); dos.writeShort(service.getValue() & 0xffff); dos.writeInt((int) (status & 0xffffffff)); dos.writeInt((int) (sessionID & 0xffffffff)); // YMSG9 body dos.write(b, 0, b.length); dos.flush(); // HTTP response header String s = readLine(pbis); if (s == null || s.indexOf(" 200 ") < 0) // Not "HTTP/1.0 200 OK" { throw new IOException("HTTP request returned didn't return OK (200): " + s); } while (s != null && s.trim().length() > 0) // Read past header s = readLine(pbis); // Payload count byte[] code = new byte[4]; int res = pbis.read(code, 0, 4); // Packet count (Little-Endian?) if (res < 4) { throw new IOException("Premature end of HTTP data"); } int count = code[0]; // Payload body YMSG9InputStream yip = new YMSG9InputStream(pbis); YMSG9Packet pkt; for (int i = 0; i < count; i++) { pkt = yip.readPacket(); if (!filterInput(pkt)) { if (!packets.add(pkt)) { throw new IllegalArgumentException("Unable to add data to the packetQueue!"); } } } soc.close(); // Reset idle timeout lastFetch = System.currentTimeMillis(); }
From source file:org.codehaus.mojo.VeraxxMojo.java
protected OutputStream getOutputStreamErr() { String OutputReportName = new String(); if (reportsfileDir.isAbsolute()) { OutputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName(); } else {/*w w w .j a v a 2 s.c o m*/ OutputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/" + getReportFileName(); } getLog().info("Vera++ report location " + OutputReportName); OutputStream output = System.err; File file = new File(OutputReportName); try { new File(file.getParent()).mkdirs(); file.createNewFile(); output = new FileOutputStream(file); } catch (IOException e) { getLog().error("Vera++ report redirected to stderr since " + OutputReportName + " can't be opened"); return output; } final DataOutputStream out = new DataOutputStream(output); try { out.writeBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); out.writeBytes("<checkstyle version=\"5.0\">\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } OutputStream outErrFilter = new OutputStream() { StringBuffer sb = new StringBuffer(); public void write(int b) throws IOException { if ((b == '\n') || (b == '\r')) { transformCurrentLine(); // cleanup for next line sb.delete(0, sb.length()); } else { sb.append((char) b); } } public void flush() throws IOException { transformCurrentLine(); getLog().debug("Vera++ xml flush() called"); if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("</checkstyle>\n"); out.flush(); } String lastfile; private void transformCurrentLine() { if (sb.length() > 0) { // parse current line // try to replace ' (RULENumber) ' with 'RULENumber:' String p = "^(.+) \\((.+)\\) (.+)$"; Pattern pattern = Pattern.compile(p); Matcher matcher = pattern.matcher(sb); getLog().debug("match " + sb + " on " + p); boolean bWinPath = false; if (sb.charAt(1) == ':') { bWinPath = true; sb.setCharAt(1, '_'); } if (matcher.matches()) { String sLine = matcher.group(1) + matcher.group(2) + ":" + matcher.group(3); getLog().debug("rebuild line = " + sLine); // extract informations pattern = Pattern.compile(":"); String[] items = pattern.split(sLine); String file, line, rule, comment, severity; file = items.length > 0 ? items[0] : ""; line = items.length > 1 ? items[1] : ""; rule = items.length > 2 ? items[2] : ""; comment = items.length > 3 ? items[3] : ""; severity = "warning"; if (bWinPath) { StringBuilder s = new StringBuilder(file); s.setCharAt(1, ':'); file = s.toString(); } // output Xml errors try { // handle <file/> tags if (!file.equals(lastfile)) { if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("\t<file name=\"" + file + "\">\n"); lastfile = file; } out.writeBytes("\t\t<error line=\"" + line + "\" severity=\"" + severity + "\" message=\"" + comment + "\" source=\"" + rule + "\"/>\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } } } } }; return outErrFilter; }
From source file:calliope.db.CouchConnection.java
/** * PUT a json file to the database/*from w w w . j a v a2 s. co m*/ * @param db the database name * @param docID the docID of the resource * @param json the json to put there * @return the server response */ @Override public String putToDb(String db, String docID, String json) throws AeseException { HttpURLConnection conn = null; try { docIDCheck(db, docID); docID = convertDocID(docID); String login = (user == null) ? "" : user + ":" + password + "@"; String url = "http://" + login + host + ":" + dbPort + "/" + db + "/" + docID; String revid = getRevId(db, docID); if (revid != null) json = addRevId(json, revid); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); byte[] jData = json.getBytes(); conn.setRequestProperty("Content-Length", Integer.toString(jData.length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); //Get Response return readResponse(conn, 0L, ""); } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }
From source file:com.stratuscom.harvester.codebase.ClassServer.java
private boolean processBadRequest(String[] args, DataOutputStream out) throws IOException { logger.log(Level.FINE, MessageNames.CLASS_SERVER_BAD_REQUEST, args); out.writeBytes("HTTP/1.0 400 Bad Request\r\n\r\n"); out.flush();//from w ww . j a v a2 s . c o m return true; }
From source file:org.socraticgrid.hl7.ucs.nifi.core.NiFiHTTPBroker.java
private int sendPOST(URL url, String content) throws IOException { HttpURLConnection connection = null; try {//w w w .j ava 2s.co m //Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length)); connection.setRequestProperty("Content-Language", "UTF-8"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); //Get Response int responseCode = connection.getResponseCode(); return responseCode; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java
/****************************************************************************************** * Uploads the note to the server//from ww w . j av a 2 s. c o m ****************************************************************************************** * @param currentNoteId Unique note ID to be uploaded * @return True if uploaded, false if not ******************************************************************************************/ boolean uploadOneNote(long currentNoteId) { boolean result = false; final String postUrl = "http://FountainCityCycling.org/post/"; try { URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); /* Change protocol to 2 for Note, and change the point where you zip up the body. (Dont zip up trip body) Since notes don't work either, this may not solve it. */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject note = getNoteJSON(currentNoteId); deviceId = getDeviceId(); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"note\"\r\n\r\n" + note.toString() + "\r\n"); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"version\"\r\n\r\n" + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"device\"\r\n\r\n" + deviceId + "\r\n"); if (imageDataNull == false) { dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n"); dos.write(imageData); dos.writeBytes("\r\n"); } dos.writeBytes("--cycle*******notedata*******columbus--\r\n"); dos.flush(); dos.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("KENNY", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); responseMessage = serverResponseMessage; responseCode = serverResponseCode; // 200 - 202 means successfully went to server and uploaded if (serverResponseCode == 200 || serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(currentNoteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } catch (IllegalStateException e) { Log.d("KENNY", "Note Catch: Illegal State Exception: " + e); e.printStackTrace(); return false; } catch (IOException e) { Log.d("KENNY", "Note Catch: IOException: " + e); e.printStackTrace(); return false; } catch (JSONException e) { Log.d("KENNY", "Note Catch: JSONException: " + e); e.printStackTrace(); return false; } return result; }
From source file:org.apache.maven.plugin.cxx.VeraxxMojo.java
@Override protected OutputStream getOutputStreamErr() { String outputReportName = new String(); if (reportsfileDir.isAbsolute()) { outputReportName = reportsfileDir.getAbsolutePath() + File.separator + getReportFileName(); } else {//from ww w . j a v a 2s . c o m outputReportName = basedir.getAbsolutePath() + File.separator + reportsfileDir.getPath() + File.separator + getReportFileName(); } getLog().info("Vera++ report location " + outputReportName); OutputStream output = System.err; File file = new File(outputReportName); try { new File(file.getParent()).mkdirs(); file.createNewFile(); output = new FileOutputStream(file); } catch (IOException e) { getLog().error("Vera++ report redirected to stderr since " + outputReportName + " can't be opened"); return output; } final DataOutputStream out = new DataOutputStream(output); try { out.writeBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); out.writeBytes("<checkstyle version=\"5.0\">\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } OutputStream outErrFilter = new OutputStream() { StringBuffer sb = new StringBuffer(); public void write(int b) throws IOException { if ((b == '\n') || (b == '\r')) { transformCurrentLine(); // cleanup for next line sb.delete(0, sb.length()); } else { sb.append((char) b); } } public void flush() throws IOException { transformCurrentLine(); getLog().debug("Vera++ xml flush() called"); if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("</checkstyle>\n"); out.flush(); } String lastfile; private void transformCurrentLine() { if (sb.length() > 0) { // parse current line // try to replace ' (RULENumber) ' with 'RULENumber:' String p = "^(.+) \\((.+)\\) (.+)$"; Pattern pattern = Pattern.compile(p); Matcher matcher = pattern.matcher(sb); getLog().debug("match " + sb + " on " + p); boolean bWinPath = false; if (sb.charAt(1) == ':') { bWinPath = true; sb.setCharAt(1, '_'); } if (matcher.matches()) { String sLine = matcher.group(1) + matcher.group(2) + ":" + matcher.group(3); getLog().debug("rebuild line = " + sLine); // extract informations pattern = Pattern.compile(":"); String[] items = pattern.split(sLine); String file, line, rule, comment, severity; file = items.length > 0 ? items[0] : ""; line = items.length > 1 ? items[1] : ""; rule = items.length > 2 ? items[2] : ""; comment = items.length > 3 ? items[3] : ""; severity = "warning"; if (bWinPath) { StringBuilder s = new StringBuilder(file); s.setCharAt(1, ':'); file = s.toString(); } // output Xml errors try { // handle <file/> tags if (!file.equals(lastfile)) { if (!StringUtils.isEmpty(lastfile)) { out.writeBytes("\t</file>\n"); } out.writeBytes("\t<file name=\"" + file + "\">\n"); lastfile = file; } out.writeBytes("\t\t<error line=\"" + line + "\" severity=\"" + severity + "\" message=\"" + comment + "\" source=\"" + rule + "\"/>\n"); } catch (IOException e) { getLog().error("Vera++ xml report write failure"); } } } } }; return outErrFilter; }
From source file:com.webkey.Ipc.java
public void sendMessage(String message) { readAuthKey();/*w w w. j a v a2s. c o m*/ try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = message.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } }