source: ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java @ 5560

Last change on this file since 5560 was 5560, checked in by olhsha@mpi.nl, 10 years ago

Unit test for getting comments of profiles and components from groups.

File size: 20.6 KB
Line 
1package clarin.cmdi.componentregistry.rest;
2
3import clarin.cmdi.componentregistry.ComponentRegistryException;
4
5import java.io.ByteArrayInputStream;
6import java.io.ByteArrayOutputStream;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.UnsupportedEncodingException;
10import java.text.ParseException;
11import java.util.regex.Matcher;
12import java.util.regex.Pattern;
13
14import javax.xml.bind.JAXBException;
15
16import clarin.cmdi.componentregistry.ComponentRegistry;
17import clarin.cmdi.componentregistry.DatesHelper;
18import clarin.cmdi.componentregistry.ItemNotFoundException;
19import clarin.cmdi.componentregistry.MDMarshaller;
20import clarin.cmdi.componentregistry.UserUnauthorizedException;
21import clarin.cmdi.componentregistry.components.CMDComponentSpec;
22import clarin.cmdi.componentregistry.model.Comment;
23import clarin.cmdi.componentregistry.model.ComponentDescription;
24import clarin.cmdi.componentregistry.model.ProfileDescription;
25import clarin.cmdi.componentregistry.persistence.jpa.CommentsDao;
26
27import java.io.BufferedReader;
28import java.io.File;
29import java.io.FileOutputStream;
30import java.io.InputStreamReader;
31import java.util.Date;
32
33import org.springframework.beans.factory.annotation.Autowired;
34
35/**
36 * Static helper methods to be used in tests
37 *
38 */
39public final class RegistryTestHelper {
40
41    private static MDMarshaller marshaller;
42   
43   
44           
45
46    @Autowired
47    public void setMarshaller(MDMarshaller marshaller) {
48        RegistryTestHelper.marshaller = marshaller;
49    }
50
51    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException {
52        return addComponent(testRegistry, id, getComponentTestContent(), isPublic);
53    }
54
55    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
56            JAXBException, UnsupportedEncodingException {
57        return addComponent(testRegistry, id, new ByteArrayInputStream(content.getBytes("UTF-8")), isPublic);
58    }
59
60    private static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
61            JAXBException {
62        ComponentDescription desc = ComponentDescription.createNewDescription();
63        desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
64        desc.setUserId(DummyPrincipal.DUMMY_PRINCIPAL.getName());
65        desc.setName(id);
66        desc.setDescription("Test Description");
67        desc.setId(ComponentDescription.COMPONENT_PREFIX + id);
68        desc.setHref("link:" + desc.getId());
69        desc.setPublic(isPublic);
70        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
71        testRegistry.register(desc, spec);
72        return desc;
73    }
74
75    public static ComponentDescription addComponentAnotherPrincipal(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException {
76        return addComponentAnotherPrincipal(testRegistry, id, getComponentTestContent(), isPublic);
77    }
78
79    private static ComponentDescription addComponentAnotherPrincipal(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
80            JAXBException {
81        ComponentDescription desc = ComponentDescription.createNewDescription();
82        desc.setCreatorName("AnotherPrincipal");
83        desc.setUserId("AnotherPrincipal");
84        desc.setDbUserId(2);
85        desc.setName(id);
86        desc.setDescription("Test Description");
87        desc.setId(ComponentDescription.COMPONENT_PREFIX + id);
88        desc.setHref("link:" + desc.getId());
89        desc.setPublic(isPublic);
90        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
91        testRegistry.register(desc, spec);
92        return desc;
93    }
94
95    public static String getProfileTestContentString() {
96        return getProfileTestContentString("Actor");
97    }
98
99    private static String getProfileTestContentString(String name) {
100        String profileContent = "";
101        profileContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
102        profileContent += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
103        profileContent += "    xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n";
104        profileContent += "    <Header />\n";
105        profileContent += "    <CMD_Component name=\"" + name + "\" CardinalityMin=\"0\" CardinalityMax=\"unbounded\">\n";
106        profileContent += "        <AttributeList>\n";
107        profileContent += "            <Attribute>\n";
108        profileContent += "                <Name>Name</Name>\n";
109        profileContent += "                <Type>string</Type>\n";
110        profileContent += "            </Attribute>\n";
111        profileContent += "        </AttributeList>\n";
112        profileContent += "        <CMD_Element name=\"Age\">\n";
113        profileContent += "            <ValueScheme>\n";
114        profileContent += "                <pattern>[23][0-9]</pattern>\n";
115        profileContent += "            </ValueScheme>\n";
116        profileContent += "        </CMD_Element>\n";
117        profileContent += "    </CMD_Component>\n";
118        profileContent += "</CMD_ComponentSpec>\n";
119        return profileContent;
120    }
121
122    public static InputStream getTestProfileContent() {
123        return getTestProfileContent("Actor");
124    }
125
126    public static InputStream getTestProfileContent(String name) {
127        return new ByteArrayInputStream(getProfileTestContentString(name).getBytes());
128    }
129
130    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException, ItemNotFoundException {
131        return addProfile(testRegistry, id, RegistryTestHelper.getTestProfileContent(), isPublic);
132    }
133
134    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
135            JAXBException, ItemNotFoundException {
136        return addProfile(testRegistry, id, new ByteArrayInputStream(content.getBytes()), isPublic);
137    }
138
139    private static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
140            JAXBException, ItemNotFoundException {
141        ProfileDescription desc = ProfileDescription.createNewDescription();
142        desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
143        desc.setUserId(DummyPrincipal.DUMMY_CREDENTIALS.getPrincipalName());
144        desc.setName(id);
145        desc.setDescription("Test Description");
146        desc.setId(ProfileDescription.PROFILE_PREFIX + id);
147        desc.setHref("link:" + ProfileDescription.PROFILE_PREFIX + id);
148        desc.setPublic(isPublic);
149        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
150        testRegistry.register(desc, spec);
151        return desc;
152    }
153
154    public static ProfileDescription addProfileAnotherPrincipal(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException, ItemNotFoundException {
155        return addProfileAnotherPrincipal(testRegistry, id, RegistryTestHelper.getTestProfileContent(), isPublic);
156    }
157
158    private static ProfileDescription addProfileAnotherPrincipal(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
159            JAXBException, ItemNotFoundException {
160        ProfileDescription desc = ProfileDescription.createNewDescription();
161        desc.setCreatorName("AnotherPrincipal");
162        desc.setUserId("AnotherPrincipal");
163        desc.setDbUserId(2);
164        desc.setName(id);
165        desc.setDescription("Test Description");
166        desc.setId(ProfileDescription.PROFILE_PREFIX + id);
167        desc.setHref("link:" + ProfileDescription.PROFILE_PREFIX + id);
168        desc.setPublic(isPublic);
169        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
170        testRegistry.register(desc, spec);
171        return desc;
172    }
173
174    public static CMDComponentSpec getTestProfile() throws JAXBException {
175        return marshaller.unmarshal(CMDComponentSpec.class, getTestProfileContent(), marshaller.getCMDComponentSchema());
176    }
177
178    public static String getComponentTestContentString() {
179        return getComponentTestContentString("Access");
180    }
181
182    public static InputStream getComponentTestContent() {
183        return getComponentTestContentAsStream("Access");
184    }
185
186    public static String getComponentTestContentString(String componentName) {
187        String compContent = "";
188        compContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
189        compContent += "\n";
190        compContent += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
191        compContent += "    xsi:noNamespaceSchemaLocation=\"../../general-component-schema.xsd\">\n";
192        compContent += "    \n";
193        compContent += "    <Header/>\n";
194        compContent += "    \n";
195        compContent += "    <CMD_Component name=\"" + componentName + "\" CardinalityMin=\"1\" CardinalityMax=\"1\">\n";
196        compContent += "        <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
197        compContent += "        <CMD_Element name=\"Date\">\n";
198        compContent += "            <ValueScheme>\n";
199        compContent += "                <!-- matching dates of the pattern yyyy-mm-dd (ISO 8601); this only matches dates from the years 1000 through 2999 and does allow some invalid dates (e.g. February, the 30th) -->\n";
200        compContent += "                <pattern>(1|2)\\d{3}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])</pattern>                \n";
201        compContent += "            </ValueScheme>\n";
202        compContent += "        </CMD_Element>\n";
203        compContent += "        <CMD_Element name=\"Owner\" ValueScheme=\"string\" />\n";
204        compContent += "        <CMD_Element name=\"Publisher\" ValueScheme=\"string\" />\n";
205        compContent += "    </CMD_Component>\n";
206        compContent += "\n";
207        compContent += "</CMD_ComponentSpec>\n";
208        return compContent;
209    }
210
211    public static String getStringFromStream(InputStream largeProfileStream) throws IOException {
212        try {
213            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(largeProfileStream));
214            StringBuilder profileStringBuilder = new StringBuilder();
215            String line;
216            while (null != (line = bufferedReader.readLine())) {
217                profileStringBuilder.append(line);
218            }
219            return profileStringBuilder.toString();
220        } finally {
221            largeProfileStream.close();
222        }
223    }
224    ///////////////////////////////////////////////////////
225
226    public static String getLargeProfileContent() throws IOException {
227        InputStream largeProfileStream = RegistryTestHelper.class.getResourceAsStream("/xml/largeProfile.xml");
228        return getStringFromStream(largeProfileStream);
229    }
230
231    //////////////////////
232    public static CMDComponentSpec getComponentFromString(String contentString) throws JAXBException {
233        return marshaller.unmarshal(CMDComponentSpec.class, getComponentContentAsStream(contentString), marshaller.getCMDComponentSchema());
234    }
235
236    public static InputStream getComponentContentAsStream(String content) {
237        return new ByteArrayInputStream(content.getBytes());
238    }
239
240    public static InputStream getComponentTestContentAsStream(String componentName) {
241        return getComponentContentAsStream(getComponentTestContentString(componentName));
242    }
243
244    public static CMDComponentSpec getTestComponent() throws JAXBException {
245        return marshaller.unmarshal(CMDComponentSpec.class, getComponentTestContent(), marshaller.getCMDComponentSchema());
246    }
247
248    public static CMDComponentSpec getTestComponent(String name) throws JAXBException {
249        return marshaller.unmarshal(CMDComponentSpec.class, getComponentTestContentAsStream(name), marshaller.getCMDComponentSchema());
250    }
251
252    public static String getXml(CMDComponentSpec componentSpec) throws JAXBException, UnsupportedEncodingException {
253        ByteArrayOutputStream os = new ByteArrayOutputStream();
254        marshaller.marshal(componentSpec, os);
255        String xml = os.toString();
256        try {
257            os.close();
258        } catch (IOException ex) {
259        }
260        return xml;
261    }
262
263    public static Comment addComment(ComponentRegistry testRegistry, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
264        return addComment(testRegistry, RegistryTestHelper.getTestCommentContent(id, descriptionId), principal);
265    }
266
267    private static Comment addComment(ComponentRegistry testRegistry, InputStream content, String principal) throws ParseException,
268            JAXBException,
269            ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
270        Comment spec = marshaller.unmarshal(Comment.class, content, null);
271        testRegistry.registerComment(spec, principal);
272        return spec;
273    }
274   
275    public Comment addCommentBypassAuthorisation(CommentsDao commentsDao, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
276        return addCommentBypassAuthorisation(commentsDao, RegistryTestHelper.getTestCommentContent(id, descriptionId), principal);
277    }
278
279
280    private Comment addCommentBypassAuthorisation(CommentsDao commentsDao, InputStream content, String principal) throws ParseException,
281            JAXBException,
282            ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
283        Comment comment = marshaller.unmarshal(Comment.class, content, null);
284        comment.setCommentDate(new Date());
285        comment.setUserId(2);
286        commentsDao.saveAndFlush(comment);
287        return comment;
288    }
289
290    public static String getCommentTestContentStringForProfile(String commentName, String profileId) {
291        String comContent = "";
292        comContent += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
293        comContent += "<comment xmlns:ns2=\"http://www.w3.org/1999/xlink\">\n";
294        comContent += "    <comments>" + commentName + "</comments>\n";
295        comContent += "    <commentDate>" + DatesHelper.createNewDate() + "</commentDate>\n";
296        comContent += "    <componentId>" + profileId + "</componentId>\n";
297        comContent += "    <userName>JUnit@test.com</userName>\n";
298        comContent += "</comment>\n";
299        return comContent;
300    }
301   
302     public static String getanotherPrincipalCommentTestContentStringForProfile(String commentName, String profileId) {
303        String comContent = "";
304        comContent += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
305        comContent += "<comment xmlns:ns2=\"http://www.w3.org/1999/xlink\">\n";
306        comContent += "    <comments>" + commentName + "</comments>\n";
307        comContent += "    <commentDate>" + DatesHelper.createNewDate() + "</commentDate>\n";
308        comContent += "    <componentId>" + profileId + "</componentId>\n";
309        comContent += "    <userName>anotherPrincipal</userName>\n";
310        comContent += "</comment>\n";
311        return comContent;
312    }
313
314    public static String getCommentTestContentStringForComponent(String commentName, String componentId) {
315        String comContent = "";
316        comContent += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
317        comContent += "<comment xmlns:ns2=\"http://www.w3.org/1999/xlink\">\n";
318        comContent += "    <comments>" + commentName + "</comments>\n";
319        comContent += "    <commentDate>" + DatesHelper.createNewDate() + "</commentDate>\n";
320        comContent += "     <componentId>" + componentId + "</componentId>";
321        comContent += "    <userName>JUnit@test.com</userName>\n";
322        comContent += "</comment>\n";
323        return comContent;
324    }
325   
326     public static String getAnotherPrincipalCommentTestContentStringForComponent(String commentName, String componentId) {
327        String comContent = "";
328        comContent += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
329        comContent += "<comment xmlns:ns2=\"http://www.w3.org/1999/xlink\">\n";
330        comContent += "    <comments>" + commentName + "</comments>\n";
331        comContent += "    <commentDate>" + DatesHelper.createNewDate() + "</commentDate>\n";
332        comContent += "     <componentId>" + componentId + "</componentId>";
333        comContent += "    <userName>anotherPrincipal</userName>\n";
334        comContent += "</comment>\n";
335        return comContent;
336    }
337
338    public static InputStream getTestCommentContent(String content, String descriptionId) {
339        if (descriptionId.contains("profile")) {
340            return new ByteArrayInputStream(getCommentTestContentStringForProfile(content, descriptionId).getBytes());
341        } else {
342            return new ByteArrayInputStream(getCommentTestContentStringForComponent(content, descriptionId).getBytes());
343        }
344    }
345
346    public static String getCommentTestContent(String commentId, String descriptionId) {
347        return getCommentTestContentStringForProfile(commentId, descriptionId);
348    }
349
350    public static InputStream getCommentTestContent() {
351        return getTestCommentContent("Actual", ProfileDescription.PROFILE_PREFIX + "profile1");
352    }
353
354    /**
355     * Testing a big xsd string is a bit hard, so doing a best effort by
356     * checking the xs:element which represent the nested components used in a
357     * profile/component
358     */
359    public static boolean hasComponent(String xsd, String name, String min, String max) {
360        Pattern pattern = Pattern.compile("<xs:element name=\"" + name + "\" minOccurs=\"" + min + "\" maxOccurs=\"" + max + "\">");
361        Matcher matcher = pattern.matcher(xsd);
362        return matcher.find() && !matcher.find(); //find only one
363    }
364
365    /**
366     *
367     * @param bytes is an array of bytes to be written in the file filename
368     * (from scratch!)
369     * @param filename is the name of the file where the array "bytes" is to be
370     * written to
371     * @throws IOException
372     * @throws JAXBException
373     */
374    public static void writeBytesToFile(byte[] bytes, String filename) throws IOException, JAXBException {
375
376        File file = new File(filename);
377        FileOutputStream fop = new FileOutputStream(file);
378
379        fop.write(bytes);
380
381        fop.flush();
382        fop.close();
383
384
385    }
386
387    /**
388     *
389     * @param str is a string which is to be written into the filename (from
390     * scratch!)
391     * @param filename is a filename where the string is to be written to
392     * @throws IOException
393     * @throws JAXBException
394     */
395    public static void writeStringToFile(String str, String filename) throws IOException, JAXBException {
396
397        writeBytesToFile(str.getBytes(), filename);
398
399
400    }
401
402    /**
403     *
404     * @param os is an output stream which is to be written into the filename
405     * (from scratch!)
406     * @param filename is a filename where the stream is to be written to
407     * @throws IOException
408     * @throws JAXBException
409     */
410    public static void writeStreamToFile(ByteArrayOutputStream os, String filename) throws IOException, JAXBException {
411
412        writeBytesToFile(os.toByteArray(), filename);
413
414
415    }
416
417    /**
418     *
419     * @param cdesc is a component which is to be written into the filename
420     * (from scratch!)
421     * @param filename is a filename where the component is to be written to
422     * @throws IOException
423     * @throws JAXBException
424     */
425    public static void writeComponentIntoFile(ComponentDescription cdesc, String filename) throws IOException, JAXBException {
426
427
428        ByteArrayOutputStream os = new ByteArrayOutputStream();
429        marshaller.marshal(cdesc, os);
430
431        writeStreamToFile(os, filename);
432
433    }
434
435    /**
436     * opens a temporary sub-directory dirName in /target/
437     *
438     * @param dirName is the name of the temporary subdirectory which is to be
439     * opened
440     * @return the absolute part for this directory
441     */
442    public static String openTestDir(String dirName) {
443
444        File testDir = new File("target/" + dirName);
445
446
447        testDir.mkdir();
448
449        System.out.println(dirName);
450        //String retval = new File(testDir, dirName).getAbsolutePath();
451        String retval = new File(testDir, "/").getAbsolutePath();
452
453        return (retval);
454
455    }
456}
Note: See TracBrowser for help on using the repository browser.