summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/binding-atom-runtime/src/test/java/org/apache/tuscany/sca/binding/atom/ContentNegotiationTest.java
blob: e9ebf046a66a124fd90985eea5fd677e5f90f223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.tuscany.sca.binding.atom;

import java.io.IOException;
import java.io.Reader;
import java.util.Date;

import junit.framework.Assert;

import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.protocol.Response.ResponseType;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.tuscany.sca.node.Contribution;
import org.apache.tuscany.sca.node.ContributionLocationHelper;
import org.apache.tuscany.sca.node.Node;
import org.apache.tuscany.sca.node.NodeFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;


/**
 * Tests use of content negotiation for Atom binding in Tuscany.
 * Uses the SCA provided Provider composite to act as a server.
 * Uses the Abdera provided Client to act as a client.
 *
 * @version $Rev$ $Date$
 */
public class ContentNegotiationTest {
    public final static String providerURI = "http://localhost:8084/customer";

    protected static Node scaProviderNode;

    protected static CustomerClient testService;
    protected static Abdera abdera;
    protected static AbderaClient client;
    protected static Parser abderaParser;
    protected static String lastId;

    @BeforeClass
    public static void init() throws Exception {
        try {
            //System.out.println(">>>ContentNegotiationTest.init");
            String contribution = ContributionLocationHelper.getContributionLocation(ContentNegotiationTest.class);

            scaProviderNode = NodeFactory.newInstance().createNode("org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution));
            scaProviderNode.start();

            abdera = new Abdera();
            client = new AbderaClient(abdera);
            abderaParser = Abdera.getNewParser();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    @AfterClass
    public static void destroy() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.destroy");
        if (scaProviderNode != null) {
            scaProviderNode.stop();
        }
    }

    @Test
    public void testPrelim() throws Exception {
        Assert.assertNotNull(scaProviderNode);
        Assert.assertNotNull( client );
    }

    @Test
    public void testPost() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.testPost");
        // Testing of entry creation
        Factory factory = abdera.getFactory();
        String customerName = "Fred Farkle";
        Entry entry = factory.newEntry();
        entry.setTitle("customer " + customerName);
        entry.setUpdated(new Date());
        entry.addAuthor("Apache Tuscany");
        // ID created by collection.
        Content content = abdera.getFactory().newContent();
        content.setContentType(Content.Type.TEXT);
        content.setValue(customerName);
        entry.setContentElement(content);

        RequestOptions opts = new RequestOptions();
        final String contentType = "application/atom+xml";
        opts.setContentType(contentType);
        // AtomTestCaseUtils.printRequestHeaders( "Post request headers", "   ", opts );
        IRI colUri = new IRI(providerURI).resolve("customer");
        // res = client.post(colUri.toString() + "?test=foo", entry, opts);
        ClientResponse res = client.post(colUri.toString(), entry, opts);

        // Assert response status code is 201-OK.
        // Assert response header Content-Type: application/atom+xml; charset=UTF-8
        Assert.assertEquals(201, res.getStatus());
        String returnedContentType = res.getContentType().toString().trim();
        Assert.assertEquals(contentType, returnedContentType );

        String eTag = res.getHeader( "ETag" );
        if ( eTag != null)
            lastId = eTag.substring( 1, eTag.length()-1);

        // AtomTestCaseUtils.printResponseHeaders( "Entry post response headers:", "   ", res );
        // System.out.println("Entry post response content:");
        // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument());
    }

    @Test
    public void testXMLEntryGet() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.testXMLEntryGet");
        RequestOptions opts = new RequestOptions();
        opts.setHeader( "Accept", "application/atom+xml" );

        IRI colUri = new IRI(providerURI).resolve("customer");
        ClientResponse res = client.get(colUri.toString() + "/" + lastId, opts);
        Assert.assertEquals(200, res.getStatus());
        String returnedContentType = res.getContentType().toString().trim();
        // Assert.assertEquals(contentType, returnedContentType );
        res.release();
    }

    @Test
    public void testJSONEntryGet() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.testJSONEntryGet");
        RequestOptions opts = new RequestOptions();
        opts.setHeader( "Accept", "application/json" );

        IRI colUri = new IRI(providerURI).resolve("customer");
        ClientResponse res = client.get(colUri.toString() + "/" + lastId, opts);
        try {
            Assert.assertEquals(200, res.getStatus());
            // Abdera 0.4 throws exception on getContentType with application/json.
            // System.out.println( "ContentNegotiationTest.testJSONEntryGet contentType=" + res.getContentType());
            String contentType = res.getHeader( "Content-Type");
            Assert.assertTrue( -1 < contentType.indexOf( "application/json" ));
            // Following is a poor man's JSONObject test to avoid dependency on JSON libs.
            // JSONObject jsonResp = new JSONObject(res.);
            // Assert.assertEquals(12345, jsonResp.getInt("result"));
            String responseBody = readResponse( res.getReader() );
            Assert.assertTrue( responseBody.startsWith( "{") );
            Assert.assertTrue( responseBody.endsWith( "}") );
            Assert.assertTrue( -1 < responseBody.indexOf( "\"id\"" ));
            Assert.assertTrue( -1 < responseBody.indexOf( "\"title\"" ));
            Assert.assertTrue( -1 < responseBody.indexOf( "\"updated\"" ));
            // AtomTestCaseUtils.printResponseHeaders( "JSON Entry response headers:", "   ", res );
            // System.out.println( "ContentNegotiationTest.testJSONEntryGet JSON entry body=" + responseBody );
        } finally {
            res.release();
        }
    }

    @Test
    public void testXMLFeedGet() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.testXMLFeedGet");
        RequestOptions opts = new RequestOptions();
        opts.setHeader( "Accept", "application/atom+xml" );

        // Atom feed request
        ClientResponse res = client.get(providerURI, opts);
        Assert.assertNotNull(res);
        try {
            // Asser feed provided since no predicates
            Assert.assertEquals(200, res.getStatus());
            Assert.assertEquals(ResponseType.SUCCESS, res.getType());
            // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", "   ", res );
            // System.out.println("Feed response content:");
            // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument());

            // Perform other tests on feed.
            Document<Feed> doc = res.getDocument();
            Assert.assertNotNull( doc );
            Feed feed = doc.getRoot();
            Assert.assertNotNull( feed );
            // RFC 4287 requires non-null id, title, updated elements
            Assert.assertNotNull( feed.getId() );
            Assert.assertNotNull( feed.getTitle() );
            Assert.assertNotNull( feed.getUpdated() );
            // AtomTestCaseUtils.printFeed( "Feed values", "   ", feed );
        } finally {
            res.release();
        }
    }

    @Test
    public void testJSONFeedGet() throws Exception {
        //System.out.println(">>>ContentNegotiationTest.testJSONFeedGet");
        RequestOptions opts = new RequestOptions();
        opts.setHeader( "Accept", "application/json" );

        // JSON feed request
        ClientResponse res = client.get(providerURI, opts);
        Assert.assertNotNull(res);
        try {
            // Assert feed provided since no predicates
            Assert.assertEquals(200, res.getStatus());
            // Abdera 0.4 throws exception on getContentType with application/json.
            // System.out.println( "ContentNegotiationTest.testJSONEntryGet contentType=" + res.getContentType());
            String contentType = res.getHeader( "Content-Type");
            Assert.assertTrue( -1 < contentType.indexOf( "application/json" ));
            // Following is a poor man's JSONObject test to avoid dependency on JSON libs.
            // JSONObject jsonResp = new JSONObject(res.);
            // Assert.assertEquals(12345, jsonResp.getInt("result"));
            String responseBody = readResponse( res.getReader() );
            Assert.assertTrue( responseBody.startsWith( "{") );
            Assert.assertTrue( responseBody.endsWith( "}") );
            Assert.assertTrue( -1 < responseBody.indexOf( "\"id\"" ));
            Assert.assertTrue( -1 < responseBody.indexOf( "\"title\"" ));
            Assert.assertTrue( -1 < responseBody.indexOf( "\"updated\"" ));
            Assert.assertTrue( -1 < responseBody.indexOf( "\"entries\"" ));
            // AtomTestCaseUtils.printResponseHeaders( "JSON Entry response headers:", "   ", res );
            // System.out.println( "ContentNegotiationTest.testJSONEntryGet JSON entry body=" + responseBody );
        } finally {
            res.release();
        }
    }

    protected String readResponse( Reader responseReader ) {
        if ( responseReader == null ) return "";
        StringBuffer sb = new StringBuffer(1024);
        try {
            int charValue = 0;
            while ((charValue = responseReader.read()) != -1) {
                //result = result + (char) charValue;
                sb.append((char)charValue);
            }
        } catch ( IOException e ) {
        }
        return sb.toString();
    }
}