Skip to content
Snippets Groups Projects
Commit cb9a66ff authored by Dustin Jenkins's avatar Dustin Jenkins
Browse files

Story 1734: Added UserRequestReader test and implementation for JSON.

parent 7da562b5
No related branches found
No related tags found
No related merge requests found
Showing
with 607 additions and 267 deletions
...@@ -67,9 +67,8 @@ ...@@ -67,9 +67,8 @@
************************************************************************ ************************************************************************
--> -->
<!DOCTYPE project>
<project name="cadcAccessControl-Server" default="build" basedir="."> <project name="cadcAccessControl-Server" default="build" basedir=".">
<property environment="env"/> <property environment="env"/>
<property file="local.build.properties"/> <property file="local.build.properties"/>
...@@ -102,7 +101,8 @@ ...@@ -102,7 +101,8 @@
<property name="unboundid" value="${ext.lib}/unboundid-ldapsdk-se.jar"/> <property name="unboundid" value="${ext.lib}/unboundid-ldapsdk-se.jar"/>
<property name="xerces" value="${ext.lib}/xerces.jar"/> <property name="xerces" value="${ext.lib}/xerces.jar"/>
<property name="jars" value="${javacsv}:${jdom2}:${log4j}:${servlet}:${unboundid}:${xerces}:${cadcAccessControl}:${cadcLog}:${cadcRegistry}:${cadcUtil}:${cadcUWS}:${wsUtil}" /> <property name="jars"
value="${javacsv}:${jdom2}:${log4j}:${servlet}:${unboundid}:${xerces}:${cadcAccessControl}:${cadcLog}:${cadcRegistry}:${cadcUtil}:${cadcUWS}:${wsUtil}"/>
<target name="build" depends="compile"> <target name="build" depends="compile">
<jar jarfile="${build}/lib/${project}.jar" <jar jarfile="${build}/lib/${project}.jar"
...@@ -121,29 +121,16 @@ ...@@ -121,29 +121,16 @@
<property name="objenesis" value="${ext.dev}/objenesis.jar"/> <property name="objenesis" value="${ext.dev}/objenesis.jar"/>
<property name="asm" value="${ext.dev}/asm.jar"/> <property name="asm" value="${ext.dev}/asm.jar"/>
<property name="testingJars" value="${jars}:${json}:${easyMock}:${junit}:${xmlunit}:${cglib}:${asm}:${objenesis}" /> <property name="testingJars"
value="${jars}:${json}:${easyMock}:${junit}:${xmlunit}:${cglib}:${asm}:${objenesis}"/>
<target name="resources">
<copy todir="${build}/class">
<fileset dir="config">
<include name="**.properties" />
</fileset>
</copy>
</target>
<target name="test" depends="compile,compile-test,resources"> <target name="setup-test">
<echo message="Running test suite..." /> <echo>******************</echo>
<junit printsummary="yes" haltonfailure="yes" fork="yes"> <echo>******************</echo>
<classpath> <echo>Don't forget to set the ca.nrc.cadc.util.PropertiesReader.dir system property first!</echo>
<pathelement path="${build}/class"/> <echo>e.g. ant -Dca.nrc.cadc.util.PropertiesReader.dir=test clean build test</echo>
<pathelement path="${build}/test/class"/> <echo>******************</echo>
<pathelement path="${testingJars}"/> <echo>******************</echo>
</classpath>
<test name="ca.nrc.cadc.ac.server.ldap.LdapUserDAOTest" />
<!--<test name="ca.nrc.cadc.ac.server.web.users.UserActionFactoryTest" />-->
<!--<test name="ca.nrc.cadc.ac.server.web.users.UsersActionTest" />-->
<formatter type="plain" usefile="false" />
</junit>
</target> </target>
</project> </project>
...@@ -140,9 +140,10 @@ public class PluginFactory ...@@ -140,9 +140,10 @@ public class PluginFactory
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Principal> UserPersistence<T> getUserPersistence() public <T extends Principal> UserPersistence<T> getUserPersistence()
{ {
UserPersistence<T> ret = null; UserPersistence ret = null;
String name = UserPersistence.class.getName(); String name = UserPersistence.class.getName();
String cname = config.getProperty(name); String cname = config.getProperty(name);
if (cname == null) if (cname == null)
{ {
ret = new LdapUserPersistence<T>(); ret = new LdapUserPersistence<T>();
...@@ -152,7 +153,7 @@ public class PluginFactory ...@@ -152,7 +153,7 @@ public class PluginFactory
try try
{ {
Class<?> c = Class.forName(cname); Class<?> c = Class.forName(cname);
ret = (UserPersistence<T>) c.newInstance(); ret = (UserPersistence) c.newInstance();
} }
catch (Exception ex) catch (Exception ex)
{ {
......
...@@ -79,7 +79,7 @@ import ca.nrc.cadc.net.TransientException; ...@@ -79,7 +79,7 @@ import ca.nrc.cadc.net.TransientException;
import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.DN;
public abstract interface UserPersistence<T extends Principal> public interface UserPersistence<T extends Principal>
{ {
/** /**
* Get all user names. * Get all user names.
...@@ -88,7 +88,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -88,7 +88,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public Collection<String> getUserNames() Collection<String> getUserNames()
throws TransientException, AccessControlException; throws TransientException, AccessControlException;
/** /**
...@@ -101,7 +101,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -101,7 +101,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract User<T> addUser(UserRequest<T> user) User<T> addUser(UserRequest<T> user)
throws TransientException, AccessControlException; throws TransientException, AccessControlException;
/** /**
...@@ -115,7 +115,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -115,7 +115,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract User<T> getUser(T userID) User<T> getUser(T userID)
throws UserNotFoundException, TransientException, throws UserNotFoundException, TransientException,
AccessControlException; AccessControlException;
...@@ -130,7 +130,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -130,7 +130,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract User<T> modifyUser(User<T> user) User<T> modifyUser(User<T> user)
throws UserNotFoundException, TransientException, throws UserNotFoundException, TransientException,
AccessControlException; AccessControlException;
...@@ -143,7 +143,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -143,7 +143,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract void deleteUser(T userID) void deleteUser(T userID)
throws UserNotFoundException, TransientException, throws UserNotFoundException, TransientException,
AccessControlException; AccessControlException;
...@@ -160,7 +160,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -160,7 +160,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract Collection<DN> getUserGroups(T userID, boolean isAdmin) Collection<DN> getUserGroups(T userID, boolean isAdmin)
throws UserNotFoundException, TransientException, throws UserNotFoundException, TransientException,
AccessControlException; AccessControlException;
...@@ -176,7 +176,7 @@ public abstract interface UserPersistence<T extends Principal> ...@@ -176,7 +176,7 @@ public abstract interface UserPersistence<T extends Principal>
* @throws TransientException If an temporary, unexpected problem occurred. * @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted. * @throws AccessControlException If the operation is not permitted.
*/ */
public abstract boolean isMember(T userID, String groupID) boolean isMember(T userID, String groupID)
throws UserNotFoundException, TransientException, throws UserNotFoundException, TransientException,
AccessControlException; AccessControlException;
} }
...@@ -77,7 +77,7 @@ import ca.nrc.cadc.ac.xml.UserWriter; ...@@ -77,7 +77,7 @@ import ca.nrc.cadc.ac.xml.UserWriter;
import java.security.Principal; import java.security.Principal;
public class CreateUserAction extends UsersAction public class CreateUserAction<T extends Principal> extends UsersAction
{ {
private final InputStream inputStream; private final InputStream inputStream;
...@@ -90,11 +90,10 @@ public class CreateUserAction extends UsersAction ...@@ -90,11 +90,10 @@ public class CreateUserAction extends UsersAction
public Object run() public Object run()
throws Exception throws Exception
{ {
UserPersistence userPersistence = getUserPersistence(); UserPersistence<Principal> userPersistence = getUserPersistence();
UserRequest userRequest = UserRequestReader.read(this.inputStream); UserRequest<Principal> userRequest = readUserRequest(this.inputStream);
User<? extends Principal> newUser = userPersistence.addUser(userRequest); User<Principal> newUser = userPersistence.addUser(userRequest);
this.response.setContentType(acceptedContentType); writeUser(newUser);
writeUser(newUser, this.response.getWriter());
logUserInfo(newUser.getUserID().getName()); logUserInfo(newUser.getUserID().getName());
return null; return null;
} }
......
...@@ -69,10 +69,10 @@ ...@@ -69,10 +69,10 @@
import ca.nrc.cadc.ac.User; import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.UserPersistence; import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.ac.xml.UserWriter;
import java.security.Principal; import java.security.Principal;
public class GetUserAction extends UsersAction public class GetUserAction extends UsersAction
{ {
private final Principal userID; private final Principal userID;
...@@ -83,13 +83,11 @@ public class GetUserAction extends UsersAction ...@@ -83,13 +83,11 @@ public class GetUserAction extends UsersAction
this.userID = userID; this.userID = userID;
} }
public Object run() public Object run() throws Exception
throws Exception
{ {
UserPersistence userPersistence = getUserPersistence(); UserPersistence<Principal> userPersistence = getUserPersistence();
User<? extends Principal> user = userPersistence.getUser(userID); User<Principal> user = userPersistence.getUser(userID);
this.response.setContentType(acceptedContentType); writeUser(user);
writeUser(user, this.response.getWriter());
return null; return null;
} }
......
...@@ -69,7 +69,7 @@ ...@@ -69,7 +69,7 @@
package ca.nrc.cadc.ac.server.web.users; package ca.nrc.cadc.ac.server.web.users;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.InputStream;
import java.io.Writer; import java.io.Writer;
import java.security.AccessControlException; import java.security.AccessControlException;
import java.security.Principal; import java.security.Principal;
...@@ -80,6 +80,7 @@ import javax.security.auth.Subject; ...@@ -80,6 +80,7 @@ import javax.security.auth.Subject;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import ca.nrc.cadc.ac.User; import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserRequest;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.UserNotFoundException; import ca.nrc.cadc.ac.UserNotFoundException;
...@@ -200,6 +201,7 @@ public abstract class UsersAction ...@@ -200,6 +201,7 @@ public abstract class UsersAction
} }
} }
@SuppressWarnings("unchecked")
<T extends Principal> UserPersistence<T> getUserPersistence() <T extends Principal> UserPersistence<T> getUserPersistence()
{ {
PluginFactory pluginFactory = new PluginFactory(); PluginFactory pluginFactory = new PluginFactory();
...@@ -216,10 +218,80 @@ public abstract class UsersAction ...@@ -216,10 +218,80 @@ public abstract class UsersAction
this.acceptedContentType = acceptedContentType; this.acceptedContentType = acceptedContentType;
} }
protected final <T extends Principal> void writeUser(final User<T> user, /**
final Writer writer) * Read a user request (User pending approval) from the HTTP Request's
* stream.
*
* @param inputStream The Input Stream to read from.
* @return User Request instance.
* @throws IOException Any reading errors.
*/
protected final UserRequest<Principal> readUserRequest(
final InputStream inputStream) throws IOException
{
final UserRequest<Principal> userRequest;
if (acceptedContentType.equals(DEFAULT_CONTENT_TYPE))
{
userRequest = ca.nrc.cadc.ac.xml.UserRequestReader.read(inputStream);
}
else if (acceptedContentType.equals(JSON_CONTENT_TYPE))
{
userRequest =
ca.nrc.cadc.ac.json.UserRequestReader.read(inputStream);
}
else
{
// Should never happen.
throw new IOException("Unknown content being asked for: "
+ acceptedContentType);
}
return userRequest;
}
/**
* Read a user from the HTTP Request's stream.
*
* @param inputStream The Input Stream to read from.
* @return User instance.
* @throws IOException Any reading error(s)
*/
protected final User<Principal> readUser(
final InputStream inputStream) throws IOException
{
final User<Principal> user;
if (acceptedContentType.equals(DEFAULT_CONTENT_TYPE))
{
user = ca.nrc.cadc.ac.xml.UserReader.read(inputStream);
}
else if (acceptedContentType.equals(JSON_CONTENT_TYPE))
{
user = ca.nrc.cadc.ac.json.UserReader.read(inputStream);
}
else
{
// Should never happen.
throw new IOException("Unknown content being asked for: "
+ acceptedContentType);
}
return user;
}
/**
* Write a user to the response's writer.
*
* @param user The user object to marshall and write out.
* @throws IOException Any writing errors.
*/
protected final <T extends Principal> void writeUser(final User<T> user)
throws IOException throws IOException
{ {
response.setContentType(acceptedContentType);
final Writer writer = response.getWriter();
if (acceptedContentType.equals(DEFAULT_CONTENT_TYPE)) if (acceptedContentType.equals(DEFAULT_CONTENT_TYPE))
{ {
ca.nrc.cadc.ac.xml.UserWriter.write(user, writer); ca.nrc.cadc.ac.xml.UserWriter.write(user, writer);
......
...@@ -75,25 +75,20 @@ import ca.nrc.cadc.auth.HttpPrincipal; ...@@ -75,25 +75,20 @@ import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.auth.NumericPrincipal; import ca.nrc.cadc.auth.NumericPrincipal;
import ca.nrc.cadc.auth.OpenIdPrincipal; import ca.nrc.cadc.auth.OpenIdPrincipal;
import ca.nrc.cadc.util.StringUtil; import ca.nrc.cadc.util.StringUtil;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.security.Principal; import java.security.Principal;
import javax.security.auth.x500.X500Principal; import javax.security.auth.x500.X500Principal;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.server.web.AddGroupMemberAction;
import ca.nrc.cadc.ac.server.web.AddUserMemberAction;
import ca.nrc.cadc.ac.server.web.DeleteGroupAction;
import ca.nrc.cadc.ac.server.web.GetGroupAction;
import ca.nrc.cadc.ac.server.web.ModifyGroupAction;
import ca.nrc.cadc.ac.server.web.RemoveGroupMemberAction;
import ca.nrc.cadc.ac.server.web.RemoveUserMemberAction;
import ca.nrc.cadc.util.StringUtil;
public class UsersActionFactory public class UsersActionFactory
{ {
private static final Logger log = Logger.getLogger(UsersActionFactory.class); private static final Logger log = Logger
.getLogger(UsersActionFactory.class);
static UsersAction getUsersAction(HttpServletRequest request, UserLogInfo logInfo) static UsersAction getUsersAction(HttpServletRequest request, UserLogInfo logInfo)
throws IOException throws IOException
...@@ -133,7 +128,8 @@ public class UsersActionFactory ...@@ -133,7 +128,8 @@ public class UsersActionFactory
} }
else if (method.equals("PUT")) else if (method.equals("PUT"))
{ {
action = new CreateUserAction(logInfo, request.getInputStream()); action = new CreateUserAction(logInfo, request
.getInputStream());
} }
} }
...@@ -151,7 +147,8 @@ public class UsersActionFactory ...@@ -151,7 +147,8 @@ public class UsersActionFactory
} }
else if (method.equals("POST")) else if (method.equals("POST"))
{ {
final URL requestURL = new URL(request.getRequestURL().toString()); final URL requestURL = new URL(request.getRequestURL()
.toString());
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(requestURL.getProtocol()); sb.append(requestURL.getProtocol());
sb.append("://"); sb.append("://");
...@@ -166,7 +163,8 @@ public class UsersActionFactory ...@@ -166,7 +163,8 @@ public class UsersActionFactory
sb.append("/"); sb.append("/");
sb.append(path); sb.append(path);
action = new ModifyUserAction(logInfo, user.getUserID(), sb.toString(), action = new ModifyUserAction(logInfo, user.getUserID(), sb
.toString(),
request.getInputStream()); request.getInputStream());
} }
} }
...@@ -180,8 +178,10 @@ public class UsersActionFactory ...@@ -180,8 +178,10 @@ public class UsersActionFactory
throw new IllegalArgumentException(error); throw new IllegalArgumentException(error);
} }
private static User<? extends Principal> getUser(final String userName, final String idType, private static User<? extends Principal> getUser(final String userName,
final String method, final String path) final String idType,
final String method,
final String path)
{ {
if (idType == null || idType.isEmpty()) if (idType == null || idType.isEmpty())
{ {
...@@ -189,23 +189,24 @@ public class UsersActionFactory ...@@ -189,23 +189,24 @@ public class UsersActionFactory
} }
else if (idType.equals(IdentityType.USERNAME.getValue())) else if (idType.equals(IdentityType.USERNAME.getValue()))
{ {
return new User(new HttpPrincipal(userName)); return new User<HttpPrincipal>(new HttpPrincipal(userName));
} }
else if (idType.equals(IdentityType.X500.getValue())) else if (idType.equals(IdentityType.X500.getValue()))
{ {
return new User(new X500Principal(userName)); return new User<X500Principal>(new X500Principal(userName));
} }
else if (idType.equals(IdentityType.UID.getValue())) else if (idType.equals(IdentityType.UID.getValue()))
{ {
return new User(new NumericPrincipal(Long.parseLong(userName))); return new User<NumericPrincipal>(new NumericPrincipal(
Long.parseLong(userName)));
} }
else if (idType.equals(IdentityType.OPENID.getValue())) else if (idType.equals(IdentityType.OPENID.getValue()))
{ {
return new User(new OpenIdPrincipal(userName)); return new User<OpenIdPrincipal>(new OpenIdPrincipal(userName));
} }
else if (idType.equals(IdentityType.COOKIE.getValue())) else if (idType.equals(IdentityType.COOKIE.getValue()))
{ {
return new User(new CookiePrincipal(userName)); return new User<CookiePrincipal>(new CookiePrincipal(userName));
} }
else else
{ {
......
...@@ -3,6 +3,7 @@ server = proc5-03.cadc.dao.nrc.ca ...@@ -3,6 +3,7 @@ server = proc5-03.cadc.dao.nrc.ca
port = 636 port = 636
proxyUser = webproxy proxyUser = webproxy
usersDn = ou=Users,ou=ds,dc=canfar,dc=net usersDn = ou=Users,ou=ds,dc=canfar,dc=net
userRequestsDN = ou=UserRequests,ou=ds,dc=canfar,dc=net
newUsersDn = ou=NewUsers,ou=ds,dc=canfar,dc=net newUsersDn = ou=NewUsers,ou=ds,dc=canfar,dc=net
groupsDn = ou=Groups,ou=ds,dc=canfar,dc=net groupsDn = ou=Groups,ou=ds,dc=canfar,dc=net
adminGroupsDn = ou=adminGroups,ou=ds,dc=canfar,dc=net adminGroupsDn = ou=adminGroups,ou=ds,dc=canfar,dc=net
\ No newline at end of file
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2015. (c) 2015.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web.users;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.auth.HttpPrincipal;
import org.junit.Test;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import static org.easymock.EasyMock.*;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
public class GetUserActionTest
{
@Test
public void writeUserXML() throws Exception
{
final HttpServletResponse mockResponse =
createMock(HttpServletResponse.class);
final UserPersistence<HttpPrincipal> mockUserPersistence =
createMock(UserPersistence.class);
final HttpPrincipal userID = new HttpPrincipal("CADCtest");
final GetUserAction testSubject = new GetUserAction(null, userID)
{
@Override
UserPersistence<HttpPrincipal> getUserPersistence()
{
return mockUserPersistence;
}
};
final User<HttpPrincipal> user = new User<HttpPrincipal>(userID);
final Writer writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
expect(mockUserPersistence.getUser(userID)).andReturn(user).once();
expect(mockResponse.getWriter()).andReturn(printWriter).once();
mockResponse.setContentType("text/xml");
expectLastCall().once();
replay(mockResponse, mockUserPersistence);
testSubject.doAction(null, mockResponse);
assertEquals("Wrong XML output.",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<user>\r\n" +
" <userID>\r\n" +
" <identity type=\"HTTP\">CADCtest</identity>\r\n" +
" </userID>\r\n" +
"</user>\r\n", writer.toString());
verify(mockResponse, mockUserPersistence);
}
@Test
public void writeUserJSON() throws Exception
{
final HttpServletResponse mockResponse =
createMock(HttpServletResponse.class);
final UserPersistence<HttpPrincipal> mockUserPersistence =
createMock(UserPersistence.class);
final HttpPrincipal userID = new HttpPrincipal("CADCtest");
final GetUserAction testSubject = new GetUserAction(null, userID)
{
@Override
UserPersistence<HttpPrincipal> getUserPersistence()
{
return mockUserPersistence;
}
};
testSubject.setAcceptedContentType(UsersAction.JSON_CONTENT_TYPE);
final User<HttpPrincipal> user = new User<HttpPrincipal>(userID);
final Writer writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
expect(mockUserPersistence.getUser(userID)).andReturn(user).once();
expect(mockResponse.getWriter()).andReturn(printWriter).once();
mockResponse.setContentType("application/json");
expectLastCall().once();
replay(mockResponse, mockUserPersistence);
testSubject.doAction(null, mockResponse);
assertEquals("Wrong JSON output.",
"{\"user\":{\"userID\":{\"identity\":{\"name\":\"CADCtest\",\"type\":\"HTTP\"}}}}",
writer.toString());
verify(mockResponse, mockUserPersistence);
}
}
...@@ -70,18 +70,22 @@ package ca.nrc.cadc.ac.server.web.users; ...@@ -70,18 +70,22 @@ package ca.nrc.cadc.ac.server.web.users;
import ca.nrc.cadc.ac.User; import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserNotFoundException; import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.auth.HttpPrincipal; import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.net.TransientException; import ca.nrc.cadc.net.TransientException;
import ca.nrc.cadc.util.Log4jInit; import ca.nrc.cadc.util.Log4jInit;
import java.io.*; import java.io.*;
import java.security.AccessControlException; import java.security.AccessControlException;
import java.security.Principal;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Level; import org.apache.log4j.Level;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.Assert.*;
...@@ -99,59 +103,6 @@ public class UsersActionTest ...@@ -99,59 +103,6 @@ public class UsersActionTest
Log4jInit.setLevel("ca.nrc.cadc.ac", Level.INFO); Log4jInit.setLevel("ca.nrc.cadc.ac", Level.INFO);
} }
@Test
public void writeUserXML() throws Exception
{
final UsersAction usersAction = new UsersAction(null)
{
@Override
public Object run() throws Exception
{
// Do nothing.
return null;
}
};
final User<HttpPrincipal> user =
new User<HttpPrincipal>(new HttpPrincipal("CADCtest"));
final Writer writer = new StringWriter();
usersAction.writeUser(user, writer);
assertEquals("Wrong XML output.",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<user>\r\n" +
" <userID>\r\n" +
" <identity type=\"HTTP\">CADCtest</identity>\r\n" +
" </userID>\r\n" +
"</user>\r\n", writer.toString());
}
@Test
public void writeUserJSON() throws Exception
{
final UsersAction usersAction = new UsersAction(null)
{
@Override
public Object run() throws Exception
{
// Do nothing.
return null;
}
};
final User<HttpPrincipal> user =
new User<HttpPrincipal>(new HttpPrincipal("CADCtest"));
final Writer writer = new StringWriter();
usersAction.setAcceptedContentType(UsersAction.JSON_CONTENT_TYPE);
usersAction.writeUser(user, writer);
assertEquals("Wrong JSON output.",
"{\"user\":{\"userID\":{\"identity\":{\"name\":\"CADCtest\",\"type\":\"HTTP\"}}}}",
writer.toString());
}
@Test @Test
public void testDoActionAccessControlException() throws Exception public void testDoActionAccessControlException() throws Exception
{ {
...@@ -191,70 +142,53 @@ public class UsersActionTest ...@@ -191,70 +142,53 @@ public class UsersActionTest
@Test @Test
public void testDoActionTransientException() throws Exception public void testDoActionTransientException() throws Exception
{ {
try HttpServletResponse response = createMock(HttpServletResponse.class);
{ expect(response.isCommitted()).andReturn(Boolean.FALSE);
HttpServletResponse response = EasyMock
.createMock(HttpServletResponse.class);
EasyMock.expect(response.isCommitted()).andReturn(Boolean.FALSE);
response.setContentType("text/plain"); response.setContentType("text/plain");
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.expect(response.getWriter()) expect(response.getWriter())
.andReturn(new PrintWriter(new StringWriter())); .andReturn(new PrintWriter(new StringWriter())).once();
EasyMock.expectLastCall().once();
response.setStatus(503); response.setStatus(503);
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.replay(response); replay(response);
UserLogInfo logInfo = EasyMock.createMock(UserLogInfo.class); UserLogInfo logInfo = createMock(UserLogInfo.class);
logInfo.setSuccess(false); logInfo.setSuccess(false);
EasyMock.expectLastCall().once(); expectLastCall().once();
logInfo.setMessage("Internal Transient Error: foo"); logInfo.setMessage("Internal Transient Error: foo");
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.replay(logInfo); replay(logInfo);
UsersActionImpl action = new UsersActionImpl(logInfo); UsersActionImpl action = new UsersActionImpl(logInfo);
action.setException(new TransientException("foo")); action.setException(new TransientException("foo"));
action.doAction(null, response); action.doAction(null, response);
} }
catch (Throwable t)
{
log.error(t.getMessage(), t);
fail("unexpected error: " + t.getMessage());
}
}
private void testDoAction(String message, int responseCode, Exception e) private void testDoAction(String message, int responseCode, Exception e)
throws Exception throws Exception
{ {
try HttpServletResponse response =
{ createMock(HttpServletResponse.class);
HttpServletResponse response = EasyMock expect(response.isCommitted()).andReturn(Boolean.FALSE);
.createMock(HttpServletResponse.class);
EasyMock.expect(response.isCommitted()).andReturn(Boolean.FALSE);
response.setContentType("text/plain"); response.setContentType("text/plain");
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.expect(response.getWriter()) expect(response.getWriter())
.andReturn(new PrintWriter(new StringWriter())); .andReturn(new PrintWriter(new StringWriter())).once();
EasyMock.expectLastCall().once();
response.setStatus(responseCode); response.setStatus(responseCode);
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.replay(response); replay(response);
UserLogInfo logInfo = EasyMock.createMock(UserLogInfo.class); UserLogInfo logInfo = createMock(UserLogInfo.class);
logInfo.setMessage(message); logInfo.setMessage(message);
EasyMock.expectLastCall().once(); expectLastCall().once();
EasyMock.replay(logInfo); replay(logInfo);
UsersActionImpl action = new UsersActionImpl(logInfo); UsersActionImpl action = new UsersActionImpl(logInfo);
action.setException(e); action.setException(e);
action.doAction(null, response); action.doAction(null, response);
} }
catch (Throwable t)
{
log.error(t.getMessage(), t);
fail("unexpected error: " + t.getMessage());
}
}
public class UsersActionImpl extends UsersAction public class UsersActionImpl extends UsersAction
{ {
......
...@@ -100,4 +100,27 @@ public class UserRequest<T extends Principal> ...@@ -100,4 +100,27 @@ public class UserRequest<T extends Principal>
return this.password; return this.password;
} }
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
UserRequest<?> that = (UserRequest<?>) o;
return user.equals(that.user);
}
@Override
public int hashCode()
{
return user.hashCode();
}
} }
...@@ -91,8 +91,8 @@ public class UserReader ...@@ -91,8 +91,8 @@ public class UserReader
* @throws ReaderException * @throws ReaderException
* @throws IOException * @throws IOException
*/ */
public static User<? extends Principal> read(InputStream in) public static User<Principal> read(InputStream in)
throws ReaderException, IOException throws IOException
{ {
if (in == null) if (in == null)
{ {
...@@ -113,8 +113,8 @@ public class UserReader ...@@ -113,8 +113,8 @@ public class UserReader
* @throws ReaderException * @throws ReaderException
* @throws IOException * @throws IOException
*/ */
public static User<? extends Principal> read(Reader reader) public static User<Principal> read(Reader reader)
throws ReaderException, IOException throws IOException
{ {
if (reader == null) if (reader == null)
{ {
...@@ -135,8 +135,8 @@ public class UserReader ...@@ -135,8 +135,8 @@ public class UserReader
* @throws ReaderException * @throws ReaderException
* @throws IOException * @throws IOException
*/ */
public static User<? extends Principal> read(String json) public static User<Principal> read(String json)
throws ReaderException, IOException throws IOException
{ {
if (json == null || json.isEmpty()) if (json == null || json.isEmpty())
{ {
...@@ -156,7 +156,7 @@ public class UserReader ...@@ -156,7 +156,7 @@ public class UserReader
} }
} }
protected static User<? extends Principal> parseUser(JSONObject userObject) protected static User<Principal> parseUser(JSONObject userObject)
throws ReaderException, JSONException throws ReaderException, JSONException
{ {
JSONObject userIDObject = userObject.getJSONObject("userID"); JSONObject userIDObject = userObject.getJSONObject("userID");
......
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.json;
import ca.nrc.cadc.ac.ReaderException;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.security.Principal;
import java.util.Scanner;
public class UserRequestReader
{
/**
* Construct a UserRequest from an XML String source.
*
* @param json String of the XML.
* @return UserRequest UserRequest.
* @throws IOException
*/
public static UserRequest<Principal> read(String json)
throws IOException
{
if (json == null)
{
throw new IllegalArgumentException("XML must not be null");
}
else
{
try
{
return parseUserRequest(new JSONObject(json));
}
catch (JSONException e)
{
String error = "Unable to parse JSON to User because " +
e.getMessage();
throw new ReaderException(error, e);
}
}
}
/**
* Construct a User from a InputStream.
*
* @param in InputStream.
* @return User User.
* @throws ReaderException
* @throws IOException
*/
public static UserRequest<Principal> read(InputStream in)
throws IOException
{
if (in == null)
{
throw new IOException("stream closed");
}
Scanner s = new Scanner(in).useDelimiter("\\A");
String json = s.hasNext() ? s.next() : "";
return read(json);
}
/**
* Construct a User from a Reader.
*
* @param reader Reader.
* @return User User.
* @throws ReaderException
* @throws IOException
*/
public static UserRequest<Principal> read(Reader reader)
throws IOException
{
if (reader == null)
{
throw new IllegalArgumentException("reader must not be null");
}
Scanner s = new Scanner(reader).useDelimiter("\\A");
String json = s.hasNext() ? s.next() : "";
return read(json);
}
protected static UserRequest<Principal> parseUserRequest(
JSONObject userRequestObject)
throws ReaderException, JSONException
{
final User<Principal> user =
ca.nrc.cadc.ac.json.UserReader.parseUser(
userRequestObject.getJSONObject("user"));
return new UserRequest<Principal>(user, userRequestObject.
getString("password"));
}
}
...@@ -96,8 +96,8 @@ public class UserReader ...@@ -96,8 +96,8 @@ public class UserReader
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.net.URISyntaxException * @throws java.net.URISyntaxException
*/ */
public static User<? extends Principal> read(String xml) public static User<Principal> read(String xml)
throws ReaderException, IOException, URISyntaxException throws IOException, URISyntaxException
{ {
if (xml == null) if (xml == null)
{ {
...@@ -111,12 +111,10 @@ public class UserReader ...@@ -111,12 +111,10 @@ public class UserReader
* *
* @param in InputStream. * @param in InputStream.
* @return User User. * @return User User.
* @throws ReaderException
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.net.URISyntaxException
*/ */
public static User<? extends Principal> read(InputStream in) public static User<Principal> read(InputStream in)
throws ReaderException, IOException, URISyntaxException throws IOException
{ {
if (in == null) if (in == null)
{ {
...@@ -142,8 +140,8 @@ public class UserReader ...@@ -142,8 +140,8 @@ public class UserReader
* @throws ReaderException * @throws ReaderException
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public static User<? extends Principal> read(Reader reader) public static User<Principal> read(Reader reader)
throws ReaderException, IOException throws IOException
{ {
if (reader == null) if (reader == null)
{ {
...@@ -168,7 +166,7 @@ public class UserReader ...@@ -168,7 +166,7 @@ public class UserReader
return parseUser(root); return parseUser(root);
} }
protected static User<? extends Principal> parseUser(Element userElement) protected static User<Principal> parseUser(Element userElement)
throws ReaderException throws ReaderException
{ {
// userID element of the User element // userID element of the User element
......
...@@ -78,7 +78,6 @@ import java.io.InputStreamReader; ...@@ -78,7 +78,6 @@ import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.security.Principal; import java.security.Principal;
import org.jdom2.Document; import org.jdom2.Document;
...@@ -92,12 +91,10 @@ public class UserRequestReader ...@@ -92,12 +91,10 @@ public class UserRequestReader
* *
* @param xml String of the XML. * @param xml String of the XML.
* @return UserRequest UserRequest. * @return UserRequest UserRequest.
* @throws ReaderException
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.net.URISyntaxException
*/ */
public static UserRequest<? extends Principal> read(String xml) public static UserRequest<Principal> read(String xml)
throws ReaderException, IOException, URISyntaxException throws IOException
{ {
if (xml == null) if (xml == null)
{ {
...@@ -113,10 +110,9 @@ public class UserRequestReader ...@@ -113,10 +110,9 @@ public class UserRequestReader
* @return UserRequest UserRequest. * @return UserRequest UserRequest.
* @throws ReaderException * @throws ReaderException
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.net.URISyntaxException
*/ */
public static UserRequest<? extends Principal> read(InputStream in) public static UserRequest<Principal> read(InputStream in)
throws ReaderException, IOException, URISyntaxException throws IOException
{ {
if (in == null) if (in == null)
{ {
...@@ -142,8 +138,8 @@ public class UserRequestReader ...@@ -142,8 +138,8 @@ public class UserRequestReader
* @throws ReaderException * @throws ReaderException
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public static UserRequest<? extends Principal> read(Reader reader) public static UserRequest<Principal> read(Reader reader)
throws ReaderException, IOException throws IOException
{ {
if (reader == null) if (reader == null)
{ {
...@@ -168,7 +164,8 @@ public class UserRequestReader ...@@ -168,7 +164,8 @@ public class UserRequestReader
return parseUserRequest(root); return parseUserRequest(root);
} }
protected static UserRequest parseUserRequest(Element userRequestElement) protected static UserRequest<Principal> parseUserRequest(
Element userRequestElement)
throws ReaderException throws ReaderException
{ {
// user element of the UserRequest element // user element of the UserRequest element
...@@ -178,7 +175,7 @@ public class UserRequestReader ...@@ -178,7 +175,7 @@ public class UserRequestReader
String error = "user element not found in userRequest element"; String error = "user element not found in userRequest element";
throw new ReaderException(error); throw new ReaderException(error);
} }
User<? extends Principal> user = ca.nrc.cadc.ac.xml.UserReader.parseUser(userElement); User<Principal> user = ca.nrc.cadc.ac.xml.UserReader.parseUser(userElement);
// password element of the userRequest element // password element of the userRequest element
Element passwordElement = userRequestElement.getChild("password"); Element passwordElement = userRequestElement.getChild("password");
...@@ -189,9 +186,6 @@ public class UserRequestReader ...@@ -189,9 +186,6 @@ public class UserRequestReader
} }
String password = passwordElement.getText(); String password = passwordElement.getText();
UserRequest userRequest = new UserRequest(user, password); return new UserRequest<Principal>(user, password);
return userRequest;
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment