List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:JavaTron.AudioTron.java
/** * Method to execute a POST Request to the Audiotron - JSC * // ww w .j a v a 2 s. c o m * @param address - The requested page * @param args - The POST data * @param parser - A Parser Object fit for parsing the response * * @return null on success, a string on error. The string describes * the error. * * @throws IOException */ protected String post(String address, Vector args, Parser parser) throws IOException { String ret = null; URL url; HttpURLConnection conn; String formData = new String(); // Build the POST data for (int i = 0; i < args.size(); i += 2) { if (showPost) { System.out.print("POST: " + args.get(i).toString() + " = "); System.out.println(args.get(i + 1).toString()); } formData += URLEncoder.encode(args.get(i).toString(), "UTF-8") + "=" + URLEncoder.encode(args.get(i + 1).toString(), "UTF-8"); if (i + 2 != args.size()) formData += "&"; } // Build the connection Headers and POST the data try { url = new URL("http://" + getServer() + address); if (showAddress || showPost) { System.out.println("POST: " + address); System.out.println("POST: " + formData); } conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", USER_AGENT); // Authorization header String auth = getUsername() + ":" + getPassword(); conn.setRequestProperty("Authorization", "Basic " + B64Encode(auth.getBytes())); // Debug if (showAuth) { System.out.println("POST: AUTH: " + auth); } conn.setRequestProperty("Content Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "" + Integer.toString(formData.getBytes().length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); // Send the request to the audiotron DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(formData); wr.flush(); wr.close(); // Process the Response if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) { try { ret = conn.getResponseMessage(); } catch (IOException ioe) { ioe.printStackTrace(); } if (ret == null) { ret = "Unknown Error"; } if (parser != null) { parser.begin(ret); } return ret; } isr = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(isr); String s; getBuffer = new StringBuffer(); if (parser != null) { parser.begin(null); } while ((s = reader.readLine()) != null) { if (showGet) { System.out.println(s); } getBuffer.append(s); getBuffer.append("\n"); if (parser == null) { // getBuffer.append(s); } else { if (!parser.parse(s)) { return "Parse Error"; } } } if (parser == null && showUnparsedOutput) { System.out.println(getBuffer); } if (parser != null) { parser.end(false); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { // if this happens, call the parse method if there is a parser // with a null value to indicate an error if (parser != null) { parser.end(true); } throw (ioe); } finally { try { isr.close(); } catch (Exception e) { // this is ok } } return ret; }
From source file:org.openxdata.server.servlet.DataImportServletTest.java
@Test @Ignore("this is an integration test for localhost") public void integrationTest() throws Exception { final String urlString = "http://localhost:8888/org.openxdata.server.admin.OpenXDataServerAdmin/dataimport?msisdn=2222222"; final String userName = "dagmar"; final String password = "dagmar"; // open url connection URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true);/* w w w . ja va2 s.c o m*/ con.setDoInput(true); con.setChunkedStreamingMode(1024); // stuff the Authorization request header byte[] encodedPassword = (userName + ":" + password).getBytes(); con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(encodedPassword))); // put the form data on the output stream DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.writeByte(new Integer(1)); String data = "<?xml version='1.0' encoding='UTF-8' ?><cmt_lesotho_tlpp_session_report_v1 formKey=\"cmt_lesotho_tlpp_session_report_v1\" id=\"2\" name=\"Treatment literacy programme_v1\" xmlns:xf=\"http://www.w3.org/2002/xforms\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <name>TEEHEE</name> <session_type>treatment_literacy_session</session_type> <session_date>2010-04-15</session_date> <district>berea</district> <session_location>secondary_school</session_location> <session_location_other/> <session_place_name>dsds</session_place_name> <participant_number_male>1</participant_number_male> <participant_number_female>2</participant_number_female> <session_start_time>10:22:00</session_start_time> <session_finish_time>01:22:00</session_finish_time> <session_topic>children_HIV_incl_ARVs</session_topic> <session_topic_other/> <support_group>false</support_group> <one_on_one_session>false</one_on_one_session> <CMT_AV_kit>false</CMT_AV_kit> <CMT_DVD>false</CMT_DVD> <CMT_co_facilitator>false</CMT_co_facilitator> <co_facilitator_name/> <clinic_hospital_department/> <clinic_hospital_department_other/> <clinic_hospital_TV/> <school_grade>12</school_grade> <school_CMT_materials>true</school_CMT_materials> <session_confirmed>true</session_confirmed></cmt_lesotho_tlpp_session_report_v1>"; out.writeUTF(data); out.flush(); // pull the information back from the URL InputStream is = con.getInputStream(); StringBuffer buf = new StringBuffer(); int c; while ((c = is.read()) != -1) { buf.append((char) c); } con.disconnect(); // output the information System.out.println(buf); }
From source file:com.trifork.riak.RiakClient.java
public ByteString[] store(RiakObject[] values, RequestMeta meta) throws IOException { RiakConnection c = getConnection();/*from w w w . j av a 2s .c o m*/ try { BulkReader reader = new BulkReader(c, values.length); Thread worker = new Thread(reader); worker.start(); DataOutputStream dout = c.getOutputStream(); for (int i = 0; i < values.length; i++) { RiakObject value = values[i]; RPB.RpbPutReq.Builder builder = RPB.RpbPutReq.newBuilder().setBucket(value.getBucketBS()) .setKey(value.getKeyBS()).setContent(value.buildContent()); if (value.getVclock() != null) { builder.setVclock(value.getVclock()); } builder.setReturnBody(false); if (meta != null) { if (meta.writeQuorum != null) { builder.setW(meta.writeQuorum.intValue()); } if (meta.durableWriteQuorum != null) { builder.setDw(meta.durableWriteQuorum.intValue()); } } RpbPutReq req = builder.build(); int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(MSG_PutReq); req.writeTo(dout); } dout.flush(); try { worker.join(); } catch (InterruptedException e) { e.printStackTrace(); } return reader.vclocks; } finally { release(c); } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
private void getBatteryInfo() { Process sh = null;/*from ww w. j a va 2 s . c o m*/ DataOutputStream os = null; try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); dumpsysTimestamp = System.currentTimeMillis(); String Command = "dumpsys batteryinfo > " + mApp.getTcpDumpTraceFolderName() + outBatteryInfoFileName + "\n"; os.writeBytes(Command); os.flush(); Log.d(TAG, "getBatteryInfo timestamp " + dumpsysTimestamp); Runtime.getRuntime().exec("cat " + dumpsysTimestamp + " >> " + mApp.getTcpDumpTraceFolderName() + outBatteryInfoFileName + "\n"); } catch (IOException e) { Log.e(TAG, "exception in getBatteryInfo ", e); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "exception in getBatteryInfo closing output stream ", e); } } }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make tokenrequest.//from w ww .ja v a 2 s. c om * * @param tokenurl * the tokenurl * @param urlParameters * the url parameters * @param authheader * the authheader * @return the string */ protected String makeTokenrequest(String tokenurl, String urlParameters, String authheader, MessageContext messageContext) { ICallresponse icallresponse = null; String retStr = ""; URL neturl; HttpURLConnection connection = null; log.info("url : " + tokenurl + " | urlParameters : " + urlParameters + " | authheader : " + authheader + " Request ID: " + UID.getRequestID(messageContext)); if ((tokenurl != null && tokenurl.length() > 0) && (urlParameters != null && urlParameters.length() > 0) && (authheader != null && authheader.length() > 0)) { try { byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(tokenurl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authheader); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postData); wr.flush(); wr.close(); if ((connection.getResponseCode() != 200) && (connection.getResponseCode() != 201) && (connection.getResponseCode() != 400) && (connection.getResponseCode() != 401)) { log.info("connection.getResponseMessage() : " + connection.getResponseMessage()); throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode()); } InputStream is = null; if ((connection.getResponseCode() == 200) || (connection.getResponseCode() == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } } else { log.error("Token refresh details are invalid."); } return retStr; }
From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java
public void uploadFiles(long companyId, long groupId, long userId, File file, long fileTypeId, String[] assetTagNames) throws IOException, PortalException { String fileName = file.getName(); if (!fileName.endsWith(".zip")) { if (_log.isWarnEnabled()) { _log.warn(">>> Unsupported compressed file type. Supports ZIP" + "compressed files only. "); }//from w ww . j a va 2s . co m throw new FileUploaderException("error.unsupported-file-type"); } DataOutputStream outputStream = null; try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) { ZipEntry fileEntry; while ((fileEntry = inputStream.getNextEntry()) != null) { boolean isDir = fileEntry.isDirectory(); boolean isSubDirFile = fileEntry.getName().contains(SLASH); if (isDir || isSubDirFile) { if (_log.isWarnEnabled()) { _log.warn(">>> Directory found inside the zip file " + "uploaded."); } continue; } String fileEntryName = fileEntry.getName(); String extension = PERIOD + FileUtil.getExtension(fileEntryName); File tempFile = null; try { tempFile = File.createTempFile("tempfile", extension); byte[] buffer = new byte[INPUT_BUFFER]; outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile))); int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); String fileDescription = BLANK; String changeLog = BLANK; uploadFile(companyId, groupId, userId, tempFile, fileDescription, fileEntryName, fileTypeId, changeLog, assetTagNames); } finally { StreamUtil.cleanUp(outputStream); if ((tempFile != null) && tempFile.exists()) { tempFile.delete(); } } } } catch (FileNotFoundException fnfe) { if (_log.isWarnEnabled()) { _log.warn(">>> Unable to upload files" + fnfe); } } }
From source file:com.smartbear.collaborator.issue.IssueRest.java
/** * Uploads zip file of raw files to Collaborator server * /*w ww. j ava 2s .c om*/ * @param targetZipFile * @throws Exception */ private void uploadRawFilesToCollab(java.io.File targetZipFile) throws Exception { HttpURLConnection httpUrlConnection = null; try { String crlf = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; URL url = new URL(configModel.getUrl() + URI_COLAB_UPLOAD); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); String loginCookie = "CodeCollaboratorLogin=" + configModel.getLogin(); String ticketCookie = "CodeCollaboratorTicketId=" + configModel.getAuthTicket(); httpUrlConnection.setRequestProperty("Cookie", loginCookie + "," + ticketCookie); DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream()); request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + targetZipFile.getName() + "\"" + crlf); request.writeBytes("Content-Type: application/x-zip-compressed" + crlf); request.writeBytes(crlf); InputStream fileInStream = new FileInputStream(targetZipFile); request.write(IOUtils.toByteArray(fileInStream)); request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); request.flush(); request.close(); if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception(); } } catch (Exception e) { LOGGER.error(e); throw new Exception( "Can't upload raw versions to Collaborator Server. Check plugin collaborator configuration (url, login, password).", e); } finally { if (httpUrlConnection != null) { httpUrlConnection.disconnect(); } } }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make delete request.// w w w. j a v a 2 s . c o m * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @return the string */ public String makeDeleteRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { int statusCode = 0; String retStr = ""; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Content-Type", "application/json"); if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a // ConcurrentModificationException } } } connection.setUseCaches(false); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); if (requestStr != null) { connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestStr); wr.flush(); wr.close(); } statusCode = connection.getResponseCode(); log.info("response code: " + statusCode); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401) && (statusCode != 204)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201) || (statusCode == 204)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }
From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java
public TokenRequester getTokenRequester() { final OnlineControllerFragment self = this; final TokenRequester requester = new TokenRequester(); requester.setRunnable(new Runnable() { @Override/*from w ww . j a v a 2s .co m*/ public void run() { String url = self.getPreferencesEditor().getString("preference_server_login", self.getString(R.string.preference_value_login)); try { URL location = new URL(url); HttpsURLConnection s_connection = null; HttpURLConnection connection = null; InputStream input; int responseCode; boolean isHttps = url.contains("https"); DataOutputStream writeStream; if (isHttps) { s_connection = (HttpsURLConnection) location.openConnection(); s_connection.setRequestMethod("POST"); writeStream = new DataOutputStream(s_connection.getOutputStream()); } else { connection = (HttpURLConnection) location.openConnection(); connection.setRequestMethod("POST"); writeStream = new DataOutputStream(connection.getOutputStream()); } StringBuilder urlParams = new StringBuilder(); urlParams.append("name=").append(Build.MODEL).append("&email=").append(self.getOwnerEmail()) .append("&host=").append(true).append("&longitude=").append(self.longitude) .append("&latitude=").append(self.latitude); writeStream.writeBytes(urlParams.toString()); writeStream.flush(); writeStream.close(); if (isHttps) { input = s_connection.getInputStream(); responseCode = s_connection.getResponseCode(); } else { input = connection.getInputStream(); responseCode = connection.getResponseCode(); } if (input != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input)); String line; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } input.close(); requester.finishRequest(result); } } catch (IOException e) { //e.printStackTrace(); requester.cancelRequest(e); } } }); return requester; }
From source file:ManagerQuery.java
private void notifyEvent(String eventType, String furtherDetails) { Properties conf2 = new Properties(); try {/*from ww w . ja va 2s. c o m*/ FileInputStream in = new FileInputStream("./config.properties"); conf2.load(in); in.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } String url = conf2.getProperty("notificatorRestInterfaceUrl"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr"); String apiPwd = conf2.getProperty("notificatorRestInterfacePwd"); String operation = "notifyEvent"; String generatorOriginalName = this.idProc; String generatorOriginalType = this.metricType; String containerName = this.dataSourceId; Calendar date = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String eventTime = sdf.format(date.getTime()); String appName = "Dashboard Data Process"; String params = null; URL obj = null; HttpURLConnection con = null; try { obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Charset", charset); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); params = String.format( "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&furtherDetails=%s", URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset), URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset), URLEncoder.encode(generatorOriginalName, charset), URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset), URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset), URLEncoder.encode(furtherDetails, charset)); } catch (MalformedURLException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } // Questo rende la chiamata una POST con.setDoOutput(true); DataOutputStream wr = null; try { wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); String responseMessage = con.getResponseMessage(); } catch (IOException ex) { Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex); } }