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

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

The integrity unit test is fully repared. Add tests for all rest-methods

File size: 13.3 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        return sqlString;
116    }
117   
118    private String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException {
119        final URL sqlUrl = AnnotationsTest.class.getResource("/test-data/InsertTestData.sql");
120        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
121        return sqlString;
122    }
123   
124   
125   
126    @Override
127    @Before
128    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException, Exception {
129        super.setUp();
130        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
131        // consume the DashishAnnotatorCreate sql script to create the database
132        jdbcTemplate.execute(getNormalisedSql());
133        jdbcTemplate.execute(getTestDataInsertSql());
134    }
135
136   
137    @Override
138    public void tearDown() throws Exception {
139        super.tearDown();
140    }
141    /**
142     * Test of getAnnotation method, of class annotationResource. Get <aid>. GET
143     * api/annotations/<aid>
144     */
145    @Test
146    public void testGetAnnotation() throws SQLException, DatatypeConfigurationException {
147        System.out.println("testGetAnnotation");
148        final String externalIDstring = TestBackendConstants._TEST_ANNOT_2_EXT;
149        final Annotation testAnnotation = (new TestInstances(resource().getURI().toString())).getAnnotationOne();       
150       
151        final String requestUrl = "annotations/" + externalIDstring;
152        System.out.println("requestUrl: " + requestUrl);
153       
154        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);       
155        ClientResponse response = responseBuilder.get(ClientResponse.class);       
156       
157        assertEquals(200, response.getStatus());
158        Annotation entity = response.getEntity(Annotation.class);
159        assertEquals(testAnnotation.getBody().getTextBody().getValue(), entity.getBody().getTextBody().getValue());
160        assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
161        assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
162        assertEquals(3, entity.getPermissions().getUserWithPermission().size());
163        assertEquals("owner", entity.getPermissions().getUserWithPermission().get(0).getPermission().value());       
164        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_3_EXT_ID, entity.getPermissions().getUserWithPermission().get(0).getRef()); 
165        assertEquals("writer", entity.getPermissions().getUserWithPermission().get(1).getPermission().value());
166        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_4_EXT_ID, entity.getPermissions().getUserWithPermission().get(1).getRef()); 
167        assertEquals("reader", entity.getPermissions().getUserWithPermission().get(2).getPermission().value()); 
168        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID, entity.getPermissions().getUserWithPermission().get(2).getRef()); 
169        assertEquals(2, entity.getTargets().getTargetInfo().size());
170        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_1_EXT_ID, entity.getTargets().getTargetInfo().get(0).getRef());
171        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_2_EXT_ID, entity.getTargets().getTargetInfo().get(1).getRef());
172        assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
173        assertEquals(resource().getURI()+requestUrl, entity.getURI());
174    }
175
176    /**
177     * Test of deleteAnnotation method, of class AnnotationResource. Delete
178     * <nid>. DELETE api/annotations/<aid>
179     */
180    @Test
181    public void testDeleteAnnotation() throws SQLException {
182        System.out.println("testDeleteAnnotation");
183        String externalIDstring  =  TestBackendConstants._TEST_ANNOT_5_EXT;
184        final String requestUrl = "annotations/" + externalIDstring;
185        System.out.println("requestUrl: " + requestUrl);
186       
187        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);       
188        ClientResponse response = responseBuilder.delete(ClientResponse.class);   
189        assertEquals(200, response.getStatus());
190        assertEquals("1 annotation(s) deleted.", response.getEntity(String.class));
191    }
192
193    /**
194     * Test of createAnnotation method, of class AnnotationResource. POST
195     * api/annotations/
196     */
197    @Test
198    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception {
199        System.out.println("test createAnnotation");
200        System.out.println("POST "+resource().getURI().toString()+"annotations/");
201        final String ownerString = resource().getURI().toString()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID;
202        final Annotation annotationToAdd = new Annotation();
203        final JAXBElement<Annotation> jaxbElement = (new ObjectFactory()).createAnnotation(annotationToAdd);
204        annotationToAdd.setPermissions(null);
205        annotationToAdd.setOwnerRef(ownerString);
206        annotationToAdd.setURI(resource().getURI().toString()+"annotations/"+ UUID.randomUUID().toString());       
207        annotationToAdd.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(TestBackendConstants._TEST_ANNOT_2_TIME_STAMP));       
208       
209        TargetInfoList targetInfoList = new TargetInfoList();
210        annotationToAdd.setTargets(targetInfoList);
211        TargetInfo targetInfo = new TargetInfo();
212        targetInfo.setLink("http://nl.wikipedia.org/wiki/Viktor_Janoekovytsj#Biografie");
213        targetInfo.setRef(resource().getURI().toString()+"targets/"+UUID.randomUUID().toString());
214        targetInfo.setVersion("5 apr 2013 om 18:42");
215        targetInfoList.getTargetInfo().add(targetInfo);       
216       
217        AnnotationBody annotationBody = new AnnotationBody();
218        annotationBody.setXmlBody(null);
219        TextBody textBody = new TextBody();
220        textBody.setMimeType("plain/text");
221        textBody.setValue("yanuk - zek");
222        annotationBody.setTextBody(textBody);
223        annotationToAdd.setBody(annotationBody);
224     
225        Builder responseBuilder = getAuthenticatedResource(resource().path("annotations/")).type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);       
226        ClientResponse response = responseBuilder.post(ClientResponse.class, jaxbElement);
227        assertEquals(200, response.getStatus());
228       
229        ResponseBody entity = response.getEntity(ResponseBody.class);       
230        Annotation entityA = entity.getAnnotation();
231        assertEquals(annotationToAdd.getBody().getTextBody().getValue(), entityA.getBody().getTextBody().getValue());
232        assertEquals(annotationToAdd.getBody().getTextBody().getMimeType(), entityA.getBody().getTextBody().getMimeType());
233        assertEquals(annotationToAdd.getHeadline(), entityA.getHeadline());
234        assertEquals(1, entityA.getPermissions().getUserWithPermission().size());
235        assertEquals("owner", entityA.getPermissions().getUserWithPermission().get(0).getPermission().value());
236        assertEquals(annotationToAdd.getOwnerRef(), entityA.getPermissions().getUserWithPermission().get(0).getRef());
237        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getLink(), entityA.getTargets().getTargetInfo().get(0).getLink());
238        // new ref is generated
239        //assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getRef(), entityA.getTargets().getTargetInfo().get(0).getRef());
240        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getVersion(), entityA.getTargets().getTargetInfo().get(0).getVersion());
241        //last modified is updated by the server
242        //assertEquals(annotationToAdd.getLastModified(), entityA.getLastModified());
243        assertEquals(annotationToAdd.getOwnerRef(), entityA.getOwnerRef());
244    }
245   
246   
247   
248    protected Builder getAuthenticatedResource(WebResource resource) {
249        return resource.header(HttpHeaders.AUTHORIZATION, "Basic "  + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName()+":olhapassword")));
250    }
251}
Note: See TracBrowser for help on using the repository browser.