From 8d8cac0cde3c0f4c05de9a7f5ef5c77ba3df3f44 Mon Sep 17 00:00:00 2001
From: "Endi S. Dewata" <edewata@redhat.com>
Date: Thu, 24 Oct 2013 09:17:37 -0400
Subject: [PATCH] Added TPS profile resource.

A new REST service and clients have been added to manage the profiles
in the TPS configuration file.

Ticket #652
---
 .../src/com/netscape/certsrv/tps/TPSClient.java    |   2 +
 .../certsrv/tps/profile/ProfileClient.java         |  76 +++++
 .../certsrv/tps/profile/ProfileCollection.java}    |  26 +-
 .../netscape/certsrv/tps/profile/ProfileData.java  | 232 +++++++++++++++
 .../certsrv/tps/profile/ProfileResource.java       |  90 ++++++
 .../cmstools/tps/profile/ProfileAddCLI.java        |  96 ++++++
 .../netscape/cmstools/tps/profile/ProfileCLI.java  |  35 +++
 .../cmstools/tps/profile/ProfileFindCLI.java       |  94 ++++++
 .../cmstools/tps/profile/ProfileModifyCLI.java     | 112 +++++++
 .../{ProfileCLI.java => ProfileRemoveCLI.java}     |  25 +-
 .../cmstools/tps/profile/ProfileShowCLI.java       |  87 ++++++
 .../netscape/cms/authorization/ACLInterceptor.java |  14 +-
 .../cms/authorization/AuthMethodInterceptor.java   |   4 +-
 base/tps-tomcat/shared/conf/acl.ldif               |   1 +
 .../shared/webapps/tps/WEB-INF/auth.properties     |   5 +
 base/tps-tomcat/src/CMakeLists.txt                 |   9 +-
 .../org/dogtagpki/server/tps/TPSApplication.java   |   2 +
 .../src/org/dogtagpki/server/tps/TPSSubsystem.java |   7 +
 .../tps/authenticator/AuthenticatorDatabase.java   |   3 +-
 .../server/tps/config/ConfigDatabase.java          |  20 +-
 .../server/tps/connection/ConnectionDatabase.java  |   3 +-
 .../server/tps/profile/ProfileDatabase.java        | 176 +++++++++++
 .../server/tps/profile/ProfileMappingDatabase.java |   3 +-
 .../server/tps/profile/ProfileRecord.java          | 112 +++++++
 .../server/tps/profile/ProfileService.java         | 325 +++++++++++++++++++++
 25 files changed, 1518 insertions(+), 41 deletions(-)
 create mode 100644 base/common/src/com/netscape/certsrv/tps/profile/ProfileClient.java
 copy base/{java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java => common/src/com/netscape/certsrv/tps/profile/ProfileCollection.java} (66%)
 create mode 100644 base/common/src/com/netscape/certsrv/tps/profile/ProfileData.java
 create mode 100644 base/common/src/com/netscape/certsrv/tps/profile/ProfileResource.java
 create mode 100644 base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileAddCLI.java
 create mode 100644 base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileFindCLI.java
 create mode 100644 base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileModifyCLI.java
 copy base/java-tools/src/com/netscape/cmstools/tps/profile/{ProfileCLI.java => ProfileRemoveCLI.java} (60%)
 create mode 100644 base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileShowCLI.java
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileDatabase.java
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileRecord.java
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileService.java

diff --git a/base/common/src/com/netscape/certsrv/tps/TPSClient.java b/base/common/src/com/netscape/certsrv/tps/TPSClient.java
index 40820d84ded6ec308c7b19540e46e64052ab8aa7..7f65784c9e648d553384b6ae8220e02f3cfd0f7b 100644
--- a/base/common/src/com/netscape/certsrv/tps/TPSClient.java
+++ b/base/common/src/com/netscape/certsrv/tps/TPSClient.java
@@ -29,6 +29,7 @@ import com.netscape.certsrv.tps.authenticator.AuthenticatorClient;
 import com.netscape.certsrv.tps.cert.TPSCertClient;
 import com.netscape.certsrv.tps.config.ConfigClient;
 import com.netscape.certsrv.tps.connection.ConnectionClient;
+import com.netscape.certsrv.tps.profile.ProfileClient;
 import com.netscape.certsrv.tps.profile.ProfileMappingClient;
 import com.netscape.certsrv.tps.token.TokenClient;
 import com.netscape.certsrv.user.UserClient;
@@ -51,6 +52,7 @@ public class TPSClient extends SubsystemClient {
         addClient(new ConfigClient(client, name));
         addClient(new ConnectionClient(client, name));
         addClient(new GroupClient(client, name));
+        addClient(new ProfileClient(client, name));
         addClient(new ProfileMappingClient(client, name));
         addClient(new SelfTestClient(client, name));
         addClient(new TokenClient(client, name));
diff --git a/base/common/src/com/netscape/certsrv/tps/profile/ProfileClient.java b/base/common/src/com/netscape/certsrv/tps/profile/ProfileClient.java
new file mode 100644
index 0000000000000000000000000000000000000000..6f262e95a67c5884bfaa549cb0aecf63eb2a8f18
--- /dev/null
+++ b/base/common/src/com/netscape/certsrv/tps/profile/ProfileClient.java
@@ -0,0 +1,76 @@
+//--- BEGIN COPYRIGHT BLOCK ---
+//This program is free software; you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation; version 2 of the License.
+//
+//This program is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License along
+//with this program; if not, write to the Free Software Foundation, Inc.,
+//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+//(C) 2013 Red Hat, Inc.
+//All rights reserved.
+//--- END COPYRIGHT BLOCK ---
+package com.netscape.certsrv.tps.profile;
+
+import java.net.URISyntaxException;
+
+import org.jboss.resteasy.client.ClientResponse;
+
+import com.netscape.certsrv.client.Client;
+import com.netscape.certsrv.client.PKIClient;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileClient extends Client {
+
+    public ProfileResource resource;
+
+    public ProfileClient(PKIClient client) throws URISyntaxException {
+        this(client, client.getSubsystem());
+    }
+
+    public ProfileClient(PKIClient client, String subsystem) throws URISyntaxException {
+        super(client, subsystem, "profile");
+        init();
+    }
+
+    public void init() throws URISyntaxException {
+        resource = createProxy(ProfileResource.class);
+    }
+
+    public ProfileCollection findProfiles(Integer start, Integer size) {
+        return resource.findProfiles(start, size);
+    }
+
+    public ProfileData getProfile(String profileID) {
+        return resource.getProfile(profileID);
+    }
+
+    public ProfileData addProfile(ProfileData profileData) {
+        @SuppressWarnings("unchecked")
+        ClientResponse<ProfileData> response = (ClientResponse<ProfileData>)resource.addProfile(profileData);
+        return client.getEntity(response);
+    }
+
+    public ProfileData updateProfile(String profileID, ProfileData profileData) {
+        @SuppressWarnings("unchecked")
+        ClientResponse<ProfileData> response = (ClientResponse<ProfileData>)resource.updateProfile(profileID, profileData);
+        return client.getEntity(response);
+    }
+
+    public ProfileData changeProfileStatus(String profileID, String action) {
+        @SuppressWarnings("unchecked")
+        ClientResponse<ProfileData> response = (ClientResponse<ProfileData>)resource.changeProfileStatus(profileID, action);
+        return client.getEntity(response);
+    }
+
+    public void removeProfile(String profileID) {
+        resource.removeProfile(profileID);
+    }
+}
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java b/base/common/src/com/netscape/certsrv/tps/profile/ProfileCollection.java
similarity index 66%
copy from base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
copy to base/common/src/com/netscape/certsrv/tps/profile/ProfileCollection.java
index 41270f6f971e52be91298251e8ce6a98df49bb3d..a802cb680c73c0894a225b50434fed44870fcb39 100644
--- a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
+++ b/base/common/src/com/netscape/certsrv/tps/profile/ProfileCollection.java
@@ -16,25 +16,23 @@
 // All rights reserved.
 // --- END COPYRIGHT BLOCK ---
 
-package com.netscape.cmstools.tps.profile;
+package com.netscape.certsrv.tps.profile;
 
-import com.netscape.cmstools.cli.CLI;
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import com.netscape.certsrv.base.DataCollection;
 
 /**
  * @author Endi S. Dewata
  */
-public class ProfileCLI extends CLI {
+@XmlRootElement(name="Profiles")
+public class ProfileCollection extends DataCollection<ProfileData> {
 
-    public ProfileCLI(CLI parent) {
-        super("profile", "Profile management commands", parent);
-
-        addModule(new ProfileMappingCLI(this));
-    }
-
-    public void execute(String[] args) throws Exception {
-
-        client = parent.getClient();
-
-        super.execute(args);
+    @XmlElementRef
+    public Collection<ProfileData> getEntries() {
+        return super.getEntries();
     }
 }
diff --git a/base/common/src/com/netscape/certsrv/tps/profile/ProfileData.java b/base/common/src/com/netscape/certsrv/tps/profile/ProfileData.java
new file mode 100644
index 0000000000000000000000000000000000000000..c4bbc037e189bd689d528e928e1d5515be49836c
--- /dev/null
+++ b/base/common/src/com/netscape/certsrv/tps/profile/ProfileData.java
@@ -0,0 +1,232 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.certsrv.tps.profile;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlValue;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+import org.jboss.resteasy.plugins.providers.atom.Link;
+
+/**
+ * @author Endi S. Dewata
+ */
+@XmlRootElement(name="Profile")
+public class ProfileData {
+
+    public static Marshaller marshaller;
+    public static Unmarshaller unmarshaller;
+
+    static {
+        try {
+            marshaller = JAXBContext.newInstance(ProfileData.class).createMarshaller();
+            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+            unmarshaller = JAXBContext.newInstance(ProfileData.class).createUnmarshaller();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    String id;
+    String status;
+    Map<String, String> properties = new LinkedHashMap<String, String>();
+
+    Link link;
+
+    @XmlAttribute(name="id")
+    public String getID() {
+        return id;
+    }
+
+    public void setID(String id) {
+        this.id = id;
+    }
+
+    @XmlElement(name="Status")
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    @XmlElement(name="Properties")
+    @XmlJavaTypeAdapter(MapAdapter.class)
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties.clear();
+        this.properties.putAll(properties);
+    }
+
+    public Collection<String> getPropertyNames() {
+        return properties.keySet();
+    }
+
+    public String getProperty(String name) {
+        return properties.get(name);
+    }
+
+    public void setProperty(String name, String value) {
+        properties.put(name, value);
+    }
+
+    public String removeProperty(String name) {
+        return properties.remove(name);
+    }
+
+    public static class MapAdapter extends XmlAdapter<PropertyList, Map<String, String>> {
+
+        public PropertyList marshal(Map<String, String> map) {
+            PropertyList list = new PropertyList();
+            for (Map.Entry<String, String> entry : map.entrySet()) {
+                Property property = new Property();
+                property.name = entry.getKey();
+                property.value = entry.getValue();
+                list.properties.add(property);
+            }
+            return list;
+        }
+
+        public Map<String, String> unmarshal(PropertyList list) {
+            Map<String, String> map = new LinkedHashMap<String, String>();
+            for (Property property : list.properties) {
+                map.put(property.name, property.value);
+            }
+            return map;
+        }
+    }
+
+    public static class PropertyList {
+        @XmlElement(name="Property")
+        public List<Property> properties = new ArrayList<Property>();
+    }
+
+    public static class Property {
+
+        @XmlAttribute
+        public String name;
+
+        @XmlValue
+        public String value;
+    }
+
+    @XmlElement(name="Link")
+    public Link getLink() {
+        return link;
+    }
+
+    public void setLink(Link link) {
+        this.link = link;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((id == null) ? 0 : id.hashCode());
+        result = prime * result + ((link == null) ? 0 : link.hashCode());
+        result = prime * result + ((properties == null) ? 0 : properties.hashCode());
+        result = prime * result + ((status == null) ? 0 : status.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        ProfileData other = (ProfileData) obj;
+        if (id == null) {
+            if (other.id != null)
+                return false;
+        } else if (!id.equals(other.id))
+            return false;
+        if (link == null) {
+            if (other.link != null)
+                return false;
+        } else if (!link.equals(other.link))
+            return false;
+        if (properties == null) {
+            if (other.properties != null)
+                return false;
+        } else if (!properties.equals(other.properties))
+            return false;
+        if (status == null) {
+            if (other.status != null)
+                return false;
+        } else if (!status.equals(other.status))
+            return false;
+        return true;
+    }
+
+    public String toString() {
+        try {
+            StringWriter sw = new StringWriter();
+            marshaller.marshal(this, sw);
+            return sw.toString();
+
+        } catch (Exception e) {
+            return super.toString();
+        }
+    }
+
+    public static ProfileData valueOf(String string) throws Exception {
+        try {
+            return (ProfileData)unmarshaller.unmarshal(new StringReader(string));
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+
+        ProfileData before = new ProfileData();
+        before.setID("profile1");
+        before.setStatus("ENABLED");
+        before.setProperty("param1", "value1");
+        before.setProperty("param2", "value2");
+
+        String string = before.toString();
+        System.out.println(string);
+
+        ProfileData after = ProfileData.valueOf(string);
+        System.out.println(before.equals(after));
+    }
+}
diff --git a/base/common/src/com/netscape/certsrv/tps/profile/ProfileResource.java b/base/common/src/com/netscape/certsrv/tps/profile/ProfileResource.java
new file mode 100644
index 0000000000000000000000000000000000000000..d86a4d809a86340f7487e61518eab570463e8523
--- /dev/null
+++ b/base/common/src/com/netscape/certsrv/tps/profile/ProfileResource.java
@@ -0,0 +1,90 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package com.netscape.certsrv.tps.profile;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.jboss.resteasy.annotations.ClientResponseType;
+
+import com.netscape.certsrv.acls.ACLMapping;
+import com.netscape.certsrv.authentication.AuthMethodMapping;
+
+
+/**
+ * @author Endi S. Dewata
+ */
+@Path("profiles")
+@AuthMethodMapping("profiles")
+@ACLMapping("profiles.read")
+public interface ProfileResource {
+
+    @GET
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public ProfileCollection findProfiles(
+            @QueryParam("start") Integer start,
+            @QueryParam("size") Integer size);
+
+    @GET
+    @Path("{profileID}")
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public ProfileData getProfile(@PathParam("profileID") String profileID);
+
+    @POST
+    @ACLMapping("profiles.add")
+    @ClientResponseType(entityType=ProfileData.class)
+    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public Response addProfile(ProfileData profileData);
+
+    @PUT
+    @Path("{profileID}")
+    @ACLMapping("profiles.modify")
+    @ClientResponseType(entityType=ProfileData.class)
+    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public Response updateProfile(
+            @PathParam("profileID") String profileID,
+            ProfileData profileData);
+
+    @POST
+    @Path("{profileID}")
+    @ACLMapping("profiles.approve")
+    @ClientResponseType(entityType=ProfileData.class)
+    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public Response changeProfileStatus(
+            @PathParam("profileID") String profileID,
+            @QueryParam("action") String action);
+
+
+    @DELETE
+    @Path("{profileID}")
+    @ACLMapping("profiles.remove")
+    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+    public void removeProfile(@PathParam("profileID") String profileID);
+}
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileAddCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileAddCLI.java
new file mode 100644
index 0000000000000000000000000000000000000000..d44ddc08e045351d8f7a88463a2748cd84bc8aba
--- /dev/null
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileAddCLI.java
@@ -0,0 +1,96 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.cmstools.tps.profile;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+
+import com.netscape.certsrv.tps.profile.ProfileData;
+import com.netscape.cmstools.cli.CLI;
+import com.netscape.cmstools.cli.MainCLI;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileAddCLI extends CLI {
+
+    public ProfileCLI profileCLI;
+
+    public ProfileAddCLI(ProfileCLI profileCLI) {
+        super("add", "Add profile", profileCLI);
+        this.profileCLI = profileCLI;
+    }
+
+    public void printHelp() {
+        formatter.printHelp(getFullName() + " <Profile ID> [OPTIONS...]", options);
+    }
+
+    public void execute(String[] args) throws Exception {
+
+        Option option = new Option(null, "input", true, "Input file containing profile properties.");
+        option.setArgName("file");
+        option.setRequired(true);
+        options.addOption(option);
+
+        CommandLine cmd = null;
+
+        try {
+            cmd = parser.parse(options, args);
+
+        } catch (Exception e) {
+            System.err.println("Error: " + e.getMessage());
+            printHelp();
+            System.exit(1);
+        }
+
+        String[] cmdArgs = cmd.getArgs();
+
+        if (cmdArgs.length != 0) {
+            printHelp();
+            System.exit(1);
+        }
+
+        String input = cmd.getOptionValue("input");
+
+        ProfileData profileData;
+
+        try (BufferedReader in = new BufferedReader(new FileReader(input));
+            StringWriter sw = new StringWriter();
+            PrintWriter out = new PrintWriter(sw, true)) {
+
+            String line;
+            while ((line = in.readLine()) != null) {
+                out.println(line);
+            }
+
+            profileData = ProfileData.valueOf(sw.toString());
+        }
+
+        profileData = profileCLI.profileClient.addProfile(profileData);
+
+        MainCLI.printMessage("Added profile \"" + profileData.getID() + "\"");
+
+        ProfileCLI.printProfileData(profileData, true);
+    }
+}
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
index 41270f6f971e52be91298251e8ce6a98df49bb3d..8b02f2e577979a94b435c60b0577fc08b455a3f2 100644
--- a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
@@ -18,6 +18,13 @@
 
 package com.netscape.cmstools.tps.profile;
 
+import java.io.IOException;
+import java.util.Map;
+
+import org.jboss.resteasy.plugins.providers.atom.Link;
+
+import com.netscape.certsrv.tps.profile.ProfileClient;
+import com.netscape.certsrv.tps.profile.ProfileData;
 import com.netscape.cmstools.cli.CLI;
 
 /**
@@ -25,16 +32,44 @@ import com.netscape.cmstools.cli.CLI;
  */
 public class ProfileCLI extends CLI {
 
+    public ProfileClient profileClient;
+
     public ProfileCLI(CLI parent) {
         super("profile", "Profile management commands", parent);
 
+        addModule(new ProfileAddCLI(this));
+        addModule(new ProfileFindCLI(this));
+        addModule(new ProfileModifyCLI(this));
+        addModule(new ProfileRemoveCLI(this));
+        addModule(new ProfileShowCLI(this));
+
         addModule(new ProfileMappingCLI(this));
     }
 
     public void execute(String[] args) throws Exception {
 
         client = parent.getClient();
+        profileClient = (ProfileClient)parent.getClient("profile");
 
         super.execute(args);
     }
+
+    public static void printProfileData(ProfileData profileData, boolean showProperties) throws IOException {
+        System.out.println("  Profile ID: " + profileData.getID());
+        if (profileData.getStatus() != null) System.out.println("  Status: " + profileData.getStatus());
+
+        if (showProperties) {
+            System.out.println("  Properties:");
+            Map<String, String> properties = profileData.getProperties();
+            for (String name : properties.keySet()) {
+                String value = properties.get(name);
+                System.out.println("    " + name + ": " + value);
+            }
+        }
+
+        Link link = profileData.getLink();
+        if (verbose && link != null) {
+            System.out.println("  Link: " + link.getHref());
+        }
+    }
 }
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileFindCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileFindCLI.java
new file mode 100644
index 0000000000000000000000000000000000000000..9f822f6ba5ad9f3045c41396527d578f96976552
--- /dev/null
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileFindCLI.java
@@ -0,0 +1,94 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.cmstools.tps.profile;
+
+import java.util.Collection;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+
+import com.netscape.certsrv.tps.profile.ProfileCollection;
+import com.netscape.certsrv.tps.profile.ProfileData;
+import com.netscape.cmstools.cli.CLI;
+import com.netscape.cmstools.cli.MainCLI;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileFindCLI extends CLI {
+
+    public ProfileCLI profileCLI;
+
+    public ProfileFindCLI(ProfileCLI profileCLI) {
+        super("find", "Find profiles", profileCLI);
+        this.profileCLI = profileCLI;
+    }
+
+    public void printHelp() {
+        formatter.printHelp(getFullName() + " [OPTIONS...]", options);
+    }
+
+    public void execute(String[] args) throws Exception {
+
+        Option option = new Option(null, "start", true, "Page start");
+        option.setArgName("start");
+        options.addOption(option);
+
+        option = new Option(null, "size", true, "Page size");
+        option.setArgName("size");
+        options.addOption(option);
+
+        CommandLine cmd = null;
+
+        try {
+            cmd = parser.parse(options, args);
+
+        } catch (Exception e) {
+            System.err.println("Error: " + e.getMessage());
+            printHelp();
+            System.exit(1);
+        }
+
+        String s = cmd.getOptionValue("start");
+        Integer start = s == null ? null : Integer.valueOf(s);
+
+        s = cmd.getOptionValue("size");
+        Integer size = s == null ? null : Integer.valueOf(s);
+
+        ProfileCollection result = profileCLI.profileClient.findProfiles(start, size);
+        Collection<ProfileData> profiles = result.getEntries();
+
+        MainCLI.printMessage(profiles.size() + " profile(s) matched");
+
+        boolean first = true;
+
+        for (ProfileData profileData : profiles) {
+
+            if (first) {
+                first = false;
+            } else {
+                System.out.println();
+            }
+
+            ProfileCLI.printProfileData(profileData, false);
+        }
+
+        MainCLI.printMessage("Number of entries returned " + profiles.size());
+    }
+}
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileModifyCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileModifyCLI.java
new file mode 100644
index 0000000000000000000000000000000000000000..b4db037063e35d7d264732d4ceca5aff068f95b2
--- /dev/null
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileModifyCLI.java
@@ -0,0 +1,112 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.cmstools.tps.profile;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+
+import com.netscape.certsrv.tps.profile.ProfileData;
+import com.netscape.cmstools.cli.CLI;
+import com.netscape.cmstools.cli.MainCLI;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileModifyCLI extends CLI {
+
+    public ProfileCLI profileCLI;
+
+    public ProfileModifyCLI(ProfileCLI profileCLI) {
+        super("mod", "Modify profile", profileCLI);
+        this.profileCLI = profileCLI;
+    }
+
+    public void printHelp() {
+        formatter.printHelp(getFullName() + " <Profile ID> [OPTIONS...]", options);
+    }
+
+    public void execute(String[] args) throws Exception {
+
+        Option option = new Option(null, "input", true, "Input file containing profile properties.");
+        option.setArgName("file");
+        options.addOption(option);
+
+        option = new Option(null, "action", true, "Action: approve, reject, enable, disable.");
+        option.setArgName("action");
+        options.addOption(option);
+
+        CommandLine cmd = null;
+
+        try {
+            cmd = parser.parse(options, args);
+
+        } catch (Exception e) {
+            System.err.println("Error: " + e.getMessage());
+            printHelp();
+            System.exit(1);
+        }
+
+        String[] cmdArgs = cmd.getArgs();
+
+        if (cmdArgs.length != 1) {
+            printHelp();
+            System.exit(1);
+        }
+
+        String profileID = cmdArgs[0];
+        String input = cmd.getOptionValue("input");
+        String action = cmd.getOptionValue("action");
+
+        ProfileData profileData;
+
+        if (input == null && action == null || input != null && action != null) {
+            System.err.println("Error: Either input file or action should be specified");
+            printHelp();
+            System.exit(1);
+            return;
+
+        } else if (input != null) {
+            try (BufferedReader in = new BufferedReader(new FileReader(input));
+                StringWriter sw = new StringWriter();
+                PrintWriter out = new PrintWriter(sw, true)) {
+
+                String line;
+                while ((line = in.readLine()) != null) {
+                    out.println(line);
+                }
+
+                profileData = ProfileData.valueOf(sw.toString());
+            }
+
+            profileData = profileCLI.profileClient.updateProfile(profileID, profileData);
+
+        } else { // action != null
+            profileData = profileCLI.profileClient.changeProfileStatus(profileID, action);
+        }
+
+        MainCLI.printMessage("Modified profile \"" + profileID + "\"");
+
+        ProfileCLI.printProfileData(profileData, true);
+    }
+}
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileRemoveCLI.java
similarity index 60%
copy from base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
copy to base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileRemoveCLI.java
index 41270f6f971e52be91298251e8ce6a98df49bb3d..20913103f2099e9402e4f3515be526d4b7887f2b 100644
--- a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileCLI.java
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileRemoveCLI.java
@@ -19,22 +19,35 @@
 package com.netscape.cmstools.tps.profile;
 
 import com.netscape.cmstools.cli.CLI;
+import com.netscape.cmstools.cli.MainCLI;
 
 /**
  * @author Endi S. Dewata
  */
-public class ProfileCLI extends CLI {
+public class ProfileRemoveCLI extends CLI {
 
-    public ProfileCLI(CLI parent) {
-        super("profile", "Profile management commands", parent);
+    public ProfileCLI profileCLI;
 
-        addModule(new ProfileMappingCLI(this));
+    public ProfileRemoveCLI(ProfileCLI profileCLI) {
+        super("del", "Remove profile", profileCLI);
+        this.profileCLI = profileCLI;
+    }
+
+    public void printHelp() {
+        formatter.printHelp(getFullName() + " <Profile ID>", options);
     }
 
     public void execute(String[] args) throws Exception {
 
-        client = parent.getClient();
+        if (args.length != 1) {
+            printHelp();
+            System.exit(1);
+        }
 
-        super.execute(args);
+        String profileID = args[0];
+
+        profileCLI.profileClient.removeProfile(profileID);
+
+        MainCLI.printMessage("Deleted profile \"" + profileID + "\"");
     }
 }
diff --git a/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileShowCLI.java b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileShowCLI.java
new file mode 100644
index 0000000000000000000000000000000000000000..7c4c2fa1ebad7c3da9c98f2680d9ab3c1f0061fc
--- /dev/null
+++ b/base/java-tools/src/com/netscape/cmstools/tps/profile/ProfileShowCLI.java
@@ -0,0 +1,87 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.cmstools.tps.profile;
+
+import java.io.FileWriter;
+import java.io.PrintWriter;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+
+import com.netscape.certsrv.tps.profile.ProfileData;
+import com.netscape.cmstools.cli.CLI;
+import com.netscape.cmstools.cli.MainCLI;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileShowCLI extends CLI {
+
+    public ProfileCLI profileCLI;
+
+    public ProfileShowCLI(ProfileCLI profileCLI) {
+        super("show", "Show profile", profileCLI);
+        this.profileCLI = profileCLI;
+    }
+
+    public void printHelp() {
+        formatter.printHelp(getFullName() + " <Profile ID>", options);
+    }
+
+    public void execute(String[] args) throws Exception {
+
+        Option option = new Option(null, "output", true, "Output file to store profile properties.");
+        option.setArgName("file");
+        options.addOption(option);
+
+        CommandLine cmd = null;
+
+        try {
+            cmd = parser.parse(options, args);
+
+        } catch (Exception e) {
+            System.err.println("Error: " + e.getMessage());
+            printHelp();
+            System.exit(1);
+        }
+
+        String[] cmdArgs = cmd.getArgs();
+
+        if (cmdArgs.length != 1) {
+            printHelp();
+            System.exit(1);
+        }
+
+        String profileID = args[0];
+        String output = cmd.getOptionValue("output");
+
+        ProfileData profileData = profileCLI.profileClient.getProfile(profileID);
+
+        if (output == null) {
+            MainCLI.printMessage("Profile \"" + profileID + "\"");
+            ProfileCLI.printProfileData(profileData, true);
+
+        } else {
+            try (PrintWriter out = new PrintWriter(new FileWriter(output))) {
+                out.println(profileData);
+            }
+            MainCLI.printMessage("Stored profile \"" + profileID + "\" into " + output);
+        }
+    }
+}
diff --git a/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java b/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java
index 52d9eb8995a9e6265863bb5d118cf0b4f2a6eb78..b43eb3cbeabe77842fd501a2dc7b79d45890688b 100644
--- a/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java
+++ b/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java
@@ -72,12 +72,14 @@ public class ACLInterceptor implements ContainerRequestFilter {
         ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
                 .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
         Method method = methodInvoker.getMethod();
+        Class<?> clazz = methodInvoker.getResourceClass();
+
+        CMS.debug("ACLInterceptor: " + clazz.getSimpleName() + "." + method.getName() + "()");
 
         ACLMapping aclMapping = method.getAnnotation(ACLMapping.class);
 
         // If not available, get ACL mapping for the class.
         if (aclMapping == null) {
-            Class<?> clazz = method.getDeclaringClass();
             aclMapping = clazz.getAnnotation(ACLMapping.class);
         }
 
@@ -87,6 +89,9 @@ public class ACLInterceptor implements ContainerRequestFilter {
             return;
         }
 
+        String name = aclMapping.value();
+        CMS.debug("ACLInterceptor: mapping: " + name);
+
         Principal principal = securityContext.getUserPrincipal();
 
         // If unauthenticated, reject request.
@@ -95,6 +100,8 @@ public class ACLInterceptor implements ContainerRequestFilter {
             throw new ForbiddenException("No user principal provided.");
         }
 
+        CMS.debug("ACLInterceptor: principal: " + principal.getName());
+
         // If unrecognized principal, reject request.
         if (!(principal instanceof PKIPrincipal)) {
             CMS.debug("ACLInterceptor: Invalid user principal.");
@@ -113,7 +120,6 @@ public class ACLInterceptor implements ContainerRequestFilter {
         try {
             loadAuthProperties();
 
-            String name = aclMapping.value();
             String value = authProperties.getProperty(name);
 
             // If no property defined, allow request.
@@ -130,6 +136,8 @@ public class ACLInterceptor implements ContainerRequestFilter {
                 throw new ForbiddenException("Invalid ACL mapping.");
             }
 
+            CMS.debug("ACLInterceptor: ACL: " + value);
+
             // Check authorization.
             IAuthzSubsystem mAuthz = (IAuthzSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTHZ);
             AuthzToken authzToken = mAuthz.authorize(
@@ -144,6 +152,8 @@ public class ACLInterceptor implements ContainerRequestFilter {
                 throw new ForbiddenException("No authorization token present.");
             }
 
+            CMS.debug("ACLInterceptor: access granted");
+
         } catch (EAuthzAccessDenied e) {
             CMS.debug("ACLInterceptor: " + e.getMessage());
             throw new ForbiddenException(e.toString());
diff --git a/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java b/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java
index fa2648bc724881a2c4678e65872660a2bff379e1..25e24a54045dfe75239e40eeddb24e0225507f21 100644
--- a/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java
+++ b/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java
@@ -105,7 +105,7 @@ public class AuthMethodInterceptor implements ContainerRequestFilter {
             name = authMapping.value();
         }
 
-        CMS.debug("AuthMethodInterceptor: mapping name: " + name);
+        CMS.debug("AuthMethodInterceptor: mapping: " + name);
 
         try {
             loadAuthProperties();
@@ -156,7 +156,7 @@ public class AuthMethodInterceptor implements ContainerRequestFilter {
             }
 
             if (authMethods.isEmpty() || authMethods.contains(authManager) || authMethods.contains("*")) {
-                CMS.debug("AuthMethodInterceptor: " + authManager + " allowed");
+                CMS.debug("AuthMethodInterceptor: access granted");
                 return;
             }
 
diff --git a/base/tps-tomcat/shared/conf/acl.ldif b/base/tps-tomcat/shared/conf/acl.ldif
index 4e1e1a6fbb7cde108fb91d0ef1b093ca994ba982..1e1d8740ca904a8cb5dfb5d9ef05bc750ceb9e0b 100644
--- a/base/tps-tomcat/shared/conf/acl.ldif
+++ b/base/tps-tomcat/shared/conf/acl.ldif
@@ -23,4 +23,5 @@ resourceACLS: certServer.clone.configuration:read,modify:allow (modify,read) gro
 resourceACLS: certServer.tps.account:login,logout:allow (login,logout) user="anybody":Anybody can login and logout
 resourceACLS: certServer.tps.groups:execute:allow (execute) group="TUS Administrators":Admins may execute group operations
 resourceACLS: certServer.tps.users:execute:allow (execute) group="TUS Administrators":Admins may execute user operations
+resourceACLS: certServer.tps.profiles:read,add,modify,approve,remove:allow (read) group="TUS Administrators" || group="TUS Agents" ; allow (add,remove,modify) group="TUS Administrators" ; allow (approve) group="TUS Agents":Admins, agents, and operators can read profiles, but only admins can add, modify, and remove profiles, and only agents can approve profiles.
 resourceACLS: certServer.tps.tokens:read,add,modify,remove:allow (read) group="TUS Administrators" || group="TUS Agents" || group="TUS Operators"; allow (add,remove) group="TUS Administrators" ; allow (modify) group="TUS Agents":Admins, agents, operators can read tokens, but only admins can add and remove tokens, and only agents can modify tokens.
diff --git a/base/tps-tomcat/shared/webapps/tps/WEB-INF/auth.properties b/base/tps-tomcat/shared/webapps/tps/WEB-INF/auth.properties
index f3f2fd99f12f3dceb3e32eba4e1f265a5b9eaa35..4d18d757ab6139ffbf11d8a71ead0991022a2e87 100644
--- a/base/tps-tomcat/shared/webapps/tps/WEB-INF/auth.properties
+++ b/base/tps-tomcat/shared/webapps/tps/WEB-INF/auth.properties
@@ -8,6 +8,11 @@ account.login = certServer.tps.account,login
 account.logout = certServer.tps.account,logout
 admin.users = certServer.tps.users,execute
 admin.groups = certServer.tps.groups,execute
+profiles.read = certServer.tps.profiles,read
+profiles.add = certServer.tps.profiles,add
+profiles.modify = certServer.tps.profiles,modify
+profiles.approve = certServer.tps.profiles,approve
+profiles.remove = certServer.tps.profiles,remove
 tokens.read = certServer.tps.tokens,read
 tokens.add = certServer.tps.tokens,add
 tokens.modify = certServer.tps.tokens,modify
diff --git a/base/tps-tomcat/src/CMakeLists.txt b/base/tps-tomcat/src/CMakeLists.txt
index a0a7ac5052f9a4068ef20f88d939584572be8393..837587f63dc72d97b616a5e559fcbc350750fa73 100644
--- a/base/tps-tomcat/src/CMakeLists.txt
+++ b/base/tps-tomcat/src/CMakeLists.txt
@@ -42,6 +42,13 @@ find_file(JAXRS_API_JAR
         ${RESTEASY_LIB}
 )
 
+find_file(TOMCAT_CATALINA_JAR
+    NAMES
+        catalina.jar
+    PATHS
+        /usr/share/java/tomcat
+)
+
 find_file(PKI_CERTSRV_JAR
     NAMES
         pki-certsrv.jar
@@ -108,7 +115,7 @@ javac(pki-tps-classes
         ${PKI_CERTSRV_JAR} ${PKI_CMS_JAR} ${PKI_CMSCORE_JAR}
         ${PKI_CMSUTIL_JAR} ${PKI_NSUTIL_JAR}
         ${APACHE_COMMONS_LANG_JAR} ${LDAPJDK_JAR} ${JAXRS_API_JAR} ${RESTEASY_ATOM_PROVIDER_JAR}
-        ${JSS_JAR} ${COMMONS_CODEC_JAR} ${SYMKEY_JAR} ${SERVLET_JAR}
+        ${JSS_JAR} ${COMMONS_CODEC_JAR} ${SYMKEY_JAR} ${SERVLET_JAR} ${TOMCAT_CATALINA_JAR}
     OUTPUT_DIR
         ${CMAKE_BINARY_DIR}/classes
     DEPENDS
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSApplication.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSApplication.java
index 194c398a287d2fb9e0fcf32d153c31240272b28b..5ec99bc11b17a5ce1b2d7b3e7faab5873f7f6f13 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSApplication.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSApplication.java
@@ -28,6 +28,7 @@ import org.dogtagpki.server.tps.config.ConfigService;
 import org.dogtagpki.server.tps.connection.ConnectionService;
 import org.dogtagpki.server.tps.logging.ActivityService;
 import org.dogtagpki.server.tps.profile.ProfileMappingService;
+import org.dogtagpki.server.tps.profile.ProfileService;
 import org.dogtagpki.server.tps.token.TokenService;
 
 import com.netscape.certsrv.base.PKIException;
@@ -83,6 +84,7 @@ public class TPSApplication extends Application {
         classes.add(ConnectionService.class);
 
         // profiles
+        classes.add(ProfileService.class);
         classes.add(ProfileMappingService.class);
 
         // selftests
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSubsystem.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSubsystem.java
index 9698cae80399038e438c1347cf78317045696035..e17d37d10ec478f22817359b4eab58a46ab0ceed 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSubsystem.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSubsystem.java
@@ -22,6 +22,7 @@ import org.dogtagpki.server.tps.cert.TPSCertDatabase;
 import org.dogtagpki.server.tps.config.ConfigDatabase;
 import org.dogtagpki.server.tps.connection.ConnectionDatabase;
 import org.dogtagpki.server.tps.logging.ActivityDatabase;
+import org.dogtagpki.server.tps.profile.ProfileDatabase;
 import org.dogtagpki.server.tps.profile.ProfileMappingDatabase;
 import org.dogtagpki.server.tps.token.TokenDatabase;
 import org.mozilla.jss.CryptoManager;
@@ -59,6 +60,7 @@ public class TPSSubsystem implements IAuthority, ISubsystem {
     public TPSCertDatabase certDatabase;
     public ConfigDatabase configDatabase;
     public ConnectionDatabase connectionDatabase;
+    public ProfileDatabase profileDatabase;
     public ProfileMappingDatabase profileMappingDatabase;
     public TokenDatabase tokenDatabase;
 
@@ -92,6 +94,7 @@ public class TPSSubsystem implements IAuthority, ISubsystem {
         configDatabase = new ConfigDatabase();
         authenticatorDatabase = new AuthenticatorDatabase();
         connectionDatabase = new ConnectionDatabase();
+        profileDatabase = new ProfileDatabase();
         profileMappingDatabase = new ProfileMappingDatabase();
     }
 
@@ -160,6 +163,10 @@ public class TPSSubsystem implements IAuthority, ISubsystem {
         return connectionDatabase;
     }
 
+    public ProfileDatabase getProfileDatabase() {
+        return profileDatabase;
+    }
+
     public ProfileMappingDatabase getProfileMappingDatabase() {
         return profileMappingDatabase;
     }
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/authenticator/AuthenticatorDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/authenticator/AuthenticatorDatabase.java
index f7347a497006c44e46ac91d1ecf74ef62276e91a..ce390016a736436a9df8ac3a5e79b46fc96b94ff 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/authenticator/AuthenticatorDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/authenticator/AuthenticatorDatabase.java
@@ -26,6 +26,7 @@ import org.dogtagpki.server.tps.config.ConfigDatabase;
 import org.dogtagpki.server.tps.config.ConfigRecord;
 
 import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
 import com.netscape.cmscore.dbs.Database;
 
 /**
@@ -39,7 +40,7 @@ public class AuthenticatorDatabase extends Database<AuthenticatorRecord> {
         super("Authenticator");
     }
 
-    public AuthenticatorRecord createAuthenticatorRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String authenticatorID) {
+    public AuthenticatorRecord createAuthenticatorRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String authenticatorID) throws EBaseException {
         AuthenticatorRecord authenticatorRecord = new AuthenticatorRecord();
         authenticatorRecord.setID(authenticatorID);
         Map<String, String> properties = configDatabase.getProperties(configRecord, authenticatorID);
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
index 8a3850165e20db3ef727c899f524ae577e11d943..e5a0d440409609a3629375f44293387d32a0629a 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
@@ -43,12 +43,9 @@ import com.netscape.cmscore.dbs.Database;
 public class ConfigDatabase extends Database<ConfigRecord> {
 
     IConfigStore configStore = CMS.getConfigStore();
-    Map<String, String> map;
 
     public ConfigDatabase() throws EBaseException {
         super("Configuration");
-
-        map = configStore.getProperties();
     }
 
     public String createFilter(ConfigRecord record, String key) {
@@ -67,12 +64,12 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         Collection<String> configIDs = new LinkedHashSet<String>();
         configIDs.add("Generals");
 
-        String list = map.get("target.configure.list");
+        String list = configStore.get("target.configure.list");
         if (list != null) {
             configIDs.addAll(Arrays.asList(list.split(",")));
         }
 
-        list = map.get("target.agent_approve.list");
+        list = configStore.get("target.agent_approve.list");
         if (list != null) {
             configIDs.addAll(Arrays.asList(list.split(",")));
         }
@@ -93,13 +90,13 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         ConfigRecord record = new ConfigRecord();
         record.setID(configID);
 
-        String displayName = map.get("target." + configID + ".displayname");
+        String displayName = configStore.get("target." + configID + ".displayname");
         if (displayName == null) {
             throw new ResourceNotFoundException("Configuration " + configID + " not found.");
         }
         record.setDisplayName(displayName);
 
-        String pattern = map.get("target." + configID + ".pattern");
+        String pattern = configStore.get("target." + configID + ".pattern");
         if (pattern == null) {
             throw new ResourceNotFoundException("Missing pattern for " + configID + " configuration.");
         }
@@ -107,7 +104,7 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         // replace \| with |
         record.setPattern(pattern.replace("\\|",  "|"));
 
-        String list = map.get("target." + configID + ".list");
+        String list = configStore.get("target." + configID + ".list");
         if (list != null) {
             record.setKeys(Arrays.asList(list.split(",")));
         }
@@ -126,10 +123,9 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         configStore.put("target." + configID + ".list", StringUtils.join(newRecord.getKeys(), ","));
 
         configStore.commit(true);
-        map = configStore.getProperties();
     }
 
-    public Map<String, String> getProperties(ConfigRecord record, String key) {
+    public Map<String, String> getProperties(ConfigRecord record, String key) throws EBaseException {
 
         CMS.debug("ConfigDatabase.getProperties(\"" + record.getID() + "\")");
 
@@ -137,6 +133,7 @@ public class ConfigDatabase extends Database<ConfigRecord> {
 
         // get properties that match the filter
         String filter = createFilter(record, key);
+        Map<String, String> map = configStore.getProperties();
         for (String name : map.keySet()) {
             if (!name.matches(filter)) continue;
 
@@ -184,8 +181,5 @@ public class ConfigDatabase extends Database<ConfigRecord> {
 
         // save configuration
         configStore.commit(true);
-
-        // reload configuration
-        map = configStore.getProperties();
     }
 }
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/connection/ConnectionDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/connection/ConnectionDatabase.java
index 5ffdbdd6745961eb31300f48b638f641321f4846..b12c6b395c1c5b1d47fb42e8857767b787d9f2bc 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/connection/ConnectionDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/connection/ConnectionDatabase.java
@@ -26,6 +26,7 @@ import org.dogtagpki.server.tps.config.ConfigDatabase;
 import org.dogtagpki.server.tps.config.ConfigRecord;
 
 import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
 import com.netscape.cmscore.dbs.Database;
 
 /**
@@ -39,7 +40,7 @@ public class ConnectionDatabase extends Database<ConnectionRecord> {
         super("Connection");
     }
 
-    public ConnectionRecord createConnectionRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String connectionID) {
+    public ConnectionRecord createConnectionRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String connectionID) throws EBaseException {
         ConnectionRecord connectionRecord = new ConnectionRecord();
         connectionRecord.setID(connectionID);
         Map<String, String> properties = configDatabase.getProperties(configRecord, connectionID);
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileDatabase.java
new file mode 100644
index 0000000000000000000000000000000000000000..646822f67fa0c690907c4739664eeecce72dfa54
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileDatabase.java
@@ -0,0 +1,176 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package org.dogtagpki.server.tps.profile;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+
+import org.apache.commons.lang.StringUtils;
+import org.dogtagpki.server.tps.config.ConfigDatabase;
+import org.dogtagpki.server.tps.config.ConfigRecord;
+
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
+import com.netscape.certsrv.base.IConfigStore;
+import com.netscape.cms.realm.PKIPrincipal;
+import com.netscape.cmscore.dbs.Database;
+
+/**
+ * This class provides access to the profiles in CS.cfg.
+ *
+ * @author Endi S. Dewata
+ */
+public class ProfileDatabase extends Database<ProfileRecord> {
+
+    IConfigStore configStore = CMS.getConfigStore();
+
+    public ProfileDatabase() {
+        super("Profile");
+    }
+
+    public boolean requiresApproval() throws EBaseException {
+        String value = configStore.getString("target.agent_approve.list", "");
+        return Arrays.asList(StringUtils.split(value, ",")).contains("Profiles");
+    }
+
+    public boolean canApprove(Principal principal) {
+        if (!(principal instanceof PKIPrincipal)) {
+            return false;
+        }
+
+        PKIPrincipal pkiPrincipal = (PKIPrincipal)principal;
+        return pkiPrincipal.hasRole("TUS Agents");
+    }
+
+    public ProfileRecord createProfileRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String profileID) throws EBaseException {
+        ProfileRecord profileRecord = new ProfileRecord();
+        profileRecord.setID(profileID);
+
+        String status = configStore.getString("config.Profiles." + profileID + ".state", "Disabled");
+        profileRecord.setStatus(status);
+
+        Map<String, String> properties = configDatabase.getProperties(configRecord, profileID);
+        profileRecord.setProperties(properties);
+
+        return profileRecord;
+    }
+
+    @Override
+    public Collection<ProfileRecord> getRecords() throws Exception {
+
+        Collection<ProfileRecord> result = new ArrayList<ProfileRecord>();
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord("Profiles");
+
+        for (String profileID : configRecord.getKeys()) {
+            ProfileRecord profileRecord = createProfileRecord(configDatabase, configRecord, profileID);
+            result.add(profileRecord);
+        }
+
+        return result;
+    }
+
+    @Override
+    public ProfileRecord getRecord(String profileID) throws Exception {
+
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord("Profiles");
+
+        return createProfileRecord(configDatabase, configRecord, profileID);
+    }
+
+    @Override
+    public void addRecord(String profileID, ProfileRecord profileRecord) throws Exception {
+
+        CMS.debug("ProfileDatabase.addRecord(\"" + profileID + "\")");
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord("Profiles");
+
+        // validate new properties
+        Map<String, String> properties = profileRecord.getProperties();
+        configDatabase.validateProperties(configRecord, profileID, properties);
+
+        // add new profile
+        configRecord.addKey(profileID);
+        configDatabase.updateRecord("Profiles", configRecord);
+
+        // store new properties
+        configDatabase.addProperties(configRecord, profileID, properties);
+
+        // store status
+        String status = profileRecord.getStatus();
+        if (status == null || requiresApproval()) {
+            status = "Disabled";
+        }
+
+        IConfigStore configStore = CMS.getConfigStore();
+        configStore.put("config.Profiles." + profileID + ".state", status);
+        configStore.put("config.Profiles." + profileID + ".timestamp", "" + (System.currentTimeMillis() * 1000));
+
+        configDatabase.commit();
+    }
+
+    @Override
+    public void updateRecord(String profileID, ProfileRecord profileRecord) throws Exception {
+
+        CMS.debug("ProfileDatabase.updateRecord(\"" + profileID + "\")");
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord("Profiles");
+
+        // validate new properties
+        Map<String, String> properties = profileRecord.getProperties();
+        configDatabase.validateProperties(configRecord, profileID, properties);
+
+        // remove old properties
+        configDatabase.removeProperties(configRecord, profileID);
+
+        // add new properties
+        configDatabase.addProperties(configRecord, profileID, properties);
+
+        IConfigStore configStore = CMS.getConfigStore();
+        configStore.put("config.Profiles." + profileID + ".state", profileRecord.getStatus());
+        configStore.put("config.Profiles." + profileID + ".timestamp", "" + (System.currentTimeMillis() * 1000));
+
+        configDatabase.commit();
+    }
+
+    @Override
+    public void removeRecord(String profileID) throws Exception {
+
+        CMS.debug("ProfileDatabase.removeRecord(\"" + profileID + "\")");
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord("Profiles");
+
+        // remove properties
+        configDatabase.removeProperties(configRecord, profileID);
+
+        // remove profile
+        configRecord.removeKey(profileID);
+        configDatabase.updateRecord("Profiles", configRecord);
+
+        IConfigStore configStore = CMS.getConfigStore();
+        configStore.remove("config.Profiles." + profileID + ".state");
+        configStore.remove("config.Profiles." + profileID + ".timestamp");
+
+        configDatabase.commit();
+    }
+}
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileMappingDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileMappingDatabase.java
index a550f222d738560d87e37ff325a1fa4a5305dadd..496cce5b3e454f4bdde9fd481afd706aaea31bc4 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileMappingDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileMappingDatabase.java
@@ -26,6 +26,7 @@ import org.dogtagpki.server.tps.config.ConfigDatabase;
 import org.dogtagpki.server.tps.config.ConfigRecord;
 
 import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
 import com.netscape.cmscore.dbs.Database;
 
 /**
@@ -39,7 +40,7 @@ public class ProfileMappingDatabase extends Database<ProfileMappingRecord> {
         super("Profile Mapping");
     }
 
-    public ProfileMappingRecord createProfileMappingRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String profileMappingID) {
+    public ProfileMappingRecord createProfileMappingRecord(ConfigDatabase configDatabase, ConfigRecord configRecord, String profileMappingID) throws EBaseException {
         ProfileMappingRecord profileMappingRecord = new ProfileMappingRecord();
         profileMappingRecord.setID(profileMappingID);
         Map<String, String> properties = configDatabase.getProperties(configRecord, profileMappingID);
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileRecord.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileRecord.java
new file mode 100644
index 0000000000000000000000000000000000000000..4a35841a31d6008e0a671afa8e398d004ed99cf4
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileRecord.java
@@ -0,0 +1,112 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package org.dogtagpki.server.tps.profile;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.TreeMap;
+
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileRecord {
+
+    String id;
+    String status;
+    Map<String, String> properties = new TreeMap<String, String>();
+
+    public String getID() {
+        return id;
+    }
+
+    public void setID(String id) {
+        this.id = id;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties.clear();
+        this.properties.putAll(properties);
+    }
+
+    public Collection<String> getPropertyNames() {
+        return properties.keySet();
+    }
+
+    public String getProperty(String name) {
+        return properties.get(name);
+    }
+
+    public void setProperty(String name, String value) {
+        properties.put(name, value);
+    }
+
+    public String removeProperty(String name) {
+        return properties.remove(name);
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((id == null) ? 0 : id.hashCode());
+        result = prime * result + ((properties == null) ? 0 : properties.hashCode());
+        result = prime * result + ((status == null) ? 0 : status.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        ProfileRecord other = (ProfileRecord) obj;
+        if (id == null) {
+            if (other.id != null)
+                return false;
+        } else if (!id.equals(other.id))
+            return false;
+        if (properties == null) {
+            if (other.properties != null)
+                return false;
+        } else if (!properties.equals(other.properties))
+            return false;
+        if (status == null) {
+            if (other.status != null)
+                return false;
+        } else if (!status.equals(other.status))
+            return false;
+        return true;
+    }
+}
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileService.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileService.java
new file mode 100644
index 0000000000000000000000000000000000000000..6e52aeec6fe6e19cc8bb219b429a183c73d5a4c2
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/profile/ProfileService.java
@@ -0,0 +1,325 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package org.dogtagpki.server.tps.profile;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.security.Principal;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Request;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.dogtagpki.server.tps.TPSSubsystem;
+import org.jboss.resteasy.plugins.providers.atom.Link;
+
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.BadRequestException;
+import com.netscape.certsrv.base.ForbiddenException;
+import com.netscape.certsrv.base.PKIException;
+import com.netscape.certsrv.tps.profile.ProfileCollection;
+import com.netscape.certsrv.tps.profile.ProfileData;
+import com.netscape.certsrv.tps.profile.ProfileResource;
+import com.netscape.cms.servlet.base.PKIService;
+
+/**
+ * @author Endi S. Dewata
+ */
+public class ProfileService extends PKIService implements ProfileResource {
+
+    @Context
+    private UriInfo uriInfo;
+
+    @Context
+    private HttpHeaders headers;
+
+    @Context
+    private Request request;
+
+    @Context
+    private HttpServletRequest servletRequest;
+
+    public final static int DEFAULT_SIZE = 20;
+
+    public ProfileService() {
+        CMS.debug("ProfileService.<init>()");
+    }
+
+    public ProfileData createProfileData(ProfileRecord profileRecord) throws UnsupportedEncodingException {
+
+        String profileID = profileRecord.getID();
+
+        ProfileData profileData = new ProfileData();
+        profileData.setID(profileID);
+        profileData.setStatus(profileRecord.getStatus());
+        profileData.setProperties(profileRecord.getProperties());
+
+        profileID = URLEncoder.encode(profileID, "UTF-8");
+        URI uri = uriInfo.getBaseUriBuilder().path(ProfileResource.class).path("{profileID}").build(profileID);
+        profileData.setLink(new Link("self", uri));
+
+        return profileData;
+    }
+
+    public ProfileRecord createProfileRecord(ProfileData profileData) {
+
+        ProfileRecord profileRecord = new ProfileRecord();
+        profileRecord.setID(profileData.getID());
+        profileRecord.setStatus(profileData.getStatus());
+        profileRecord.setProperties(profileData.getProperties());
+
+        return profileRecord;
+    }
+
+    @Override
+    public ProfileCollection findProfiles(Integer start, Integer size) {
+
+        CMS.debug("ProfileService.findProfiles()");
+
+        try {
+            start = start == null ? 0 : start;
+            size = size == null ? DEFAULT_SIZE : size;
+
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            Iterator<ProfileRecord> profiles = database.getRecords().iterator();
+
+            ProfileCollection response = new ProfileCollection();
+
+            int i = 0;
+
+            // skip to the start of the page
+            for ( ; i<start && profiles.hasNext(); i++) profiles.next();
+
+            // return entries up to the page size
+            for ( ; i<start+size && profiles.hasNext(); i++) {
+                response.addEntry(createProfileData(profiles.next()));
+            }
+
+            // count the total entries
+            for ( ; profiles.hasNext(); i++) profiles.next();
+
+            if (start > 0) {
+                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
+                response.addLink(new Link("prev", uri));
+            }
+
+            if (start+size < i) {
+                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
+                response.addLink(new Link("next", uri));
+            }
+
+            return response;
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+
+    @Override
+    public ProfileData getProfile(String profileID) {
+
+        CMS.debug("ProfileService.getProfile(\"" + profileID + "\")");
+
+        try {
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            return createProfileData(database.getRecord(profileID));
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+
+    @Override
+    public Response addProfile(ProfileData profileData) {
+
+        CMS.debug("ProfileService.addProfile(\"" + profileData.getID() + "\")");
+
+        try {
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            database.addRecord(profileData.getID(), createProfileRecord(profileData));
+
+            profileData = createProfileData(database.getRecord(profileData.getID()));
+
+            return Response
+                    .created(profileData.getLink().getHref())
+                    .entity(profileData)
+                    .type(MediaType.APPLICATION_XML)
+                    .build();
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+
+    @Override
+    public Response updateProfile(String profileID, ProfileData profileData) {
+
+        CMS.debug("ProfileService.updateProfile(\"" + profileID + "\")");
+
+        try {
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            ProfileRecord record = database.getRecord(profileID);
+            String status = record.getStatus();
+
+            if (!"Disabled".equals(status)) {
+                throw new ForbiddenException("Unable to update profile " + profileID);
+            }
+
+            status = profileData.getStatus();
+            if ("Enabled".equals(status)) {
+                Principal principal = servletRequest.getUserPrincipal();
+                if (database.requiresApproval() && !database.canApprove(principal)) {
+                    status = "Pending_Approval";
+                }
+                record.setStatus(status);;
+
+            } else {
+                throw new ForbiddenException("Invalid profile status: " + status);
+            }
+
+            record.setProperties(profileData.getProperties());
+            database.updateRecord(profileID, record);
+
+            profileData = createProfileData(database.getRecord(profileID));
+
+            return Response
+                    .ok(profileData)
+                    .type(MediaType.APPLICATION_XML)
+                    .build();
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+
+    @Override
+    public Response changeProfileStatus(String profileID, String action) {
+
+        CMS.debug("ProfileService.changeProfileStatus(\"" + profileID + "\")");
+
+        try {
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            ProfileRecord record = database.getRecord(profileID);
+            String status = record.getStatus();
+
+            if ("Disabled".equals(status)) {
+                if ("enable".equals(action)) {
+                    status = "Enabled";
+                } else {
+                    throw new BadRequestException("Invalid action: " + action);
+                }
+
+            } else if ("Enabled".equals(status)) {
+                if ("disable".equals(action)) {
+                    status = "Disabled";
+                } else {
+                    throw new BadRequestException("Invalid action: " + action);
+                }
+
+            } else if ("Pending_Approval".equals(status)) {
+                if ("approve".equals(action)) {
+                    status = "Enabled";
+                } else if ("reject".equals(action)) {
+                    status = "Disabled";
+                } else {
+                    throw new BadRequestException("Invalid action: " + action);
+                }
+
+            } else {
+                throw new PKIException("Invalid profile status: " + status);
+            }
+
+            record.setStatus(status);
+            database.updateRecord(profileID, record);
+
+            ProfileData profileData = createProfileData(database.getRecord(profileID));
+
+            return Response
+                    .ok(profileData)
+                    .type(MediaType.APPLICATION_XML)
+                    .build();
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+
+    @Override
+    public void removeProfile(String profileID) {
+
+        CMS.debug("ProfileService.removeProfile(\"" + profileID + "\")");
+
+        try {
+            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+            ProfileDatabase database = subsystem.getProfileDatabase();
+
+            ProfileRecord record = database.getRecord(profileID);
+            String status = record.getStatus();
+
+            if (!"Disabled".equals(status)) {
+                throw new ForbiddenException("Unable to delete profile " + profileID);
+            }
+
+            database.removeRecord(profileID);
+
+        } catch (PKIException e) {
+            throw e;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new PKIException(e.getMessage());
+        }
+    }
+}
-- 
1.8.1.4

