List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:de.gebatzens.sia.SiaAPI.java
public APIResponse doRequest(String url, JSONObject request) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(BuildConfig.BACKEND_SERVER + url).openConnection(); con.setRequestProperty("User-Agent", "SchulinfoAPP/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + " " + BuildConfig.BUILD_TYPE + " Android " + Build.VERSION.RELEASE + " " + Build.PRODUCT + ")"); con.setRequestProperty("Accept-Encoding", "gzip"); con.setConnectTimeout(3000);// www. j a v a 2 s .c om con.setRequestMethod(request == null ? "GET" : "POST"); con.setInstanceFollowRedirects(false); if (request != null) { con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(request.toString()); wr.flush(); wr.close(); } if (BuildConfig.DEBUG) Log.d("ggvp", "connection to " + con.getURL() + " established"); InputStream in = con.getResponseCode() != 200 ? con.getErrorStream() : con.getInputStream(); String encoding = con.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { in = new GZIPInputStream(in); } BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String response = ""; String line = ""; while ((line = reader.readLine()) != null) response += line; JSONObject json = null; try { json = new JSONObject(response); String state = json.getString("state"); Object data = json.opt("data"); String reason = json.optString("reason", ""); Log.d("ggvp", "received state " + state + " " + con.getResponseCode() + " reason: " + reason); return new APIResponse(state.equals("succeeded") ? APIState.SUCCEEDED : APIState.FAILED, data, reason); } catch (JSONException e) { Log.e("ggvp", e.toString()); e.printStackTrace(); return new APIResponse(APIState.FAILED); } }
From source file:net.phalapi.sdk.PhalApiClient.java
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception { String result = null;/*from w w w . j a va 2 s .c o m*/ URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); // ? connection.setUseCaches(false); connection.setConnectTimeout(timeoutMs); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //POST? String postContent = ""; Iterator<Entry<String, String>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); postContent += "&" + entry.getKey() + "=" + entry.getValue(); } out.writeBytes(postContent); out.flush(); out.close(); Log.d("[PhalApiClient requestUrl]", requestUrl + postContent); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.d("[PhalApiClient apiResult]", result); if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
@SuppressWarnings("deprecation") public String runAsRoot(String command) { String output = new String(); try {/*from ww w.ja v a 2 s . com*/ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); DataInputStream is = new DataInputStream(p.getInputStream()); os.writeBytes(command + "\n"); os.flush(); String line = new String(); while ((line = is.readLine()) != null) { output = output + line; } os.writeBytes("exit\n"); os.flush(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return output; }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
@SuppressWarnings("deprecation") public String runAsUser(String command) { String output = new String(); try {/*from ww w.java 2 s . c om*/ Process p = Runtime.getRuntime().exec("sh"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); DataInputStream is = new DataInputStream(p.getInputStream()); os.writeBytes("exec " + command + "\n"); os.flush(); String line = new String(); while ((line = is.readLine()) != null) { output = output + line; } // os.writeBytes("exit\n"); os.flush(); p.waitFor(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return output; }
From source file:pl.edu.agh.BackgroundServiceConnection.java
/** * Compares sent hash to the one in database *///from w w w . j a va 2s.c o m public void run() { while (true) { try { LOGGER.info("Accepting connections on port: " + serverPort); Socket client = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String message = in.readLine(); DataOutputStream out = new DataOutputStream(client.getOutputStream()); LOGGER.info("Daemon message: " + message); String[] data = message.trim().split("\\|"); try { Service service = serviceDAO.getById(Integer.parseInt(data[1])); if (!data[0].equalsIgnoreCase(service.getPassword())) throw new IllegalArgumentException("Daemon password: " + data[0] + " does not match server password: " + service.getPassword()); out.writeBytes("OK\r\n"); } catch (Exception e) { LOGGER.error("Could not find server: " + message.trim(), e); out.writeBytes("ERROR\r\n"); } in.close(); out.close(); client.close(); } catch (Exception e) { LOGGER.error("Error connecting with server: " + e.getMessage()); } } }
From source file:org.royaldev.royalcommands.rcommands.BaseCommand.java
/** * Gets a link to a Hastebin paste with the given content. * * @param paste Content to paste/*from w w w.j a va 2 s. co m*/ * @return Link to Hastebin paste with the given content * @throws IOException Upon any issue */ private String hastebin(final String paste) throws IOException { final URL url = new URL("http://hastebin.com/documents"); final HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("POST"); huc.setDoOutput(true); final DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.writeBytes(paste); dos.flush(); dos.close(); final BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String inputLine; final StringBuilder sb = new StringBuilder(); while ((inputLine = br.readLine()) != null) sb.append(inputLine); br.close(); final HastebinData hd = new Gson().fromJson(sb.toString(), HastebinData.class); return "http://hastebin.com/" + hd.getKey() + ".txt"; }
From source file:org.apache.hadoop.hive.ql.exec.SentryFilterDDLTask.java
/** * Filter the command "show columns in table" * *///from w w w.j a va 2 s. com private int showFilterColumns(ShowColumnsDesc showCols) throws HiveException { Table table = Hive.get(conf).getTable(showCols.getTableName()); // write the results in the file DataOutputStream outStream = null; try { Path resFile = new Path(showCols.getResFile()); FileSystem fs = resFile.getFileSystem(conf); outStream = fs.create(resFile); List<FieldSchema> cols = table.getCols(); cols.addAll(table.getPartCols()); // In case the query is served by HiveServer2, don't pad it with spaces, // as HiveServer2 output is consumed by JDBC/ODBC clients. boolean isOutputPadded = !SessionState.get().isHiveServerQuery(); outStream.writeBytes(MetaDataFormatUtils.getAllColumnsInformation(fiterColumns(cols, table), false, isOutputPadded, null)); outStream.close(); outStream = null; } catch (IOException e) { throw new HiveException(e, ErrorMsg.GENERIC_ERROR); } finally { IOUtils.closeStream(outStream); } return 0; }
From source file:org.dcm4che3.tool.stowrs.StowRS.java
private StowRSResponse sendMetaDataAndBulkData(Attributes metadata, ExtractedBulkData extractedBulkData) throws IOException { Attributes responseAttrs = new Attributes(); URL newUrl;// w w w . j av a2 s. c o m try { newUrl = new URL(URL); } catch (MalformedURLException e2) { throw new RuntimeException(e2); } HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setChunkedStreamingMode(2048); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); String metaDataType = mediaType == StowMetaDataType.XML ? "application/dicom+xml" : "application/json"; connection.setRequestProperty("Content-Type", "multipart/related; type=" + metaDataType + "; boundary=" + MULTIPART_BOUNDARY); String bulkDataTransferSyntax = "transfer-syntax=" + transferSyntax; MediaType pixelDataMediaType = getBulkDataMediaType(metadata); connection.setRequestProperty("Accept", "application/dicom+xml"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // write metadata wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "\r\n"); if (mediaType == StowMetaDataType.XML) wr.writeBytes("Content-Type: application/dicom+xml; " + bulkDataTransferSyntax + " \r\n"); else wr.writeBytes("Content-Type: application/json; " + bulkDataTransferSyntax + " \r\n"); wr.writeBytes("\r\n"); coerceAttributes(metadata, keys); try { if (mediaType == StowMetaDataType.XML) SAXTransformer.getSAXWriter(new StreamResult(wr)).write(metadata); else { JsonGenerator gen = Json.createGenerator(wr); JSONWriter writer = new JSONWriter(gen); writer.write(metadata); gen.flush(); } } catch (TransformerConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } // write bulkdata for (BulkData chunk : extractedBulkData.otherBulkDataChunks) { writeBulkDataPart(MediaType.APPLICATION_OCTET_STREAM_TYPE, wr, chunk.getURIOrUUID(), Collections.singletonList(chunk)); } if (!extractedBulkData.pixelDataBulkData.isEmpty()) { // pixeldata as a single bulk data part if (extractedBulkData.pixelDataBulkData.size() > 1) { LOG.info("Combining bulk data of multiple pixel data fragments"); } writeBulkDataPart(pixelDataMediaType, wr, extractedBulkData.pixelDataBulkDataURI, extractedBulkData.pixelDataBulkData); } // end of multipart message wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "--\r\n"); wr.close(); String response = connection.getResponseMessage(); int rspCode = connection.getResponseCode(); LOG.info("response: " + response); try { responseAttrs = SAXReader.parse(connection.getInputStream()); } catch (Exception e) { LOG.error("Error creating response attributes", e); } connection.disconnect(); return new StowRSResponse(rspCode, response, responseAttrs); }
From source file:org.apache.hadoop.mapred.TestTaskLogsTruncater.java
/** * Test logs monitoring with {@link MiniMRCluster} * // w ww. j av a2s . com * @throws IOException */ @Test @Ignore // Trunction is now done in the Child JVM, because the TaskTracker // no longer has write access to the user log dir. MiniMRCluster // needs to be modified to put the config params set here in a config // on the Child's classpath public void testLogsMonitoringWithMiniMR() throws IOException { MiniMRCluster mr = null; try { final long LSIZE = 10000L; JobConf clusterConf = new JobConf(); clusterConf.setLong(TaskLogsTruncater.MAP_USERLOG_RETAIN_SIZE, LSIZE); clusterConf.setLong(TaskLogsTruncater.REDUCE_USERLOG_RETAIN_SIZE, LSIZE); mr = new MiniMRCluster(1, "file:///", 3, null, null, clusterConf); JobConf conf = mr.createJobConf(); Path inDir = new Path(TEST_ROOT_DIR + "/input"); Path outDir = new Path(TEST_ROOT_DIR + "/output"); FileSystem fs = FileSystem.get(conf); if (fs.exists(outDir)) { fs.delete(outDir, true); } if (!fs.exists(inDir)) { fs.mkdirs(inDir); } String input = "The quick brown fox jumped over the lazy dog"; DataOutputStream file = fs.create(new Path(inDir, "part-0")); file.writeBytes(input); file.close(); conf.setInputFormat(TextInputFormat.class); conf.setOutputKeyClass(LongWritable.class); conf.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(conf, inDir); FileOutputFormat.setOutputPath(conf, outDir); conf.setNumMapTasks(1); conf.setNumReduceTasks(0); conf.setMapperClass(LoggingMapper.class); RunningJob job = JobClient.runJob(conf); assertTrue(job.getJobState() == JobStatus.SUCCEEDED); for (TaskCompletionEvent tce : job.getTaskCompletionEvents(0)) { long length = TaskLog.getTaskLogFile(tce.getTaskAttemptId(), false, TaskLog.LogName.STDOUT) .length(); assertTrue("STDOUT log file length for " + tce.getTaskAttemptId() + " is " + length + " and not <=" + LSIZE, length <= LSIZE + truncatedMsgSize); if (tce.isMap) { String stderr = TestMiniMRMapRedDebugScript.readTaskLog(LogName.STDERR, tce.getTaskAttemptId(), false); System.out.println("STDERR log:" + stderr); assertTrue(stderr.equals(STDERR_LOG)); } } } finally { if (mr != null) { mr.shutdown(); } } }
From source file:org.opentox.toxotis.client.https.PostHttpsClient.java
@Override public void post() throws ServiceInvocationException { String query = getParametersAsQuery(); if (fileContentToPost != null && query != null && !query.isEmpty()) { postMultiPart();//from www. j ava 2s .c o m } else { connect(getUri().toURI()); DataOutputStream wr; try { getPostLock().lock(); // LOCK wr = new DataOutputStream(getConnection().getOutputStream()); if (query != null && !query.isEmpty()) { wr.writeBytes(getParametersAsQuery());// POST the parameters } else if (model != null) { model.write(wr); } else if (staxComponent != null) { staxComponent.writeRdf(wr); } else if (postableString != null) { wr.writeChars(postableString); } else if (postableBytes != null) { wr.writeBytes(postableBytes); } else if (fileContentToPost != null) { FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(fileContentToPost); br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { wr.writeBytes(line); wr.writeChars("\n"); } } catch (IOException ex) { throw new ConnectionException("Unable to post data to the remote service at '" + getUri() + "' - The connection dropped " + "unexpectidly while POSTing.", ex); } finally { Throwable thr = null; if (br != null) { try { br.close(); } catch (final IOException ex) { thr = ex; } } if (fr != null) { try { fr.close(); } catch (final IOException ex) { thr = ex; } } if (thr != null) { ConnectionException connExc = new ConnectionException("Stream could not close", thr); connExc.setActor(getUri() != null ? getUri().toString() : "N/A"); } } } wr.flush(); wr.close(); } catch (final IOException ex) { ConnectionException postException = new ConnectionException( "Exception caught while posting the parameters to the " + "remote web service located at '" + getUri() + "'", ex); postException.setActor(getUri() != null ? getUri().toString() : "N/A"); throw postException; } finally { getPostLock().unlock(); // UNLOCK } } }