Example usage for org.apache.commons.httpclient.methods GetMethod setQueryString

List of usage examples for org.apache.commons.httpclient.methods GetMethod setQueryString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod setQueryString.

Prototype

public void setQueryString(String queryString) 

Source Link

Usage

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

/**
 * @return/*from   w  w w. j  a v a2  s  . com*/
 * @throws IdentityProvisioningException
 */
public String listUsers(String query) throws IdentityProvisioningException {

    if (log.isTraceEnabled()) {
        log.trace("Starting listUsers() of " + SalesforceProvisioningConnector.class);
    }
    boolean isDebugEnabled = log.isDebugEnabled();

    if (StringUtils.isBlank(query)) {
        query = SalesforceConnectorDBQueries.SALESFORCE_LIST_USER_SIMPLE_QUERY;
    }

    HttpClient httpclient = new HttpClient();
    GetMethod get = new GetMethod(this.getDataQueryEndpoint());
    setAuthorizationHeader(get);

    // set the SOQL as a query param
    NameValuePair[] params = new NameValuePair[1];
    params[0] = new NameValuePair("q", query);
    get.setQueryString(params);

    StringBuilder sb = new StringBuilder();
    try {
        httpclient.executeMethod(get);
        if (get.getStatusCode() == HttpStatus.SC_OK) {

            JSONObject response = new JSONObject(
                    new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Query response: " + response.toString(2));
            }

            // Build the returning string
            sb.append(response.getString("totalSize") + " record(s) returned\n\n");
            JSONArray results = response.getJSONArray("records");
            for (int i = 0; i < results.length(); i++) {
                sb.append(results.getJSONObject(i).getString("Id") + ", "

                        + results.getJSONObject(i).getString("Alias") + ", "
                        + results.getJSONObject(i).getString("Email") + ", "
                        + results.getJSONObject(i).getString("LastName") + ", "
                        + results.getJSONObject(i).getString("Name") + ", "
                        + results.getJSONObject(i).getString("ProfileId") + ", "
                        + results.getJSONObject(i).getString("Username") + "\n");
            }
            sb.append("\n");
        } else {
            log.error(
                    "recieved response status code:" + get.getStatusCode() + " text : " + get.getStatusText());
        }
    } catch (JSONException | IOException e) {
        log.error("Error in invoking provisioning operation for the user listing");
        throw new IdentityProvisioningException(e);
    } finally {
        get.releaseConnection();
    }

    if (isDebugEnabled) {
        log.debug("Returning string : " + sb.toString());
    }

    if (log.isTraceEnabled()) {
        log.trace("Ending listUsers() of " + SalesforceProvisioningConnector.class);
    }
    return sb.toString();
}

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

/**
 * /*from ww w  .  j  av a  2  s.  co  m*/
 * @return
 * @throws IdentityProvisioningException
 */
public String listUsers(String query) throws IdentityProvisioningException {

    if (log.isTraceEnabled()) {
        log.trace("Starting listUsers() of " + SampleProvisioningConnector.class);
    }
    boolean isDebugEnabled = log.isDebugEnabled();

    if (query == null || query.isEmpty()) {
        query = SampleProvisioningConnectorConfig.SALESFORCE_LIST_USER_SIMPLE_QUERY;
        // SalesforceProvisioningConnectorConfig.SALESFORCE_LIST_USER_FULL_QUERY;
    }

    HttpClient httpclient = new HttpClient();
    GetMethod get = new GetMethod(this.getDataQueryEndpoint());
    setAuthorizationHeader(get);

    // set the SOQL as a query param
    NameValuePair[] params = new NameValuePair[1];
    params[0] = new NameValuePair("q", query);
    get.setQueryString(params);

    StringBuilder sb = new StringBuilder();
    try {
        httpclient.executeMethod(get);
        if (get.getStatusCode() == HttpStatus.SC_OK) {

            JSONObject response = new JSONObject(
                    new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Query response: " + response.toString(2));
            }

            // Build the returning string
            sb.append(response.getString("totalSize") + " record(s) returned\n\n");
            JSONArray results = response.getJSONArray("records");
            for (int i = 0; i < results.length(); i++) {
                sb.append(results.getJSONObject(i).getString("Id") + ", "

                        + results.getJSONObject(i).getString("Alias") + ", "
                        + results.getJSONObject(i).getString("Email") + ", "
                        + results.getJSONObject(i).getString("LastName") + ", "
                        + results.getJSONObject(i).getString("Name") + ", "
                        + results.getJSONObject(i).getString("ProfileId") + ", "

                        // +
                        // results.getJSONObject(i).getString("EmailEncodingKey")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("LanguageLocaleKey")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("LocaleSidKey")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("TimeZoneSidKey")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("UserPermissionsCallCenterAutoLogin")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("UserPermissionsMarketingUser")
                        // + ", "
                        // +
                        // results.getJSONObject(i).getString("UserPermissionsOfflineUser")
                        // + ", "

                        + results.getJSONObject(i).getString("Username") + "\n");
            }
            sb.append("\n");
        } else {
            log.error(
                    "recieved response status code:" + get.getStatusCode() + " text : " + get.getStatusText());
        }
    } catch (JSONException e) {
        log.error("Error in decoding response to JSON");
        throw new IdentityProvisioningException(e);
    } catch (HttpException e) {
        log.error("Error in invoking provisioning operation for the user listing");
        throw new IdentityProvisioningException(e);
    } catch (IOException e) {
        throw new IdentityProvisioningException(e);
    } finally {
        get.releaseConnection();
    }

    if (isDebugEnabled) {
        log.debug("Returning string : " + sb.toString());
    }

    if (log.isTraceEnabled()) {
        log.trace("Ending listUsers() of " + SampleProvisioningConnector.class);
    }
    return sb.toString();
}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionDeleteUser() throws IdentitySCIMException {
    String userName = null;// w  w w.j  a va 2 s .c  o  m

    try {
        //get provider details
        String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (contentType == null) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }

        /*get the userId of the user being provisioned from the particular provider by filtering
          with user name*/
        GetMethod getMethod = new GetMethod(userEPURL);
        //add filter query parameter
        getMethod.setQueryString(USER_FILTER + ((User) scimObject).getUserName());
        //add authorization headers
        getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));

        //create http client
        HttpClient httpFilterClient = new HttpClient();
        //send the request
        int responseStatus = httpFilterClient.executeMethod(getMethod);

        String response = getMethod.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("SCIM - filter operation inside 'delete user' provisioning "
                    + "returned with response code: " + responseStatus);
            logger.debug("Filter User Response: " + response);
        }
        SCIMClient scimClient = new SCIMClient();
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //decode the response to extract the userId.
            ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response,
                    SCIMConstants.identifyFormat(contentType), objectType);
            List<SCIMObject> users = listedResource.getScimObjects();
            String userId = null;
            //we expect only one user in the list
            for (SCIMObject user : users) {
                userId = ((User) user).getId();
            }
            String url = userEPURL + "/" + userId;
            //now send the delete request.
            DeleteMethod deleteMethod = new DeleteMethod(url);
            deleteMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            HttpClient httpDeleteClient = new HttpClient();
            int deleteResponseStatus = httpDeleteClient.executeMethod(deleteMethod);
            String deleteResponse = deleteMethod.getResponseBodyAsString();
            logger.info("SCIM - delete user operation returned with response code: " + deleteResponseStatus);
            if (!scimClient.evaluateResponseStatus(deleteResponseStatus)) {
                //decode scim exception and extract the specific error message.
                AbstractCharonException exception = scimClient.decodeSCIMException(deleteResponse,
                        SCIMConstants.identifyFormat(contentType));
                logger.error(exception.getDescription());
            }
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(response,
                    SCIMConstants.identifyFormat(contentType));
            logger.error(exception.getDescription());
        }
    } catch (CharonException | IOException | BadRequestException e) {
        throw new IdentitySCIMException("Error in provisioning 'delete user' operation for user :" + userName,
                e);
    }
}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionUpdateUser() throws IdentitySCIMException {
    String userName = null;/*from  w w  w. j a v  a  2s.com*/
    try {
        //get provider details
        String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (contentType == null) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }

        /*get the userId of the user being provisioned from the particular provider by filtering
          with user name*/
        GetMethod getMethod = new GetMethod(userEPURL);
        //add filter query parameter
        getMethod.setQueryString(USER_FILTER + ((User) scimObject).getUserName());
        //add authorization headers
        getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));

        //create http client
        HttpClient httpFilterClient = new HttpClient();
        //send the request
        int responseStatus = httpFilterClient.executeMethod(getMethod);

        String response = getMethod.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("SCIM - filter operation inside 'delete user' provisioning "
                    + "returned with response code: " + responseStatus);
            logger.debug("Filter User Response: " + response);
        }
        SCIMClient scimClient = new SCIMClient();
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //decode the response to extract the userId.
            ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response,
                    SCIMConstants.identifyFormat(contentType), objectType);
            List<SCIMObject> users = listedResource.getScimObjects();
            String userId = null;
            //we expect only one user in the list
            for (SCIMObject user : users) {
                userId = ((User) user).getId();
                if (userId == null) {
                    logger.error("Trying to update a user entry which doesn't support SCIM. "
                            + "Usually internal carbon User entries such as admin role doesn't support SCIM attributes.");
                    return;
                }
            }
            String url = userEPURL + "/" + userId;
            //now send the update request.
            PutMethod putMethod = new PutMethod(url);
            putMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            String encodedUser = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject,
                    SCIMConstants.identifyFormat(contentType));
            RequestEntity putRequestEntity = new StringRequestEntity(encodedUser, contentType, null);
            putMethod.setRequestEntity(putRequestEntity);

            HttpClient httpUpdateClient = new HttpClient();
            int updateResponseStatus = httpUpdateClient.executeMethod(putMethod);
            String updateResponse = putMethod.getResponseBodyAsString();
            logger.info("SCIM - update user operation returned with response code: " + updateResponseStatus);
            if (!scimClient.evaluateResponseStatus(updateResponseStatus)) {
                //decode scim exception and extract the specific error message.
                AbstractCharonException exception = scimClient.decodeSCIMException(updateResponse,
                        SCIMConstants.identifyFormat(contentType));
                logger.error(exception.getDescription());
            }
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(response,
                    SCIMConstants.identifyFormat(contentType));
            logger.error(exception.getDescription());
        }
    } catch (CharonException e) {
        throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName);
    } catch (HttpException e) {
        throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName);
    } catch (IOException e) {
        throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName);
    } catch (BadRequestException e) {
        throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName);
    }

}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionPatchUser() throws IdentitySCIMException {
    String userName = null;/*from w w w. ja  v a  2s.  c o m*/
    try {
        //get provider details
        String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (StringUtils.isEmpty(contentType)) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }

        /*get the userId of the user being provisioned from the particular provider by filtering
          with user name*/
        GetMethod getMethod = new GetMethod(userEPURL);
        //add filter query parameter
        getMethod.setQueryString(USER_FILTER + ((User) scimObject).getUserName());
        //add authorization headers
        getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));

        //create http client
        HttpClient httpFilterClient = new HttpClient();
        //send the request
        int responseStatus = httpFilterClient.executeMethod(getMethod);

        String response = getMethod.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("SCIM - filter operation inside 'delete user' provisioning "
                    + "returned with response code: " + responseStatus);
            logger.debug("Filter User Response: " + response);
        }
        SCIMClient scimClient = new SCIMClient();
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //decode the response to extract the userId.
            ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response,
                    SCIMConstants.identifyFormat(contentType), objectType);
            List<SCIMObject> users = listedResource.getScimObjects();
            String userId = null;
            //we expect only one user in the list
            for (SCIMObject user : users) {
                userId = ((User) user).getId();
                if (StringUtils.isEmpty(userId)) {
                    logger.error("Trying to update a user entry which doesn't support SCIM. "
                            + "Usually internal carbon User entries such as admin role doesn't support SCIM attributes.");
                    return;
                }
            }
            String url = userEPURL + "/" + userId;
            PostMethod patchMethod = new PostMethod(url) {
                @Override
                public String getName() {
                    return "PATCH";
                }
            };

            patchMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            String encodedUser = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject,
                    SCIMConstants.identifyFormat(contentType));
            RequestEntity putRequestEntity = new StringRequestEntity(encodedUser, contentType, null);
            patchMethod.setRequestEntity(putRequestEntity);

            HttpClient httpUpdateClient = new HttpClient();
            int updateResponseStatus = httpUpdateClient.executeMethod(patchMethod);
            String updateResponse = patchMethod.getResponseBodyAsString();
            logger.info("SCIM - update user operation returned with response code: " + updateResponseStatus);
            if (!scimClient.evaluateResponseStatus(updateResponseStatus)) {
                //decode scim exception and extract the specific error message.
                AbstractCharonException exception = scimClient.decodeSCIMException(updateResponse,
                        SCIMConstants.identifyFormat(contentType));
                logger.error(exception.getDescription());
            }
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(response,
                    SCIMConstants.identifyFormat(contentType));
            logger.error(exception.getDescription());
        }
    } catch (CharonException | IOException | BadRequestException e) {
        throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName,
                e);
    }
}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionCreateGroup() throws IdentitySCIMException {
    String userName = null;//from www  .j  a  va 2 s.c  o m
    try {
        //get provider details
        String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT);
        String groupEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_GROUP_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (contentType == null) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }
        SCIMClient scimClient = new SCIMClient();
        //get list of users in the group, if any, by userNames
        List<String> users = ((Group) scimObject).getMembersWithDisplayName();

        Group copiedGroup = null;

        if (CollectionUtils.isNotEmpty(users)) {
            //create a deep copy of the group since we are going to update the member ids
            copiedGroup = (Group) CopyUtil.deepCopy(scimObject);
            //delete existing members in the group since we are going to update it with
            copiedGroup.deleteAttribute(SCIMConstants.GroupSchemaConstants.MEMBERS);
            //create http client
            HttpClient httpFilterUserClient = new HttpClient();
            //create get method for filtering
            GetMethod getMethod = new GetMethod(userEPURL);
            getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            //get corresponding userIds
            for (String user : users) {
                String filter = USER_FILTER + user;
                getMethod.setQueryString(filter);
                int responseCode = httpFilterUserClient.executeMethod(getMethod);
                String response = getMethod.getResponseBodyAsString();
                if (logger.isDebugEnabled()) {
                    logger.debug("SCIM - 'filter user' operation inside 'create group' provisioning "
                            + "returned with response code: " + responseCode);
                    logger.debug("Filter User Response: " + response);
                }
                //check for success of the response
                if (scimClient.evaluateResponseStatus(responseCode)) {
                    ListedResource listedUserResource = scimClient.decodeSCIMResponseWithListedResource(
                            response, SCIMConstants.identifyFormat(contentType), SCIMConstants.USER_INT);
                    List<SCIMObject> filteredUsers = listedUserResource.getScimObjects();
                    String userId = null;
                    for (SCIMObject filteredUser : filteredUsers) {
                        //we expect only one result here
                        userId = ((User) filteredUser).getId();
                    }
                    copiedGroup.setGroupMember(userId, user);
                } else {
                    //decode scim exception and extract the specific error message.
                    AbstractCharonException exception = scimClient.decodeSCIMException(response,
                            SCIMConstants.identifyFormat(contentType));
                    logger.error(exception.getDescription());
                }
            }
        }

        //provision create group operation
        HttpClient httpCreateGroupClient = new HttpClient();

        PostMethod postMethod = new PostMethod(groupEPURL);
        //add basic auth header
        postMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
        //encode group
        String encodedGroup = null;
        if (copiedGroup != null) {
            encodedGroup = scimClient.encodeSCIMObject(copiedGroup, SCIMConstants.identifyFormat(contentType));
        } else {
            encodedGroup = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject,
                    SCIMConstants.identifyFormat(contentType));
        }

        //create request entity with the payload.
        RequestEntity requestEntity = new StringRequestEntity(encodedGroup, contentType, null);
        postMethod.setRequestEntity(requestEntity);

        //send the request
        int responseStatus = httpCreateGroupClient.executeMethod(postMethod);

        logger.info("SCIM - create group operation returned with response code: " + responseStatus);

        String postResponse = postMethod.getResponseBodyAsString();

        if (logger.isDebugEnabled()) {
            logger.debug("Create Group Response: " + postResponse);
        }
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //try to decode the scim object to verify that it gets decoded without issue.
            scimClient.decodeSCIMResponse(postResponse, SCIMConstants.JSON, objectType);
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(postResponse,
                    SCIMConstants.JSON);
            logger.error(exception.getDescription());
        }
    } catch (BadRequestException | IOException | CharonException e) {
        throw new IdentitySCIMException("Error in provisioning 'create group' operation for user :" + userName,
                e);
    }
}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionDeleteGroup() throws IdentitySCIMException {
    String userName = null;//  ww w . j  av  a2s . c  om
    try {
        //get provider details
        String groupEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_GROUP_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (contentType == null) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }

        /*get the groupId of the group being provisioned from the particular provider by filtering
          with display name*/
        GetMethod getMethod = new GetMethod(groupEPURL);
        //add filter query parameter
        getMethod.setQueryString(GROUP_FILTER + ((Group) scimObject).getDisplayName());
        //add authorization headers
        getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));

        //create http client
        HttpClient httpFilterClient = new HttpClient();
        //send the request
        int responseStatus = httpFilterClient.executeMethod(getMethod);
        String response = getMethod.getResponseBodyAsString();

        if (logger.isDebugEnabled()) {
            logger.debug("SCIM - filter operation inside 'delete group' provisioning "
                    + "returned with response code: " + responseStatus);
            logger.debug("Filter Group Response: " + response);
        }
        SCIMClient scimClient = new SCIMClient();
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //decode the response to extract the groupId.
            ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response,
                    SCIMConstants.identifyFormat(contentType), objectType);
            List<SCIMObject> groups = listedResource.getScimObjects();
            String groupId = null;
            //we expect only one user in the list
            for (SCIMObject group : groups) {
                groupId = ((Group) group).getId();
            }
            String url = groupEPURL + "/" + groupId;
            //now send the delete request.
            DeleteMethod deleteMethod = new DeleteMethod(url);
            deleteMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            HttpClient httpDeleteClient = new HttpClient();
            int deleteResponseStatus = httpDeleteClient.executeMethod(deleteMethod);
            String deleteResponse = deleteMethod.getResponseBodyAsString();
            logger.info("SCIM - delete group operation returned with response code: " + deleteResponseStatus);
            if (!scimClient.evaluateResponseStatus(deleteResponseStatus)) {
                //decode scim exception and extract the specific error message.
                AbstractCharonException exception = scimClient.decodeSCIMException(deleteResponse,
                        SCIMConstants.identifyFormat(contentType));
                logger.error(exception.getDescription());
            }
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(response,
                    SCIMConstants.identifyFormat(contentType));
            logger.error(exception.getDescription());
        }
    } catch (CharonException | IOException | BadRequestException e) {
        throw new IdentitySCIMException("Error in provisioning 'delete group' operation for user :" + userName,
                e);
    }
}

From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java

public void provisionUpdateGroup() throws IdentitySCIMException {
    String userName = null;//  w w  w  .  j a v a  2 s .co  m
    try {
        //get provider details
        String groupEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_GROUP_ENDPOINT);
        String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT);
        userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME);
        String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD);
        String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER);

        if (contentType == null) {
            contentType = SCIMConstants.APPLICATION_JSON;
        }

        /*get the groupId of the group being provisioned from the particular provider by filtering
          with display name*/
        GetMethod getMethod = new GetMethod(groupEPURL);
        //add filter query parameter
        //check if role name is updated
        if (additionalProvisioningInformation != null && (Boolean) additionalProvisioningInformation
                .get(SCIMCommonConstants.IS_ROLE_NAME_CHANGED_ON_UPDATE)) {
            getMethod.setQueryString(
                    GROUP_FILTER + additionalProvisioningInformation.get(SCIMCommonConstants.OLD_GROUP_NAME));
        } else {
            getMethod.setQueryString(GROUP_FILTER + ((Group) scimObject).getDisplayName());
        }
        //add authorization headers
        getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));

        //create http client
        HttpClient httpFilterClient = new HttpClient();
        //send the request
        int responseStatus = httpFilterClient.executeMethod(getMethod);

        String response = getMethod.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("SCIM - filter operation inside 'update group' provisioning "
                    + "returned with response code: " + responseStatus);
            logger.debug("Filter Group Response: " + response);
        }
        SCIMClient scimClient = new SCIMClient();
        if (scimClient.evaluateResponseStatus(responseStatus)) {
            //decode the response to extract the groupId.
            ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response,
                    SCIMConstants.identifyFormat(contentType), objectType);
            List<SCIMObject> groups = listedResource.getScimObjects();
            String groupId = null;
            //we expect only one user in the list
            for (SCIMObject group : groups) {
                groupId = ((Group) group).getId();
            }

            String url = groupEPURL + "/" + groupId;

            //now start sending the update request.

            //get list of users in the group, if any, by userNames
            List<String> users = ((Group) scimObject).getMembersWithDisplayName();

            Group copiedGroup = null;

            if (CollectionUtils.isNotEmpty(users)) {
                //create a deep copy of the group since we are going to update the member ids
                copiedGroup = (Group) CopyUtil.deepCopy(scimObject);
                //delete existing members in the group since we are going to update it with
                copiedGroup.deleteAttribute(SCIMConstants.GroupSchemaConstants.MEMBERS);
                //create http client
                HttpClient httpFilterUserClient = new HttpClient();
                //create get method for filtering
                GetMethod getUserMethod = new GetMethod(userEPURL);
                getUserMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                        BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
                //get corresponding userIds
                for (String user : users) {
                    String filter = USER_FILTER + user;
                    getUserMethod.setQueryString(filter);
                    int responseCode = httpFilterUserClient.executeMethod(getUserMethod);
                    String filterUserResponse = getUserMethod.getResponseBodyAsString();
                    if (logger.isDebugEnabled()) {
                        logger.debug("SCIM - 'filter user' operation inside 'update group' provisioning "
                                + "returned with response code: " + responseCode);
                        logger.debug("Filter User Response: " + filterUserResponse);
                    }
                    //check for success of the response
                    if (scimClient.evaluateResponseStatus(responseCode)) {
                        ListedResource listedUserResource = scimClient.decodeSCIMResponseWithListedResource(
                                filterUserResponse, SCIMConstants.identifyFormat(contentType),
                                SCIMConstants.USER_INT);
                        List<SCIMObject> filteredUsers = listedUserResource.getScimObjects();
                        String userId = null;
                        for (SCIMObject filteredUser : filteredUsers) {
                            //we expect only one result here
                            userId = ((User) filteredUser).getId();
                        }
                        copiedGroup.setGroupMember(userId, user);
                    } else {
                        //decode scim exception and extract the specific error message.
                        AbstractCharonException exception = scimClient.decodeSCIMException(filterUserResponse,
                                SCIMConstants.identifyFormat(contentType));
                        logger.error(exception.getDescription());
                    }
                }
            }

            //now send the update request.
            PutMethod putMethod = new PutMethod(url);
            putMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER,
                    BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password));
            String encodedGroup = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject,
                    SCIMConstants.identifyFormat(contentType));
            RequestEntity putRequestEntity = new StringRequestEntity(encodedGroup, contentType, null);
            putMethod.setRequestEntity(putRequestEntity);

            HttpClient httpUpdateClient = new HttpClient();
            int updateResponseStatus = httpUpdateClient.executeMethod(putMethod);
            String updateResponse = putMethod.getResponseBodyAsString();

            logger.info("SCIM - update group operation returned with response code: " + updateResponseStatus);
            if (!scimClient.evaluateResponseStatus(updateResponseStatus)) {
                //decode scim exception and extract the specific error message.
                AbstractCharonException exception = scimClient.decodeSCIMException(updateResponse,
                        SCIMConstants.identifyFormat(contentType));
                logger.error(exception.getDescription());
            }
        } else {
            //decode scim exception and extract the specific error message.
            AbstractCharonException exception = scimClient.decodeSCIMException(response,
                    SCIMConstants.identifyFormat(contentType));
            logger.error(exception.getDescription());
        }
    } catch (CharonException | IOException | BadRequestException e) {
        throw new IdentitySCIMException("Error in provisioning 'delete group' operation for user :" + userName,
                e);
    }
}

From source file:org.wso2.carbon.identity.user.store.ws.WSUserStoreManager.java

public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName)
        throws UserStoreException {

    UserAttributeCacheEntry cacheEntry = getUserAttributesFromCache(userName);
    Map<String, String> allUserAttributes = new HashMap<>();
    Map<String, String> mapAttributes = new HashMap<>();
    if (cacheEntry == null) {
        GetMethod getMethod = new GetMethod(
                EndpointUtil.getUserClaimRetrievalEndpoint(getHostName(), userName));
        try {//w  ww  . j av  a 2 s. c om
            if (this.httpClient == null) {
                this.httpClient = new HttpClient();
            }

            ClaimManager claimManager = WSUserStoreComponentHolder.getInstance().getRealmService()
                    .getBootstrapRealm().getClaimManager();
            getMethod.setQueryString(
                    getQueryString("attributes", getAllClaimMapAttributes(claimManager.getAllClaimMappings())));
            setAuthorizationHeader(getMethod);
            int response = httpClient.executeMethod(getMethod);
            if (response == HttpStatus.SC_OK) {
                String respStr = new String(getMethod.getResponseBody());
                JSONObject resultObj = new JSONObject(respStr);
                Iterator iterator = resultObj.keys();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    allUserAttributes.put(key, (String) resultObj.get(key));
                }
                addAttributesToCache(userName, allUserAttributes);
            }
        } catch (IOException | JSONException | WSUserStoreException e) {
            log.error("Error occurred while calling backed to authenticate request for tenantId - ["
                    + this.tenantId + "]", e);
            return Collections.EMPTY_MAP;
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            log.error("Error occurred while calling backed to authenticate request for tenantId - ["
                    + this.tenantId + "]", e);
            return Collections.EMPTY_MAP;
        }
    } else {
        allUserAttributes = cacheEntry.getUserAttributes();
    }
    for (String propertyName : propertyNames) {
        mapAttributes.put(propertyName, allUserAttributes.get(propertyName));
    }
    return mapAttributes;
}

From source file:org.wso2.carbon.identity.user.store.ws.WSUserStoreManager.java

public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Processing getListUsers request for tenantId  - [" + this.tenantId + "]");
    }/*from  ww  w.j ava2  s .c  om*/
    GetMethod getMethod = new GetMethod(EndpointUtil.getUserListEndpoint(getHostName()));
    List<String> userList = new ArrayList<>();
    try {

        if (this.httpClient == null) {
            this.httpClient = new HttpClient();
        }

        getMethod.setQueryString(getQueryString("limit", new String[] { String.valueOf(maxItemLimit) }));
        setAuthorizationHeader(getMethod);
        int response = httpClient.executeMethod(getMethod);
        if (response == HttpStatus.SC_OK) {
            String respStr = new String(getMethod.getResponseBody());
            JSONObject resultObj = new JSONObject(respStr);
            JSONArray users = resultObj.getJSONArray("usernames");
            for (int i = 0; i < users.length(); i++) {
                String user = (String) users.get(i);
                if (!"wso2.anonymous.user".equals(user)) {
                    String domain = this.realmConfig.getUserStoreProperty("DomainName");
                    user = UserCoreUtil.addDomainToName(user, domain);
                }
                userList.add(user);
            }
        }

    } catch (IOException | JSONException | WSUserStoreException e) {
        log.error("Error occurred while calling backed to authenticate request for tenantId - [" + this.tenantId
                + "]", e);
    }
    return userList.toArray(new String[userList.size()]);
}