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

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

<tt>201 Created</tt> (HTTP/1.0 - RFC 1945)

Usage

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

/**
 * Update user in user store/*w  w w.  j a  v a  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.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder.java

/**
 * Builds the response to change the password of a user
 * @param credentials - User credentials
 * @return Response Object//w ww. j a  v a  2  s  .c o m
 */
public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) {
    ResponsePayload responsePayload = new ResponsePayload();

    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
        byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword());
        userStoreManager.updateCredential(credentials.getUsername(), new String(decodedNewPassword, "UTF-8"),
                new String(decodedOldPassword, "UTF-8"));
        responsePayload.setStatusCode(HttpStatus.SC_CREATED);
        responsePayload.setMessageFromServer(
                "UserImpl password by username: " + credentials.getUsername() + " was successfully changed.");
        return Response.status(Response.Status.CREATED).entity(responsePayload).build();
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
        responsePayload.setMessageFromServer("Old password does not match.");
        return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
    } catch (UnsupportedEncodingException e) {
        String errorMsg = "Could not change the password of the user: " + credentials.getUsername()
                + ". The Character Encoding is not supported.";
        log.error(errorMsg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
    } catch (MDMAPIException e) {
        log.error(e.getErrorMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
    }
}

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

/**
 * Builds the response to reset the password of a user
 * @param credentials - User credentials
 * @return Response Object/*w  w  w  .  j av  a  2  s .com*/
 */
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) {
    ResponsePayload responsePayload = new ResponsePayload();
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
        userStoreManager.updateCredentialByAdmin(credentials.getUsername(),
                new String(decodedNewPassword, "UTF-8"));
        responsePayload.setStatusCode(HttpStatus.SC_CREATED);
        responsePayload.setMessageFromServer(
                "UserImpl password by username: " + credentials.getUsername() + " was successfully changed.");
        return Response.status(Response.Status.CREATED).entity(responsePayload).build();
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
        responsePayload.setMessageFromServer("Could not change the password.");
        return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
    } catch (UnsupportedEncodingException e) {
        String errorMsg = "Could not change the password of the user: " + credentials.getUsername()
                + ". The Character Encoding is not supported.";
        log.error(errorMsg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
    } catch (MDMAPIException e) {
        log.error(e.getErrorMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
    }
}

From source file:org.wso2.carbon.identity.provisioning.connector.salesforce.SalesforceProvisioningConnector.java

/**
 * @param provisioningEntity/*w ww  . ja v  a  2s .c o  m*/
 * @return
 * @throws IdentityProvisioningException
 */
private String createUser(ProvisioningEntity provisioningEntity) throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    HttpClient httpclient = new HttpClient();
    JSONObject user = buildJsonObject(provisioningEntity);

    PostMethod post = new PostMethod(this.getUserObjectEndpoint());
    setAuthorizationHeader(post);

    try {
        post.setRequestEntity(new StringRequestEntity(user.toString(),
                SalesforceConnectorConstants.CONTENT_TYPE_APPLICATION_JSON, null));
    } catch (UnsupportedEncodingException e) {
        log.error("Error in encoding provisioning request");
        throw new IdentityProvisioningException(e);
    }

    String provisionedId = null;

    try {

        httpclient.executeMethod(post);

        if (isDebugEnabled) {
            log.debug("HTTP status " + post.getStatusCode() + " creating user");
        }

        if (post.getStatusCode() == HttpStatus.SC_CREATED) {
            JSONObject response = new JSONObject(
                    new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Create response: " + response.toString(2));
            }

            if (response.getBoolean("success")) {
                provisionedId = response.getString("id");
                if (isDebugEnabled) {
                    log.debug("New record id " + provisionedId);
                }
            }
        } else {
            log.error("recieved response status code :" + post.getStatusCode() + " text : "
                    + post.getStatusText());
            if (isDebugEnabled) {
                log.debug("Error response : " + readResponse(post));
            }
        }
    } catch (IOException | JSONException e) {
        throw new IdentityProvisioningException("Error in invoking provisioning operation for the user", e);
    } finally {
        post.releaseConnection();
    }

    if (isDebugEnabled) {
        log.debug("Returning created user's ID : " + provisionedId);
    }

    return provisionedId;
}

From source file:org.wso2.carbon.identity.provisioning.connector.sample.SampleProvisioningConnector.java

/**
 * //from  w  w w.ja  va2  s  . c  om
 * @param provisioningEntity
 * @return
 * @throws IdentityProvisioningException
 */
private String createUser(ProvisioningEntity provisioningEntity) throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    HttpClient httpclient = new HttpClient();
    JSONObject user = buildJsonObject(provisioningEntity);

    PostMethod post = new PostMethod(this.getUserObjectEndpoint());
    setAuthorizationHeader(post);

    try {
        post.setRequestEntity(new StringRequestEntity(user.toString(),
                SampleConnectorConstants.CONTENT_TYPE_APPLICATION_JSON, null));
    } catch (UnsupportedEncodingException e) {
        log.error("Error in encoding provisioning request");
        throw new IdentityProvisioningException(e);
    }

    String provisionedId = null;

    try {

        httpclient.executeMethod(post);

        if (isDebugEnabled) {
            log.debug("HTTP status " + post.getStatusCode() + " creating user");
        }

        if (post.getStatusCode() == HttpStatus.SC_CREATED) {
            JSONObject response = new JSONObject(
                    new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Create response: " + response.toString(2));
            }

            if (response.getBoolean("success")) {
                provisionedId = response.getString("id");
                if (isDebugEnabled) {
                    log.debug("New record id " + provisionedId);
                }
            }
        } else {
            log.error("recieved response status code :" + post.getStatusCode() + " text : "
                    + post.getStatusText());
            if (isDebugEnabled) {
                log.debug("Error response : " + readResponse(post));
            }
        }
    } catch (HttpException e) {
        log.error("Error in invoking provisioning operation for the user");
        throw new IdentityProvisioningException(e);
    } catch (IOException e) {
        log.error("Error in invoking provisioning operation for the user");
        throw new IdentityProvisioningException(e);
    } catch (JSONException e) {
        log.error("Error in decoding response to JSON");
        throw new IdentityProvisioningException(e);
    } finally {
        post.releaseConnection();
    }

    if (isDebugEnabled) {
        log.debug("Returning created user's ID : " + provisionedId);
    }

    return provisionedId;
}

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

@POST
public ResponsePayload saveTenantConfiguration(TenantConfiguration configuration) throws MDMAPIException {
    ResponsePayload responseMsg = new ResponsePayload();
    try {//from w ww .  j ava2  s  .c o  m
        MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
                MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
        //Schedule the task service
        MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration));
        Response.status(HttpStatus.SC_CREATED);
        responseMsg.setMessageFromServer("Tenant configuration saved successfully.");
        responseMsg.setStatusCode(HttpStatus.SC_CREATED);
        return responseMsg;
    } catch (ConfigurationManagementException e) {
        String msg = "Error occurred while saving the tenant configuration.";
        log.error(msg, e);
        throw new MDMAPIException(msg, e);
    }
}

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

@PUT
public ResponsePayload updateConfiguration(TenantConfiguration configuration) throws MDMAPIException {
    ResponsePayload responseMsg = new ResponsePayload();
    try {/*w ww.  j  ava 2  s . c  om*/
        MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
                MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
        //Schedule the task service
        MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration));
        Response.status(HttpStatus.SC_CREATED);
        responseMsg.setMessageFromServer("Tenant configuration updated successfully.");
        responseMsg.setStatusCode(HttpStatus.SC_CREATED);
        return responseMsg;
    } catch (ConfigurationManagementException e) {
        String msg = "Error occurred while updating the tenant configuration.";
        log.error(msg, e);
        throw new MDMAPIException(msg, e);
    }
}

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

@POST
public ResponsePayload addNotification(Notification notification) throws MDMAPIException {
    ResponsePayload responseMsg = new ResponsePayload();
    try {/*from www  .j a  v a 2 s  .c o  m*/
        MDMAPIUtils.getNotificationManagementService().addNotification(notification);
        Response.status(HttpStatus.SC_CREATED);
        responseMsg.setMessageFromServer("Notification has added successfully.");
        responseMsg.setStatusCode(HttpStatus.SC_CREATED);
        return responseMsg;
    } catch (NotificationManagementException e) {
        String msg = "Error occurred while updating notification status.";
        log.error(msg, e);
        throw new MDMAPIException(msg, e);
    }
}

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

@POST
public Message addOperation(DeviceOperationContext operationContext) throws MDMAPIException {
    DeviceManagementService dmService;//ww  w  . ja v  a 2 s . co  m
    OperationManager operationManager;
    Message responseMsg = new Message();
    try {
        dmService = MDMAPIUtils.getDeviceManagementService();
        operationManager = dmService
                .getOperationManager(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
        boolean status = operationManager.addOperation(operationContext.getOperation(),
                operationContext.getDevices());
        if (status) {
            Response.status(HttpStatus.SC_CREATED);
            responseMsg.setResponseMessage("Operation has added successfully.");
        } else {
            Response.status(HttpStatus.SC_OK);
            responseMsg.setResponseMessage("Failure in adding the Operation.");
        }
        return responseMsg;
    } catch (DeviceManagementServiceException deviceServiceMgtEx) {
        String errorMsg = "Device management service error";
        log.error(errorMsg, deviceServiceMgtEx);
        throw new MDMAPIException(errorMsg, deviceServiceMgtEx);
    } catch (DeviceManagementException deviceMgtEx) {
        String errorMsg = "Error occurred while adding the operation";
        log.error(errorMsg, deviceMgtEx);
        throw new MDMAPIException(errorMsg, deviceMgtEx);
    } catch (OperationManagementException ex) {
        String errorMsg = "Error occurred while saving the operation";
        log.error(errorMsg, ex);
        throw new MDMAPIException(errorMsg, ex);
    }
}

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

@POST
@Path("inactive-policy")
public ResponsePayload addPolicy(PolicyWrapper policyWrapper) throws MDMAPIException {

    PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService();
    ResponsePayload responseMsg = new ResponsePayload();
    org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
    policy.setPolicyName(policyWrapper.getPolicyName());
    policy.setProfileId(policyWrapper.getProfileId());
    policy.setDescription(policyWrapper.getDescription());
    policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile()));
    policy.setOwnershipType(policyWrapper.getOwnershipType());
    policy.setRoles(policyWrapper.getRoles());
    policy.setUsers(policyWrapper.getUsers());
    policy.setTenantId(policyWrapper.getTenantId());
    policy.setCompliance(policyWrapper.getCompliance());
    try {//  ww  w.j a va  2s. c  o  m
        PolicyAdministratorPoint pap = policyManagementService.getPAP();
        pap.addPolicy(policy);
        Response.status(HttpStatus.SC_CREATED);
        responseMsg.setStatusCode(HttpStatus.SC_CREATED);
        responseMsg.setMessageFromServer("Policy has been added successfully.");
        return responseMsg;
    } catch (PolicyManagementException e) {
        String error = "Policy Management related exception";
        log.error(error, e);
        throw new MDMAPIException(error, e);
    }
}