Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getErrorStream.

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:com.rapid.actions.Webservice.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    _logger.trace("Webservice action : " + jsonAction);

    // get the application
    Application application = rapidRequest.getApplication();

    // get the page
    Page page = rapidRequest.getPage();/*from   w w  w .  jav  a2s . c o  m*/

    // get the webservice action call sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // placeholder for the object we're about to return
    JSONObject jsonData = null;

    // only proceed if there is a request and application and page
    if (_request != null && application != null && page != null) {

        // get any json inputs 
        JSONArray jsonInputs = jsonAction.optJSONArray("inputs");

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Webservice action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString());

        }

        // if there is either no cache or we got no data
        if (jsonData == null) {

            // get the body into a string
            String body = _request.getBody().trim();
            // remove prolog if present
            if (body.indexOf("\"?>") > 0)
                body = body.substring(body.indexOf("\"?>") + 3).trim();
            // check number of parameters
            int pCount = Strings.occurrences(body, "?");
            // throw error if incorrect
            if (pCount != jsonInputs.length())
                throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", "
                        + jsonInputs.length() + " provided");
            // retain the current position
            int pos = body.indexOf("?");
            // keep track of the index of the ?
            int index = 0;
            // if there are any question marks
            if (pos > 0 && jsonInputs.length() > index) {
                // loop, but check condition at the end
                do {
                    // get the input
                    JSONObject input = jsonInputs.getJSONObject(index);
                    // url escape the value
                    String value = XML.escape(input.optString("value"));
                    // replace the ? with the input value
                    body = body.substring(0, pos) + value + body.substring(pos + 1);
                    // look for the next question mark
                    pos = body.indexOf("?", pos + 1);
                    // inc the index for the next round
                    index++;
                    // stop looping if no more ?
                } while (pos > 0);
            }

            // retrieve the action
            String action = _request.getAction();
            // create a placeholder for the request url
            URL url = null;
            // get the request url
            String requestURL = _request.getUrl();

            // if we got one
            if (requestURL != null) {

                // if the given request url starts with http use it as is, otherwise use the soa servlet
                if (_request.getUrl().startsWith("http")) {
                    // trim it
                    requestURL = requestURL.trim();
                    // insert any parameters
                    requestURL = application
                            .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL);
                    // use the url 
                    url = new URL(requestURL);
                } else {
                    // get our request
                    HttpServletRequest httpRequest = rapidRequest.getRequest();
                    // make a url for the soa servlet
                    url = new URL(httpRequest.getScheme(), httpRequest.getServerName(),
                            httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa");
                    // check whether we have any id / version seperators
                    String[] actionParts = action.split("/");
                    // add this app and version if none
                    if (actionParts.length < 2)
                        action = application.getId() + "/" + application.getVersion() + "/" + action;
                }

                // establish the connection
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // if we are requesting from ourself
                if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) {
                    // get our session id
                    String sessionId = rapidRequest.getRequest().getSession().getId();
                    // add it to the call for internal authentication
                    connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
                }

                // set the content type and action header accordingly
                if ("SOAP".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    connection.setRequestProperty("SOAPAction", action);
                } else if ("JSON".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "application/json");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                } else if ("XML".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                }

                // if a body has been specified
                if (body.length() > 0) {

                    // Triggers POST.
                    connection.setDoOutput(true);

                    // get the output stream from the connection into which we write the request
                    OutputStream output = connection.getOutputStream();

                    // write the processed body string into the request output stream
                    output.write(body.getBytes("UTF8"));
                }

                // check the response code
                int responseCode = connection.getResponseCode();

                // read input stream if all ok, otherwise something meaningful should be in error stream
                if (responseCode == 200) {

                    // get the input stream
                    InputStream response = connection.getInputStream();
                    // prepare an soaData object
                    SOAData soaData = null;

                    // read the response accordingly
                    if ("JSON".equals(_request.getType())) {
                        SOAJSONReader jsonReader = new SOAJSONReader();
                        String jsonResponse = Strings.getString(response);
                        soaData = jsonReader.read(jsonResponse);
                    } else {
                        SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot());
                        soaData = xmlReader.read(response);
                    }

                    SOADataWriter jsonWriter = new SOARapidWriter(soaData);

                    String jsonString = jsonWriter.write();

                    jsonData = new JSONObject(jsonString);

                    if (actionCache != null)
                        actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData);

                    response.close();

                } else {

                    InputStream response = connection.getErrorStream();

                    String errorMessage = null;

                    if ("SOAP".equals(_request.getType())) {

                        String responseXML = Strings.getString(response);

                        errorMessage = XML.getElementValue(responseXML, "faultcode");

                    }

                    if (errorMessage == null) {

                        BufferedReader rd = new BufferedReader(new InputStreamReader(response));

                        errorMessage = rd.readLine();

                        rd.close();

                    }

                    // log the error
                    _logger.error(errorMessage);

                    // only if there is no application cache show the error, otherwise it sends an empty response
                    if (actionCache == null) {

                        throw new JSONException(
                                " response code " + responseCode + " from server : " + errorMessage);

                    } else {

                        _logger.debug("Error not shown to user due to cache : " + errorMessage);

                    }

                }

                connection.disconnect();

            } // request url != null

        } // jsonData == null

    } // got app and page

    // if the jsonData is still null make an empty one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add the sequence
    jsonData.put("sequence", sequence);

    // return the object
    return jsonData;

}

From source file:com.orange.datavenue.client.common.ApiInvoker.java

public HttpResponse invokeAPI(String host, String path, String method, Map<String, String> queryParams,
        Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType)
        throws SDKException, HTTPException {

    System.out.println("invokeAPI()");

    System.out.println(String.format("host : %1$s", host));
    System.out.println(String.format("path : %1$s", path));
    System.out.println(String.format("method : %1$s", method));
    System.out.println(String.format("contentType : %1$s", contentType));

    HttpResponse response = new HttpResponse();

    StringBuilder paramsBuilder = new StringBuilder();

    for (String key : queryParams.keySet()) {
        String value = queryParams.get(key);
        if (value != null) {
            if (paramsBuilder.toString().length() == 0)
                paramsBuilder.append("?");
            else//from  w  w  w .  ja v a 2s. c  o  m
                paramsBuilder.append("&");
            paramsBuilder.append(escapeString(key)).append("=").append(escapeString(value));
        }
    }

    String query = paramsBuilder.toString();
    //System.out.println( String.format("query : %1$s", query));
    //System.out.println( String.format("body : %1$s", (String)body));

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(String.format("%1$s%2$s%3$s", host, path, query));
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);

        for (String key : headerParams.keySet()) {
            urlConnection.setRequestProperty(key, headerParams.get(key));
        }

        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Content-Type", contentType);

        if (body != null) {
            urlConnection.setDoOutput(true);
        }

        if ("GET".equals(method)) {
            if (body != null) {
                writeStream(urlConnection.getOutputStream(), serialize(body));
            }
            response.body = readStream(urlConnection.getInputStream());

            System.out.println(String.format("response : %1$s", response.body));
        } else if ("POST".equals(method)) {
            if (body != null) {
                writeStream(urlConnection.getOutputStream(), serialize(body));
            }
            response.body = readStream(urlConnection.getInputStream());

            System.out.println(String.format("response : %1$s", response.body));
        } else if ("PUT".equals(method)) {

            if ("application/x-www-form-urlencoded".equals(contentType)) {
                StringBuilder formParamBuilder = new StringBuilder();

                // encode the form params

                for (String key : formParams.keySet()) {
                    String value = formParams.get(key);
                    if (value != null && !"".equals(value.trim())) {
                        if (formParamBuilder.length() > 0) {
                            formParamBuilder.append("&");
                        }
                        try {
                            formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=")
                                    .append(URLEncoder.encode(value, "utf8"));
                        } catch (Exception e) {
                            // move on to next
                            System.out.println(e.toString());
                        }
                    }
                }

                writeStream(urlConnection.getOutputStream(), formParamBuilder.toString());
            } else {
                writeStream(urlConnection.getOutputStream(), serialize(body));
            }

            response.body = readStream(urlConnection.getInputStream());

            System.out.println(String.format("response : %1$s", response));
        } else if ("DELETE".equals(method)) {
            if (body != null) {
                writeStream(urlConnection.getOutputStream(), serialize(body));
            }
            response.body = readStream(urlConnection.getInputStream());

            System.out.println(String.format("response : %1$s", response));
        } else if ("OPTIONS".equals(method)) {
            System.out.println("method not implemented");
            throw new SDKException(500, String.format("method not implemented %1$s", method));
        } else if ("HEAD".equals(method)) {
            System.out.println("method not implemented");
            throw new SDKException(500, String.format("method not implemented %1$s", method));
        } else if ("TRACE".equals(method)) {
            System.out.println("method not implemented");
            throw new SDKException(500, String.format("method not implemented %1$s", method));
        } else {
            System.out.println("Unknown method");
            throw new SDKException(500, String.format("method not implemented %1$s", method));
        }

        response.headers = urlConnection.getHeaderFields();

    } catch (MalformedURLException e) {
        System.out.println(e.toString());
    } catch (IOException e) {
        // When an IOException occured, we have to read on the ErrorStream
        if (urlConnection != null) {
            try {
                int code = urlConnection.getResponseCode();
                String json = readStream(urlConnection.getErrorStream());
                try {

                    JSONObject jsonObject = new JSONObject(json);

                    int datavenueCode = 0;

                    if (jsonObject.has("code")) {
                        datavenueCode = jsonObject.getInt("code");
                    }

                    String datavenueMessage = "";

                    if (jsonObject.has("message")) {
                        datavenueMessage = jsonObject.getString("message");
                    }

                    String datavenueDescription = "";

                    if (jsonObject.has("description")) {
                        datavenueDescription = jsonObject.getString("description");
                    }

                    DatavenueError datavenueError = new DatavenueError();
                    datavenueError.setCode(datavenueCode);
                    datavenueError.setMessage(datavenueMessage);
                    datavenueError.setDescription(datavenueDescription);

                    throw new HTTPException(code, datavenueError);

                } catch (JSONException je) {
                    System.out.println(je.toString());
                }

            } catch (IOException io) {
                System.out.println(io.toString());
                throw new SDKException(500, io.toString(), io);
            }
        } else {
            System.out.println(e.toString());
            throw new SDKException(500, e.toString(), e);
        }
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    response.log();

    return response;
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
     */*from  ww 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 ava2 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;/*from w ww.  j  a v  a2 s  . c  o 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:com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.java

/**
 * @param apiUrl//from   www . j  a  va  2  s.co  m
 * @param expected
 * @param httpHeaders
 * @return
 */
protected InputStream callApiMethod(String apiUrl, int expected, List<HttpHeader> httpHeaders) {
    try {
        LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance()
                .createLinkedInOAuthService(apiConsumer.getConsumerKey(), apiConsumer.getConsumerSecret());

        if (accessToken.getOauth2Token() != null && !accessToken.getOauth2Token().isEmpty()) {
            // oauth2 token hack, this seemed like the easiest... place to do it
            if (apiUrl.contains("?")) {
                apiUrl = apiUrl + "&oauth2_access_token=" + accessToken.getOauth2Token();
            } else {
                apiUrl = apiUrl + "?oauth2_access_token=" + accessToken.getOauth2Token();
            }
        }

        if (OUTPUT_RESPONSE) {
            LOG.info("Calling LinkedIn URL: " + apiUrl);
        }

        URL url = new URL(apiUrl);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();

        if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
            request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
        }

        if (ApplicationConstants.READ_TIMEOUT > -1) {
            request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
        }

        for (String headerName : requestHeaders.keySet()) {
            request.setRequestProperty(headerName, requestHeaders.get(headerName));
        }

        for (HttpHeader header : httpHeaders) {
            request.setRequestProperty(header.getName(), header.getValue());
        }

        oAuthService.signRequestWithToken(request, accessToken);
        request.connect();

        if (request.getResponseCode() != expected) {
            Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(),
                    GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())));

            throw createLinkedInApiClientException(error);
        } else {
            return getWrappedInputStream(request.getInputStream(),
                    GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
        }
    } catch (IOException e) {
        throw new LinkedInApiClientException(e);
    }
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 *
 * @param url/*  w w  w. j  a  v a  2s.c om*/
 * @param requestStr
 * @param messageContext
 * @return
 */
public String makeWalletRequest(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.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));

        //========================UNICODE PATCH=========================================
        BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream());
        wr.write(requestStr.getBytes("UTF-8"));
        wr.flush();
        wr.close();
        //========================UNICODE PATCH=========================================

        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();
        }
        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 delete request.// www . j ava 2  s .co 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;
}