Example usage for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR

List of usage examples for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

<tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.wso2.am.integration.tests.stats.APIInvocationStatPublisherTestCase.java

@Test(groups = {
        "wso2.am" }, description = "Test fault Event stream", dependsOnMethods = "testExecutionTimeEventTest")
public void testFaultEventTest() throws Exception {
    if (TestUserMode.SUPER_TENANT_ADMIN != userMode) {
        //skipping test method for tenant mode, due to socket read timeout exception
        return;//from  www. j a v  a 2s .  co m
    }
    //clear the test thrift server received event to avoid event conflicting among tenants
    thriftTestServer.clearTables();

    //subscribe to the api
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(FAULT_API_NAME, user.getUserName());
    subscriptionRequest.setApplicationName(APP_NAME);
    subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
    HttpResponse serviceResponse = apiStore.subscribe(subscriptionRequest);
    verifyResponse(serviceResponse);

    //invoke api
    requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken);
    String invokeURL = getAPIInvocationURLHttp(FAULT_API_CONTEXT, API_VERSION);
    serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders);
    Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, serviceResponse.getResponseCode(),
            "Error in response code");

    String context, resourcePath, userId;
    if (TestUserMode.SUPER_TENANT_ADMIN == userMode) {
        context = "/" + FAULT_API_CONTEXT + "/" + API_VERSION;
        resourcePath = "/add?x=1&y=1";
        userId = user.getUserName() + "@" + user.getUserDomain();
    } else {
        context = "/" + "t/" + user.getUserDomain() + "/" + FAULT_API_CONTEXT + "/" + API_VERSION;
        resourcePath = "/" + FAULT_API_CONTEXT + "/" + API_VERSION + "/add?x=1&y=1";
        userId = user.getUserName();
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("consumerKey", consumerKey);
    map.put("context", context);
    map.put("api_version", FAULT_API_NAME + ":v" + API_VERSION);
    map.put("api", FAULT_API_NAME);
    map.put("resourcePath", resourcePath);
    map.put("method", "GET");
    map.put("version", API_VERSION);
    map.put("errorCode", "");
    map.put("errorMessage", "");
    map.put("requestTime", "");
    map.put("userId", userId);
    map.put("tenantDomain", user.getUserDomain());
    map.put("hostName", "");
    map.put("apiPublisher", user.getUserName());
    map.put("applicationName", APP_NAME);
    map.put("applicationId", "");
    map.put("protocol", "http");
    testFaultEvent(map);

    //invoke api anonymously
    thriftTestServer.clearTables();
    invokeURL = getAPIInvocationURLHttp(FAULT_API_CONTEXT, API_VERSION);
    serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/multiply?x=1&y=1", null);
    Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, serviceResponse.getResponseCode(),
            "Error in response code");
    map.put("consumerKey", null);

    map.put("userId", "anonymous");
    map.put("applicationName", null);
    map.put("applicationId", null);
    if (TestUserMode.SUPER_TENANT_ADMIN == userMode) {
        resourcePath = "/multiply?x=1&y=1";
    } else {
        resourcePath = "/" + FAULT_API_CONTEXT + "/" + API_VERSION + "/multiply?x=1&y=1";
    }
    map.put("resourcePath", resourcePath);
    testFaultEvent(map);
}

From source file:org.wso2.automation.platform.tests.apim.bam.APIUsageBAMIntegrationTestCase.java

@Test(groups = { "wso2.am" }, description = "APIM - BAM Integration API Usage statistics analysis test")
public void testGenerateStatistics() throws Exception {
    String providerName = user.getUserName();
    String password = user.getPassword();

    String apiContext = "UsageTestAPI";
    String tags = "UsageTestAPI";
    String description = "This is test API create by API manager usage integration test";
    String visibility = "user";
    String url = "http://en.wikipedia.org/w/api.php";

    APIRequest apiRequest = new APIRequest(apiName, apiContext, new URL(url));
    apiRequest.setTags(tags);//ww  w  .j  a v a  2  s  . c  om
    apiRequest.setDescription(description);
    apiRequest.setVersion(apiVersion);
    apiRequest.setVisibility(visibility);
    apiRequest.setProvider(providerName);
    HttpResponse response;

    response = apiPublisher.login(providerName, password);
    checkError(response.getData(), "Error while authenticating to publisher " + providerName);
    HttpResponse addApiResponse = apiPublisher.addAPI(apiRequest);
    checkError(addApiResponse.getData(), "Error while adding API " + apiName);

    APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, providerName,
            APILifeCycleState.PUBLISHED);

    response = apiPublisher.changeAPILifeCycleStatus(updateRequest);
    checkError(response.getData(), "Error while publishing API " + apiName);

    // subscribing to api
    response = apiStore.login(providerName, password);
    checkError(response.getData(), "Error when authenticating to Store " + providerName);
    app1Name = "Statistics-Application-" + new Random().nextInt(10000);
    response = apiStore.addApplication(app1Name, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test");
    checkError(response.getData(), "Error while adding Application " + app1Name);
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, providerName);
    subscriptionRequest.setApplicationName(app1Name);
    response = apiStore.subscribe(subscriptionRequest);
    checkError(response.getData(), "Error while subscribing fro API " + apiName);

    //Here will do 11 faulty invocations

    String apiContextFaultyAPI = "UsageTestAPIFaultyAPI";
    String tagsFaultyAPI = "youtube, video, media";
    //this url should not exists and then it will return with API fault invocation
    String urlFaultyAPI = "http://thisiswrong.com/feeds/api/standardfeeds";
    String descriptionFaultyAPI = "This is test API create by API manager usage integration test";

    app2Name = "Statistics-Application-" + new Random().nextInt(10000);

    APIRequest apiRequestFaultyAPI = new APIRequest(apiNameFaultyAPI, apiContextFaultyAPI,
            new URL(urlFaultyAPI));
    apiRequestFaultyAPI.setTags(tagsFaultyAPI);
    apiRequestFaultyAPI.setDescription(descriptionFaultyAPI);
    apiRequestFaultyAPI.setVersion(apiVersion);
    response = apiPublisher.addAPI(apiRequestFaultyAPI);
    checkError(response.getData(), "Error while adding API " + apiNameFaultyAPI);

    APILifeCycleStateRequest updateRequestFaultyAPI = new APILifeCycleStateRequest(apiNameFaultyAPI,
            providerName, APILifeCycleState.PUBLISHED);
    response = apiPublisher.changeAPILifeCycleStatus(updateRequestFaultyAPI);
    checkError(response.getData(), "Error while publishing API " + apiNameFaultyAPI);
    SubscriptionRequest subscriptionRequestFaultyAPI = new SubscriptionRequest(apiNameFaultyAPI, providerName);
    subscriptionRequestFaultyAPI.setApplicationName(app2Name);
    response = apiStore.addApplication(app2Name, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test");
    checkError(response.getData(), "Error while adding application " + app2Name);
    response = apiStore.subscribe(subscriptionRequestFaultyAPI);
    checkError(response.getData(), "Error while subscribing to API " + apiNameFaultyAPI);

    //host object tests
    String fileName = "testUsageWithBAM.jag";
    String sourcePath = computeJaggeryResourcePath(fileName);
    String destinationPath = computeDestinationPath(fileName);
    copySampleFile(sourcePath, destinationPath);

    //getting api counts before invocation
    String finalOutputUsageTest;
    finalOutputUsageTest = HttpRequestUtil
            .doGet(getTestApplicationUsagePublisherServerURLHttp(), new HashMap<String, String>()).getData();
    assert finalOutputUsageTest != null;

    String[] array = finalOutputUsageTest.split("==");

    if (array.length > 3) {
        JSONArray apiCountJsonArray = new JSONArray(array[2]);
        if (apiCountJsonArray.length() > 0 && !apiCountJsonArray.isNull(0)) {
            apiCountByUserBefore = apiCountJsonArray.getJSONObject(0).getInt("count");
        }

        JSONArray faultCountJsonArray = new JSONArray(array[0]);
        if (faultCountJsonArray.length() > 0 && !faultCountJsonArray.isNull(0)) {
            faultCountBefore = faultCountJsonArray.getJSONObject(0).getInt("count");
        }
    }

    //invoking the API UsageTestAPI
    APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(app1Name);
    String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
    JSONObject jsonResponse = new JSONObject(responseString);
    String accessToken = jsonResponse.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put("Authorization", "Bearer " + accessToken);
    HttpResponse apiResponse;
    //Here will do 10 successful invocations
    for (int i = 0; i < successRequestCount; i++) {
        apiResponse = HttpRequestUtil.doGet(
                getAPIInvocationURLHttp("UsageTestAPI", apiVersion)
                        + "?format=json&action=query&titles=MainPage" + "&prop=revisions&rvprop=content",
                requestHeaders);
        assertEquals(apiResponse.getResponseCode(), HttpStatus.SC_OK, "Response code mismatched");
    }

    //invoking faulty API UsageTestAPIFaultyAPI
    APPKeyRequestGenerator generateAppKeyRequestFaultyAPI = new APPKeyRequestGenerator(app2Name);
    String responseStringFaultyAPI = apiStore.generateApplicationKey(generateAppKeyRequestFaultyAPI).getData();
    JSONObject responseFaultyAPI = new JSONObject(responseStringFaultyAPI);
    String accessTokenFaultyAPI = responseFaultyAPI.getJSONObject("data").getJSONObject("key")
            .get("accessToken").toString();
    Map<String, String> requestHeadersFaultyAPI = new HashMap<String, String>();
    requestHeadersFaultyAPI.put("Authorization", "Bearer " + accessTokenFaultyAPI);
    HttpResponse apiResponseFaultyAPI;
    for (int i = 0; i < faultRequestCount; i++) {
        apiResponseFaultyAPI = HttpRequestUtil.doGet(
                getAPIInvocationURLHttp("UsageTestAPIFaultyAPI", apiVersion)
                        + "?format=json&action=query&titles=MainPage" + "&prop=revisions&rvprop=content",
                requestHeadersFaultyAPI);
        assertEquals(apiResponseFaultyAPI.getResponseCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                "Response code mismatched");
    }

    //sleep toolbox to run and populate the result to database
    log.info("waiting for hive job to run and populate statics data");
    Thread.sleep(240000);

    finalOutputUsageTest = HttpRequestUtil
            .doGet(getTestApplicationUsagePublisherServerURLHttp(), new HashMap<String, String>()).getData();
    assertNotNull(finalOutputUsageTest, "No response from " + getTestApplicationUsagePublisherServerURLHttp());

    arrayStat = finalOutputUsageTest.split("==");

    log.info(finalOutputUsageTest + "\n");
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This Method is used to deploy BPMN packages to the BPMN Server
 *
 * @param fileName The name of the Package to be deployed
 * @param filePath The location of the BPMN package to be deployed
 * @throws java.io.IOException/*from  w w  w  . ja va  2  s . c  om*/
 * @throws org.json.JSONException
 * @returns String array with status, deploymentID and Name
 */
public String[] deployBPMNPackage(String filePath, String fileName) throws Exception {
    String url = serviceURL + "repository/deployments";

    HttpHost target = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpPost httpPost = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName);
    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String deploymentID = jsonResponseObject.getString("id");
        String name = jsonResponseObject.getString("name");
        return new String[] { status, deploymentID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) {

        String errorMessage = jsonResponseObject.getString("errorMessage");
        throw new RestClientException(errorMessage);
        //            return new String[]{status, errorMessage};
    } else {
        throw new RestClientException("Failed to deploy package " + fileName);
    }
}

From source file:org.wso2.carbon.dataservices.google.tokengen.servlet.ConsentUrl.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (log.isDebugEnabled()) {
        log.debug("Request Received for consent URL");
    }/*from w w  w  . j a  va2s.  co m*/
    StringBuffer jb = new StringBuffer();
    JSONObject jsonObject;
    String line = null;
    String responseString;
    int responseStatus;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        jsonObject = new JSONObject(new JSONTokener(jb.toString()));
        String clientId = jsonObject.getString(DBConstants.GSpread.CLIENT_ID);

        String redirectURIs = jsonObject.getString(DBConstants.GSpread.REDIRECT_URIS);

        if (clientId == null || clientId.isEmpty()) {
            responseStatus = HttpStatus.SC_BAD_REQUEST;
            responseString = "ClientID is null or empty";
        } else if (redirectURIs == null || redirectURIs.isEmpty()) {
            responseStatus = HttpStatus.SC_BAD_REQUEST;
            responseString = "Redirect URIs is null or empty";
        } else {
            String[] SCOPESArray = { "https://spreadsheets.google.com/feeds" };
            final List SCOPES = Arrays.asList(SCOPESArray);
            /*
            Security Comment :
            This response is trustworthy, url is hard coded in GoogleAuthorizationCodeRequestUrl constructor.
             */
            responseString = new GoogleAuthorizationCodeRequestUrl(clientId, redirectURIs, SCOPES)
                    .setAccessType("offline").setApprovalPrompt("force").build();

            response.setContentType("text/html");
            responseStatus = HttpStatus.SC_OK;
        }
    } catch (Exception e) {
        responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        responseString = "Error in Processing accessTokenRequest Error - " + e.getMessage();
        log.error(responseString, e);
    }
    try {
        PrintWriter out = response.getWriter();
        out.println(responseString);
        response.setStatus(responseStatus);
    } catch (IOException e) {
        log.error("Error Getting print writer to write http response Error - " + e.getMessage(), e);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.wso2.carbon.dataservices.google.tokengen.servlet.TokenEndpoint.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    AuthCode authCode = CodeHolder.getInstance().getAuthCodeForSession(request.getSession().getId());
    String responseMsg = "";
    JSONObject resJson = new JSONObject();
    int responseStatus;
    if (authCode != null) {
        if (log.isDebugEnabled()) {
            log.debug("Request received for retrieve access token from session - "
                    + request.getSession().getId());
        }//from  w w  w . j  ava2s. c om
        StringBuffer jb = new StringBuffer();
        JSONObject jsonObject;
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }

            jsonObject = new JSONObject(new JSONTokener(jb.toString()));
            String clientId = jsonObject.getString(DBConstants.GSpread.CLIENT_ID);
            String clientSecret = jsonObject.getString(DBConstants.GSpread.CLIENT_SECRET);
            String redirectURIs = jsonObject.getString(DBConstants.GSpread.REDIRECT_URIS);

            if (clientId == null || clientId.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "ClientID is null or empty";
            } else if (clientSecret == null || clientSecret.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "Client Secret is null or empty";
            } else if (redirectURIs == null || redirectURIs.isEmpty()) {
                responseStatus = HttpStatus.SC_BAD_REQUEST;
                responseMsg = "Redirect URIs is null or empty";
            } else {
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsonFactory = new JacksonFactory();

                // Step 2: Exchange auth code for tokens
                GoogleTokenResponse googleTokenResponse = new GoogleAuthorizationCodeTokenRequest(httpTransport,
                        jsonFactory, "https://www.googleapis.com/oauth2/v3/token", clientId, clientSecret,
                        authCode.getAuthCode(), redirectURIs).execute();
                resJson.append(DBConstants.GSpread.ACCESS_TOKEN, googleTokenResponse.getAccessToken());
                resJson.append(DBConstants.GSpread.REFRESH_TOKEN, googleTokenResponse.getRefreshToken());
                responseMsg = resJson.toString();
                responseStatus = HttpStatus.SC_OK;
                if (log.isDebugEnabled()) {
                    log.debug("Access token request successfully served for client id " + clientId);
                }
            }
        } catch (JSONException e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        } catch (IOException e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        } catch (Exception e) {
            responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage();
            log.error(responseMsg, e);
        }
    } else {
        responseStatus = HttpStatus.SC_ACCEPTED;
        responseMsg = resJson.toString();
    }
    try {
        PrintWriter out = response.getWriter();
        out.println(responseMsg);
        response.setStatus(responseStatus);
    } catch (IOException e) {
        log.error("Error Getting print writer to write http response Error - " + e.getMessage(), e);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/bulb/{state}")
@POST/* ww w . jav a 2s  .c  o  m*/
public void switchBulb(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @PathParam("state") String state,
        @Context HttpServletResponse response) {

    try {
        DeviceValidator deviceValidator = new DeviceValidator();
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    } catch (DeviceManagementException e) {
        log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    String switchToState = state.toUpperCase();

    if (!switchToState.equals(FireAlarmConstants.STATE_ON)
            && !switchToState.equals(FireAlarmConstants.STATE_OFF)) {
        log.error("The requested state change shoud be either - 'ON' or 'OFF'");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String deviceIP = deviceToIpMap.get(deviceId);
    if (deviceIP == null) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    }

    String protocolString = protocol.toUpperCase();
    String callUrlPattern = BULB_CONTEXT + switchToState;

    log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + "via" + " "
            + protocol);

    try {
        switch (protocolString) {
        case HTTP_PROTOCOL:
            sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            break;
        case MQTT_PROTOCOL:
            callUrlPattern = BULB_CONTEXT.replace("/", "");
            sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState);
            break;
        default:
            if (protocolString == null) {
                sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            } else {
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + " " + protocol);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    response.setStatus(HttpStatus.SC_OK);
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/fan/{state}")
@POST/*ww w  .  ja va2s.  c  o m*/
public void switchFan(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @PathParam("state") String state,
        @Context HttpServletResponse response) {

    try {
        DeviceValidator deviceValidator = new DeviceValidator();
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    } catch (DeviceManagementException e) {
        log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    String switchToState = state.toUpperCase();

    if (!switchToState.equals(FireAlarmConstants.STATE_ON)
            && !switchToState.equals(FireAlarmConstants.STATE_OFF)) {
        log.error("The requested state change shoud be either - 'ON' or 'OFF'");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String deviceIP = deviceToIpMap.get(deviceId);

    if (deviceIP == null) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    }

    String protocolString = protocol.toUpperCase();
    String callUrlPattern = FAN_CONTEXT + switchToState;

    log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + "via" + " "
            + protocol);

    try {
        switch (protocolString) {
        case HTTP_PROTOCOL:
            sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            break;
        case MQTT_PROTOCOL:
            callUrlPattern = FAN_CONTEXT.replace("/", "");
            sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState);
            break;
        default:
            if (protocolString == null) {
                sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            } else {
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + " " + protocol);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    response.setStatus(HttpStatus.SC_OK);
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/readtemperature")
@GET/*from   www. j a  v a2  s .  c  o  m*/
public String requestTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) {
    String replyMsg = "";

    DeviceValidator deviceValidator = new DeviceValidator();
    try {
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return "Unauthorized Access";
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    String deviceIp = deviceToIpMap.get(deviceId);

    if (deviceIp == null) {
        replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return replyMsg;
    }

    try {
        switch (protocol) {
        case HTTP_PROTOCOL:
            log.info(
                    "Sending request to read firealarm-temperature at : " + deviceIp + " via " + HTTP_PROTOCOL);

            replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
            break;

        case XMPP_PROTOCOL:
            log.info(
                    "Sending request to read firealarm-temperature at : " + deviceIp + " via " + XMPP_PROTOCOL);
            replyMsg = requestTemperatureViaXMPP(deviceIp, response);
            break;

        default:
            if (protocol == null) {
                log.info("Sending request to read firealarm-temperature at : " + deviceIp + " via "
                        + HTTP_PROTOCOL);

                replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
            } else {
                replyMsg = "Requested protocol '" + protocol + "' is not supported";
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return replyMsg;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    response.setStatus(HttpStatus.SC_OK);
    replyMsg = "The current temperature of the device is " + replyMsg;
    return replyMsg;
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/readsonar")
@GET//from w  w w .j a v  a 2  s  .  c  o m
public String requestSonar(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) {
    String replyMsg = "";

    DeviceValidator deviceValidator = new DeviceValidator();
    try {
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return "Unauthorized Access";
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    String deviceIp = deviceToIpMap.get(deviceId);

    if (deviceIp == null) {
        replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return replyMsg;
    }

    try {
        switch (protocol) {
        case HTTP_PROTOCOL:
            log.info("Sending request to read firealarm-sonar at : " + deviceIp + " via " + HTTP_PROTOCOL);

            replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
            break;

        //            case XMPP_PROTOCOL:
        //               log.info("Sending request to read firealarm-sonar at : " + deviceIp +
        //                            " via " +
        //                            XMPP_PROTOCOL);
        //               replyMsg = requestTemperatureViaXMPP(deviceIp, response);
        //               break;

        default:
            if (protocol == null) {
                log.info("Sending request to read firealarm-sonar at : " + deviceIp + " via " + HTTP_PROTOCOL);

                replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
            } else {
                replyMsg = "Requested protocol '" + protocol + "' is not supported";
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return replyMsg;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    response.setStatus(HttpStatus.SC_OK);
    replyMsg = "The current sonar reading of the device is " + replyMsg;
    return replyMsg;
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/push_temperature")
@POST/* w  w  w.j  a va  2s  . c  o  m*/
@Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
    boolean result;
    String deviceId = dataMsg.deviceId;
    String deviceIp = dataMsg.reply;
    String temperature = dataMsg.value;

    String registeredIp = deviceToIpMap.get(deviceId);

    if (registeredIp == null) {
        log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp
                + " for device ID - " + deviceId);
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    } else if (!registeredIp.equals(deviceIp)) {
        log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId
                + " is already registered under some other IP. Re-registration " + "required");
        response.setStatus(HttpStatus.SC_CONFLICT);
        return;
    }

    try {
        DeviceController deviceController = new DeviceController();
        result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId,
                System.currentTimeMillis(), "DeviceData", temperature,
                DataStreamDefinitions.StreamTypeLabel.TEMPERATURE);

        if (!result) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (UnauthorizedException e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        log.error("Data Push Attempt Failed for BAM Publisher: " + e.getMessage());
    }

    try {
        DeviceController deviceController = new DeviceController();
        result = deviceController.pushCepData(dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId,
                System.currentTimeMillis(), "DeviceData", temperature,
                DataStreamDefinitions.StreamTypeLabel.TEMPERATURE);

        if (!result) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (UnauthorizedException e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        log.error("Data Push Attempt Failed for CEP Publisher: " + e.getMessage());
    }
}