Accepting code review comments ... simple stuff
[simpleHTTP.git] / src / eu / cepl / network / SimpleHTTPTest.java
blob98124dbd3177c492166f81c128baf308f6f8e384
1 package eu.cepl.network;
3 import java.io.BufferedInputStream;
4 import java.io.BufferedReader;
5 import java.io.ByteArrayInputStream;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileNotFoundException;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.net.HttpURLConnection;
13 import java.net.URL;
14 import java.util.Arrays;
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.prefs.Preferences;
19 import javax.naming.AuthenticationException;
21 import org.junit.Assert;
22 import org.junit.Before;
23 import org.junit.Test;
24 import org.monkey.nelson.io.BrokenInputStream;
25 import org.monkey.nelson.testurl.TestURLRegistry;
27 public class SimpleHTTPTest {
29 private static final String GoogleLoginURL = "https://www.google.com/accounts/ClientLogin";
30 private static final String feedURL = "http://www.blogger.com/feeds/default/blogs";
31 private static final String testDataString = "Byl pozdní večer první máj!\n"
32 + "Нас было много на челне;\nИные парус напрягали,\nДругие дружно упирали\n"
33 + "В глубь мощны веслы. В тишине\nНа руль склонясь, наш кормщик умный\nВ "
34 + "молчаньи правил грузный чолн;\nА я — беспечной веры полн —\nПловцам я пел....";
35 private static final String testFileName = "test/Wave.svg";
36 private static final int MAX_BYTE_ARRAY = 100000;
38 @Before
39 public void setupTestURLs() throws Exception {
40 InputStream stringIS = new ByteArrayInputStream(testDataString
41 .getBytes());
42 InputStream imageIS = null;
43 imageIS = new FileInputStream(new File(testFileName));
44 TestURLRegistry.register("machaPuskin", stringIS);
45 TestURLRegistry.register("dukeAI", imageIS);
47 // Special inputStream which fails
48 // when read more than 10 bytes it will throw an IOException.
49 // saved for future testing, not used now
50 int bytesToRead = 10;
51 @SuppressWarnings("unused")
52 BrokenInputStream testStringIS = new BrokenInputStream(stringIS,
53 bytesToRead);
57 @Test
58 public final void virtualTestSimpleHTTPGet() throws IOException {
59 SimpleHTTP testURL = new SimpleHTTP(new URL("testurl:machaPuskin"));
60 Assert.assertNotNull(testURL);
61 String caughtString = testURL.get();
62 Assert.assertEquals(testDataString, caughtString);
65 @Test
66 public final void virtualTestSimpleHTTPGetBinary() throws IOException {
67 SimpleHTTP testURL = null;
69 testURL = new SimpleHTTP(new URL("testurl:dukeAI"));
70 Assert.assertNotNull(testURL);
72 byte[] caughtByteArray = new byte[MAX_BYTE_ARRAY];
73 BufferedInputStream caughtIS = testURL.getInputStream(null);
74 int caughtReadCount = caughtIS.read(caughtByteArray);
75 caughtIS.close();
77 byte[] expectedByteArray = new byte[MAX_BYTE_ARRAY];
78 BufferedInputStream expectedIS = new BufferedInputStream(
79 new FileInputStream(testFileName));
80 int expectedReadCount = expectedIS.read(expectedByteArray);
81 expectedIS.close();
83 Assert.assertEquals(expectedReadCount, caughtReadCount);
85 Assert.assertTrue(Arrays.equals(expectedByteArray, caughtByteArray));
88 @Test
89 public final void yahooTestSimpleHTTPBufReader() throws IOException {
90 SimpleHTTP yahoo = new SimpleHTTP("http://www.yahoo.com/");
91 BufferedReader in = new BufferedReader(new InputStreamReader(yahoo
92 .getInputStream(null), "UTF-8"));
94 String outString = "";
95 String inputLine = "";
96 while ((inputLine = in.readLine()) != null)
97 outString += inputLine + "\n";
99 Assert.assertTrue(outString.length() > 0);
102 @Test
103 public final void yahooTestSimpleHTTPReader() throws IOException {
104 SimpleHTTP yahoo = new SimpleHTTP("http://www.yahoo.com/");
105 BufferedReader in = new BufferedReader(new InputStreamReader(yahoo
106 .getInputStream(null), "UTF-8"));
108 String outString = "";
109 String inCh = "";
110 while ((inCh = in.readLine()) != null)
111 outString += inCh;
113 Assert.assertTrue(outString.length() > 0);
116 @Test
117 public final void yahooTestSimpleHTTPGet() throws IOException {
118 String content = new SimpleHTTP("http://www.yahoo.com/").get();
119 Assert.assertTrue(content.length() > 0);
122 @Test
123 public final void yahooTestCheckResponseCode() throws Exception {
124 SimpleHTTP req = new SimpleHTTP("http://www.ceplovi.cz/");
125 @SuppressWarnings("unused")
126 String content = req.get();
127 Assert.assertEquals(HttpURLConnection.HTTP_OK, req.getResponseCode());
129 req = new SimpleHTTP("http://www.ceplovi.cz/testFailureSimpleHTTP");
130 content = req.get();
131 Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, req
132 .getResponseCode());
136 * Get ClientLogin token from Google Blogger.
138 * @see {@link http
139 * ://code.google.com/apis/accounts/docs/AuthForInstalledApps.html}
141 * @return String ClientLogin token
142 * @throws IOException
144 private String googleLogin(SimpleHTTP poster, Preferences prefs)
145 throws IOException {
146 String logname = prefs.get("login", "");
147 String passwd = prefs.get("password", "");
148 if (logname.length() == 0) { // TODO testing of environment should be
149 // separated
150 throw new RuntimeException(
151 "Missing login in the system preferences");
154 Map<String, String> loginHeaders = new HashMap<String, String>();
155 loginHeaders.put("accountType", "HOSTED_OR_GOOGLE");
156 loginHeaders.put("Email", logname);
157 loginHeaders.put("Passwd", passwd);
158 loginHeaders.put("service", "blogger");
159 loginHeaders.put("source", "none-mcepl-simpleHTTPTest");
161 String result = poster.post(loginHeaders);
163 int respCode = 0;
164 if ((respCode = poster.getResponseCode()) != HttpURLConnection.HTTP_OK) {
165 Assert.fail("Login to Google failed (response code " + respCode
166 + ")");
169 String[] tmpSplit;
170 String token = "";
171 String[] splitted = result.split(System.getProperty("line.separator"));
173 for (String spl : splitted) {
174 tmpSplit = spl.split("=", 2);
175 if (tmpSplit[0].equals("Auth")) {
176 token = tmpSplit[1];
179 return token;
182 @Test
183 public final void googleLoginTestSimpleHTTPPost() throws IOException,
184 AuthenticationException {
185 Preferences prefs = Preferences.userRoot().node(
186 "eu.cepl.postBlog.PostBlog");
188 String token = googleLogin(new SimpleHTTP(GoogleLoginURL), prefs);
189 Assert.assertTrue("Not having Google token!", token.length() > 0);
191 Map<String, String> postHeaders = new HashMap<String, String>();
192 postHeaders.put("GData-Version", "2");
193 postHeaders.put("Authorization", "GoogleLogin auth=" + token);
194 int respLen = new SimpleHTTP(feedURL).get(postHeaders).length();
196 Assert.assertTrue("response.length = " + respLen, respLen > 0);