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

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

Introduction

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

Prototype

int SC_CONFLICT

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

Click Source Link

Document

<tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616)

Usage

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

@Path("/device/register")
@PUT// w  w w . j ava  2 s  .  c  om
public boolean register(@QueryParam("deviceId") String deviceId, @QueryParam("name") String name,
        @QueryParam("owner") String owner) {

    DeviceManagement deviceManagement = new DeviceManagement();

    DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
    deviceIdentifier.setId(deviceId);
    deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE);
    try {
        if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
            Response.status(HttpStatus.SC_CONFLICT).build();
            return false;
        }

        Device device = new Device();
        device.setDeviceIdentifier(deviceId);
        EnrolmentInfo enrolmentInfo = new EnrolmentInfo();

        enrolmentInfo.setDateOfEnrolment(new Date().getTime());
        enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
        enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
        enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);

        device.setName(name);
        device.setType(FireAlarmConstants.DEVICE_TYPE);
        enrolmentInfo.setOwner(owner);
        device.setEnrolmentInfo(enrolmentInfo);
        boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);

        if (added) {
            Response.status(HttpStatus.SC_OK).build();
        } else {
            Response.status(HttpStatus.SC_EXPECTATION_FAILED).build();
        }

        return added;
    } catch (DeviceManagementException e) {
        log.error(e.getErrorMessage());
        return false;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.sensebot.api.SensebotManagerService.java

@Path("/device/register")
@PUT/*from   ww  w  . ja v  a 2 s .c  o  m*/
public boolean register(@QueryParam("deviceId") String deviceId, @QueryParam("name") String name,
        @QueryParam("owner") String owner) {

    DeviceManagement deviceManagement = new DeviceManagement();

    DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
    deviceIdentifier.setId(deviceId);
    deviceIdentifier.setType(SensebotConstants.DEVICE_TYPE);
    try {
        if (deviceManagement.isExist(deviceIdentifier)) {
            Response.status(HttpStatus.SC_CONFLICT).build();
            return false;
        }

        Device device = new Device();
        device.setDeviceIdentifier(deviceId);

        device.setDateOfEnrolment(new Date().getTime());
        device.setDateOfLastUpdate(new Date().getTime());
        //      device.setStatus(true);

        device.setName(name);
        device.setType(SensebotConstants.DEVICE_TYPE);
        device.setOwner(owner);
        boolean added = deviceManagement.addNewDevice(device);
        if (added) {
            Response.status(HttpStatus.SC_OK).build();

        } else {
            Response.status(HttpStatus.SC_EXPECTATION_FAILED).build();

        }

        return added;
    } catch (DeviceManagementException e) {
        log.error(e.getErrorMessage());
        return false;
    }
}

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

/**
 * Method to add user to emm-user-store.
 *
 * @param userWrapper Wrapper object representing input json payload
 * @return {Response} Status of the request wrapped inside Response object
 *//*  w  w w.  j a  v  a2  s.  c  o  m*/
@Override
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response addUser(UserWrapper userWrapper) {
    ResponsePayload responsePayload = new ResponsePayload();
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
            // if user already exists
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername()
                        + " already exists. Therefore, request made to add user was refused.");
            }
            // returning response with bad request state
            responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
            responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername()
                    + " already exists. Therefore, request made to add user was refused.");
            return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
        } else {
            String initialUserPassword = generateInitialUserPassword();
            Map<String, String> defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(),
                    userWrapper.getLastname(), userWrapper.getEmailAddress());
            // calling addUser method of carbon user api
            userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword, userWrapper.getRoles(),
                    defaultUserClaims, null);
            // invite newly added user to enroll device
            inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
            // Outputting debug message upon successful addition of user
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
            }
            // returning response with success state
            responsePayload.setStatusCode(HttpStatus.SC_CREATED);
            responsePayload.setMessageFromServer(
                    "User by username: " + userWrapper.getUsername() + " was successfully added.");
            return Response.status(Response.Status.CREATED).entity(responsePayload).build();
        }
    } catch (UserStoreException | MDMAPIException e) {
        String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
        log.error(msg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    }
}

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

/**
 * Update user in user store//w ww  . j ava  2 s.  co  m
 *
 * @param userWrapper Wrapper object representing input json payload
 * @return {Response} Status of the request wrapped inside Response object.
 */
@Override
@PUT
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) {
    ResponsePayload responsePayload = new ResponsePayload();
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
            Map<String, String> defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(),
                    userWrapper.getLastname(), userWrapper.getEmailAddress());
            if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
                // Decoding Base64 encoded password
                byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
                userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
                        new String(decodedBytes, "UTF-8"));
                log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
            }
            List<String> currentRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
            List<String> newRoles = Arrays.asList(userWrapper.getRoles());

            List<String> rolesToAdd = new ArrayList<>(newRoles);
            List<String> rolesToDelete = new ArrayList<>();

            for (String role : currentRoles) {
                if (newRoles.contains(role)) {
                    rolesToAdd.remove(role);
                } else {
                    rolesToDelete.add(role);
                }
            }
            rolesToDelete.remove(ROLE_EVERYONE);
            userStoreManager.updateRoleListOfUser(userWrapper.getUsername(),
                    rolesToDelete.toArray(new String[rolesToDelete.size()]),
                    rolesToAdd.toArray(new String[rolesToAdd.size()]));
            userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
            // Outputting debug message upon successful addition of user
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
            }
            // returning response with success state
            responsePayload.setStatusCode(HttpStatus.SC_CREATED);
            responsePayload.setMessageFromServer(
                    "User by username: " + userWrapper.getUsername() + " was successfully updated.");
            return Response.status(Response.Status.CREATED).entity(responsePayload).build();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername()
                        + " doesn't exists. Therefore, request made to update user was refused.");
            }
            // returning response with bad request state
            responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
            responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername()
                    + " doesn't  exists. Therefore, request made to update user was refused.");
            return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
        }
    } catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) {
        String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
        log.error(msg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    }
}

From source file:org.wso2.carbon.mdm.api.User.java

/**
 * Method to add user to emm-user-store.
 *
 * @param userWrapper Wrapper object representing input json payload
 * @return {Response} Status of the request wrapped inside Response object
 * @throws MDMAPIException/*from ww  w. j a va  2  s  .co m*/
 */
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response addUser(UserWrapper userWrapper) throws MDMAPIException {
    UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
    ResponsePayload responsePayload = new ResponsePayload();
    try {
        if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
            // if user already exists
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername()
                        + " already exists. Therefore, request made to add user was refused.");
            }
            // returning response with bad request state
            responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
            responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername()
                    + " already exists. Therefore, request made to add user was refused.");
            return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build();
        } else {
            String initialUserPassword = generateInitialUserPassword();
            Map<String, String> defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(),
                    userWrapper.getLastname(), userWrapper.getEmailAddress());
            // calling addUser method of carbon user api
            userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword, userWrapper.getRoles(),
                    defaultUserClaims, null);
            // invite newly added user to enroll device
            inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
            // Outputting debug message upon successful addition of user
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
            }
            // returning response with success state
            responsePayload.setStatusCode(HttpStatus.SC_CREATED);
            responsePayload.setMessageFromServer(
                    "User by username: " + userWrapper.getUsername() + " was successfully added.");
            return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build();
        }
    } catch (UserStoreException e) {
        String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
        log.error(msg, e);
        throw new MDMAPIException(msg, e);
    }
}

From source file:org.wso2.carbon.mdm.api.User.java

/**
 * Update user in user store//from  ww w . j  a v  a2s .c om
 *
 * @param userWrapper Wrapper object representing input json payload
 * @return {Response} Status of the request wrapped inside Response object
 * @throws MDMAPIException
 */
@PUT
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username)
        throws MDMAPIException {
    UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
    ResponsePayload responsePayload = new ResponsePayload();
    try {
        if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
            Map<String, String> defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(),
                    userWrapper.getLastname(), userWrapper.getEmailAddress());
            if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
                // Decoding Base64 encoded password
                byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
                userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
                        new String(decodedBytes, "UTF-8"));
                log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
            }
            List<String> listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
            final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]);

            /*
            Use the Set theory to find the roles to delete and roles to add
            The difference of roles in existingRolesSet and newRolesSet needed to be deleted
            new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet
            */
            final TreeSet<String> existingRolesSet = new TreeSet<>();
            Collections.addAll(existingRolesSet, existingRoles);
            final TreeSet<String> newRolesSet = new TreeSet<>();
            Collections.addAll(newRolesSet, userWrapper.getRoles());
            existingRolesSet.removeAll(newRolesSet);
            // Now we have the roles to delete
            String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]);
            List<String> roles = new ArrayList<>(Arrays.asList(rolesToDelete));
            roles.remove(ROLE_EVERYONE);
            rolesToDelete = new String[0];
            // Clearing and re-initializing the set
            existingRolesSet.clear();
            Collections.addAll(existingRolesSet, existingRoles);
            newRolesSet.removeAll(existingRolesSet);
            // Now we have the roles to add
            String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]);
            userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd);
            userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
            // Outputting debug message upon successful addition of user
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
            }
            // returning response with success state
            responsePayload.setStatusCode(HttpStatus.SC_CREATED);
            responsePayload.setMessageFromServer(
                    "User by username: " + userWrapper.getUsername() + " was successfully updated.");
            return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + userWrapper.getUsername()
                        + " doesn't exists. Therefore, request made to update user was refused.");
            }
            // returning response with bad request state
            responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
            responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername()
                    + " doesn't  exists. Therefore, request made to update user was refused.");
            return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build();
        }
    } catch (UserStoreException | UnsupportedEncodingException e) {
        String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
        log.error(msg, e);
        throw new MDMAPIException(msg, e);
    }
}

From source file:org.xwiki.test.escaping.framework.AbstractEscapingTest.java

/**
 * Download a page from the server and return its content. Throws a {@link RuntimeException} on connection problems
 * etc./*from   www .  ja v a  2 s.c  o  m*/
 * 
 * @param url URL of the page
 * @return content of the page
 */
protected static URLContent getUrlContent(String url) {
    GetMethod get = new GetMethod(url);
    get.setFollowRedirects(true);
    if (isLoggedIn()) {
        get.setDoAuthentication(true);
        get.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64("Admin:admin".getBytes())));
    }

    try {
        int statusCode = AbstractEscapingTest.getClient().executeMethod(get);
        switch (statusCode) {
        case HttpStatus.SC_OK:
            // everything is fine
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            // do not fail on 401 (unauthorized), used in some tests
            System.out.println("WARNING, Ignoring status 401 (unauthorized) for URL: " + url);
            break;
        case HttpStatus.SC_CONFLICT:
            // do not fail on 409 (conflict), used in some templates
            System.out.println("WARNING, Ignoring status 409 (conflict) for URL: " + url);
            break;
        case HttpStatus.SC_NOT_FOUND:
            // ignore 404 (the page is still rendered)
            break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            // ignore 500 (internal server error), which is used by the standard exception.vm error display
            break;
        default:
            throw new RuntimeException("HTTP GET request returned status " + statusCode + " ("
                    + get.getStatusText() + ") for URL: " + url);
        }

        return new URLContent(get.getResponseHeader("Content-Type").getValue(), get.getResponseBody());
    } catch (IOException exception) {
        throw new RuntimeException("Error retrieving URL: " + url, exception);
    } finally {
        get.releaseConnection();
    }
}

From source file:se.sperber.cryson.apitest.CrysonAPITest.java

@Test
public void shouldNotCommitStaleEntities() throws Exception {
    Long entityId = foundEntity.getId();
    Long childEntityId = foundEntity.getChildEntities().iterator().next().getId();
    String commitJson = "{\"updatedEntities\":[{\"crysonEntityClass\":\"CrysonTestEntity\",\"id\":" + entityId
            + ",\"name\":\"will not update\",\"childEntities_cryson_ids\":[]}], \"deletedEntities\":[], \"persistedEntities\":[]}";

    PostMethod postMethod = new PostMethod("http://localhost:8789/cryson/commit");
    postMethod.setRequestEntity(new StringRequestEntity(commitJson, "application/json", "UTF-8"));
    assertEquals(HttpStatus.SC_CONFLICT, httpClient.executeMethod(postMethod));
    assertEquals("{\"message\":\"Optimistic locking failed\"}", postMethod.getResponseBodyAsString());
}

From source file:terrastore.integration.IntegrationTest.java

@Test
public void testPutValueAndConditionallyPutAgainWithConflict() throws Exception {
    String bucket = UUID.randomUUID().toString();

    TestValue value = new TestValue("value1", 1);
    PutMethod putValue = makePutMethod(NODE1_PORT, bucket + "/value");
    putValue.setRequestEntity(new StringRequestEntity(fromObjectToJson(value), "application/json", null));
    HTTP_CLIENT.executeMethod(putValue);
    assertEquals(HttpStatus.SC_NO_CONTENT, putValue.getStatusCode());
    putValue.releaseConnection();/*from   www.jav  a2s.  com*/

    TestValue newValue = new TestValue("value2", 1);
    PutMethod conditionallyPutValue = makePutMethodWithPredicate(NODE1_PORT, bucket + "/value",
            "jxpath:/stringField[.='wrong']");
    conditionallyPutValue
            .setRequestEntity(new StringRequestEntity(fromObjectToJson(newValue), "application/json", null));
    HTTP_CLIENT.executeMethod(conditionallyPutValue);
    assertEquals(HttpStatus.SC_CONFLICT, conditionallyPutValue.getStatusCode());
    conditionallyPutValue.releaseConnection();

    GetMethod getValue = makeGetMethod(NODE2_PORT, bucket + "/value");
    HTTP_CLIENT.executeMethod(getValue);
    assertEquals(HttpStatus.SC_OK, getValue.getStatusCode());
    TestValue returned = fromJsonToObject(getValue.getResponseBodyAsString());
    assertEquals(value, returned);
    getValue.releaseConnection();
}