List of usage examples for java.io DataOutputStream write
public synchronized void write(int b) throws IOException
b
) to the underlying output stream. From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java
/** * Stores the current set of tokens to the token file */// w w w. j a v a2 s . c o m private void saveTokens() { FileOutputStream fout = null; DataOutputStream keyOutputStream = null; try { File parent = tokenFile.getAbsoluteFile().getParentFile(); log.info("Token File {} parent {} ", tokenFile, parent); if (!parent.exists()) { parent.mkdirs(); } fout = new FileOutputStream(tmpTokenFile); keyOutputStream = new DataOutputStream(fout); keyOutputStream.writeInt(currentToken); keyOutputStream.writeLong(nextUpdate); for (int i = 0; i < currentTokens.length; i++) { if (currentTokens[i] == null) { keyOutputStream.writeInt(0); } else { keyOutputStream.writeInt(1); byte[] b = currentTokens[i].getEncoded(); keyOutputStream.writeInt(b.length); keyOutputStream.write(b); } } keyOutputStream.close(); tmpTokenFile.renameTo(tokenFile); } catch (IOException e) { log.error("Failed to save cookie keys " + e.getMessage()); } finally { try { keyOutputStream.close(); } catch (Exception e) { } try { fout.close(); } catch (Exception e) { } } }
From source file:com.google.gwt.dev.javac.CachedCompilationUnit.java
public static void save(SourceFileCompilationUnit unit, OutputStream outputStream) throws Exception { DataOutputStream dos = null; try {/*from w w w . jav a2s . c om*/ dos = new DataOutputStream(new BufferedOutputStream(outputStream)); // version dos.writeLong(CompilationUnitDiskCache.CACHE_VERSION); // simple stuff dos.writeLong(unit.getLastModified()); dos.writeUTF(unit.getDisplayLocation()); dos.writeUTF(unit.getTypeName()); dos.writeUTF(unit.getContentId().get()); dos.writeBoolean(unit.isSuperSource()); // compiled classes { Collection<CompiledClass> compiledClasses = unit.getCompiledClasses(); int size = compiledClasses.size(); dos.writeInt(size); if (size > 0) { // sort in enclosing order to be able to restore enclosing classes by name CompiledClass[] compiledClassesArray = compiledClasses .toArray(new CompiledClass[compiledClasses.size()]); Arrays.sort(compiledClassesArray, new Comparator<CompiledClass>() { public int compare(CompiledClass o1, CompiledClass o2) { int o1count = countMatches(o1.getInternalName(), Signature.C_DOLLAR); int o2count = countMatches(o2.getInternalName(), Signature.C_DOLLAR); return o1count - o2count; } }); // store for (CompiledClass compiledClass : compiledClassesArray) { // internal name dos.writeUTF(compiledClass.getInternalName()); // is local dos.writeBoolean(compiledClass.isLocal()); // bytes byte[] bytes = compiledClass.getBytes(); dos.writeInt(bytes.length); dos.write(bytes); // enclosing class, write the name only CompiledClass enclosingClass = compiledClass.getEnclosingClass(); String enclosingClassName = enclosingClass != null ? enclosingClass.getInternalName() : ""; dos.writeUTF(enclosingClassName); } } } // dependencies { Set<ContentId> dependencies = unit.getDependencies(); int size = dependencies.size(); dos.writeInt(size); if (size > 0) { for (ContentId contentId : dependencies) { dos.writeUTF(contentId.get()); } } } // JSNI methods { List<JsniMethod> jsniMethods = unit.getJsniMethods(); int size = jsniMethods.size(); dos.writeInt(size); if (size > 0) { for (JsniMethod jsniMethod : jsniMethods) { dos.writeUTF(jsniMethod.name()); JsFunction function = jsniMethod.function(); SourceInfo sourceInfo = function.getSourceInfo(); dos.writeInt(sourceInfo.getStartPos()); dos.writeInt(sourceInfo.getEndPos()); dos.writeInt(sourceInfo.getStartLine()); dos.writeUTF(function.toSource()); } } } // Method lookup { MethodArgNamesLookup methodArgs = unit.getMethodArgs(); MethodArgNamesLookup.save(methodArgs, dos); } } finally { IOUtils.closeQuietly(dos); } }
From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java
/****************************************************************************************** * Uploads the note to the server/*from w w w . j a va 2 s . c om*/ ****************************************************************************************** * @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:edu.pdx.cecs.orcycle.NoteUploader.java
boolean uploadOneNote(long noteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/* ww w . j a va2 s . co m*/ JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId); 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"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonNote; if (null != (jsonNote = getNoteJSON(noteId))) { try { String deviceId = userId; dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n"); dos.writeBytes( notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n"); if (null != imageData) { dos.writeBytes(notesep + "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(notesep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } else { result = false; } } catch (IllegalStateException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (IOException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (JSONException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { NoteUploader.setPending(noteId, false); } return result; }
From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java
private byte[] createBigVolume(String useTimeStamp, String useNumberSeq, String format, String charset, String sizeArray) throws IOException, NumberFormatException { ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream d = new DataOutputStream(b); // flags byte flags = 0x00; if ("TRUE".equals(useTimeStamp)) flags |= 0x80;//from ww w. j ava 2 s. co m if ("TRUE".equals(useNumberSeq)) flags |= 0x40; d.writeByte(flags); // TimeStamp if ("TRUE".equals(useTimeStamp)) { Date date = new java.util.Date(); d.writeLong(date.getTime()); } // Number Sequence if ("TRUE".equals(useNumberSeq)) { d.writeInt(numSeq++); } int size = Integer.parseInt(sizeArray); byte[] content = new byte[size]; for (int i = 0; i < size; i++) { content[i] = (byte) (i % 10); } d.write(content); // Format: Encoding if (MQTTPublisherGui.BINARY.equals(format)) { BinaryCodec encoder = new BinaryCodec(); return encoder.encode(b.toByteArray()); } else if (MQTTPublisherGui.BASE64.equals(format)) { return Base64.encodeBase64(b.toByteArray()); } else if (MQTTPublisherGui.BINHEX.equals(format)) { Hex encoder = new Hex(); return encoder.encode(b.toByteArray()); } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) { String s = new String(b.toByteArray(), charset); return s.getBytes(); } else return b.toByteArray(); }
From source file:org.apache.jsp.fileUploader_jsp.java
private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId, Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request, HttpServletResponse response) {//from w w w . j a v a 2 s. c o m String charset = "UTF-8"; String url = ""; try { if (isJson) { //first check if bytes are actually json try { new JsonParser().parse(new String(bytes)); } catch (Exception ex) { return "Failed, file was not valid JSON"; } if (newShare) url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } else { if (newShare) url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/binary/" + prevId + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } if (localCookie) CookieHandler.setDefault(cm); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); } if (mimeType != null && mimeType.length() > 0) connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset); DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(bytes); DataInputStream responseStream = new DataInputStream(connection.getInputStream()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = responseStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } String json = buffer.toString(); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } buffer.flush(); buffer.close(); output.close(); responseStream.close(); if (isJson) { jsonResponse jr = new Gson().fromJson(json, jsonResponse.class); if (jr == null) { return "Failed: " + json; } if (jr.response.success == true) { if (jr.data != null && jr.data._id != null) { addRemoveCommunities(jr.data._id, communities, request, response); return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload } } return "Upload Failed: " + jr.response.message; } else { modResponse mr = new Gson().fromJson(json, modResponse.class); if (mr == null) { return "Failed: " + json; } if (mr.response.success == true) { if (prevId != null && mr.data == null) { addRemoveCommunities(prevId, communities, request, response); return prevId; } else { addRemoveCommunities(mr.data, communities, request, response); return mr.data; //When a new upload, mr.data contains the ShareID for the upload } } else { return "Upload Failed: " + mr.response.message; } } } catch (IOException e) { e.printStackTrace(); return "Upload Failed: " + e.getMessage(); } }
From source file:com.netease.qa.emmagee.service.EmmageeService.java
public void getlog() { new Thread(new Runnable() { @Override/*w ww . j a va 2 s .c o m*/ public void run() { try { Process process = null; DataOutputStream os = null; String logcatCommand; if (packageName.contains("elong")) { logcatCommand = "logcat -v time |grep --line-buffered -E \"GreenDaoHelper_insert_e|Displayed\" | grep -v -E \"show|logs|back|info\""; } else { logcatCommand = "logcat -v time |grep --line-buffered -E \"Displayed\""; } Runtime.getRuntime().exec("logcat -c"); process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); os.write(logcatCommand.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); bufferedWriter = new BufferedWriter(new FileWriter(new File("/sdcard/logcat.log"))); String line = null; while (!isServiceStop) { while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line + Constants.LINE_END); } try { Thread.currentThread().sleep(Settings.SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } os.close(); bufferedWriter.flush(); bufferedReader.close(); process.destroy(); } catch (IOException e) { e.printStackTrace(); } finally { } } }).start(); }
From source file:org.echocat.jomon.net.dns.DnsServer.java
public void TCPclient(Socket s) { try {/*w w w . j a v a 2 s . c o m*/ final int inLength; final DataInputStream dataIn; final DataOutputStream dataOut; final byte[] in; final InputStream is = s.getInputStream(); dataIn = new DataInputStream(is); inLength = dataIn.readUnsignedShort(); in = new byte[inLength]; dataIn.readFully(in); final Message query; byte[] response; try { query = new Message(in); response = generateReply(query, in, in.length, s); if (response == null) { return; } } catch (final IOException ignored) { response = formerrMessage(in); } dataOut = new DataOutputStream(s.getOutputStream()); dataOut.writeShort(response.length); dataOut.write(response); } catch (final IOException e) { LOG.warn("TCPclient(" + addrport(s.getLocalAddress(), s.getLocalPort()) + ").", e); } finally { try { s.close(); } catch (final IOException ignored) { } } }
From source file:org.apache.jxtadoop.hdfs.server.datanode.DataXceiver.java
/** * Reads the metadata and sends the data in one 'DATA_CHUNK'. * @param in//www . j av a2 s . c o m */ void readMetadata(DataInputStream in) throws IOException { LOG.debug("Mathod called : readMetadata()"); Block block = new Block(in.readLong(), 0, in.readLong()); MetaDataInputStream checksumIn = null; DataOutputStream out = null; try { checksumIn = datanode.data.getMetaDataInputStream(block); long fileSize = checksumIn.getLength(); if (fileSize >= 1L << 31 || fileSize <= 0) { throw new IOException("Unexpected size for checksumFile of block" + block); } byte[] buf = new byte[(int) fileSize]; IOUtils.readFully(checksumIn, buf, 0, buf.length); //out = new DataOutputStream( // NetUtils.getOutputStream(s, datanode.socketWriteTimeout)); out = new DataOutputStream(s.getOutputStream()); out.writeByte(DataTransferProtocol.OP_STATUS_SUCCESS); out.writeInt(buf.length); out.write(buf); //last DATA_CHUNK out.writeInt(0); } finally { LOG.debug("Finalizing : readMetadata()"); IOUtils.closeStream(out); IOUtils.closeStream(checksumIn); } }
From source file:ClassFile.java
public void write(DataOutputStream dos, ConstantPoolInfo pool[]) throws IOException, Exception { dos.write(type); switch (type) { case CLASS:/*from w ww .j a va 2 s . c o m*/ case STRING: dos.writeShort(indexOf(arg1, pool)); break; case FIELDREF: case METHODREF: case INTERFACE: case NAMEANDTYPE: dos.writeShort(indexOf(arg1, pool)); dos.writeShort(indexOf(arg2, pool)); break; case INTEGER: dos.writeInt(intValue); break; case FLOAT: dos.writeFloat(floatValue); break; case LONG: dos.writeLong(longValue); break; case DOUBLE: dos.writeDouble(doubleValue); break; case ASCIZ: case UNICODE: dos.writeShort(strValue.length()); dos.writeBytes(strValue); break; default: throw new Exception("ConstantPoolInfo::write() - bad type."); } }