List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.pras.conn._HttpConHandler.java
/** * @param urlStr HTTP URL// w w w . j a v a 2 s .com * @param type Type of Connection (POST, GET, PUT or DELETE) * @param httpHeaders HTTP headers * @param postData Data to be sent as a part of POST/PUT request * * @return ATOM XML feed and Response/Error message */ public Response doConnect(String urlStr, int type, HashMap<String, String> httpHeaders, String postData) { String res = null; HttpURLConnection con = null; Response response = new Response(); String TAG = "HttpConHandler"; try { /* * IMPORTANT: * User SHOULD provide URL Encoded Parms */ Log.enableLog(); Log.p(TAG, "URL=" + urlStr); // Somehow Eclipse is not detecting Proxy // HTTP Proxy // System.getProperties().put("http.proxyHost", "168.219.61.250"); // System.getProperties().put("http.proxyPort", "8080"); // HTTPS Proxy // System.getProperties().put("https.proxyHost", "168.219.61.252"); // System.getProperties().put("https.proxyPort", "8080"); // TODO: Remove proxy // DROCA Initialisation du Proxy Log.p(TAG, "doConnect init proxy"); Proxy proxy = Proxy.NO_PROXY; proxy = getProxy(); // Log.p(TAG, "doConnect new URL BEFORE"); URL url = new URL(urlStr); // Log.p(TAG, "doConnect new URL AFTER"); // Log.p(TAG, "doConnect url.openConnection BEFORE"); con = (HttpURLConnection) url.openConnection(proxy); Log.p(TAG, "doConnect url.openConnection AFTER"); // // URL url = new URL(urlStr); // con = (HttpURLConnection) url.openConnection(); //con.setInstanceFollowRedirects(false); OutputStream out = null; // Set headers /* * All subsequent request to Google Spreadsheet/Data API * should include following 2 Headers */ //con.setRequestProperty("Authorization", "GoogleLogin auth="+ authToken); //con.setRequestProperty("GData-Version", "3.0"); if (httpHeaders != null) { Log.p(TAG, "Number of HTTP Headers: " + httpHeaders.size()); Iterator<String> keys = httpHeaders.keySet().iterator(); while (keys.hasNext()) { String k = keys.next(); con.setRequestProperty(k, httpHeaders.get(k)); } } Log.p(TAG, "doConnect type:" + type); if (type == HTTP_POST) { // Log.p(TAG, "doConnect HTTP_POST 1"); con.setDoOutput(true); // Log.p(TAG, "doConnect HTTP_POST 2"); out = con.getOutputStream(); // Log.p(TAG, "doConnect HTTP_POST 3"); out.write(postData.getBytes()); // Log.p(TAG, "doConnect HTTP_POST 4"); out.flush(); // Log.p(TAG, "doConnect HTTP_POST 5"); } else if (type == HTTP_GET) { // Log.p(TAG, "doConnect HTTP_GET 1"); con.setDoInput(true); // Log.p(TAG, "doConnect HTTP_GET 2"); } else if (type == HTTP_DELETE) { // Log.p(TAG, "doConnect HTTP_DELETE 1"); con.setRequestMethod("DELETE"); // Log.p(TAG, "doConnect HTTP_DELETE 2"); con.connect(); // Log.p(TAG, "doConnect HTTP_DELETE 3"); } else if (type == HTTP_PUT) { // Log.p(TAG, "doConnect HTTP_PUT 1"); con.setRequestMethod("PUT"); // Log.p(TAG, "doConnect HTTP_PUT 2"); // Send Data con.setDoOutput(true); // Log.p(TAG, "doConnect HTTP_PUT 3"); out = con.getOutputStream(); // Log.p(TAG, "doConnect HTTP_PUT 4"); out.write(postData.getBytes()); // Log.p(TAG, "doConnect HTTP_PUT 5"); out.flush(); // Log.p(TAG, "doConnect HTTP_PUT 6"); } // Read Response Code // Log.p(TAG, "doConnect response.setResponseCode con.getResponseCode():"+con.getResponseCode()+" BEFORE"); response.setResponseCode("" + con.getResponseCode()); // Log.p(TAG, "doConnect response.setResponseCode AFTER"); // Log.p(TAG, "doConnect response.setResponseCode con.setResponseMessage():"+con.getResponseMessage()+" BEFORE"); response.setResponseMessage(con.getResponseMessage()); // Log.p(TAG, "doConnect response.setResponseCode AFTER"); // Read InputStream // Log.p(TAG, "doConnect response.setResponseCode con.getInputStream BEFORE"); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); // Log.p(TAG, "doConnect response.setResponseCode con.getInputStream AFTER"); StringBuffer strBuf = new StringBuffer(); String line = ""; // Log.p(TAG, "doConnect response.setResponseCode reader.readLine() BEFORE"); try { while ((line = reader.readLine()) != null) { // Log.p(TAG, "doConnect response.setResponseCode reader.readLine() line:"+line); strBuf.append(line); } } // DROCA : Pour contourner une erreur (pb genere quant connexion via proxy) // Message : [HttpConHandler] Error in reading response: java.net.SocketException: Socket is closed catch (Exception ex) { Log.p(TAG, "Error in reading response: " + ex.toString()); } // Log.p(TAG, "doConnect response.setResponseCode reader.readLine() AFTER"); // Log.p(TAG, "doConnect response.setResponseCode reader.close() BEFORE"); reader.close(); // Log.p(TAG, "doConnect response.setResponseCode reader.close() AFTER"); if (out != null) out.close(); res = strBuf.toString(); response.setOutput(res); Log.p(TAG, "Response from Google Server: \n" + res); } catch (Exception ex) { Log.p(TAG, "Error in connection: " + ex.toString()); // Oops Exception response.setError(true); // Set Exception response.setException(ex); if (con == null) return response; InputStream error_in = con.getErrorStream(); if (error_in == null) return response; // Read the error stream BufferedReader reader = new BufferedReader(new InputStreamReader(error_in)); if (reader == null) return response; StringBuffer errStrBuf = new StringBuffer(); String line = ""; try { while ((line = reader.readLine()) != null) errStrBuf.append(line); // Set Error Stream Message response.setErrorStreamMsg(errStrBuf.toString()); reader.close(); // Display error on logging console response.printErrorLog(); } catch (Exception e) { Log.p(TAG, "Error in reading Stream: " + e.getMessage()); } } return response; }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
@Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { try {/* w w w . java2s . c o m*/ final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer); String expandedUrl = formatter.format(url); String querystring = ""; if (!params.isEmpty()) { querystring = params.entrySet().stream().map( e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue())) .collect(Collectors.joining("&")); expandedUrl = expandedUrl.concat("?").concat(querystring); } StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ") .append(expandedUrl); URL requestUrl = new URL(expandedUrl); HttpURLConnection httpURLConnection; if (truststorePath != null && expandedUrl.startsWith("https://")) { httpURLConnection = openSecureConnection(requestUrl); } else { httpURLConnection = (HttpURLConnection) requestUrl.openConnection(); } callDump.append("\n ").append("Method: " + method); callDump.append("\n ").append("Connection timeout: " + connectionTimeout); callDump.append("\n ").append("Read timeout: " + readTimeout); httpURLConnection.setRequestMethod(method); httpURLConnection.setConnectTimeout(connectionTimeout); httpURLConnection.setReadTimeout(readTimeout); for (Entry<String, String> header : headers.entrySet()) { String k = formatter.format(header.getKey()); String v = formatter.format(header.getValue()); httpURLConnection.setRequestProperty(k, v); callDump.append("\n ").append("Header: " + k + "=" + v); if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) { body = querystring; } } if (sendGVBufferObject && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length)); callDump.append("\n ").append("Content-Length: " + requestData.length); callDump.append("\n ").append("Request body: binary"); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(requestData); dataOutputStream.flush(); dataOutputStream.close(); } else if (Objects.nonNull(body) && body.length() > 0) { String expandedBody = formatter.format(body); callDump.append("\n ").append("Request body: " + expandedBody); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(expandedBody); outputStreamWriter.flush(); outputStreamWriter.close(); } httpURLConnection.connect(); InputStream responseStream = null; try { httpURLConnection.getResponseCode(); responseStream = httpURLConnection.getInputStream(); } catch (IOException connectionFail) { responseStream = httpURLConnection.getErrorStream(); } for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) { if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) { gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()), header.getValue().stream().collect(Collectors.joining(";"))); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { // No content gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode())); gvBuffer.setProperty(RESPONSE_MESSAGE, Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL")); httpURLConnection.disconnect(); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }
From source file:com.cr_wd.android.network.HttpClient.java
/** * Performs a HTTP GET/POST Request// w w w . jav a 2 s . c o m * * @return id of the request */ protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params, final HttpHandler handler) { if (headers == null) { headers = new HttpHeaders(); } if (params == null) { params = new HttpParams(); } handler.client = this; final int requestId = incrementRequestId(); class HandlerRunnable extends Handler implements Runnable { private final Method method; private String url; private final HttpHeaders headers; private final HttpParams params; private final HttpHandler handler; private HttpResponse response; private boolean canceled = false; private int retries = 0; protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers, final HttpParams params, final HttpHandler handler) { this.method = method; this.url = url; this.headers = headers; this.params = params; this.handler = handler; } @Override public void run() { execute(); } private void execute() { response = new HttpResponse(requestId, method, url); HttpURLConnection conn = null; try { /* append query string for GET requests */ if (method == Method.GET) { if (!params.urlParams.isEmpty()) { url += ('?' + params.getParamString()); } } /* setup headers for POST requests */ if (method == Method.POST) { headers.addHeader("Accept-Charset", requestOptions.encoding); if (params.hasMultipartParams()) { final SimpleMultipart multipart = params.getMultipart(); headers.addHeader("Content-Type", multipart.getContentType()); } else { headers.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + requestOptions.encoding); } } if (canceled) { postCancel(); return; } /* open and configure the connection */ conn = (HttpURLConnection) new URL(url).openConnection(); postStart(); if (method == Method.GET) { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); } else if (method == Method.POST) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); } conn.setAllowUserInteraction(false); conn.setReadTimeout(requestOptions.readTimeout); conn.setConnectTimeout(requestOptions.connectTimeout); /* add headers to the connection */ for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) { for (final String value : entry.getValue()) { conn.addRequestProperty(entry.getKey(), value); } } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.requestProperties = conn.getRequestProperties(); /* do post */ if (method == Method.POST) { InputStream is; if (params.hasMultipartParams()) { is = params.getMultipart().getContent(); } else { is = new ByteArrayInputStream(params.getParamString().getBytes()); } final OutputStream os = conn.getOutputStream(); writeStream(os, is); } else { conn.connect(); } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.contentEncoding = conn.getContentEncoding(); response.contentLength = conn.getContentLength(); response.contentType = conn.getContentType(); response.date = conn.getDate(); response.expiration = conn.getExpiration(); response.headerFields = conn.getHeaderFields(); response.ifModifiedSince = conn.getIfModifiedSince(); response.lastModified = conn.getLastModified(); response.responseCode = conn.getResponseCode(); response.responseMessage = conn.getResponseMessage(); /* do get */ if (conn.getResponseCode() < 400) { response.responseBody = readStream(conn.getInputStream()); postSuccess(); } else { response.responseBody = readStream(conn.getErrorStream()); response.throwable = new Exception(response.responseMessage); postError(); } } catch (final Exception e) { if (retries < requestOptions.maxRetries) { retries++; postRetry(); execute(); } else { response.responseBody = e.getMessage(); response.throwable = e; postError(); } } finally { if (conn != null) { conn.disconnect(); } } } private String readStream(final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); final ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } return new String(baf.toByteArray()); } private void writeStream(final OutputStream os, final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } os.write(buffer, 0, read); } if (!canceled) { os.flush(); } try { os.close(); } catch (final IOException e) { } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } } @Override public void handleMessage(final Message msg) { if (msg.what == HttpHandler.MESSAGE_CANCEL) { canceled = true; } } private void postSuccess() { postMessage(HttpHandler.MESSAGE_SUCCESS); } private void postError() { postMessage(HttpHandler.MESSAGE_ERROR); } private void postCancel() { postMessage(HttpHandler.MESSAGE_CANCEL); } private void postStart() { postMessage(HttpHandler.MESSAGE_START); } private void postRetry() { postMessage(HttpHandler.MESSAGE_RETRY); } private void postMessage(final int what) { final Message msg = handler.obtainMessage(); msg.what = what; msg.arg1 = requestId; msg.obj = response; handler.sendMessage(msg); } } ; /* Create a new HandlerRunnable and start it */ final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler); requests.put(requestId, new WeakReference<Handler>(hr)); new Thread(hr).start(); /* Return with the request id */ return requestId; }
From source file:com.google.ytd.picasa.PicasaApiHelper.java
public PhotoEntry doResumableUpload(com.google.ytd.model.PhotoEntry photoEntry) throws IllegalArgumentException { if (util.isNullOrEmpty(photoEntry.getResumableUploadUrl())) { throw new IllegalArgumentException(String .format("No resumable upload URL found for " + "PhotoEntry id '%s'.", photoEntry.getId())); }/*from w w w. jav a2 s . c om*/ try { URL url = new URL(photoEntry.getResumableUploadUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Range", "bytes */*"); // Response code 308 is specific to this use case and doesn't appear to have a // HttpURLConnection constant. if (connection.getResponseCode() == 308) { long previousByte = 0; String rangeHeader = connection.getHeaderField("Range"); if (!util.isNullOrEmpty(rangeHeader)) { LOG.info("Range header in 308 response is " + rangeHeader); String[] rangeHeaderSplits = rangeHeader.split("-", 2); if (rangeHeaderSplits.length == 2) { previousByte = Long.valueOf(rangeHeaderSplits[1]).longValue() + 1; } } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); byte[] bytes; String contentRangeHeader; if (photoEntry.getBlobKey() != null) { long lastByte = previousByte + CHUNK_SIZE; if (lastByte > (photoEntry.getOriginalFileSize() - 1)) { lastByte = photoEntry.getOriginalFileSize() - 1; } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, lastByte, photoEntry.getOriginalFileSize()); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); bytes = blobstoreService.fetchData(photoEntry.getBlobKey(), previousByte, lastByte); } else { bytes = dataChunkDao.getBytes(photoEntry.getId(), previousByte); if (bytes == null) { throw new IllegalArgumentException(String.format("PhotoEntry with id '%s' does not " + "have a valid blob key. Additionally, there is no DataChunk entry for the " + "initial byte '%d'.", photoEntry.getId(), previousByte)); } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, previousByte + bytes.length - 1, photoEntry.getOriginalFileSize()); } connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); LOG.info("Using the following for Content-Range header: " + contentRangeHeader); connection.setRequestProperty("Content-Range", contentRangeHeader); OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } } else if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { // It's possible that the Picasa upload associated with the specific resumable upload URL // had previously completed successfully. In that case, the response to the initial */* PUT // will be a 201 Created with the new PhotoEntry. This is probably an edge case. LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } else { // The IllegalArgumentException should be treated by the calling code as // something that is not recoverable, which is to say the resumable upload attempt // should be stopped. throw new IllegalArgumentException(String.format("HTTP POST to %s returned status %d (%s).", url.toString(), connection.getResponseCode(), connection.getResponseMessage())); } } catch (MalformedURLException e) { LOG.log(Level.WARNING, "", e); throw new IllegalArgumentException(e); } catch (IOException e) { LOG.log(Level.WARNING, "", e); } catch (ServiceException e) { LOG.log(Level.WARNING, "", e); } return null; }
From source file:com.sun.faces.systest.ant.SystestClient.java
/** * Execute the test via use of an HttpURLConnection. * * @throws BuildException if an exception occurs *///from w w w .j a va 2s . c o m protected void executeHttp() throws BuildException { // Construct a summary of the request we will be sending String summary = "[" + method + " " + request + "]"; boolean success = true; String result = null; Throwable throwable = null; HttpURLConnection conn = null; try { // Configure an HttpURLConnection for this request if (log.isDebugEnabled()) { log.debug("Configuring HttpURLConnection for this request"); } URL url = new URL("http", host, port, request); conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); conn.setDoInput(true); if (inContent != null) { conn.setDoOutput(true); conn.setRequestProperty("Content-Length", "" + inContent.length()); if (log.isTraceEnabled()) { log.trace("INPH: Content-Length: " + inContent.length()); } } else { conn.setDoOutput(false); } // Send the session id cookie (if any) if (joinSession && (sessionId != null)) { conn.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); if (log.isTraceEnabled()) { log.trace("INPH: Cookie: JSESSIONID=" + sessionId); } } if (this.redirect && log.isTraceEnabled()) { log.trace("FLAG: setInstanceFollowRedirects(" + this.redirect + ")"); } conn.setInstanceFollowRedirects(this.redirect); conn.setRequestMethod(method); if (inHeaders != null) { String headers = inHeaders; while (headers.length() > 0) { int delimiter = headers.indexOf("##"); String header = null; if (delimiter < 0) { header = headers; headers = ""; } else { header = headers.substring(0, delimiter); headers = headers.substring(delimiter + 2); } int colon = header.indexOf(":"); if (colon < 0) break; String name = header.substring(0, colon).trim(); String value = header.substring(colon + 1).trim(); conn.setRequestProperty(name, value); if (log.isTraceEnabled()) { log.trace("INPH: " + name + ": " + value); } } } // Connect to the server and send our output if necessary conn.connect(); if (inContent != null) { if (log.isTraceEnabled()) { log.trace("INPD: " + inContent); } OutputStream os = conn.getOutputStream(); for (int i = 0, length = inContent.length(); i < length; i++) os.write(inContent.charAt(i)); os.close(); } // Acquire the response data, if there is any String outData = ""; String outText = ""; boolean eol = false; InputStream is = conn.getInputStream(); int lines = 0; while (true) { String line = read(is); if (line == null) break; if (lines == 0) outData = line; else outText += line + "\r\n"; saveResponse.add(line); lines++; } is.close(); // Dump out the response stuff if (log.isTraceEnabled()) { log.trace("RESP: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } for (int i = 1; i < 1000; i++) { String name = conn.getHeaderFieldKey(i); String value = conn.getHeaderField(i); if ((name == null) || (value == null)) break; if (log.isTraceEnabled()) { log.trace("HEAD: " + name + ": " + value); } save(name, value); if ("Set-Cookie".equals(name)) parseSession(value); } if (log.isTraceEnabled()) { log.trace("DATA: " + outData); if (outText.length() > 2) { log.trace("TEXT: " + outText); } } // Validate the response against our criteria if (success) { result = validateStatus(conn.getResponseCode()); if (result != null) success = false; } if (success) { result = validateMessage(conn.getResponseMessage()); if (result != null) success = false; } if (success) { result = validateHeaders(); if (result != null) success = false; } if (success) { result = validateData(outData); if (result != null) success = false; } if (success) { result = validateGolden(); if (result != null) success = false; } } catch (Throwable t) { if (t instanceof FileNotFoundException) { if (status == 404) { success = true; result = "Not Found"; throwable = null; } else { success = false; try { result = "Status=" + conn.getResponseCode() + ", Message=" + conn.getResponseMessage(); } catch (IOException e) { result = e.toString(); } throwable = null; } } else if (t instanceof ConnectException) { success = false; result = t.getMessage(); throwable = null; } else { success = false; result = t.getMessage(); throwable = t; } } // Log the results of executing this request if (success) { System.out.println("OK " + summary); } else { System.out.println("FAIL " + summary + " " + result); if (throwable != null) throwable.printStackTrace(System.out); if (failonerror) { if (throwable != null) { throw new BuildException("System test failed", throwable); } else { throw new BuildException("System test failed"); } } } }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** *// w w w. j a v a 2 s. c o m * @param url * @param requestStr * @param messageContext * @return */ public String makeCreditRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED 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); connection.setDoInput(true); connection.setDoOutput(true); log.debug("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()); log.debug("Southbound Request Headers: " + connection.getRequestProperties()); log.debug("Southbound Request Body: " + requestStr); //UNICODE BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 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(); log.debug("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()); log.debug("Southbound Response Headers: " + connection.getHeaderFields()); log.debug("Southbound Response Body: " + retStr); } catch (Exception e) { log.error("[CreditRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make get request./*from ww w . j a v a2 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 makeGetRequest(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("GET"); connection.setRequestProperty("Accept", "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)); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 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(); 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:com.wso2telco.dep.mediator.RequestExecutor.java
public String makeRetrieveSMSGetRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { Gson gson = new GsonBuilder().serializeNulls().create(); int statusCode = 0; String retStr = ""; URL neturl;/* w ww . j a va 2s. co m*/ 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("GET"); connection.setRequestProperty("Accept", "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)); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 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(); 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)); SouthboundRetrieveResponse sbRetrieveResponse = gson.fromJson(retStr, SouthboundRetrieveResponse.class); if (sbRetrieveResponse != null && sbRetrieveResponse.getInboundSMSMessageList() != null) { if (sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage() != null && sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage().length != 0) { InboundSMSMessage[] inboundSMSMessageResponses = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponses.length)); } else { InboundSMSMessage[] inboundSMSMessageResponses = new InboundSMSMessage[0]; InboundSMSMessageList inboundSMSMessageList = new InboundSMSMessageList(); inboundSMSMessageList.setInboundSMSMessage(inboundSMSMessageResponses); inboundSMSMessageList.setNumberOfMessagesInThisBatch("0"); inboundSMSMessageList.setResourceURL("Not Available"); inboundSMSMessageList.setTotalNumberOfPendingMessages("0"); sbRetrieveResponse.setInboundSMSMessageList(inboundSMSMessageList); InboundSMSMessage[] inboundSMSMessageResponsesN = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponsesN.length)); } } else { messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); } } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }
From source file:org.apache.openaz.xacml.rest.XACMLPdpRegisterThread.java
/** * This is our thread that runs on startup to tell the PAP server we are up-and-running. *//*from ww w . j av a 2s .c o m*/ @Override public void run() { synchronized (this) { this.isRunning = true; } boolean registered = false; boolean interrupted = false; int seconds; try { seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); seconds = 5; } if (seconds < 5) { seconds = 5; } int retries; try { retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); retries = -1; } while (!registered && !interrupted && this.isRunning()) { HttpURLConnection connection = null; try { // // Get the PAP Servlet URL // URL url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); logger.info("Registering with " + url.toString()); boolean finished = false; while (!finished) { // // Open up the connection // connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "text/x-java-properties"); connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); try { // // Send our current policy configuration // String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES) + "\n"; try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); OutputStream os = connection.getOutputStream()) { IOUtils.copy(listsInputStream, os); // // Send our current PIP configuration // IOUtils.copy(pipInputStream, os); } } catch (Exception e) { logger.error("Failed to send property file", e); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 204) { logger.info("Success. We are configured correctly."); finished = true; registered = true; } else if (connection.getResponseCode() == 200) { logger.info("Success. We have a new configuration."); Properties properties = new Properties(); properties.load(connection.getInputStream()); logger.info("New properties: " + properties.toString()); // // Queue it // // The incoming properties does NOT include urls PutRequest req = new PutRequest(XACMLProperties.getPolicyProperties(properties, false), XACMLProperties.getPipProperties(properties)); XACMLPdpServlet.queue.offer(req); // // We are now registered // finished = true; registered = true; } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // // Re-direction // String newLocation = connection.getHeaderField("Location"); if (newLocation == null || newLocation.isEmpty()) { logger.warn("Did not receive a valid re-direction location"); finished = true; } else { logger.info("New Location: " + newLocation); url = new URL(newLocation); } } else { logger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); finished = true; } } } catch (Exception e) { logger.error(e); } finally { // cleanup the connection if (connection != null) { try { // For some reason trying to get the inputStream from the connection // throws an exception rather than returning null when the InputStream does not exist. InputStream is = null; try { is = connection.getInputStream(); } catch (Exception e1) { //NOPMD // ignore this } if (is != null) { is.close(); } } catch (IOException ex) { logger.error("Failed to close connection: " + ex, ex); } connection.disconnect(); } } // // Wait a little while to try again // try { if (!registered) { if (retries > 0) { retries--; } else if (retries == 0) { break; } Thread.sleep(seconds * 1000); } } catch (InterruptedException e) { interrupted = true; this.terminate(); } } synchronized (this) { this.isRunning = false; } logger.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + retries + ")"); }