List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:org.apache.flink.api.common.io.GenericCsvInputFormatTest.java
private FileInputSplit createTempGzipFile(String content) throws IOException { File tempFile = File.createTempFile("test_contents", "tmp.gz"); tempFile.deleteOnExit();/* ww w . j a va 2 s. co m*/ DataOutputStream dos = new DataOutputStream(new GZIPOutputStream(new FileOutputStream(tempFile))); dos.writeBytes(content); dos.close(); return new FileInputSplit(0, new Path(tempFile.toURI().toString()), 0, tempFile.length(), new String[] { "localhost" }); }
From source file:org.apache.flink.api.common.io.GenericCsvInputFormatTest.java
private FileInputSplit createTempDeflateFile(String content) throws IOException { File tempFile = File.createTempFile("test_contents", "tmp.deflate"); tempFile.deleteOnExit();//w w w.j ava2 s . c o m DataOutputStream dos = new DataOutputStream(new DeflaterOutputStream(new FileOutputStream(tempFile))); dos.writeBytes(content); dos.close(); return new FileInputSplit(0, new Path(tempFile.toURI().toString()), 0, tempFile.length(), new String[] { "localhost" }); }
From source file:org.sipfoundry.sipxprovision.auto.Servlet.java
protected boolean doProvisionPhone(DetectedPhone phone) { if (null == phone) { return false; }// ww w . ja v a 2 s . com boolean success = false; try { LOG.info("doProvisionPhone - " + phone); // Write the REST representation of the phone(s). HttpURLConnection connection = createRestConnection("POST", m_config.getConfigurationUri() + "/rest/phone"); DataOutputStream dstream = new java.io.DataOutputStream(connection.getOutputStream()); dstream.writeBytes("<phones>"); dstream.writeBytes(String.format( "<phone><serialNumber>%s</serialNumber>" + "<model>%s</model><description>%s</description><version>%s</version></phone>", phone.mac.toLowerCase(), phone.model.sipxconfig_id, getPhoneDescription(phone, new Date()), extractPolycomVersion(phone))); dstream.writeBytes("</phones>"); // Do the HTTPS POST. dstream.close(); // Record the result. (Only transport, internal, etc. errors will be reported. // Duplicate and/or invalid MACs for example will result in 200 OK.) if (HttpsURLConnection.HTTP_OK == connection.getResponseCode()) { success = true; LOG.info("REST HTTPS POST success."); } else { LOG.error("REST HTTPS POST failed:" + connection.getResponseCode() + " - " + connection.getResponseMessage()); } } catch (Exception e) { LOG.error("REST HTTPS POST failed:", e); } return success; }
From source file:de.wikilab.android.friendica01.TwAjax.java
private void runFileUpload() throws IOException { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594"; Log.i("Andfrnd/TwAjax", "URL=" + getURL()); URL url = new URL(getURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true);/*from w w w .j ava2s . c om*/ connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); //generate auth header if user/pass are provided to this class if (this.myHttpAuthUser != null) { connection.setRequestProperty("Authorization", "Basic " + Base64 .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP)); } //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--"); connection.setRequestProperty("Host", url.getHost()); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); for (NameValuePair nvp : myPostData) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd); outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd); } for (PostFile pf : myPostFiles) { pf.writeToStream(outputStream, boundary); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) myHttpStatus = connection.getResponseCode(); outputStream.flush(); outputStream.close(); if (myHttpStatus < 400) { myResult = convertStreamToString(connection.getInputStream()); } else { myResult = convertStreamToString(connection.getErrorStream()); } success = true; }
From source file:org.searsia.engine.Resource.java
private String getCompleteWebPage(String urlString, String postString, Map<String, String> headers) throws IOException { if (rateLimitReached()) { throw new IOException("Rate limited"); }/*from www. j a va 2 s . c om*/ URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Searsia/0.4"); connection.setRequestProperty("Accept", this.mimeType); //TODO: "*/*" connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // TODO: from browser? for (Map.Entry<String, String> entry : headers.entrySet()) { String value = entry.getValue(); for (String param : this.privateParameters.keySet()) { value = value.replace("{" + param + "}", this.privateParameters.get(param)); } if (value.contains("{")) { throw new IOException("Missing header parameter"); // TODO: better error } connection.setRequestProperty(entry.getKey(), value); } connection.setReadTimeout(9000); connection.setConnectTimeout(9000); connection.setInstanceFollowRedirects(true); if (postString != null && !postString.equals("")) { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postString.getBytes().length)); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postString); wr.flush(); wr.close(); } else { connection.setRequestMethod("GET"); connection.connect(); } //int responseCode = connection.getResponseCode(); BufferedReader in = null; StringBuilder page = new StringBuilder(); in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); if (in != null) { String inputLine; while ((inputLine = in.readLine()) != null) { page.append(inputLine); } in.close(); } return page.toString(); }
From source file:org.phaidra.apihooks.APIRESTHooksImpl.java
/** * Runs the hook if enabled in fedora.fcfg. * * @param method The name of the method that calls the hook * @param pid The PID that is being accessed * @param params Method parameters, depend on the method called * @return String Hook verdict. Begins with "OK" if it's ok to proceed. * @throws APIHooksException If the remote call went wrong *///from w w w. j ava 2s .co m public String runHook(String method, DOWriter w, Context context, String pid, Object[] params) throws APIHooksException { String rval = null; // Only do this if the method is enabled in fedora.fcfg if (getParameter(method) == null) { log.debug("runHook: method |" + method + "| not configured, not calling webservice"); return "OK"; } Iterator i = context.subjectAttributes(); String attrs = ""; while (i.hasNext()) { String name = ""; try { name = (String) i.next(); String[] value = context.getSubjectValues(name); for (int j = 0; j < value.length; j++) { attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8"); log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute"); } } catch (NullPointerException ex) { log.debug( "runHook: caught NullPointerException while trying to retrieve subject attribute " + name); } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute " + name); } } String paramstr = ""; try { for (int j = 0; j < params.length; j++) { paramstr += "¶m" + Integer.toString(j) + "="; if (params[j] != null) { String p = params[j].toString(); paramstr += URLEncoder.encode(p, "UTF-8"); } } } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter"); } String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri); log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|"); try { // TODO: timeout? retries? URL url; URLConnection urlConn; DataOutputStream printout; BufferedReader input; url = new URL(getParameter("restmethod")); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "method=" + URLEncoder.encode(method, "UTF-8") + "&username=" + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr + attrs; printout.writeBytes(content); printout.flush(); printout.close(); // Get response data. input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); String str; rval = ""; while (null != ((str = input.readLine()))) { rval += str + "\n"; } input.close(); String ct = urlConn.getContentType(); if (ct.startsWith("text/xml")) { log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval); } else if (ct.startsWith("text/plain")) { log.debug("runHook: successful REST invocation for method |" + method + "|, but hook returned an error: " + rval); throw new Exception(rval); } else { throw new Exception("Invalid content type " + ct); } } catch (Exception ex) { log.error("runHook: error calling REST hook: " + ex.toString()); throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex); } return processResults(rval, w, context); }
From source file:com.chummy.jezebel.material.dark.activities.Main.java
public void RunAsRoot(String[] cmds) { try {/* w ww. j av a2s .co m*/ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); for (String tmpCmd : cmds) { os.writeBytes(tmpCmd + "\n"); } os.writeBytes("exit\n"); os.flush(); } catch (IOException e) { e.printStackTrace(); Toast toast = Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG); toast.show(); } }
From source file:org.cerberus.engine.execution.impl.RecorderService.java
@Override public TestCaseExecutionFile recordSeleniumLog(TestCaseExecution testCaseExecution) { TestCaseExecutionFile object = null; // Used for logging purposes String logPrefix = Infos.getInstance().getProjectNameAndVersion() + " - "; if (testCaseExecution.getApplicationObj().getType().equals("GUI")) { if (testCaseExecution.getSeleniumLog() == 2 || (testCaseExecution.getSeleniumLog() == 1 && !testCaseExecution.getControlStatus().equals("OK"))) { LOG.debug(logPrefix + "Starting to save Selenium log file."); try { Recorder recorder = this.initFilenames(testCaseExecution.getId(), null, null, null, null, null, null, null, 0, "selenium_log", "txt"); File dir = new File(recorder.getFullPath()); dir.mkdirs();// ww w. java 2 s . c o m File file = new File(recorder.getFullFilename()); FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); for (String element : this.webdriverService .getSeleniumLog(testCaseExecution.getSession())) { out.writeBytes(element); } byte[] bytes = baos.toByteArray(); fileOutputStream.write(bytes); out.close(); baos.close(); fileOutputStream.close(); // Index file created to database. object = testCaseExecutionFileFactory.create(0, testCaseExecution.getId(), recorder.getLevel(), "Selenium log", recorder.getRelativeFilenameURL(), "TXT", "", null, "", null); testCaseExecutionFileService.save(object); } catch (FileNotFoundException ex) { LOG.error(logPrefix + ex.toString()); } catch (IOException ex) { LOG.error(logPrefix + ex.toString()); } LOG.debug(logPrefix + "Selenium log recorded in : " + recorder.getRelativeFilenameURL()); } catch (CerberusException ex) { LOG.error(logPrefix + ex.toString()); } } } else { LOG.debug(logPrefix + "Selenium Log not recorded because test on non GUI application"); } return object; }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * ?// ww w . ja v a 2 s . c om * @param appWorkspace ? * @param source ? * @param target ?? * @param args JSONArray * @param callbackCtx nativejs * * args[2] fileKey ?name file? * args[3] fileName ??? image.jpg? * args[4] mimeType ?mimeimage/jpeg? * args[5] params HTTP????/ * args[6] trustEveryone * args[7] chunkedMode ??????true * @return FileUploadResult */ private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args, XCallbackContext callbackCtx) { XLog.d(CLASS_NAME, "upload " + source + " to " + target); HttpURLConnection conn = null; try { String fileKey = getArgument(args, 2, "file"); String fileName = getArgument(args, 3, "image.jpg"); String mimeType = getArgument(args, 4, "image/jpeg"); JSONObject params = args.optJSONObject(5); if (params == null) { params = new JSONObject(); } boolean trustEveryone = args.optBoolean(6); boolean chunkedMode = args.optBoolean(7) || args.isNull(7); JSONObject headers = args.optJSONObject(8); if (headers == null && params != null) { headers = params.optJSONObject("headers"); } String objectId = args.getString(9); //------------------ URL url = new URL(target); conn = getURLConnection(url, trustEveryone); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); setCookieProperty(conn, target); // ?? handleRequestHeader(headers, conn); byte[] extraBytes = extraBytesFromParams(params, fileKey); String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END; String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE); FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source); int maxBufferSize = XConstant.BUFFER_LEN; if (chunkedMode) { conn.setChunkedStreamingMode(maxBufferSize); } else { int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length; XLog.d(CLASS_NAME, "String Length: " + stringLength); int fixedLength = (int) fileInputStream.getChannel().size() + stringLength; XLog.d(CLASS_NAME, "Content Length: " + fixedLength); conn.setFixedLengthStreamingMode(fixedLength); } // ??? OutputStream ouputStream = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(ouputStream); dos.write(extraBytes); dos.write(fileNameBytes); dos.writeBytes(midParams); XFileUploadResult result = new XFileUploadResult(); FileTransferProgress progress = new FileTransferProgress(); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); long totalBytes = 0; while (bytesRead > 0) { totalBytes += bytesRead; result.setBytesSent(totalBytes); dos.write(buffer, 0, bytesRead); bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (objectId != null) { //?js??object ID? progress.setTotal(bytesAvailable); XLog.d(CLASS_NAME, "total=" + bytesAvailable); progress.setLoaded(totalBytes); progress.setLengthComputable(true); XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); callbackCtx.sendExtensionResult(progressResult); } synchronized (abortTriggered) { if (objectId != null && abortTriggered.contains(objectId)) { abortTriggered.remove(objectId); throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED); } } } dos.writeBytes(tailParams); fileInputStream.close(); dos.flush(); dos.close(); checkConnection(conn); setUploadResult(result, conn); // if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory); } XLog.d(CLASS_NAME, "****** About to return a result from upload"); return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject()); } catch (AbortException e) { JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { XLog.e(CLASS_NAME, e.getMessage()); return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION); } catch (Throwable t) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:core.AbstractTest.java
private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) { Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: " + mParameters + "\nPayload: " + payload + "\n"); HttpURLConnection conn = null; BufferedReader br = null;//from w w w .j a va2s .com int nRet = 0; boolean fIsMultipart = false; try { setStatusCode(-1); setResponse(null); conn = getHttpConnection(sUrl, sMethod); if (mHeaders.size() > 0) { Set<String> keys = mHeaders.keySet(); for (String sKey : keys) { conn.addRequestProperty(sKey, mHeaders.get(sKey)); if (sKey.equals(HTTP.CONTENT_TYPE)) { if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) { fIsMultipart = true; } } } } if (payload != null || mParameters != null) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); try { if (payload != null) { //conn.setRequestProperty("Content-Length", "" + node.toString().length()); out.writeBytes(payload.toString()); } if (mParameters != null) { Set<String> sKeys = mParameters.keySet(); if (fIsMultipart) { out.writeBytes("--" + BOUNDARY + "\r\n"); } for (String sKey : sKeys) { if (fIsMultipart) { out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n"); out.writeBytes(mParameters.get(sKey)); out.writeBytes("\r\n"); out.writeBytes("--" + BOUNDARY + "--\r\n"); } else { out.writeBytes(URLEncoder.encode(sKey, "UTF-8")); out.writeBytes("="); out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8")); out.writeBytes("&"); } } if (fIsMultipart) { if (nvpFile != null) { File f = Play.application().getFile(nvpFile.getName()); if (f == null) { assertFail("Cannot find file <" + nvpFile.getName() + ">"); } FileBody fb = new FileBody(f); out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE + "\";filename=\"" + fb.getFilename() + "\"\r\n"); out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n"); out.write(getResource(nvpFile.getName())); } out.writeBytes("\r\n--" + BOUNDARY + "--\r\n"); } } } catch (Exception ex) { assertFail("Send request: " + ex.getMessage()); } finally { try { out.flush(); } catch (Exception ex) { } try { out.close(); } catch (Exception ex) { } } } nRet = conn.getResponseCode(); setStatusCode(nRet); if (nRet / 100 != 2) { if (conn.getErrorStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } } else { if (conn.getInputStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } } if (br != null) { String temp = null; StringBuilder sb = new StringBuilder(1024); while ((temp = br.readLine()) != null) { sb.append(temp).append("\n"); } setResponse(sb.toString().trim()); } Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n"); } catch (Exception ex) { assertFail("httpRequest: " + ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (Exception ex) { } } if (conn != null) { conn.disconnect(); } } return nRet; }