List of usage examples for java.io DataOutputStream DataOutputStream
public DataOutputStream(OutputStream out)
From source file:com.clearcenter.mobile_demo.mdRest.java
static public String Login(String host, String username, String password, String token) throws JSONException { if (password == null) Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username); else/*from ww w. j a v a 2s .c o m*/ Log.i(TAG, "Login by password, host: " + host + ", username: " + username); try { URL url = new URL("https://" + host + URL_LOGIN); HttpsURLConnection http = CreateConnection(url); if (password != null) { // Setup HTTPS POST request String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&submit=submit"; http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length)); // Write request DataOutputStream outputStream = new DataOutputStream(http.getOutputStream()); outputStream.writeBytes(urlParams); outputStream.flush(); outputStream.close(); } else { http.setRequestMethod("GET"); http.setRequestProperty("Cookie", token); } final StringBuffer response = ProcessRequest(http); // Process response JSONObject json_data = null; try { Log.i(TAG, "response: " + response.toString()); json_data = new JSONObject(response.toString()); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return ""; } if (json_data.has("result")) { final String cookie = http.getHeaderField("Set-Cookie"); Integer result = RESULT_UNKNOWN; try { result = Integer.valueOf(json_data.getString("result")); } catch (NumberFormatException e) { } Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie); if (result == RESULT_SUCCESS) { if (cookie != null) return cookie; else return token; } // All other results are failures... return ""; } } catch (Exception e) { Log.e(TAG, "Exception", e); } Log.i(TAG, "Malformed result"); return ""; }
From source file:gridool.util.xfer.TransferUtils.java
public static void sendfile(@Nonnull final File file, final long fromPos, final long count, @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort, final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler) throws IOException { if (!file.exists()) { throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist"); }// w w w . j a v a 2s. c o m if (!file.isFile()) { throw new IllegalArgumentException(file.getAbsolutePath() + " is not file"); } if (!file.canRead()) { throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read"); } final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort); SocketChannel channel = null; Socket socket = null; final OutputStream out; try { channel = SocketChannel.open(); socket = channel.socket(); socket.connect(dstSockAddr); out = socket.getOutputStream(); } catch (IOException e) { LOG.error("failed to connect: " + dstSockAddr, e); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); throw e; } DataInputStream din = null; if (sync) { InputStream in = socket.getInputStream(); din = new DataInputStream(in); } final DataOutputStream dos = new DataOutputStream(out); final StopWatch sw = new StopWatch(); FileInputStream src = null; final long nbytes; try { src = new FileInputStream(file); FileChannel fc = src.getChannel(); String fileName = file.getName(); IOUtils.writeString(fileName, dos); IOUtils.writeString(writeDirPath, dos); long xferBytes = (count == -1L) ? fc.size() : count; dos.writeLong(xferBytes); dos.writeBoolean(append); // append=false dos.writeBoolean(sync); if (handler == null) { dos.writeBoolean(false); } else { dos.writeBoolean(true); handler.writeAdditionalHeader(dos); } // send file using zero-copy send nbytes = fc.transferTo(fromPos, xferBytes, channel); if (LOG.isDebugEnabled()) { LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to " + dstSockAddr.toString() + " in " + sw.toString()); } if (sync) {// receive ack in sync mode long remoteRecieved = din.readLong(); if (remoteRecieved != xferBytes) { throw new IllegalStateException( "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes"); } } } catch (FileNotFoundException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(din, dos); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); } }
From source file:com.mozilla.hadoop.hbase.mapreduce.MultiScanTableMapReduceUtil.java
/** * Converts an array of Scan objects into a base64 string * @param scans/*from ww w. jav a 2 s. c o m*/ * @return * @throws IOException */ public static String convertScanArrayToString(final Scan[] scans) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos); ArrayWritable aw = new ArrayWritable(Scan.class, scans); aw.write(dos); return Base64.encodeBytes(baos.toByteArray()); }
From source file:logout2_servlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w . j a v a2s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String access_token = ""; Cookie cookie = null; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie1 = cookies[i]; if (cookies[i].getName().equals("access_token")) { access_token = cookie1.getValue(); cookie = cookie1; } } System.out.println("TOKEN = " + access_token); String USER_AGENT = "Mozilla/5.0"; String url = "http://localhost:8082/Identity_Service/logout_servlet"; URL connection = new URL(url); HttpURLConnection con = (HttpURLConnection) connection.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "access_token=" + access_token; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder resp = new StringBuilder(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine); } in.close(); JSONParser parser = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) parser.parse(resp.toString()); } catch (ParseException ex) { Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex); } String status = (String) obj.get("status"); System.out.println(status); if (status.equals("ok")) { cookie.setMaxAge(0); response.sendRedirect("login.jsp"); } else { } }
From source file:com.fullhousedev.globalchat.bukkit.PluginMessageManager.java
public static void userToggleSocialspy(String username, boolean on, Plugin pl) { try {/*from w ww. ja v a2 s.c o m*/ ByteArrayOutputStream customData = new ByteArrayOutputStream(); DataOutputStream outCustom = new DataOutputStream(customData); outCustom.writeUTF(username); outCustom.writeBoolean(on); sendRawMessage("toggless", "ALL", customData.toByteArray(), pl); } catch (IOException ex) { Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.haulmont.yarg.formatters.impl.HtmlFormatter.java
protected void renderPdfDocument(String htmlContent, OutputStream outputStream) { ITextRenderer renderer = new ITextRenderer(); File temporaryFile = null;/* w w w . j ava 2s. co m*/ try { temporaryFile = File.createTempFile("htmlReport", ".htm"); DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(temporaryFile)); dataOutputStream.write(htmlContent.getBytes(Charset.forName("UTF-8"))); dataOutputStream.close(); String url = temporaryFile.toURI().toURL().toString(); renderer.setDocument(url); renderer.layout(); renderer.createPDF(outputStream); } catch (Exception e) { throw wrapWithReportingException("", e); } finally { FileUtils.deleteQuietly(temporaryFile); } }
From source file:io.dacopancm.socketdcm.net.StreamSocket.java
public ObservableList<StreamFile> getStreamList() { ObservableList<StreamFile> list = FXCollections.observableArrayList(); try {//w w w .j ava2 s .c o m if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) { logger.log(Level.INFO, "get stream list call"); sock = new Socket(ip, port); DataOutputStream dOut = new DataOutputStream(sock.getOutputStream()); DataInputStream dIn = new DataInputStream(sock.getInputStream()); dOut.writeUTF(ConectType.STREAM.name());//send stream type dOut.writeUTF("uncompressed");//send comprimido o no dOut.writeUTF(ConectType.GET_STREAMLIST.toString()); //send type dOut.writeUTF("mayra"); dOut.flush(); // Send off the data System.out.println("Request list send"); String resp = dIn.readUTF(); dOut.close(); logger.log(Level.INFO, "resp get streamlist: {0}", resp); List<StreamFile> files = HelperUtil.fromJSON(resp); list.addAll(files); } } catch (IOException ex) { HelperUtil.showErrorB("No se pudo establecer conexin"); logger.log(Level.INFO, "get streamlist error no connect:{0}", ex.getMessage()); try { if (sock != null) { sock.close(); } } catch (IOException e) { } } return list; }
From source file:com.panet.imeta.trans.steps.blockingstep.BlockingStep.java
private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) { if (r != null) { data.buffer.add(r); // Save row }//from w ww. java 2s. c o m // Time to write to disk: buffer in core is full! if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk ) { // Then write them to disk... DataOutputStream dos; GZIPOutputStream gzos; int p; try { FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp", environmentSubstitute(meta.getDirectory())); data.files.add(fileObject); // Remember the files! OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false); if (meta.getCompress()) { gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream)); dos = new DataOutputStream(gzos); } else { dos = new DataOutputStream(outputStream); gzos = null; } // How many records do we have? dos.writeInt(data.buffer.size()); for (p = 0; p < data.buffer.size(); p++) { // Just write the data, nothing else rowMeta.writeData(dos, (Object[]) data.buffer.get(p)); } // Close temp-file dos.close(); // close data stream if (gzos != null) { gzos.close(); // close gzip stream } outputStream.close(); // close file stream } catch (Exception e) { logError("Error processing tmp-file: " + e.toString()); return false; } data.buffer.clear(); } return true; }
From source file:edu.pdx.cecs.orcycle.Uploader.java
private boolean uploadOneSegment(long currentNoteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {//from w ww . j av a 2s .co m 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"); SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId); JSONObject json = segmentData.getJSON(); String deviceId = userId; DataOutputStream stream = new DataOutputStream(conn.getOutputStream()); stream.writeBytes(makeContentField("ratesegment", json.toString())); stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion))); stream.writeBytes(makeContentField("device", deviceId)); stream.writeBytes(contentFieldPrefix); stream.flush(); stream.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { segmentData.updateSegmentStatus(SegmentData.STATUS_SENT); result = true; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java
public static long writeInputStreamAndGetSize(String directory, String filename, InputStream is) throws IOException { File outDir = new File(directory); if (!outDir.exists()) outDir.mkdirs();/*ww w . ja v a 2 s. c o m*/ File outFile = new File(directory, filename); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) dos.write(buf, 0, len); dos.close(); return outFile.length(); }