source: DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationsTest.java @ 4209

Last change on this file since 4209 was 4209, checked in by olhsha, 10 years ago

following Eric's instruction in security management in Dasish: removing a separate security DB, making authentication tables the part of the main DB, keeping hashed passwords. Used spring-security configuration for hashes with BCryptPasswordEncoder as recommended.

File size: 13.4 KB
Line 
1/*
2 * Copyright (C) 2013 DASISH
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18package eu.dasish.annotation.backend.rest;
19
20import com.sun.jersey.api.client.ClientResponse;
21import com.sun.jersey.api.client.WebResource;
22import com.sun.jersey.api.client.WebResource.Builder;
23import com.sun.jersey.core.util.Base64;
24import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
25import com.sun.jersey.test.framework.AppDescriptor;
26import com.sun.jersey.test.framework.JerseyTest;
27import com.sun.jersey.test.framework.WebAppDescriptor;
28import eu.dasish.annotation.backend.TestBackendConstants;
29import eu.dasish.annotation.backend.TestInstances;
30import eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest;
31import eu.dasish.annotation.schema.Annotation;
32import eu.dasish.annotation.schema.AnnotationBody;
33import eu.dasish.annotation.schema.AnnotationBody.TextBody;
34import eu.dasish.annotation.schema.ObjectFactory;
35import eu.dasish.annotation.schema.ResponseBody;
36import eu.dasish.annotation.schema.TargetInfo;
37import eu.dasish.annotation.schema.TargetInfoList;
38import java.io.File;
39import java.io.FileNotFoundException;
40import java.net.URISyntaxException;
41import java.net.URL;
42import java.sql.SQLException;
43import java.util.Scanner;
44import java.util.UUID;
45import javax.ws.rs.core.HttpHeaders;
46import javax.ws.rs.core.MediaType;
47import javax.xml.bind.JAXBElement;
48import javax.xml.datatype.DatatypeConfigurationException;
49import javax.xml.datatype.DatatypeFactory;
50import org.junit.Test;
51import static org.junit.Assert.*;
52import org.junit.Before;
53import org.junit.runner.RunWith;
54import org.springframework.beans.factory.annotation.Autowired;
55import org.springframework.dao.DataAccessException;
56import org.springframework.jdbc.core.JdbcTemplate;
57import org.springframework.test.context.ContextConfiguration;
58import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
59import org.springframework.web.context.ContextLoaderListener;
60import org.springframework.web.context.request.RequestContextListener;
61
62/**
63 *
64 * @author olhsha
65 */
66@RunWith(value = SpringJUnit4ClassRunner.class)
67@ContextConfiguration({"/spring-test-config/dataSource.xml"})
68public class AnnotationsTest extends JerseyTest {   
69   
70    @Autowired
71    private JdbcTemplate jdbcTemplate;
72   
73   
74   
75   
76    @Override
77    protected AppDescriptor configure() {
78       return new WebAppDescriptor.Builder(AnnotationResource.class.getPackage().getName())
79                .servletClass(SpringServlet.class)
80                .contextParam("contextConfigLocation", getApplicationContextFile())
81                .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
82                .requestListenerClass(RequestContextListener.class)
83                .contextListenerClass(ContextLoaderListener.class)
84                .build();
85       
86    }
87   
88    private String getApplicationContextFile() {
89        // sorry for the duplication, but JerseyTest is not aware of
90        // @ContextConfiguration
91        return "classpath:spring-config/componentscan.xml, classpath:spring-config/annotationDao.xml, classpath:spring-config/userDao.xml, classpath:spring-config/targetDao.xml, classpath:spring-config/cachedRepresentationDao.xml, classpath:spring-config/dbIntegrityService.xml, classpath:spring-config/jaxbMarshallerFactory.xml, classpath:spring-test-config/dataSource.xml";
92    }
93   
94    private String getNormalisedSql() throws FileNotFoundException, URISyntaxException {
95        // remove the unsupported sql for the test
96        final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/sql/DashishAnnotatorCreate.sql");
97        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
98        for (String unknownToken : new String[]{
99                    "SET client_encoding",
100                    "CREATE DATABASE",
101                    "\\\\connect",
102                    "SET default_with_oids",
103                    "ALTER SEQUENCE",
104                    "ALTER TABLE ONLY",
105                    "ADD CONSTRAINT",
106                    "CREATE INDEX", // "ALTER TABLE ONLY [a-z]* ALTER COLUMN",
107                // "ALTER TABLE ONLY [^A]* ADD CONSTRAINT"
108                }) {
109            sqlString = sqlString.replaceAll(unknownToken, "-- " + unknownToken);
110        }
111        // obsolete(?) Peter's stuff, before body has been decided to be a text with its mimetype: sqlString = sqlString.replaceAll("body_xml xml", "body_xml text");
112        sqlString = sqlString.replaceAll("CACHE 1;", "; -- CACHE 1;");
113        //sqlString = sqlString.replaceAll("UUID", "text");
114        sqlString = sqlString.replaceAll("SERIAL NOT NULL", "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");       
115        sqlString = sqlString.replaceAll("AT TIME ZONE 'UTC'", "AT TIME ZONE INTERVAL '00:00' HOUR TO MINUTE");
116        return sqlString;
117    }
118   
119    private String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException {
120        final URL sqlUrl = AnnotationsTest.class.getResource("/test-data/InsertTestData.sql");
121        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
122        return sqlString;
123    }
124   
125   
126   
127    @Override
128    @Before
129    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException, Exception {
130        super.setUp();
131        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
132        // consume the DashishAnnotatorCreate sql script to create the database
133        jdbcTemplate.execute(getNormalisedSql());
134        jdbcTemplate.execute(getTestDataInsertSql());
135    }
136
137   
138    @Override
139    public void tearDown() throws Exception {
140        super.tearDown();
141    }
142    /**
143     * Test of getAnnotation method, of class annotationResource. Get <aid>. GET
144     * api/annotations/<aid>
145     */
146    @Test
147    public void testGetAnnotation() throws SQLException, DatatypeConfigurationException {
148        System.out.println("testGetAnnotation");
149        final String externalIDstring = TestBackendConstants._TEST_ANNOT_2_EXT;
150        final Annotation testAnnotation = (new TestInstances(resource().getURI().toString())).getAnnotationOne();       
151       
152        final String requestUrl = "annotations/" + externalIDstring;
153        System.out.println("requestUrl: " + requestUrl);
154       
155        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);       
156        ClientResponse response = responseBuilder.get(ClientResponse.class);       
157       
158        assertEquals(200, response.getStatus());
159        Annotation entity = response.getEntity(Annotation.class);
160        assertEquals(testAnnotation.getBody().getTextBody().getValue(), entity.getBody().getTextBody().getValue());
161        assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
162        assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
163        assertEquals(3, entity.getPermissions().getUserWithPermission().size());
164        assertEquals("owner", entity.getPermissions().getUserWithPermission().get(0).getPermission().value());       
165        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_3_EXT_ID, entity.getPermissions().getUserWithPermission().get(0).getRef()); 
166        assertEquals("writer", entity.getPermissions().getUserWithPermission().get(1).getPermission().value());
167        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_4_EXT_ID, entity.getPermissions().getUserWithPermission().get(1).getRef()); 
168        assertEquals("reader", entity.getPermissions().getUserWithPermission().get(2).getPermission().value()); 
169        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID, entity.getPermissions().getUserWithPermission().get(2).getRef()); 
170        assertEquals(2, entity.getTargets().getTargetInfo().size());
171        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_1_EXT_ID, entity.getTargets().getTargetInfo().get(0).getRef());
172        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_2_EXT_ID, entity.getTargets().getTargetInfo().get(1).getRef());
173        assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
174        assertEquals(resource().getURI()+requestUrl, entity.getURI());
175    }
176
177    /**
178     * Test of deleteAnnotation method, of class AnnotationResource. Delete
179     * <nid>. DELETE api/annotations/<aid>
180     */
181    @Test
182    public void testDeleteAnnotation() throws SQLException {
183        System.out.println("testDeleteAnnotation");
184        String externalIDstring  =  TestBackendConstants._TEST_ANNOT_5_EXT;
185        final String requestUrl = "annotations/" + externalIDstring;
186        System.out.println("requestUrl: " + requestUrl);
187       
188        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);       
189        ClientResponse response = responseBuilder.delete(ClientResponse.class);   
190        assertEquals(200, response.getStatus());
191        assertEquals("1 annotation(s) deleted.", response.getEntity(String.class));
192    }
193
194    /**
195     * Test of createAnnotation method, of class AnnotationResource. POST
196     * api/annotations/
197     */
198    @Test
199    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception {
200        System.out.println("test createAnnotation");
201        System.out.println("POST "+resource().getURI().toString()+"annotations/");
202        final String ownerString = resource().getURI().toString()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID;
203        final Annotation annotationToAdd = new Annotation();
204        final JAXBElement<Annotation> jaxbElement = (new ObjectFactory()).createAnnotation(annotationToAdd);
205        annotationToAdd.setPermissions(null);
206        annotationToAdd.setOwnerRef(ownerString);
207        annotationToAdd.setURI(resource().getURI().toString()+"annotations/"+ UUID.randomUUID().toString());       
208        annotationToAdd.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(TestBackendConstants._TEST_ANNOT_2_TIME_STAMP));       
209       
210        TargetInfoList targetInfoList = new TargetInfoList();
211        annotationToAdd.setTargets(targetInfoList);
212        TargetInfo targetInfo = new TargetInfo();
213        targetInfo.setLink("http://nl.wikipedia.org/wiki/Viktor_Janoekovytsj#Biografie");
214        targetInfo.setRef(resource().getURI().toString()+"targets/"+UUID.randomUUID().toString());
215        targetInfo.setVersion("5 apr 2013 om 18:42");
216        targetInfoList.getTargetInfo().add(targetInfo);       
217       
218        AnnotationBody annotationBody = new AnnotationBody();
219        annotationBody.setXmlBody(null);
220        TextBody textBody = new TextBody();
221        textBody.setMimeType("plain/text");
222        textBody.setValue("yanuk - zek");
223        annotationBody.setTextBody(textBody);
224        annotationToAdd.setBody(annotationBody);
225     
226        Builder responseBuilder = getAuthenticatedResource(resource().path("annotations/")).type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);       
227        ClientResponse response = responseBuilder.post(ClientResponse.class, jaxbElement);
228        assertEquals(200, response.getStatus());
229       
230        ResponseBody entity = response.getEntity(ResponseBody.class);       
231        Annotation entityA = entity.getAnnotation();
232        assertEquals(annotationToAdd.getBody().getTextBody().getValue(), entityA.getBody().getTextBody().getValue());
233        assertEquals(annotationToAdd.getBody().getTextBody().getMimeType(), entityA.getBody().getTextBody().getMimeType());
234        assertEquals(annotationToAdd.getHeadline(), entityA.getHeadline());
235        assertEquals(1, entityA.getPermissions().getUserWithPermission().size());
236        assertEquals("owner", entityA.getPermissions().getUserWithPermission().get(0).getPermission().value());
237        assertEquals(annotationToAdd.getOwnerRef(), entityA.getPermissions().getUserWithPermission().get(0).getRef());
238        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getLink(), entityA.getTargets().getTargetInfo().get(0).getLink());
239        // new ref is generated
240        //assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getRef(), entityA.getTargets().getTargetInfo().get(0).getRef());
241        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getVersion(), entityA.getTargets().getTargetInfo().get(0).getVersion());
242        //last modified is updated by the server
243        //assertEquals(annotationToAdd.getLastModified(), entityA.getLastModified());
244        assertEquals(annotationToAdd.getOwnerRef(), entityA.getOwnerRef());
245    }
246   
247   
248   
249    protected Builder getAuthenticatedResource(WebResource resource) {
250        return resource.header(HttpHeaders.AUTHORIZATION, "Basic "  + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName()+":olhapassword")));
251    }
252   
253   
254}
Note: See TracBrowser for help on using the repository browser.