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

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

integrity-spring-configuration context is refactored

File size: 13.5 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.api.client.filter.HTTPBasicAuthFilter;
24import com.sun.jersey.core.util.Base64;
25import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
26import com.sun.jersey.test.framework.AppDescriptor;
27import com.sun.jersey.test.framework.JerseyTest;
28import com.sun.jersey.test.framework.WebAppDescriptor;
29import eu.dasish.annotation.backend.TestBackendConstants;
30import eu.dasish.annotation.backend.TestInstances;
31import eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest;
32import eu.dasish.annotation.schema.Annotation;
33import eu.dasish.annotation.schema.ObjectFactory;
34import eu.dasish.annotation.schema.ResponseBody;
35import eu.dasish.annotation.schema.TargetInfo;
36import eu.dasish.annotation.schema.TargetInfoList;
37import java.io.File;
38import java.io.FileNotFoundException;
39import java.net.URISyntaxException;
40import java.net.URL;
41import java.sql.SQLException;
42import java.util.ArrayList;
43import java.util.List;
44import java.util.Scanner;
45import java.util.UUID;
46import javax.servlet.http.HttpServletRequest;
47import javax.ws.rs.core.Context;
48import javax.ws.rs.core.HttpHeaders;
49import javax.ws.rs.core.MediaType;
50import javax.xml.bind.JAXBElement;
51import javax.xml.datatype.DatatypeConfigurationException;
52import javax.xml.datatype.DatatypeFactory;
53import org.junit.Test;
54import static org.junit.Assert.*;
55import org.junit.Before;
56import org.junit.Ignore;
57import org.junit.runner.RunWith;
58import org.springframework.beans.factory.annotation.Autowired;
59import org.springframework.dao.DataAccessException;
60import org.springframework.jdbc.core.JdbcTemplate;
61import org.springframework.mock.web.MockHttpServletRequest;
62import org.springframework.test.context.ContextConfiguration;
63import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
64import org.springframework.web.context.ContextLoaderListener;
65import org.springframework.web.context.request.RequestContextListener;
66
67/**
68 *
69 * @author olhsha
70 */
71@RunWith(value = SpringJUnit4ClassRunner.class)
72@ContextConfiguration({"/spring-test-config/dataSource.xml"})
73public class AnnotationsTest extends JerseyTest {   
74   
75    @Autowired
76    private JdbcTemplate jdbcTemplate;
77   
78   
79   
80   
81    @Override
82    protected AppDescriptor configure() {
83       return new WebAppDescriptor.Builder(AnnotationResource.class.getPackage().getName())
84                .servletClass(SpringServlet.class)
85                .contextParam("contextConfigLocation", getApplicationContextFile())
86                .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
87                .requestListenerClass(RequestContextListener.class)
88                .contextListenerClass(ContextLoaderListener.class)
89                .build();
90       
91    }
92   
93    private String getApplicationContextFile() {
94        // sorry for the duplication, but JerseyTest is not aware of
95        // @ContextConfiguration
96        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";
97    }
98   
99    private String getNormalisedSql() throws FileNotFoundException, URISyntaxException {
100        // remove the unsupported sql for the test
101        final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/sql/DashishAnnotatorCreate.sql");
102        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
103        for (String unknownToken : new String[]{
104                    "SET client_encoding",
105                    "CREATE DATABASE",
106                    "\\\\connect",
107                    "SET default_with_oids",
108                    "ALTER SEQUENCE",
109                    "ALTER TABLE ONLY",
110                    "ADD CONSTRAINT",
111                    "CREATE INDEX", // "ALTER TABLE ONLY [a-z]* ALTER COLUMN",
112                // "ALTER TABLE ONLY [^A]* ADD CONSTRAINT"
113                }) {
114            sqlString = sqlString.replaceAll(unknownToken, "-- " + unknownToken);
115        }
116        // 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");
117        sqlString = sqlString.replaceAll("CACHE 1;", "; -- CACHE 1;");
118        //sqlString = sqlString.replaceAll("UUID", "text");
119        sqlString = sqlString.replaceAll("SERIAL NOT NULL", "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
120        return sqlString;
121    }
122   
123    private String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException {
124        final URL sqlUrl = AnnotationsTest.class.getResource("/test-data/InsertTestData.sql");
125        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
126        return sqlString;
127    }
128   
129   
130   
131    @Override
132    @Before
133    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException, Exception {
134        super.setUp();
135        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
136        // consume the DashishAnnotatorCreate sql script to create the database
137        jdbcTemplate.execute(getNormalisedSql());
138        jdbcTemplate.execute(getTestDataInsertSql());
139    }
140
141   
142    @Override
143    public void tearDown() throws Exception {
144        super.tearDown();
145    }
146    /**
147     * Test of getAnnotation method, of class annotationResource. Get <aid>. GET
148     * api/annotations/<aid>
149     */
150    @Test
151    public void testGetAnnotation() throws SQLException, DatatypeConfigurationException {
152        System.out.println("testGetAnnotation");
153        final String externalIDstring = TestBackendConstants._TEST_ANNOT_2_EXT;
154        final Annotation testAnnotation = (new TestInstances(resource().getURI().toString())).getAnnotationOne();       
155       
156        final String requestUrl = "annotations/" + externalIDstring;
157        System.out.println("requestUrl: " + requestUrl);
158       
159        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);
160       
161        ClientResponse response = responseBuilder.get(ClientResponse.class);       
162       
163        assertEquals(200, response.getStatus());
164        Annotation entity = response.getEntity(Annotation.class);
165        assertEquals(testAnnotation.getBody().getTextBody().getValue(), entity.getBody().getTextBody().getValue());
166        assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
167        assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
168        assertEquals(3, entity.getPermissions().getUserWithPermission().size());
169        assertEquals("owner", entity.getPermissions().getUserWithPermission().get(0).getPermission().value());       
170        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_3_EXT_ID, entity.getPermissions().getUserWithPermission().get(0).getRef()); 
171        assertEquals("writer", entity.getPermissions().getUserWithPermission().get(1).getPermission().value());
172        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_4_EXT_ID, entity.getPermissions().getUserWithPermission().get(1).getRef()); 
173        assertEquals("reader", entity.getPermissions().getUserWithPermission().get(2).getPermission().value()); 
174        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID, entity.getPermissions().getUserWithPermission().get(2).getRef()); 
175        assertEquals(2, entity.getTargets().getTargetInfo().size());
176        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_1_EXT_ID, entity.getTargets().getTargetInfo().get(0).getRef());
177        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_2_EXT_ID, entity.getTargets().getTargetInfo().get(1).getRef());
178        assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
179        assertEquals(resource().getURI()+requestUrl, entity.getURI());
180    }
181
182    /**
183     * Test of deleteAnnotation method, of class AnnotationResource. Delete
184     * <nid>. DELETE api/annotations/<aid>
185     */
186    @Test
187    @Ignore
188    public void testDeleteAnnotation() throws SQLException {
189        System.out.println("testDeleteAnnotation");
190        //final Number annotationID = daoDispatcher.getAnnotationInternalIdentifier(UUID.fromString(UUID));
191        //int[] resultDelete = daoDispatcher.deleteAnnotation(annotationID);
192       
193        final int[] mockDelete = new int[4];
194        mockDelete[0] = 1; // # deleted annotations
195        mockDelete[3] = 1; // # deleted annotation_prinipal_permissions
196        mockDelete[2] = 2; // # deleted  annotations_target_Targets, (5,3), (5,4)
197        mockDelete[3] = 1; // # deletd Targets, 4
198       
199        final String baseURI = this.getBaseURI().toString();
200       
201        final String requestUrl = "annotations/" + TestBackendConstants._TEST_ANNOT_5_EXT;
202        System.out.println("requestUrl: " + requestUrl);
203        ClientResponse response = resource().path(requestUrl).delete(ClientResponse.class);
204        assertEquals(200, response.getStatus());
205        assertEquals("1 annotation(s) deleted.", response.getEntity(String.class));
206       
207       
208    }
209
210    /**
211     * Test of createAnnotation method, of class AnnotationResource. POST
212     * api/annotations/
213     */
214    @Test
215    @Ignore
216    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception {
217        System.out.println("test createAnnotation");
218        // Peter's workaround on absence of "ObjectFactory.create... for annotations       
219        //final JAXBElement<Annotation> jaxbElement = new JAXBElement<Annotation>(new QName("http://www.dasish.eu/ns/addit", "annotation"), Annotation.class, null, annotationToAdd);
220       
221        final String ownerString = "5";
222        final Number ownerID = 5;
223        final Number newAnnotationID = 6;
224       
225        ResponseBody responseBody = new ResponseBody();
226        final JAXBElement<ResponseBody> jaxbElement = (new ObjectFactory()).createResponseBody(responseBody);
227        responseBody.setPermissions(null);
228        final Annotation addedAnnotation = new Annotation();
229        responseBody.setAnnotation(addedAnnotation);
230        responseBody.setActionList(null);
231       
232        TargetInfoList TargetInfoList = new TargetInfoList();
233        addedAnnotation.setTargets(TargetInfoList);
234        addedAnnotation.setOwnerRef(ownerString);
235        addedAnnotation.setURI(TestBackendConstants._TEST_SERVLET_URI_annotations + UUID.randomUUID().toString());       
236        addedAnnotation.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(TestBackendConstants._TEST_ANNOT_2_TIME_STAMP));       
237        TargetInfo TargetInfo = new TargetInfo();
238        TargetInfo.setLink("google.nl");
239        TargetInfo.setRef(UUID.randomUUID().toString());
240        TargetInfo.setVersion("vandaag");
241        TargetInfoList.getTargetInfo().add(TargetInfo);       
242       
243        final List<Number> Targets = new ArrayList<Number>();
244        Targets.add(6);
245       
246        final String baseURI = this.getBaseURI().toString();
247       
248        final String requestUrl = "annotations";
249        System.out.println("requestUrl: " + requestUrl);
250        ClientResponse response = resource().path(requestUrl).type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, jaxbElement);
251        assertEquals(200, response.getStatus());
252       
253        ResponseBody entity = response.getEntity(ResponseBody.class);       
254        Annotation entityA = entity.getAnnotation();
255        assertEquals(addedAnnotation.getBody(), entityA.getBody());
256        assertEquals(addedAnnotation.getHeadline(), entityA.getHeadline());
257        assertEquals(addedAnnotation.getPermissions(), entityA.getPermissions());
258        assertEquals(addedAnnotation.getTargets().getTargetInfo().get(0).getLink(), entityA.getTargets().getTargetInfo().get(0).getLink());
259        assertEquals(addedAnnotation.getTargets().getTargetInfo().get(0).getRef(), entityA.getTargets().getTargetInfo().get(0).getRef());
260        assertEquals(addedAnnotation.getTargets().getTargetInfo().get(0).getVersion(), entityA.getTargets().getTargetInfo().get(0).getVersion());
261        assertEquals(addedAnnotation.getLastModified(), entityA.getLastModified());
262        assertEquals(addedAnnotation.getOwnerRef(), entityA.getOwnerRef());
263    }
264   
265   
266   
267    protected Builder getAuthenticatedResource(WebResource resource) {
268        return resource.header(HttpHeaders.AUTHORIZATION, "Basic "  + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName()+":olhapassword")));
269    }
270}
Note: See TracBrowser for help on using the repository browser.