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

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

lintegrity unit test reconstructed so it does not mock any more. getAnnotation works (the others are "ignored"). Needs refactoring (the subdirectory with beans and DummySecurityFilter? class.

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