List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("DELETE"); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }//from w ww . j av a2 s . c o m } // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send DELETE http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java
private String sendYeelightCommand(String location, String action, Object[] params) { int index = location.indexOf(":"); Socket clientSocket = null;// www .ja va 2s .com try { String ip = location.substring(0, index); int port = Integer.parseInt(location.substring(index + 1)); clientSocket = new Socket(ip, port); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String sentence = "{\"id\":" + msgid++ + ",\"method\":\"" + action + "\",\"params\":[" + getProperties(params) + "]}\r\n"; logger.debug("Sending sentence: {}", sentence); outToServer.writeBytes(sentence); return inFromServer.readLine(); } catch (NoRouteToHostException e) { logger.debug("Location {} is probably offline", location); if (action.equals(GET_PROP)) { //update switches if not found location to OFF state for (Object item : getOnSwitchItems(location)) { eventPublisher.postUpdate((String) item, OnOffType.OFF); } } } catch (IOException e) { logger.error(e.toString()); } finally { if (clientSocket != null) try { clientSocket.close(); } catch (IOException e) { //silence } } return null; }
From source file:com.evolveum.midpoint.gui.api.component.result.OperationResultPanel.java
private void initHeader(WebMarkupContainer box) { WebMarkupContainer iconType = new WebMarkupContainer(ID_ICON_TYPE); iconType.setOutputMarkupId(true);/*from w w w .j a v a2s .co m*/ iconType.add(new AttributeAppender("class", new AbstractReadOnlyModel<String>() { private static final long serialVersionUID = 1L; @Override public String getObject() { StringBuilder sb = new StringBuilder(); OpResult message = getModelObject(); switch (message.getStatus()) { case IN_PROGRESS: case NOT_APPLICABLE: sb.append(" fa-info"); break; case SUCCESS: sb.append(" fa-check"); break; case FATAL_ERROR: sb.append(" fa-ban"); break; case PARTIAL_ERROR: case UNKNOWN: case WARNING: case HANDLED_ERROR: default: sb.append(" fa-warning"); } return sb.toString(); } })); box.add(iconType); Label message = createMessage(); AjaxLink<String> showMore = new AjaxLink<String>(ID_MESSAGE) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { OpResult result = OperationResultPanel.this.getModelObject(); result.setShowMore(!result.isShowMore()); result.setAlreadyShown(false); // hack to be able to expand/collapse OpResult after rendered. target.add(OperationResultPanel.this); } }; showMore.add(message); box.add(showMore); AjaxLink<String> backgroundTask = new AjaxLink<String>(ID_BACKGROUND_TASK) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { final OpResult opResult = OperationResultPanel.this.getModelObject(); String oid = opResult.getBackgroundTaskOid(); if (oid == null || !opResult.isBackgroundTaskVisible()) { return; // just for safety } ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(oid, ObjectTypes.TASK); WebComponentUtil.dispatchToObjectDetailsPage(ref, getPageBase(), false); } }; backgroundTask.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return getModelObject().getBackgroundTaskOid() != null && getModelObject().isBackgroundTaskVisible(); } }); box.add(backgroundTask); AjaxLink<String> showAll = new AjaxLink<String>(ID_SHOW_ALL) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { showHideAll(true, OperationResultPanel.this.getModelObject(), target); } }; showAll.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return !OperationResultPanel.this.getModelObject().isShowMore(); } }); box.add(showAll); AjaxLink<String> hideAll = new AjaxLink<String>(ID_HIDE_ALL) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { showHideAll(false, OperationResultPanel.this.getModel().getObject(), target); } }; hideAll.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return OperationResultPanel.this.getModelObject().isShowMore(); } }); box.add(hideAll); AjaxLink<String> close = new AjaxLink<String>("close") { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { close(target); } }; box.add(close); DownloadLink downloadXml = new DownloadLink("downloadXml", new AbstractReadOnlyModel<File>() { private static final long serialVersionUID = 1L; @Override public File getObject() { String home = getPageBase().getMidpointConfiguration().getMidpointHome(); File f = new File(home, "result"); DataOutputStream dos = null; try { dos = new DataOutputStream(new FileOutputStream(f)); dos.writeBytes(OperationResultPanel.this.getModel().getObject().getXml()); } catch (IOException e) { LOGGER.error("Could not download result: {}", e.getMessage(), e); } finally { IOUtils.closeQuietly(dos); } return f; } }); downloadXml.setDeleteAfterDownload(true); box.add(downloadXml); }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse sendHttpPost(String url, String body, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("POST"); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }/*from w ww .jav a 2 s. c om*/ } // Send post request if (body != null) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod(methodType);/*w w w . j av a2s.c o m*/ // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); } } // Send post request if (body != null) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:com.plancake.api.client.PlancakeApiClient.java
/** * @param String request/* w w w. j av a2 s. c o m*/ * @param String httpMethod * @return String */ private String getResponse(String request, String httpMethod) throws MalformedURLException, IOException, PlancakeApiException { if (!(httpMethod.equals("GET")) && !(httpMethod.equals("POST"))) { throw new PlancakeApiException("httpMethod must be either GET or POST"); } String urlParameters = ""; if (httpMethod == "POST") { String[] requestParts = request.split("\\?"); request = requestParts[0]; urlParameters = requestParts[1]; } URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(httpMethod); if (httpMethod == "POST") { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { connection.setRequestProperty("Content-Type", "text/plain"); } connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setUseCaches(false); connection.connect(); if (httpMethod == "POST") { DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); } StringBuffer text = new StringBuffer(); InputStreamReader in = new InputStreamReader((InputStream) connection.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine(); while (line != null) { text.append(line + "\n"); line = buff.readLine(); } String response = text.toString(); if (response.length() == 0) { throw new PlancakeApiException("the response is empty"); } connection.disconnect(); return response; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod(method);//from w ww . j a v a 2 s . c om // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); } } if (body != null && !body.isEmpty() && !method.equals("DELETE")) { // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send {} http request, url: {}", method, url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { // response = null; logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); // if (response == null) { // restResponse.setResponse(null); // } else { // restResponse.setResponse(response.toString()); // } if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:com.sim2dial.dialer.ChatFragment.java
private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) { String fileName;// ww w . ja va 2 s .com if (filePath != null) { File sourceFile = new File(filePath); fileName = sourceFile.getName(); } else { fileName = getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis())); } if (getResources().getBoolean(R.bool.hash_images_as_name_before_upload)) { fileName = String.valueOf(hashBitmap(file)) + ".jpg"; } String response = null; HttpURLConnection conn = null; try { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "---------------------------14737809831466499882746641449"; URL url = new URL(uploadServerUri); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); 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("uploaded_file", fileName); ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream()); pos.setListener(new OutputStreamListener() { @Override public void onBytesWrite(int count) { bytesSent += count; progressBar.setProgress(bytesSent * 100 / imageSize); } }); DataOutputStream dos = new DataOutputStream(pos); dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes("Content-Type: application/octet-stream" + lineEnd); dos.writeBytes(lineEnd); file.compress(CompressFormat.JPEG, compressorQuality, dos); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead; byte[] bytes = new byte[1024]; while ((bytesRead = is.read(bytes)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] bytesReceived = baos.toByteArray(); baos.close(); is.close(); response = new String(bytesReceived); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return response; }
From source file:nu.nethome.home.items.hue.JsonRestClient.java
private String performRequest(String baseUrl, String resource, String body, String method) throws IOException { HttpURLConnection connection = null; DataOutputStream wr = null; BufferedReader rd = null;/*from w w w . j a va2s. c o m*/ StringBuilder sb = new StringBuilder(); String line; URL serverAddress; try { serverAddress = new URL(baseUrl + resource); //Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); if (body.length() > 0) { connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } connection.connect(); if (connection.getResponseCode() < 200 || connection.getResponseCode() > 299) { throw new ProtocolException("Bad HTTP response code: " + connection.getResponseCode()); } rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line); sb.append('\n'); } } finally { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } if (connection != null) { connection.disconnect(); } } return sb.toString(); }
From source file:nu.nethome.home.items.web.proxy.JsonRestClient.java
private String performRequest(String baseUrl, String resource, String body, String method) throws IOException { HttpURLConnection connection = null; DataOutputStream wr = null; BufferedReader rd = null;/*from www . j av a 2s . c o m*/ StringBuilder sb = new StringBuilder(); String line; URL serverAddress; try { serverAddress = new URL(baseUrl + resource); //Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); connection.setReadTimeout(15000); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); if (body.length() > 0) { connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } connection.connect(); if (connection.getResponseCode() < 200 || connection.getResponseCode() > 299) { throw new ProtocolException("Bad HTTP response code: " + connection.getResponseCode()); } rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line); sb.append('\n'); } } finally { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } if (connection != null) { connection.disconnect(); } } return sb.toString(); }