Search in sources :

Example 16 with PolicyException

use of com.sun.identity.policy.PolicyException in project OpenAM by OpenRock.

the class ResourceResultCache method postForm.

String postForm(SSOToken appToken, String url, String formContent) throws PolicyException {
    if (debug.messageEnabled()) {
        debug.message("ResourceResultCache." + "postForm():" + "url=" + url + ", formContent=" + formContent);
    }
    StringBuilder sb = new StringBuilder();
    HttpURLConnection conn = null;
    OutputStream out = null;
    BufferedReader reader = null;
    try {
        conn = HttpURLConnectionManager.getConnection(new URL(url));
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        setCookieAndHeader(conn, appToken, appToken);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(formContent.length()));
        conn.connect();
        out = conn.getOutputStream();
        out.write(formContent.getBytes("UTF-8"));
        out.write("\r\n".getBytes("UTF-8"));
        out.flush();
        out.close();
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            sb.append(buf, 0, len);
        }
        int responseCode = conn.getResponseCode();
        // any 200 series response code is success
        if (responseCode < 200 || responseCode > 299) {
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache." + "postForm():" + "REST call failed with HTTP response code:" + responseCode);
            }
            throw new PolicyException("Entitlement REST call failed with error code:" + responseCode);
        }
    } catch (UnsupportedEncodingException uee) {
        // should not happen
        debug.error("ResourceResultCache.postFormParams():" + "UnsupportedEncodingException:" + uee.getMessage());
    } catch (IOException ie) {
        debug.error("ResourceResultCache.postForm():IOException:" + ie.getMessage(), ie);
        throw new PolicyException(ResBundleUtils.rbName, "rest_call_failed_with_io_exception", null, ie);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
        // ignore
        }
    }
    return sb.toString();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) PolicyException(com.sun.identity.policy.PolicyException) OutputStream(java.io.OutputStream) BufferedReader(java.io.BufferedReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) JSONException(org.json.JSONException) PolicyException(com.sun.identity.policy.PolicyException) SendRequestException(com.iplanet.services.comm.client.SendRequestException) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) URLNotFoundException(com.iplanet.services.naming.URLNotFoundException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlreadyRegisteredException(com.iplanet.services.comm.client.AlreadyRegisteredException) IOException(java.io.IOException) SessionException(com.iplanet.dpro.session.SessionException)

Example 17 with PolicyException

use of com.sun.identity.policy.PolicyException in project OpenAM by OpenRock.

the class ResourceResultCache method getResourceContent.

String getResourceContent(SSOToken appToken, SSOToken userToken, String url) throws PolicyException {
    StringBuilder sb = new StringBuilder();
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    try {
        conn = HttpURLConnectionManager.getConnection(new URL(url));
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setInstanceFollowRedirects(false);
        setCookieAndHeader(conn, appToken, userToken);
        conn.connect();
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            sb.append(buf, 0, len);
        }
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            // got a 302
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache.getResourceContent():" + "got 302 redirect");
                debug.warning("ResourceResultCache.getResourceContent():" + "throwing InvalidAppSSOTokenException");
            }
            String[] args = { conn.getResponseMessage() };
            throw new InvalidAppSSOTokenException(ResBundleUtils.rbName, "rest_call_to_server_caused_302", args, null);
        } else if (responseCode != HttpURLConnection.HTTP_OK) {
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache.getResourceContent():" + "REST call failed with HTTP response code:" + responseCode);
            }
            throw new PolicyException("Entitlement REST call failed with error code:" + responseCode);
        }
    } catch (UnsupportedEncodingException uee) {
        // should not happen
        debug.error("ResourceResultCache.getResourceContent():" + "UnsupportedEncodingException:" + uee.getMessage());
    } catch (IOException ie) {
        debug.error("IOException:" + ie);
        throw new PolicyException(ResBundleUtils.rbName, "rest_call_failed_with_io_exception", null, ie);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
        // ignore
        }
    }
    return sb.toString();
}
Also used : InputStreamReader(java.io.InputStreamReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) JSONException(org.json.JSONException) PolicyException(com.sun.identity.policy.PolicyException) SendRequestException(com.iplanet.services.comm.client.SendRequestException) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) URLNotFoundException(com.iplanet.services.naming.URLNotFoundException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlreadyRegisteredException(com.iplanet.services.comm.client.AlreadyRegisteredException) IOException(java.io.IOException) SessionException(com.iplanet.dpro.session.SessionException) HttpURLConnection(java.net.HttpURLConnection) PolicyException(com.sun.identity.policy.PolicyException) BufferedReader(java.io.BufferedReader)

Example 18 with PolicyException

use of com.sun.identity.policy.PolicyException in project OpenAM by OpenRock.

the class ResourceResultCache method getRESTResultsFromServer.

private Set getRESTResultsFromServer(SSOToken appToken, String serviceName, SSOToken token, String resourceName, String scope, Set actionNames, Map env) throws InvalidAppSSOTokenException, SSOException, PolicyException {
    Set<ResourceResult> resourceResults = null;
    try {
        AMIdentity userIdentity = IdUtils.getIdentity(token);
        String restUrl = getRESTPolicyServiceURL(token, scope);
        String queryString = buildEntitlementRequestQueryString("/", serviceName, token, resourceName, actionNames, env);
        restUrl = restUrl + "?" + queryString;
        if (debug.messageEnabled()) {
            debug.message("ResourceResultCache.getRESTResultsFromServer():" + ":serviceName=" + serviceName + ":token=" + token.getPrincipal().getName() + ":resourceName=" + resourceName + ":scope=" + scope + ":actionNames=" + actionNames + ":env" + ":restUrl=" + restUrl + ":entering");
        }
        String jsonString = getResourceContent(appToken, token, restUrl);
        if (debug.messageEnabled()) {
            debug.message("ResourceResultCache.getRESTResultsFromServer():" + ":server response jsonString=" + jsonString);
        }
        resourceResults = jsonResourceContentToResourceResults(jsonString, serviceName);
    } catch (InvalidAppSSOTokenException e) {
        throw e;
    } catch (Exception e) {
        String[] args = { e.getMessage() };
        throw new PolicyEvaluationException(ResBundleUtils.rbName, "rest_policy_request_exception", args, e);
    }
    if (debug.messageEnabled()) {
        debug.message("ResourceResultCache.getRESTResultsFromServer():" + "returning");
    }
    return resourceResults;
}
Also used : ResourceResult(com.sun.identity.policy.ResourceResult) AMIdentity(com.sun.identity.idm.AMIdentity) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) JSONException(org.json.JSONException) PolicyException(com.sun.identity.policy.PolicyException) SendRequestException(com.iplanet.services.comm.client.SendRequestException) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) URLNotFoundException(com.iplanet.services.naming.URLNotFoundException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlreadyRegisteredException(com.iplanet.services.comm.client.AlreadyRegisteredException) IOException(java.io.IOException) SessionException(com.iplanet.dpro.session.SessionException)

Example 19 with PolicyException

use of com.sun.identity.policy.PolicyException in project OpenAM by OpenRock.

the class ResourceResultCache method buildEntitlementRequestQueryString.

static String buildEntitlementRequestQueryString(String realm, String serviceName, SSOToken userToken, String resource, Set actionNames, Map envMap) throws PolicyException {
    StringBuilder sb = new StringBuilder();
    try {
        realm = (realm == null || (realm.trim().length() == 0)) ? "/" : realm;
        realm = URLEncoder.encode(realm, "UTF-8");
        sb.append(REST_QUERY_REALM).append("=");
        sb.append(realm);
        if ((serviceName == null) || (serviceName.length() == 0)) {
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache." + "buildEntitlementRequestQueryString():" + "serviceName can not be null");
            }
            throw new PolicyException(ResBundleUtils.rbName, "service_name_can_not_be_null", null, null);
        } else {
            sb.append("&").append(REST_QUERY_APPLICATION).append("=");
            sb.append(URLEncoder.encode(serviceName, "UTF-8"));
        }
        if (userToken == null) {
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache." + "buildEntitlementRequestQueryString():" + "subject can not be null");
            }
            throw new PolicyException(ResBundleUtils.rbName, "subject_can_not_be_null", null, null);
        } else {
            String userTokenId = userToken.getTokenID().toString();
            String hashedUserTokenId = Hash.hash(userTokenId);
            sb.append("&").append(REST_QUERY_SUBJECT).append("=");
            sb.append(URLEncoder.encode(hashedUserTokenId, "UTF-8"));
        }
        if ((resource == null) || (resource.trim().length() == 0)) {
            if (debug.warningEnabled()) {
                debug.warning("ResourceResultCache." + "buildEntitlementRequestQueryString():" + "resource can not be null");
            }
            throw new PolicyException(ResBundleUtils.rbName, "resource_can_not_be_null", null, null);
        } else {
            sb.append("&").append(REST_QUERY_RESOURCE).append("=");
            sb.append(URLEncoder.encode(resource, "UTF-8"));
        }
        if ((actionNames != null) && !actionNames.isEmpty()) {
            for (Object actObj : actionNames) {
                sb.append("&").append(REST_QUERY_ACTION).append("=");
                sb.append(URLEncoder.encode(actObj.toString(), "UTF-8"));
            }
        }
        if ((envMap != null) && !envMap.isEmpty()) {
            String encodedEq = URLEncoder.encode("=", "UTF-8");
            Set keys = envMap.keySet();
            for (Object keyOb : keys) {
                Set values = (Set) envMap.get(keyOb);
                String key = URLEncoder.encode(keyOb.toString(), "UTF-8");
                if ((values != null) && !values.isEmpty()) {
                    for (Object valueOb : values) {
                        sb.append("&").append(REST_QUERY_ENV).append("=");
                        sb.append(key);
                        sb.append(encodedEq);
                        sb.append(URLEncoder.encode(valueOb.toString(), "UTF-8"));
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException use) {
        // should not happen
        debug.error("ResourceResultCache.buildEntitlementRequestQueryString():" + use.getMessage());
    }
    return sb.toString();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) RequestSet(com.iplanet.services.comm.share.RequestSet) PolicyException(com.sun.identity.policy.PolicyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(org.json.JSONObject)

Example 20 with PolicyException

use of com.sun.identity.policy.PolicyException in project OpenAM by OpenRock.

the class SampleCondition method setProperties.

/** Sets the properties of the condition.
     *  Evaluation of ConditionDecision is influenced by these properties.
     *  @param properties the properties of the condition that governs
     *         whether a policy applies. The properties should
     *         define value for the key USER_NAME_LENGTH. The value should
     *         be a Set with only one element. The element should be
     *         a String, parsable as an integer. Please note that
     *         properties is not cloned by the method.
     *
     *  @throws PolicyException if properties is null or does not contain
     *          value for the key USER_NAME_LENGTH or the value of the key is
     *          not a Set with one String element that is parsable as
     *          an integer.
     */
public void setProperties(Map properties) throws PolicyException {
    this.properties = (Map) ((HashMap) properties);
    if ((properties == null) || (properties.keySet() == null)) {
        throw new PolicyException("properties can not be null or empty");
    }
    //Check if the key is valid
    Set keySet = properties.keySet();
    Iterator keys = keySet.iterator();
    String key = (String) keys.next();
    if (!USER_NAME_LENGTH.equals(key)) {
        throw new PolicyException("property " + USER_NAME_LENGTH + " is not defined");
    }
    // check if the value is valid
    Set nameLengthSet = (Set) properties.get(USER_NAME_LENGTH);
    if ((nameLengthSet == null) || nameLengthSet.isEmpty() || (nameLengthSet.size() > 1)) {
        throw new PolicyException("property value is not defined or invalid");
    }
    Iterator nameLengths = nameLengthSet.iterator();
    String nameLengthString = null;
    nameLengthString = (String) nameLengths.next();
    try {
        nameLength = Integer.parseInt(nameLengthString);
    } catch (Exception e) {
        throw new PolicyException("name length value is not an integer");
    }
}
Also used : PolicyException(com.sun.identity.policy.PolicyException) SSOException(com.iplanet.sso.SSOException) PolicyException(com.sun.identity.policy.PolicyException)

Aggregations

PolicyException (com.sun.identity.policy.PolicyException)151 SSOException (com.iplanet.sso.SSOException)64 HashSet (java.util.HashSet)63 Set (java.util.Set)57 Iterator (java.util.Iterator)50 PolicyManager (com.sun.identity.policy.PolicyManager)35 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)32 HashMap (java.util.HashMap)28 Map (java.util.Map)27 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)26 ByteString (org.forgerock.opendj.ldap.ByteString)16 EntitlementException (com.sun.identity.entitlement.EntitlementException)14 LdapException (org.forgerock.opendj.ldap.LdapException)13 ResultCode (org.forgerock.opendj.ldap.ResultCode)13 Connection (org.forgerock.opendj.ldap.Connection)12 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)12 InvalidNameException (com.sun.identity.policy.InvalidNameException)11 ValidValues (com.sun.identity.policy.ValidValues)11 IOException (java.io.IOException)11 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)11