You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@directory.apache.org by sm...@apache.org on 2014/10/22 17:44:24 UTC
[05/51] [partial] Rename packages from org.openldap.fortress to
org.apache.directory.fortress.core. Change default suffix to org.apache.
Switch default ldap api from unbound to apache ldap.
http://git-wip-us.apache.org/repos/asf/directory-fortress-core/blob/687ee1ad/src/main/java/org/apache/directory/fortress/core/rest/FortResponse.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/directory/fortress/core/rest/FortResponse.java b/src/main/java/org/apache/directory/fortress/core/rest/FortResponse.java
new file mode 100755
index 0000000..2acc385
--- /dev/null
+++ b/src/main/java/org/apache/directory/fortress/core/rest/FortResponse.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.directory.fortress.core.rest;
+
+import org.apache.directory.fortress.core.rbac.FortEntity;
+import org.apache.directory.fortress.core.rbac.Session;
+
+import javax.xml.bind.annotation.*;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class is used to return response data from En Masse server.
+ * </p>
+ * This class is not thread safe.
+ *
+ * @author Shawn McKinney
+ */
+@XmlRootElement(name = "FortResponse")
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "fortResponse", propOrder =
+{
+ "errorCode",
+ "errorMessage",
+ "entity",
+ "entities",
+ "values",
+ "valueSet",
+ "isAuthorized",
+ "session"
+})
+public class FortResponse
+{
+ private int errorCode;
+ @XmlElement(nillable = true)
+ private Boolean isAuthorized;
+ private String errorMessage;
+ @XmlElement(nillable = true)
+ private FortEntity entity;
+ @XmlElement(nillable = true)
+ private List<FortEntity> entities;
+ @XmlElement(nillable = true)
+ private List<String> values;
+ @XmlElement(nillable = true)
+ private Set<String> valueSet;
+ @XmlElement(nillable = true)
+ private Session session;
+
+ public FortEntity getEntity()
+ {
+ return entity;
+ }
+
+ public void setEntity(FortEntity entity)
+ {
+ this.entity = entity;
+ }
+
+ public String getErrorMessage()
+ {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage)
+ {
+ this.errorMessage = errorMessage;
+ }
+
+ public int getErrorCode()
+ {
+ return errorCode;
+ }
+
+ public Boolean getAuthorized()
+ {
+ return isAuthorized;
+ }
+
+ public void setAuthorized(Boolean authorized)
+ {
+ isAuthorized = authorized;
+ }
+
+ public void setErrorCode(int errorCode)
+ {
+ this.errorCode = errorCode;
+ }
+
+ public <T extends FortEntity> List<T> getEntities()
+ {
+ return (List<T>)entities;
+ }
+
+ public <T extends FortEntity> void setEntities(List<T> entities)
+ {
+ this.entities = (List<FortEntity>)entities;
+ }
+
+ public List<String> getValues()
+ {
+ return values;
+ }
+
+ public void setValues(List<String> values)
+ {
+ this.values = values;
+ }
+
+ public Set<String> getValueSet()
+ {
+ return valueSet;
+ }
+
+ public void setValueSet(Set<String> valueSet)
+ {
+ this.valueSet = valueSet;
+ }
+
+ public Session getSession()
+ {
+ return session;
+ }
+
+ public void setSession(Session session)
+ {
+ this.session = session;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/directory-fortress-core/blob/687ee1ad/src/main/java/org/apache/directory/fortress/core/rest/HttpIds.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/directory/fortress/core/rest/HttpIds.java b/src/main/java/org/apache/directory/fortress/core/rest/HttpIds.java
new file mode 100644
index 0000000..97a4c99
--- /dev/null
+++ b/src/main/java/org/apache/directory/fortress/core/rest/HttpIds.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.directory.fortress.core.rest;
+
+/**
+ * Contains global HttpIds that map to the Fortress REST server EnMasse.
+ *
+ * @author Shawn McKinney
+ */
+public class HttpIds
+{
+ public static final String RBAC_AUTHN = "rbacAuthN";
+ public static final String RBAC_CREATE = "rbacCreate";
+ public static final String RBAC_CREATE_TRUSTED = "rbacCreateT";
+ public static final String RBAC_AUTHZ = "rbacAuthZ";
+ public static final String RBAC_PERMS = "rbacPerms";
+ public static final String RBAC_ROLES = "rbacRoles";
+ public static final String RBAC_AUTHZ_ROLES = "rbacAuthzRoles";
+ public static final String RBAC_ADD = "rbacAdd";
+ public static final String RBAC_DROP = "rbacDrop";
+ public static final String RBAC_USERID = "rbacUserId";
+ public static final String RBAC_USER = "rbacUser";
+ public static final String USER_READ = "userRead";
+ public static final String USER_UPDATE = "userUpdate";
+ public static final String USER_CHGPW = "userChange";
+ public static final String USER_LOCK = "userLock";
+ public static final String USER_UNLOCK = "userUnlock";
+ public static final String USER_RESET = "userReset";
+ public static final String USER_ADD = "userAdd";
+ public static final String USER_DELETE = "userDelete";
+ public static final String USER_DISABLE = "userDisable";
+ public static final String USER_SEARCH = "userSearch";
+ public static final String USER_PERMS = "userPerms";
+ public static final String USER_GRANT = "userGrant";
+ public static final String USER_REVOKE = "userRevoke";
+ public static final String USER_ASGNED = "userAsigned";
+ public static final String USER_AUTHZED = "userAuthzed";
+ public static final String USER_ASGNED_ADMIN = "userAsignedAdmin";
+ public static final String ROLE_READ = "roleRead";
+ public static final String ROLE_UPDATE = "roleUpdate";
+ public static final String ROLE_ADD = "roleAdd";
+ public static final String ROLE_DELETE = "roleDelete";
+ public static final String ROLE_SEARCH = "roleSearch";
+ public static final String ROLE_ASGN = "roleAsgn";
+ public static final String ROLE_DEASGN = "roleDeasgn";
+ public static final String ROLE_GRANT = "roleGrant";
+ public static final String ROLE_REVOKE = "roleRevoke";
+ public static final String ROLE_PERMS = "rolePerms";
+ public static final String ROLE_DESC = "roleDescendant";
+ public static final String ROLE_ASC = "roleAscendent";
+ public static final String ROLE_ADDINHERIT = "roleAddinherit";
+ public static final String ROLE_DELINHERIT = "roleDelinherit";
+ public static final String ROLE_ASGNED = "roleAsigned";
+ public static final String ROLE_AUTHZED = "roleAuthzed";
+ public static final String OBJ_READ = "objRead";
+ public static final String OBJ_UPDATE = "objUpdate";
+ public static final String OBJ_ADD = "objAdd";
+ public static final String OBJ_DELETE = "objDelete";
+ public static final String OBJ_SEARCH = "objSearch";
+ public static final String PERM_READ = "permRead";
+ public static final String PERM_UPDATE = "permUpdate";
+ public static final String PERM_ADD = "permAdd";
+ public static final String PERM_DELETE = "permDelete";
+ public static final String PERM_SEARCH = "permSearch";
+ public static final String PERM_ROLES = "permRoles";
+ public static final String PERM_USERS = "permUsers";
+ public static final String PERM_ROLES_AUTHZED = "permRolesAuthzed";
+ public static final String PERM_USERS_AUTHZED = "permUsersAuthzed";
+ public static final String ORG_READ = "orgRead";
+ public static final String ORG_UPDATE = "orgUpdate";
+ public static final String ORG_ADD = "orgAdd";
+ public static final String ORG_DELETE = "orgDelete";
+ public static final String ORG_DESC = "orgDescendant";
+ public static final String ORG_ASC = "orgAscendent";
+ public static final String ORG_ADDINHERIT = "orgAddinherit";
+ public static final String ORG_DELINHERIT = "orgDelinherit";
+ public static final String ORG_SEARCH = "orgSearch";
+ public static final String SSD_ROLE_SETS = "ssdRoleSets";
+ public static final String SSD_SETS = "ssdSets";
+ public static final String SSD_READ = "ssdRead";
+ public static final String SSD_ROLES = "ssdRoles";
+ public static final String SSD_CARD = "ssdCard";
+ public static final String SSD_ADD = "ssdAdd";
+ public static final String SSD_UPDATE = "ssdUpdate";
+ public static final String SSD_DELETE = "ssdDelete";
+ public static final String SSD_ADD_MEMBER = "ssdAddMember";
+ public static final String SSD_DEL_MEMBER = "ssdDelMember";
+ public static final String SSD_CARD_UPDATE = "ssdCardUpdate";
+ public static final String DSD_ROLE_SETS = "dsdRoleSets";
+ public static final String DSD_SETS = "dsdSets";
+ public static final String DSD_READ = "dsdRead";
+ public static final String DSD_ROLES = "dsdRoles";
+ public static final String DSD_CARD = "dsdCard";
+ public static final String DSD_ADD = "dsdAdd";
+ public static final String DSD_UPDATE = "dsdUpdate";
+ public static final String DSD_DELETE = "dsdDelete";
+ public static final String DSD_ADD_MEMBER = "dsdAddMember";
+ public static final String DSD_DEL_MEMBER = "dsdDelMember";
+ public static final String DSD_CARD_UPDATE = "dsdCardUpdate";
+ public static final String ADMIN_AUTHZ = "adminAuthZ";
+ public static final String ADMIN_ROLES = "adminRoles";
+ public static final String ADMIN_PERMS = "adminPerms";
+ public static final String ADMIN_AUTHZ_ROLES = "adminAuthzRoles";
+ public static final String ADMIN_ADD = "adminAdd";
+ public static final String ADMIN_DROP = "adminDrop";
+ public static final String ADMIN_ASSIGN = "adminAssign";
+ public static final String ADMIN_DEASSIGN = "adminDeassign";
+ public static final String ADMIN_GRANT = "adminGrant";
+ public static final String ADMIN_REVOKE = "adminRevoke";
+ public static final String ARLE_READ = "arleRead";
+ public static final String ARLE_UPDATE = "arleUpdate";
+ public static final String ARLE_ADD = "arleAdd";
+ public static final String ARLE_DELETE = "arleDelete";
+ public static final String ARLE_SEARCH = "arleSearch";
+ public static final String ARLE_DESC = "arleDescendant";
+ public static final String ARLE_ASC = "arleAscendent";
+ public static final String ARLE_ADDINHERIT = "arleAddinherit";
+ public static final String ARLE_DELINHERIT = "arleDelinherit";
+ public static final String ARLE_ASGN = "arleAsgn";
+ public static final String ARLE_DEASGN = "arleDeasgn";
+ public static final String ARLE_ASGNED = "arleAsigned";
+ public static final String PSWD_READ = "pswdRead";
+ public static final String PSWD_UPDATE = "pswdUpdate";
+ public static final String PSWD_ADD = "pswdAdd";
+ public static final String PSWD_DELETE = "pswdDelete";
+ public static final String PSWD_SEARCH = "pswdSearch";
+ public static final String PSWD_USER_ADD = "pswdUserAdd";
+ public static final String PSWD_USER_DELETE = "pswdUserDelete";
+ public static final String AUDIT_BINDS = "auditBinds";
+ public static final String AUDIT_AUTHZS = "auditAuthzs";
+ public static final String AUDIT_UAUTHZS = "auditUserAuthzs";
+ public static final String AUDIT_SESSIONS = "auditSessions";
+ public static final String AUDIT_MODS = "auditMods";
+ public static final String AUDIT_INVLD = "auditInvld";
+ public static final String CFG_ADD = "cfgAdd";
+ public static final String CFG_UPDATE = "cfgUpdate";
+ public static final String CFG_DELETE = "cfgDelete";
+ public static final String CFG_READ = "cfgRead";
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/directory-fortress-core/blob/687ee1ad/src/main/java/org/apache/directory/fortress/core/rest/JAXBCachedEntry.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/directory/fortress/core/rest/JAXBCachedEntry.java b/src/main/java/org/apache/directory/fortress/core/rest/JAXBCachedEntry.java
new file mode 100644
index 0000000..faccd06
--- /dev/null
+++ b/src/main/java/org/apache/directory/fortress/core/rest/JAXBCachedEntry.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.directory.fortress.core.rest;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+
+/**
+ * This class wraps JAXBContext and is used for simple caching mechanism during Fortress XML processing.
+ * The intent is to leave future extension point in case schema validation is needed which prevents handling in cache itself.
+ *
+ * @author Shawn McKinney
+ */
+@SuppressWarnings( "rawtypes" )
+public class JAXBCachedEntry
+{
+ private final Class cachedClass;
+ private final JAXBContext context;
+
+ /**
+ * Public constructor requires the entity class to be passed.
+ *
+ * @param type contains reference to object of type class.
+ * @throws JAXBException thrown in the event new instance cannot be created.
+ */
+ public JAXBCachedEntry( Class type ) throws JAXBException
+ {
+ context = JAXBContext.newInstance( type );
+ cachedClass = type;
+ }
+
+ /**
+ * Return the class that is associated with this cached JAXBContext.
+ *
+ * @return class associated with JAXContext
+ */
+ public Class getCachedClass()
+ {
+ return cachedClass;
+ }
+
+ /**
+ * Return the JAXBContext object associated with this wrapper class.
+ *
+ * @return handle to JAXBContext object.
+ */
+ public JAXBContext getContext()
+ {
+ return context;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/directory-fortress-core/blob/687ee1ad/src/main/java/org/apache/directory/fortress/core/rest/PwPolicyMgrRestImpl.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/directory/fortress/core/rest/PwPolicyMgrRestImpl.java b/src/main/java/org/apache/directory/fortress/core/rest/PwPolicyMgrRestImpl.java
new file mode 100644
index 0000000..8a1cfb9
--- /dev/null
+++ b/src/main/java/org/apache/directory/fortress/core/rest/PwPolicyMgrRestImpl.java
@@ -0,0 +1,453 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.directory.fortress.core.rest;
+
+import org.apache.directory.fortress.core.GlobalErrIds;
+import org.apache.directory.fortress.core.PwPolicyMgr;
+import org.apache.directory.fortress.core.SecurityException;
+import org.apache.directory.fortress.core.rbac.Manageable;
+import org.apache.directory.fortress.core.rbac.PwPolicy;
+import org.apache.directory.fortress.core.util.attr.VUtil;
+import org.apache.directory.fortress.core.rbac.User;
+
+import java.util.List;
+
+/**
+ * This class is used to perform administrative and review functions on the PWPOLICIES and USERS data sets using HTTP access to En Masse REST server.
+ * <p/>
+ * <h4>Password Policies</h4>
+ * <a href="http://www.openldap.org/">OpenLDAP</a> supports the IETF draft <a href="http://tools.ietf.org/html/draft-behera-ldap-password-policy-10/">Password Policies for LDAP directories</a></li>. Policies may be applied at the user, group or global level.
+ * <p/>
+ * <img src="../doc-files/PasswordPolicy.png">
+ * <p/>
+ * Password enforcement options include:
+ * <ol>
+ * <li>A configurable limit on failed authentication attempts.</li>
+ * <li>A counter to track the number of failed authentication attempts.</li>
+ * <li>A time frame in which the limit of consecutive failed authentication attempts must happen before action is taken.</li>
+ * <li>The action to be taken when the limit is reached. The action will either be nothing, or the account will be locked.</li>
+ * <li>An amount of time the account is locked (if it is to be locked) This can be indefinite.</li>
+ * <li>Password expiration.</li>
+ * <li>Expiration warning</li>
+ * <li>Grace authentications</li>
+ * <li>Password history</li>
+ * <li>Password minimum age</li>
+ * <li>Password minimum length</li>
+ * <li>Password Change after Reset</li>
+ * <li>Safe Modification of Password</li>
+ * </ol>
+ * <p/>
+ * This class is NOT thread safe.
+ * <p/>
+ *
+ * @author Shawn McKinney
+ */
+public class PwPolicyMgrRestImpl extends Manageable implements PwPolicyMgr
+{
+ private static final String CLS_NM = PwPolicyMgrRestImpl.class.getName();
+
+ /**
+ * This method will add a new policy entry to the POLICIES data set. This command is valid
+ * if and only if the policy entry is not already present in the POLICIES data set.
+ * <h4>required parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#name} - Maps to name attribute of pwdPolicy object class being added.</li>
+ * </ul>
+ * <h4>optional parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#minAge} - This attribute holds the number of seconds that must elapse between
+ * modifications to the password. If this attribute is not present, 0
+ * seconds is assumed.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#maxAge} - This attribute holds the number of seconds after which a modified
+ * password will expire. If this attribute is not present, or if the value is 0 the password
+ * does not expire. If not 0, the value must be greater than or equal
+ * to the value of the pwdMinAge.
+ * </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#inHistory} - This attribute specifies the maximum number of used passwords stored
+ * in the pwdHistory attribute. If this attribute is not present, or if the value is 0, used
+ * passwords are not stored in the pwdHistory attribute and thus may be reused.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#minLength} - When quality checking is enabled, this attribute holds the minimum
+ * number of characters that must be used in a password. If this
+ * attribute is not present, no minimum password length will be
+ * enforced. If the server is unable to check the length (due to a
+ * hashed password or otherwise), the server will, depending on the
+ * value of the pwdCheckQuality attribute, either accept the password
+ * without checking it ('0' or '1') or refuse it ('2').</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#expireWarning} - This attribute specifies the maximum number of seconds before a
+ * password is due to expire that expiration warning messages will be
+ * returned to an authenticating user. If this attribute is not present, or if the value is 0 no warnings
+ * will be returned. If not 0, the value must be smaller than the value
+ * of the pwdMaxAge attribute.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#graceLoginLimit} - This attribute specifies the number of times an expired password can
+ * be used to authenticate. If this attribute is not present or if the
+ * value is 0, authentication will fail. </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#lockout} - This attribute indicates, when its value is "TRUE", that the password
+ * may not be used to authenticate after a specified number of
+ * consecutive failed bind attempts. The maximum number of consecutive
+ * failed bind attempts is specified in pwdMaxFailure. If this attribute is not present, or if the
+ * value is "FALSE", the password may be used to authenticate when the number of failed bind
+ * attempts has been reached.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#lockoutDuration} - This attribute holds the number of seconds that the password cannot
+ * be used to authenticate due to too many failed bind attempts. If
+ * this attribute is not present, or if the value is 0 the password
+ * cannot be used to authenticate until reset by a password
+ * administrator.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#maxFailure} - This attribute specifies the number of consecutive failed bind
+ * attempts after which the password may not be used to authenticate.
+ * If this attribute is not present, or if the value is 0, this policy
+ * is not checked, and the value of pwdLockout will be ignored.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#failureCountInterval} - This attribute holds the number of seconds after which the password
+ * failures are purged from the failure counter, even though no
+ * successful authentication occurred. If this attribute is not present, or if its value is 0, the failure
+ * counter is only reset by a successful authentication.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#mustChange} - This attribute specifies with a value of "TRUE" that users must
+ * change their passwords when they first bind to the directory after a
+ * password is set or reset by a password administrator. If this
+ * attribute is not presen request.setContextId(this.contextId);t, or if the value is "FALSE", users are not
+ * required to change their password upon binding after the password
+ * administrator sets or resets the password. This attribute is not set
+ * due to any actions specified by this document, it is typically set by
+ * a password administrator after resetting a user's password.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#allowUserChange} - This attribute indicates whether users can change their own
+ * passwords, although the change operation is still subject to access
+ * control. If this attribute is not present, a value of "TRUE" is
+ * assumed. This attribute is intended to be used in the absence of an access control mechanism.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#safeModify} - This attribute specifies whether or not the existing password must be
+ * sent along with the new password when being changed. If this
+ * attribute is not present, a "FALSE" value is assumed.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#checkQuality} - This attribute indicates how the password quality will be verified
+ * while being modified or added. If this attribute is not present, or
+ * if the value is '0', quality checking will not be enforced. A value
+ * of '1' indicates that the server will check the quality, and if the
+ * server is unable to check it (due to a hashed password or other
+ * reasons) it will be accepted. A value of '2' indicates that the
+ * server will check the quality, and if the server is unable to verify
+ * it, it will return an error refusing the password. </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#attribute} - This holds the name of the attribute to which the password policy is
+ * applied. For example, the password policy may be applied to the
+ * userPassword attribute </li>
+ * </ul>
+ *
+ * @param policy Object must contain {@link org.apache.directory.fortress.core.rbac.PwPolicy#name} and optionally other attributes.
+ * @throws SecurityException In the event of data validation or system error.
+ */
+ @Override
+ public void add(PwPolicy policy)
+ throws SecurityException
+ {
+ VUtil.assertNotNull(policy, GlobalErrIds.PSWD_PLCY_NULL, CLS_NM + ".add");
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(policy);
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_ADD);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() != 0)
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ }
+
+
+ /**
+ * This method will update an exiting policy entry to the POLICIES data set. This command is valid
+ * if and only if the policy entry is already present in the POLICIES data set.
+ * <h4>required parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#name} - Maps to name attribute of pwdPolicy object class being updated.</li>
+ * </ul>
+ * <h4>optional parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#minAge} - This attribute holds the number of seconds that must elapse between
+ * modifications to the password. If this attribute is not present, 0
+ * seconds is assumed.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#maxAge} - This attribute holds the number of seconds after which a modified
+ * password will expire. If this attribute is not present, or if the value is 0 the password
+ * does not expire. If not 0, the value must be greater than or equal
+ * to the value of the pwdMinAge.
+ * </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#inHistory} - This attribute specifies the maximum number of used passwords stored
+ * in the pwdHistory attribute. If this attribute is not present, or if the value is 0, used
+ * passwords are not stored in the pwdHistory attribute and thus may be reused.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#minLength} - When quality checking is enabled, this attribute holds the minimum
+ * number of characters that must be used in a password. If this
+ * attribute is not present, no minimum password length will be
+ * enforced. If the server is unable to check the length (due to a
+ * hashed password or otherwise), the server will, depending on the
+ * value of the pwdCheckQuality attribute, either accept the password
+ * without checking it ('0' or '1') or refuse it ('2').</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#expireWarning} - This attribute specifies the maximum number of seconds before a
+ * password is due to expire that expiration warning messages will be
+ * returned to an authenticating user. If this attribute is not present, or if the value is 0 no warnings
+ * will be returned. If not 0, the value must be smaller than the value
+ * of the pwdMaxAge attribute.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#graceLoginLimit} - This attribute specifies the number of times an expired password can
+ * be used to authenticate. If this attribute is not present or if the
+ * value is 0, authentication will fail. </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#lockout} - This attribute indicates, when its value is "TRUE", that the password
+ * may not be used to authenticate after a specified number of
+ * consecutive failed bind attempts. The maximum number of consecutive
+ * failed bind attempts is specified in pwdMaxFailure. If this attribute is not present, or if the
+ * value is "FALSE", the password may be used to authenticate when the number of failed bind
+ * attempts has been reached.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#lockoutDuration} - This attribute holds the number of seconds that the password cannot
+ * be used to authenticate due to too many failed bind attempts. If
+ * this attribute is not present, or if the value is 0 the password
+ * cannot be used to authenticate until reset by a password
+ * administrator.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#maxFailure} - This attribute specifies the number of consecutive failed bind
+ * attempts after which the password may not be used to authenticate.
+ * If this attribute is not present, or if the value is 0, this policy
+ * is not checked, and the value of pwdLockout will be ignored.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#failureCountInterval} - This attribute holds the number of seconds after which the password
+ * failures are purged from the failure counter, even though no
+ * successful authentication occurred. If this attribute is not present, or if its value is 0, the failure
+ * counter is only reset by a successful authentication.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#mustChange} - This attribute specifies with a value of "TRUE" that users must
+ * change their passwords when they first bind to the directory after a
+ * password is set or reset by a password administrator. If this
+ * attribute is not present, or if the value is "FALSE", users are not
+ * required to change their password upon binding after the password
+ * administrator sets or resets the password. This attribute is not set
+ * due to any actions specified by this document, it is typically set by
+ * a password administrator after resetting a user's password.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#allowUserChange} - This attribute indicates whether users can change their own
+ * passwords, although the change operation is still subject to access
+ * control. If this attribute is not present, a value of "TRUE" is
+ * assumed. This attribute is intended to be used in the absence of an access control mechanism.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#safeModify} - This attribute specifies whether or not the existing password must be
+ * sent along with the new password when being changed. If this
+ * attribute is not present, a "FALSE" value is assumed.</li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#checkQuality} - This attribute indicates how the password quality will be verified
+ * while being modified or added. If this attribute is not present, or
+ * if the value is '0', quality checking will not be enforced. A value
+ * of '1' indicates that the server will check the quality, and if the
+ * server is unable to check it (due to a hashed password or other
+ * reasons) it will be accepted. A value of '2' indicates that the
+ * server will check the quality, and if the server is unable to verify
+ * it, it will return an error refusing the password. </li>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#attribute} - This holds the name of the attribute to which the password policy is
+ * applied. For example, the password policy may be applied to the
+ * userPassword attribute </li>
+ * </ul>
+ *
+ * @param policy Object must contain {@link org.apache.directory.fortress.core.rbac.PwPolicy#name} and optionally all non-null attributes will be updated. null attributes will be ignored.
+ * @throws SecurityException In the event policy not found , data validation or system error.
+ */
+ @Override
+ public void update(PwPolicy policy)
+ throws SecurityException
+ {
+ VUtil.assertNotNull(policy, GlobalErrIds.PSWD_PLCY_NULL, CLS_NM + ".update");
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(policy);
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_UPDATE);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() != 0)
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ }
+
+
+ /**
+ * This method will delete exiting policy entry from the POLICIES data set. This command is valid
+ * if and only if the policy entry is already present in the POLICIES data set. Existing users that
+ * are assigned this policy will be removed from association.
+ * <h4>required parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#name} - Maps to name attribute of pwdPolicy object class being removed.</li>
+ * </ul>
+ *
+ * @param policy Object must contain {@link org.apache.directory.fortress.core.rbac.PwPolicy#name} of the policy entity to remove.
+ * @throws org.apache.directory.fortress.core.SecurityException
+ * In the event policy entity not found or system error.
+ */
+ @Override
+ public void delete(PwPolicy policy)
+ throws SecurityException
+ {
+ VUtil.assertNotNull(policy, GlobalErrIds.PSWD_NAME_NULL, CLS_NM + ".delete");
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(policy);
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_DELETE);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() != 0)
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ }
+
+
+ /**
+ * This method will return the password policy entity to the caller. This command is valid
+ * if and only if the policy entry is present in the POLICIES data set.
+ * <h4>required parameters</h4>
+ * <ul>
+ * <li>{@link org.apache.directory.fortress.core.rbac.PwPolicy#name} - Maps to name attribute of pwdPolicy object class being read.</li>
+ * </ul>
+ *
+ * @return PswdPolicy entity returns fully populated with attributes.
+ * @throws SecurityException In the event policy entry not found, data validation or system error.
+ */
+ @Override
+ public PwPolicy read(String name)
+ throws SecurityException
+ {
+ VUtil.assertNotNullOrEmpty(name, GlobalErrIds.PSWD_NAME_NULL, CLS_NM + ".read");
+ PwPolicy retPolicy;
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(new PwPolicy(name));
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_READ);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() == 0)
+ {
+ retPolicy = (PwPolicy) response.getEntity();
+ }
+ else
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ return retPolicy;
+ }
+
+
+ /**
+ * This method will return a list of all password policy entities that match a particular search string.
+ * This command will return an empty list of no matching entries are found.
+ *
+ * @param searchVal String contains the leading chars of a policy entity. This search is not case sensitive.
+ * @return List<PswdPolicy> contains all matching password policy entities. If no records found this will be empty.
+ * @throws SecurityException In the event of data validation or system error.
+ */
+ @Override
+ public List<PwPolicy> search(String searchVal)
+ throws SecurityException
+ {
+ VUtil.assertNotNull(searchVal, GlobalErrIds.PSWD_NAME_NULL, CLS_NM + ".search");
+ List<PwPolicy> retPolicies;
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(new PwPolicy(searchVal));
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_SEARCH);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() == 0)
+ {
+ retPolicies = response.getEntities();
+ }
+ else
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ return retPolicies;
+ }
+
+
+ /**
+ * This method will associate a user entity with a password policy entity. This function is valid
+ * if and only if the user is a member of the USERS data set and the policyName refers to a
+ * policy that is a member of the PWPOLICIES data set.
+ *
+ * @param userId Contains {@link org.apache.directory.fortress.core.rbac.User#userId} of a User entity in USERS data set.
+ * @param name String contains the {@link org.apache.directory.fortress.core.rbac.PwPolicy#name} of a pw policy entity contained within the PWPOLICIES data set.
+ * @throws SecurityException thrown in the event either user or policy not valid or system error.
+ */
+ @Override
+ public void updateUserPolicy(String userId, String name)
+ throws SecurityException
+ {
+ String methodName = "updateUserPolicy";
+ VUtil.assertNotNullOrEmpty(userId, GlobalErrIds.USER_NULL, CLS_NM + "." + methodName);
+ VUtil.assertNotNullOrEmpty(name, GlobalErrIds.PSWD_NAME_NULL, CLS_NM + "." + methodName);
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setEntity(new PwPolicy(name));
+ request.setValue(userId);
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_USER_ADD);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() != 0)
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ }
+
+
+ /**
+ * This method will remove the pw policy assignment from a user entity. This function is valid
+ * if and only if the user is a member of the USERS data set and the policy attribute is assigned.
+ * Removal of pw policy assignment will revert the user's policy to use the global default for OpenLDAP
+ * instance that contains user.
+ *
+ * @param userId Contains {@link User#userId} of a User entity in USERS data set.
+ * @throws SecurityException Thrown in the event either user not valid or system error.
+ */
+ @Override
+ public void deletePasswordPolicy(String userId)
+ throws SecurityException
+ {
+ VUtil.assertNotNullOrEmpty(userId, GlobalErrIds.USER_NULL, CLS_NM + ".deletePasswordPolicy");
+ FortRequest request = new FortRequest();
+ request.setContextId(this.contextId);
+ request.setValue(userId);
+ if (this.adminSess != null)
+ {
+ request.setSession(adminSess);
+ }
+ String szRequest = RestUtils.marshal(request);
+ String szResponse = RestUtils.post(szRequest, HttpIds.PSWD_USER_DELETE);
+ FortResponse response = RestUtils.unmarshall(szResponse);
+ if (response.getErrorCode() != 0)
+ {
+ throw new SecurityException(response.getErrorCode(), response.getErrorMessage());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/directory-fortress-core/blob/687ee1ad/src/main/java/org/apache/directory/fortress/core/rest/RestUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/directory/fortress/core/rest/RestUtils.java b/src/main/java/org/apache/directory/fortress/core/rest/RestUtils.java
new file mode 100644
index 0000000..3797bd1
--- /dev/null
+++ b/src/main/java/org/apache/directory/fortress/core/rest/RestUtils.java
@@ -0,0 +1,483 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.directory.fortress.core.rest;
+
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Properties;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.RequestEntity;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.helpers.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.directory.fortress.core.GlobalErrIds;
+import org.apache.directory.fortress.core.ObjectFactory;
+import org.apache.directory.fortress.core.RestException;
+import org.apache.directory.fortress.core.cfg.Config;
+import org.apache.directory.fortress.core.rbac.Props;
+import org.apache.directory.fortress.core.util.crypto.EncryptUtil;
+
+
+/**
+ * This utility class provides methods that wrap Apache's HTTP Client APIs. This class is thread safe.
+ *
+ * @author Shawn McKinney
+ */
+public class RestUtils
+{
+ private static final String CLS_NM = RestUtils.class.getName();
+ private static final Logger LOG = LoggerFactory.getLogger( CLS_NM );
+ private final static String HTTP_UID = Config.getProperty( "http.user" );
+ private final static String HTTP_PW_PARAM = "http.pw";
+ private final static String HTTP_PW = ( ( EncryptUtil.isEnabled() ) ? EncryptUtil.decrypt( Config
+ .getProperty( HTTP_PW_PARAM ) ) : Config.getProperty( HTTP_PW_PARAM ) );
+ private final static String HTTP_HOST = Config.getProperty( "http.host" );
+ private final static String HTTP_PORT = Config.getProperty( "http.port" );
+ private final static String HTTP_PROTOCOL = Config.getProperty( "http.protocol", "http" );
+ private static final String VERSION = System.getProperty( "version" );
+ private static final String SERVICE = "enmasse-" + VERSION;
+ // TODO: add SSL capability here:
+ private static final String URI = HTTP_PROTOCOL + "://" + HTTP_HOST + ":" + HTTP_PORT + "/" + SERVICE + "/";
+ private static final int HTTP_OK = 200;
+ private static final int HTTP_401_UNAUTHORIZED = 401;
+ private static final int HTTP_403_FORBIDDEN = 403;
+ private static final int HTTP_404_NOT_FOUND = 404;
+ private static CachedJaxbContext cachedJaxbContext = new CachedJaxbContext();
+
+ /**
+ * Used to manage trust store properties. If enabled, create SSL connection.
+ *
+ */
+ private static final String TRUST_STORE = Config.getProperty( "trust.store" );
+ private static final String TRUST_STORE_PW = Config.getProperty( "trust.store.password" );
+ private static final String SET_TRUST_STORE_PROP = "trust.store.set.prop";
+ private static final boolean IS_SET_TRUST_STORE_PROP = (
+ Config.getProperty( SET_TRUST_STORE_PROP ) != null &&
+ Config.getProperty( SET_TRUST_STORE_PROP ).equalsIgnoreCase( "true" ));
+
+ static
+ {
+ if(IS_SET_TRUST_STORE_PROP)
+ {
+ LOG.info( "Set JSSE truststore properties:");
+ LOG.info( "javax.net.ssl.trustStore: " + TRUST_STORE );
+ System.setProperty( "javax.net.ssl.trustStore", TRUST_STORE );
+ System.setProperty( "javax.net.ssl.trustStorePassword", TRUST_STORE_PW );
+ }
+ }
+
+
+
+
+ /**
+ * Marshall the request into an XML String.
+ *
+ * @param request
+ * @return String containing xml request
+ * @throws RestException
+ */
+ public static String marshal( FortRequest request ) throws RestException
+ {
+ String szRetValue;
+ try
+ {
+ // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
+ final JAXBContext context = cachedJaxbContext.getJaxbContext( FortRequest.class );
+ // =============================================================================================================
+ // Marshalling OBJECT to XML
+ // =============================================================================================================
+ // Create the marshaller, that will transform the object into XML
+ final Marshaller marshaller = context.createMarshaller();
+ // Create a stringWriter to hold the XML
+ final StringWriter stringWriter = new StringWriter();
+ // Marshal the javaObject and write the XML to the stringWriter
+ marshaller.marshal( request, stringWriter );
+ szRetValue = stringWriter.toString();
+ }
+ catch ( JAXBException je )
+ {
+ String error = "marshal caught JAXBException=" + je;
+ throw new RestException( GlobalErrIds.REST_MARSHALL_ERR, error, je );
+ }
+ return szRetValue;
+ }
+
+
+ /**
+ * Unmarshall the XML response into its associated Java objects.
+ *
+ * @param szResponse
+ * @return FortResponse
+ * @throws RestException
+ */
+ public static FortResponse unmarshall( String szResponse ) throws RestException
+ {
+ FortResponse response;
+ try
+ {
+ // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
+ final JAXBContext context = cachedJaxbContext.getJaxbContext( FortResponse.class );
+
+ // Create the unmarshaller, that will transform the XML back into an object
+ final Unmarshaller unmarshaller = context.createUnmarshaller();
+ response = ( FortResponse ) unmarshaller.unmarshal( new StringReader( szResponse ) );
+ }
+ catch ( JAXBException je )
+ {
+ String error = "unmarshall caught JAXBException=" + je;
+ throw new RestException( GlobalErrIds.REST_UNMARSHALL_ERR, error, je );
+ }
+ return response;
+ }
+
+
+ /**
+ * Perform HTTP Get REST request.
+ *
+ * @param userId
+ * @param password
+ * @param id
+ * @param id2
+ * @param id3
+ * @param function
+ * @return String containing response
+ * @throws RestException
+ */
+ public static String get( String userId, String password, String id, String id2, String id3, String function )
+ throws RestException
+ {
+ String url = URI + function + "/" + id;
+ if ( id2 != null )
+ {
+ url += "/" + id2;
+ }
+ if ( id3 != null )
+ {
+ url += "/" + id3;
+ }
+ LOG.debug( "get function1:{}, id1:{}, id2:{}, id3:{}, url:{}", function, id, id2, id3, url );
+ GetMethod get = new GetMethod( url );
+ setMethodHeaders( get, userId, password );
+ return handleHttpMethod( get );
+ }
+
+
+ /**
+ * Perform HTTP Get REST request.
+ *
+ * @param id
+ * @param id2
+ * @param id3
+ * @param function
+ * @return String containing response
+ * @throws RestException
+ */
+ public static String get( String id, String id2, String id3, String function ) throws RestException
+ {
+ String url = URI + function + "/" + id;
+ if ( id2 != null )
+ {
+ url += "/" + id2;
+ }
+ if ( id3 != null )
+ {
+ url += "/" + id3;
+ }
+ LOG.debug( "get function2:{}, id1:{}, id2:{}, id3:{}, url:{}", function, id, id2, id3, url );
+ GetMethod get = new GetMethod( url );
+ setMethodHeaders( get, HTTP_UID, HTTP_PW );
+ return handleHttpMethod( get );
+ }
+
+
+ /**
+ * Perform an HTTP Post REST operation.
+ *
+ * @param userId
+ * @param password
+ * @param szInput
+ * @param function
+ * @return String containing response
+ * @throws RestException
+ */
+ public static String post( String userId, String password, String szInput, String function ) throws RestException
+ {
+ LOG.debug( "post URI=[" + URI + "], function=[" + function + "], request=" + szInput );
+ String szResponse = null;
+ PostMethod post = new PostMethod( URI + function );
+ post.addRequestHeader( "Accept", "text/xml" );
+ setMethodHeaders( post, userId, password );
+ try
+ {
+ RequestEntity entity = new StringRequestEntity( szInput, "text/xml; charset=ISO-8859-1", null );
+ post.setRequestEntity( entity );
+ HttpClient httpclient = new HttpClient();
+ int result = httpclient.executeMethod( post );
+ szResponse = IOUtils.toString( post.getResponseBodyAsStream(), "UTF-8" );
+ LOG.debug( "post URI=[{}], function=[{}], response=[{}], result=[{}]", URI, function, szResponse, result );
+ }
+ catch ( IOException ioe )
+ {
+ String error = "post URI=[" + URI + "], [" + function + "] caught IOException=" + ioe;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_IO_ERR, error, ioe );
+ }
+ catch ( WebApplicationException we )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function
+ + "] caught WebApplicationException=" + we;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_WEB_ERR, error, we );
+ }
+ finally
+ {
+ // Release current connection to the connection pool.
+ post.releaseConnection();
+ }
+ return szResponse;
+ }
+
+
+ /**
+ * Perform an HTTP Post REST operation.
+ *
+ * @param szInput
+ * @param function
+ * @return String containing response
+ * @throws RestException
+ */
+ public static String post( String szInput, String function ) throws RestException
+ {
+ LOG.debug( "post URI=[{}], function=[{}], request=[{}]", URI, function, szInput );
+ String szResponse = null;
+ PostMethod post = new PostMethod( URI + function );
+ post.addRequestHeader( "Accept", "text/xml" );
+ setMethodHeaders( post, HTTP_UID, HTTP_PW );
+ try
+ {
+ RequestEntity entity = new StringRequestEntity( szInput, "text/xml; charset=ISO-8859-1", null );
+ post.setRequestEntity( entity );
+ HttpClient httpclient = new HttpClient();
+ int result = httpclient.executeMethod( post );
+ if ( result == HTTP_OK )
+ {
+ szResponse = IOUtils.toString( post.getResponseBodyAsStream(), "UTF-8" );
+ LOG.debug( "post URI=[{}], function=[{}], response=[{}]", URI, function, szResponse );
+ }
+ else if ( result == HTTP_401_UNAUTHORIZED )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function
+ + "], 401 function unauthorized on host";
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_UNAUTHORIZED_ERR, error );
+ }
+ else if ( result == HTTP_403_FORBIDDEN )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function
+ + "], 403 function forbidden on host";
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_FORBIDDEN_ERR, error );
+ }
+ else if ( result == HTTP_404_NOT_FOUND )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function + "], 404 not found from host";
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_NOT_FOUND_ERR, error );
+ }
+ else
+ {
+ String error = "post URI=[" + URI + "], function=[" + function
+ + "], error received from host: " + result;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_UNKNOWN_ERR, error );
+ }
+ }
+ catch ( IOException ioe )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function + "] caught IOException=" + ioe;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_IO_ERR, error, ioe );
+ }
+ catch ( WebApplicationException we )
+ {
+ String error = "post URI=[" + URI + "], function=[" + function
+ + "] caught WebApplicationException=" + we;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_WEB_ERR, error, we );
+ }
+ finally
+ {
+ // Release current connection to the connection pool.
+ post.releaseConnection();
+ }
+ return szResponse;
+ }
+
+
+ /**
+ * Set these params into their associated HTTP header vars.
+ *
+ * @param httpMethod
+ * @param name
+ * @param password
+ */
+ private static void setMethodHeaders( HttpMethod httpMethod, String name, String password )
+ {
+ if ( httpMethod instanceof PostMethod || httpMethod instanceof PutMethod )
+ {
+ httpMethod.setRequestHeader( "Content-Type", "application/xml" );
+ httpMethod.setRequestHeader( "Accept", "application/xml" );
+ }
+ //httpMethod.setDoAuthentication(false);
+ httpMethod.setDoAuthentication( true );
+ httpMethod.setRequestHeader( "Authorization",
+ "Basic " + base64Encode( name + ":" + password ) );
+ }
+
+
+ /**
+ * Convert from non-Base64 to Base64 encoded.
+ *
+ * @param value
+ * @return String contains encoded data
+ */
+ private static String base64Encode( String value )
+ {
+ return Base64Utility.encode( value.getBytes() );
+ }
+
+
+ /**
+ * Process the HTTP method request.
+ *
+ * @param httpMethod
+ * @return String containing response
+ * @throws Exception
+ */
+ private static String handleHttpMethod( HttpMethod httpMethod ) throws RestException
+ {
+ HttpClient client = new HttpClient();
+ String szResponse = null;
+ try
+ {
+ int statusCode = client.executeMethod( httpMethod );
+ LOG.debug( "handleHttpMethod Response status : {}", statusCode );
+
+ Response.Status status = Response.Status.fromStatusCode( statusCode );
+
+ if ( status == Response.Status.OK )
+ {
+ szResponse = httpMethod.getResponseBodyAsString();
+ LOG.debug( szResponse );
+ }
+ else if ( status == Response.Status.FORBIDDEN )
+ {
+ LOG.debug( "handleHttpMethod Authorization failure" );
+ }
+ else if ( status == Response.Status.UNAUTHORIZED )
+ {
+ LOG.debug( "handleHttpMethod Authentication failure" );
+ }
+ else
+ {
+ LOG.debug( "handleHttpMethod Unknown error" );
+ }
+ }
+ catch ( IOException ioe )
+ {
+ String error = "handleHttpMethod caught IOException=" + ioe;
+ LOG.error( error );
+ throw new RestException( GlobalErrIds.REST_IO_ERR, error, ioe );
+ }
+ finally
+ {
+ // Release current connection to the connection pool.
+ httpMethod.releaseConnection();
+ }
+ return szResponse;
+ }
+
+
+ /**
+ * @param inProps
+ * @return Properties
+ */
+ public static Properties getProperties( Props inProps )
+ {
+ Properties properties = null;
+ List<Props.Entry> props = inProps.getEntry();
+ if ( props.size() > 0 )
+ {
+ properties = new Properties();
+ //int size = props.size();
+ for ( Props.Entry entry : props )
+ {
+ String key = entry.getKey();
+ String val = entry.getValue();
+ properties.setProperty( key, val );
+ }
+ }
+ return properties;
+ }
+
+
+ /**
+ *
+ * @param properties
+ * @return Prop contains name value pairs.
+ */
+ public static Props getProps( Properties properties )
+ {
+ Props props = null;
+ if ( properties != null )
+ {
+ props = new ObjectFactory().createProps();
+ for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); )
+ {
+ String key = ( String ) e.nextElement();
+ String val = properties.getProperty( key );
+ Props.Entry entry = new Props.Entry();
+ entry.setKey( key );
+ entry.setValue( val );
+ props.getEntry().add( entry );
+ }
+ }
+ return props;
+ }
+}
\ No newline at end of file