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

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

<tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:org.telscenter.sail.webapp.presentation.web.controllers.author.project.PostProjectController.java

/**
 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from  w w w.  ja va 2  s .c o m
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    User user = ControllerUtil.getSignedInUser();
    try {
        String projectId = request.getParameter(PROJECT_ID_PARAM);
        String encodedOtmlString = request.getParameter(OTML_CONTENT_PARAM);
        String otmlString = URLDecoder.decode(encodedOtmlString, "UTF-8");

        Project project = projectService.getById(projectId);
        Curnit curnit = project.getCurnit();
        if (curnit instanceof RooloOtmlModuleImpl) {
            ((RooloOtmlModuleImpl) project.getCurnit()).getElo().getContent().setBytes(otmlString.getBytes());
        } else if (curnit instanceof OtmlModuleImpl) {
            ((OtmlModuleImpl) project.getCurnit()).setOtml(otmlString.getBytes());
            moduleService.updateCurnit(project.getCurnit());
        }
        projectService.updateProject(project, user);
    } catch (NullPointerException e) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
    } catch (NotAuthorizedException e) {
        e.printStackTrace();
        return new ModelAndView(new RedirectView("/webapp/accessdenied.html"));
    }
    return null;
}

From source file:org.telscenter.sail.webapp.presentation.web.controllers.author.project.PostProjectControllerTest.java

@Test
public void postPOTrunkProject_failure_empty_projectId() throws ObjectNotFoundException {
    request.setParameter(PostProjectController.PROJECT_ID_PARAM, "");
    expect(projectService.getById("")).andThrow(new NullPointerException());
    replay(projectService);/*  w w  w  . j  a  v  a  2s .  com*/
    replay(moduleService);
    try {
        controller.handleRequestInternal(request, response);
        fail("exception expected but was not thrown.");
    } catch (Exception e) {
    }
    assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST);
    verify(projectService);
    verify(moduleService);
}

From source file:org.telscenter.sail.webapp.presentation.web.controllers.author.project.PostProjectControllerTest.java

@Test
public void postPOTrunkProject_failure_null_otmlcontent() throws ObjectNotFoundException {
    request.removeParameter(PostProjectController.OTML_CONTENT_PARAM);
    replay(projectService);/* ww  w. j  ava  2  s  . c  o  m*/
    replay(moduleService);
    try {
        controller.handleRequestInternal(request, response);
        fail("exception expected but was not thrown.");
    } catch (Exception e) {
    }
    assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST);
    verify(projectService);
    verify(moduleService);

}

From source file:org.wso2.carbon.appfactory.s4.integration.StratosRestService.java

/**
 * @param appName//from  w  w w.  j av a  2s  .c o  m
 *            Name of the application to be checked
 * @return if the application is already subscribed or not
 */
public boolean isAlreadySubscribed(String appName) throws AppFactoryException {
    String alias = appName;

    HttpClient httpClient = getNewHttpClient();

    try {
        // get the details of the subscription for an app
        DomainMappingResponse response = doGet(httpClient,
                this.stratosManagerURL + this.LIST_DETAILS_OF_SUBSCRIBED_CARTRIDGE + appName);
        System.out.println("response.getStatusCode() = " + response.getResponse());
        // already subscribed!
        if (response.getStatusCode() == HttpStatus.SC_OK) {

            if (log.isDebugEnabled()) {
                log.debug("Status 200 returned when retrieving the subscription info");
            }
            return true;
            // No alias found or not subscribed yet
        } else if (response.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
            return false;
        } else {
            if (log.isDebugEnabled()) {
                String subscriptionListOutput = response.getResponse();
                log.debug("Status response when retrieving the subscription info:\n" + subscriptionListOutput);
            }
            return true;
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.error("Error occurred while getting subscription info ", e);
        }
        return true;
    }

}

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 ww  w.  ja v a  2 s . 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());
        }//w w  w  . j  ava  2 s. c o  m
        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  2  s.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//from  w w w . j  ava  2  s.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.jaxrs.api.DashboardImpl.java

@GET
@Path("non-compliant-device-counts-by-features")
public Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
        @QueryParam(RESULT_COUNT) int resultCount) {

    GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
    DashboardPaginationGadgetDataWrapper dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();

    PaginationResult paginationResult;/*from w  w  w.ja v a 2  s  .  com*/
    try {
        paginationResult = gadgetDataService.getNonCompliantDeviceCountsByFeatures(startIndex, resultCount);
    } catch (InvalidStartIndexValueException e) {
        log.error("Bad request and error occurred @ Gadget Data Service layer due to "
                + "invalid (query) parameter value. This was while trying to execute relevant data service "
                + "function @ Dashboard API layer to retrieve a non-compliant set "
                + "of device counts by features.", e);
        return Response.status(HttpStatus.SC_BAD_REQUEST).entity(INVALID_QUERY_PARAM_VALUE_START_INDEX).build();
    } catch (InvalidResultCountValueException e) {
        log.error("Bad request and error occurred @ Gadget Data Service layer due to "
                + "invalid (query) parameter value. This was while trying to execute relevant data service "
                + "function @ Dashboard API layer to retrieve a non-compliant set "
                + "of device counts by features.", e);
        return Response.status(HttpStatus.SC_BAD_REQUEST).entity(INVALID_QUERY_PARAM_VALUE_RESULT_COUNT)
                .build();
    } catch (DataAccessLayerException e) {
        log.error(
                "An internal error occurred while trying to execute relevant data service function "
                        + "@ Dashboard API layer to retrieve a non-compliant set of device counts by features.",
                e);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ERROR_IN_RETRIEVING_REQUESTED_DATA)
                .build();
    }

    dashboardPaginationGadgetDataWrapper.setContext("Non-compliant-device-counts-by-features");
    dashboardPaginationGadgetDataWrapper.setGroupingAttribute(NON_COMPLIANT_FEATURE_CODE);
    dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
    dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());

    List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
    responsePayload.add(dashboardPaginationGadgetDataWrapper);

    return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}

From source file:org.wso2.carbon.device.mgt.jaxrs.api.DashboardImpl.java

@GET
@Path("device-counts-by-groups")
public Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
        @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
        @QueryParam(PLATFORM) String platform, @QueryParam(OWNERSHIP) String ownership) {

    // getting gadget data service
    GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();

    // constructing filter set
    ExtendedFilterSet filterSet = new ExtendedFilterSet();
    filterSet.setConnectivityStatus(connectivityStatus);
    filterSet.setPotentialVulnerability(potentialVulnerability);
    filterSet.setPlatform(platform);/*from w  w  w  . j a  v  a 2s.co  m*/
    filterSet.setOwnership(ownership);

    // creating device-Counts-by-platforms Data Wrapper
    List<DeviceCountByGroup> deviceCountsByPlatforms;
    try {
        deviceCountsByPlatforms = gadgetDataService.getDeviceCountsByPlatforms(filterSet);
    } catch (InvalidPotentialVulnerabilityValueException e) {
        log.error("Bad request and error occurred @ Gadget Data Service layer due to "
                + "invalid (query) parameter value. This was while trying to execute relevant data service "
                + "function @ Dashboard API layer to retrieve a filtered set of device counts by platforms.",
                e);
        return Response.status(HttpStatus.SC_BAD_REQUEST)
                .entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
    } catch (DataAccessLayerException e) {
        log.error("An internal error occurred while trying to execute relevant data service function "
                + "@ Dashboard API layer to retrieve a filtered set of device counts by platforms.", e);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ERROR_IN_RETRIEVING_REQUESTED_DATA)
                .build();
    }

    DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
    dashboardGadgetDataWrapper1.setContext("Device-counts-by-platforms");
    dashboardGadgetDataWrapper1.setGroupingAttribute(PLATFORM);
    dashboardGadgetDataWrapper1.setData(deviceCountsByPlatforms);

    // creating device-Counts-by-ownership-types Data Wrapper
    List<DeviceCountByGroup> deviceCountsByOwnerships;
    try {
        deviceCountsByOwnerships = gadgetDataService.getDeviceCountsByOwnershipTypes(filterSet);
    } catch (InvalidPotentialVulnerabilityValueException e) {
        log.error("Bad request and error occurred @ Gadget Data Service layer due to "
                + "invalid (query) parameter value. This was while trying to execute relevant data service "
                + "function @ Dashboard API layer to retrieve a filtered set of device counts by ownerships.",
                e);
        return Response.status(HttpStatus.SC_BAD_REQUEST)
                .entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
    } catch (DataAccessLayerException e) {
        log.error(
                "An internal error occurred while trying to execute relevant data service function "
                        + "@ Dashboard API layer to retrieve a filtered set of device counts by ownerships.",
                e);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ERROR_IN_RETRIEVING_REQUESTED_DATA)
                .build();
    }

    DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
    dashboardGadgetDataWrapper2.setContext("Device-counts-by-ownerships");
    dashboardGadgetDataWrapper2.setGroupingAttribute(OWNERSHIP);
    dashboardGadgetDataWrapper2.setData(deviceCountsByOwnerships);

    List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
    responsePayload.add(dashboardGadgetDataWrapper1);
    responsePayload.add(dashboardGadgetDataWrapper2);

    return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}