Merge test folder of test branch
[iotivity.git] / test / src / common / commonutil / java / java-android / cloud / org / iotivity / cloud / GetAuthCode.java
1 /******************************************************************
2  * Copyright 2018 Samsung Electronics All Rights Reserved.
3  *
4  *
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  ******************************************************************/
18
19 package org.iotivity.cloud;
20
21 import java.io.BufferedReader;
22 import java.io.DataOutputStream;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.net.CookieHandler;
26 import java.net.CookiePolicy;
27 import java.net.HttpURLConnection;
28 import java.net.URL;
29 import java.net.URLEncoder;
30 import java.net.CookieManager;
31
32 import android.os.AsyncTask;
33 import android.util.Log;
34
35 import org.iotivity.configuration.IConfiguration;
36 import org.iotivity.configuration.ReadConfigPropFile;
37
38 public class GetAuthCode extends AsyncTask<Void, String, String>
39         implements IConfiguration {
40
41     static HttpURLConnection urlConnection = null;
42     static String            authCode      = null;
43
44     @Override
45     protected String doInBackground(Void... uri) {
46         String responseString = null;
47         try {
48
49             CookieManager cookieManager = new CookieManager(null,
50                     CookiePolicy.ACCEPT_ALL);
51             CookieHandler.setDefault(cookieManager);
52
53             // get initial login page
54             responseString = getRequest(INIT_GET_LOGIN_URL);
55             int responseCode = urlConnection.getResponseCode();
56             String authText = getAuthenticationToken(responseString);
57             String authURLText = URLEncoder.encode(authText, "UTF-8");
58
59             // prepare post data
60             String demoPostData = PAR_POST_VAL + AUTHENTICITY_TOKEN
61                     + authURLText + "&login="
62                     + ReadConfigPropFile.s_mGitHubUserId + "&password="
63                     + ReadConfigPropFile.s_mGitHubUserPassword;
64
65             // Post request for login
66             responseString = postRequest(LOGIN_URL, demoPostData);
67             responseCode = urlConnection.getResponseCode();
68             Log.d(COMMON_TAG, "postRequest Response Code : " + responseCode);
69
70             // get request for auth code
71             responseString = getRequest(IOTIVITY_CLOUD_URL);
72             responseCode = urlConnection.getResponseCode();
73             Log.d(COMMON_TAG, "getRequest Response Code : " + responseCode);
74
75             authCode = getAuthenticationCode(responseString);
76
77             if (authCode.isEmpty()) {
78                 System.out.println("AuthCode Not Found !!!");
79             } else
80                 System.out.println("AUTH CODE:" + authCode);
81
82         } catch (Exception ex) {
83             System.out.println("Exception Occurred:" + ex.getMessage());
84         }
85
86         return authCode;
87     }
88
89     // Function for Get Request
90     public static String getRequest(String sUrl) {
91         BufferedReader reader = null;
92         String strRet = null;
93         try {
94             URL url = new URL(sUrl);
95
96             // Create the request to OpenWeatherMap, and open the connection
97             urlConnection = (HttpURLConnection) url.openConnection();
98             urlConnection.setRequestMethod("GET");
99             urlConnection.connect();
100
101             // Read the input stream into a String
102             InputStream inputStream = urlConnection.getInputStream();
103             StringBuffer buffer = new StringBuffer();
104             if (inputStream == null) {
105                 // Nothing to do.
106                 return null;
107             }
108             reader = new BufferedReader(new InputStreamReader(inputStream));
109
110             String line;
111             while ((line = reader.readLine()) != null) {
112                 buffer.append(line + "\n");
113             }
114
115             if (buffer.length() == 0) {
116                 // Stream was empty. No point in parsing.
117                 return null;
118             }
119
120             strRet = buffer.toString();
121         } catch (Exception ex) {
122             System.out.println("Exception Occured:" + ex.getMessage());
123         }
124
125         return strRet;
126     }
127
128     // Function for Post Request
129     public static String postRequest(String sUrl, String urlParameters) {
130         BufferedReader reader = null;
131         String strRet = null;
132         try {
133             URL url = new URL(sUrl);
134
135             // Create the request to OpenWeatherMap, and open the connection
136             urlConnection = (HttpURLConnection) url.openConnection();
137             urlConnection.setRequestMethod("POST");
138             urlConnection.setDoOutput(true);
139
140             DataOutputStream write = new DataOutputStream(
141                     urlConnection.getOutputStream());
142             write.writeBytes(urlParameters);
143             write.flush();
144             write.close();
145
146             // Read the input stream into a String
147             InputStream inputStream = urlConnection.getInputStream();
148             StringBuffer buffer = new StringBuffer();
149             if (inputStream == null) {
150                 // Nothing to do.
151                 return null;
152             }
153             reader = new BufferedReader(new InputStreamReader(inputStream));
154
155             String line;
156             while ((line = reader.readLine()) != null) {
157                 buffer.append(line + "\n");
158             }
159
160             if (buffer.length() == 0) {
161                 return null;
162             }
163
164             strRet = buffer.toString();
165         } catch (Exception ex) {
166             System.out.println("Exception Occured:" + ex.getMessage());
167         }
168
169         return strRet;
170     }
171
172     public String getAuthenticationToken(String htmlbody) {
173         String authToken = htmlbody.substring(htmlbody.indexOf(
174                 "<input name=\"authenticity_token\" type=\"hidden\" value=\"")
175                 + 1);
176         authToken = authToken.substring(
177                 authToken.indexOf("value=\"") + "value=\"".length(),
178                 authToken.indexOf("\" />"));
179         return authToken;
180     }
181
182     // get Authentication Code
183     public String getAuthenticationCode(String htmlbody) {
184         String authToken = htmlbody.substring(htmlbody.indexOf("<a href=") + 1,
185                 htmlbody.indexOf("a>"));
186         String authCode = authToken.substring(
187                 authToken.indexOf("?code=") + "?code=".length(),
188                 authToken.indexOf("\">"));
189         return authCode;
190     }
191
192     @Override
193     protected void onPostExecute(String result) {
194         super.onPostExecute(result);
195
196     }
197 }