Skip to content

Commit f1286b0

Browse files
committed
Release 0.2
1 parent 7ed8a4b commit f1286b0

1 file changed

Lines changed: 178 additions & 40 deletions

File tree

app/src/main/java/pt/IPG/messenger/Conversation.java

Lines changed: 178 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package pt.IPG.messenger;
22

33
import android.content.Context;
4+
import android.content.SharedPreferences;
5+
import android.os.AsyncTask;
46
import android.os.Bundle;
57

8+
import android.support.v4.app.FragmentTransaction;
69
import android.support.v7.widget.LinearLayoutManager;
710
import android.support.v7.widget.RecyclerView;
811
import android.view.Menu;
@@ -17,15 +20,25 @@
1720
import org.json.JSONObject;
1821

1922
import java.io.BufferedReader;
23+
import java.io.BufferedWriter;
2024
import java.io.File;
2125
import java.io.FileInputStream;
2226
import java.io.FileNotFoundException;
2327
import java.io.FileOutputStream;
2428
import java.io.IOException;
2529
import java.io.InputStreamReader;
30+
import java.io.OutputStream;
31+
import java.io.OutputStreamWriter;
32+
import java.io.UnsupportedEncodingException;
33+
import java.net.HttpURLConnection;
2634
import java.net.URISyntaxException;
35+
import java.net.URL;
36+
import java.text.ParseException;
37+
import java.text.SimpleDateFormat;
2738
import java.util.ArrayList;
2839
import java.util.Collection;
40+
import java.util.Collections;
41+
import java.util.Date;
2942
import java.util.List;
3043
import java.util.Random;
3144

@@ -140,14 +153,72 @@ public static String random() {
140153
@Override
141154
protected void onCreate(Bundle savedInstanceState) {
142155
super.onCreate(savedInstanceState);
156+
mAdapter = new ConversationRecyclerView(this,setData());
157+
room = getIntent().getExtras().getString("roomName",null);
158+
ID = getIntent().getExtras().getString("ID",null);
159+
143160
setContentView(R.layout.activity_conversation);
161+
setupToolbarWithUpNav(R.id.toolbar, "Alterar para API getuser" , R.drawable.ic_action_back);
144162

145-
setupToolbarWithUpNav(R.id.toolbar, "Julia do Trabalho", R.drawable.ic_action_back);
146163

147-
room = getIntent().getExtras().getString("roomName",null);
148-
ID = getIntent().getExtras().getString("ID",null);
149164

165+
// receber conversa do mongodb
166+
AsyncTask.execute(new Runnable() {
167+
List<ChatData> data = new ArrayList<ChatData>();
168+
169+
@Override
170+
public void run() {
171+
//TODO your background code
172+
//retrieve
173+
String result = getJSONFromUrl(room);
174+
175+
try {
176+
JSONObject jsonRoot = new JSONObject(result);
177+
JSONArray jsonData = jsonRoot.getJSONArray("conversation");
178+
179+
180+
for (int i = 0; i < jsonData.length(); i++) {
181+
ChatData item = new ChatData();
182+
String time = jsonData.getJSONObject(i).getString("createdAt");
183+
//2019-02-19T12:24:06.557Z
184+
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
185+
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
186+
Date date = format.parse(time.replaceAll("Z$", "+0000"));
187+
188+
189+
item.setTime( newFormat.format(date));
190+
String author = jsonData.getJSONObject(i).getJSONObject("author").getString("_id");
191+
if (!author.equals(ID)) {
192+
item.setType("1");
193+
}else{item.setType("2");}
194+
String body = jsonData.getJSONObject(i).getString("body");
195+
item.setText(body);
196+
197+
data.add(item);
198+
}
199+
// update do UI deve ser feito pelo UI
200+
runOnUiThread(new Runnable() {
201+
202+
@Override
203+
public void run() {
204+
Collections.reverse(data);
205+
mAdapter.addItem(data);
206+
// Stuff that updates the UI
207+
208+
}
209+
});
210+
211+
} catch (JSONException e) {
212+
// System.out.println(e.getMessage());
213+
} catch (ParseException e) {
214+
e.printStackTrace();
215+
}
216+
217+
218+
}
219+
});
150220

221+
//--fim receber conversas
151222
// IPG - Alteração -------------- Dinis
152223
encryption = new Encryption();
153224

@@ -164,7 +235,6 @@ protected void onCreate(Bundle savedInstanceState) {
164235
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
165236
mRecyclerView.setHasFixedSize(true);
166237
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
167-
mAdapter = new ConversationRecyclerView(this,setData());
168238
mRecyclerView.setAdapter(mAdapter);
169239
mRecyclerView.postDelayed(new Runnable() {
170240
@Override
@@ -210,6 +280,17 @@ public void onClick(View view) {
210280

211281
// IPG - Alteração -------------- Dinis
212282
try {
283+
// background para fazer cenas na base de dados mongop
284+
AsyncTask.execute(new Runnable() {
285+
@Override
286+
public void run() {
287+
//TODO your background code
288+
// mongoDB save stuff
289+
sendReplyToConversation(room, text.getText().toString());
290+
}
291+
});
292+
293+
213294
//mSocket.emit("new message", room, encryption.Encrypt(text.getText().toString(), Encryption.MessageType.Encrypted), ID);
214295
mSocket.emit("new message", room, text.getText() , ID);
215296
} catch (Exception e) {
@@ -231,7 +312,7 @@ public void onClick(View view) {
231312

232313
@Override
233314
public void onBackPressed() {
234-
Toast.makeText(this,"Fechar Socket!!",Toast.LENGTH_LONG).show();
315+
// Toast.makeText(this,"Fechar Socket!!",Toast.LENGTH_LONG).show();
235316
// fechar socket!!!
236317
// mSocket.disconnect();
237318
// mSocket.emit("leave-room", room);
@@ -243,54 +324,111 @@ public void onBackPressed() {
243324

244325
public List<ChatData> setData(){
245326
List<ChatData> data = new ArrayList<>();
246-
/*
247-
String text[] = {"15 September","Hi, Julia! How are you?", "Hi, Joe, looks great! :) ", "I'm fine. Wanna go out somewhere?", "Yes! Coffe maybe?", "Great idea! You can come 9:00 pm? :)))", "Ok!", "Ow my good, this Kit is totally awesome", "Can you provide other kit?", "I don't have much time, :`("};
248-
String time[] = {"", "5:30pm", "5:35pm", "5:36pm", "5:40pm", "5:41pm", "5:42pm", "5:40pm", "5:41pm", "5:42pm"};
249-
String type[] = {"0", "2", "1", "1", "2", "1", "2", "2", "2", "1"};
327+
return data;
328+
}
250329

251330

331+
@Override
332+
public boolean onCreateOptionsMenu(Menu menu) {
333+
MenuInflater inflater = getMenuInflater();
334+
inflater.inflate(R.menu.menu_userphoto, menu);
335+
return true;
336+
}
252337

253-
String jsonText = new Gson().toJson(text);
254-
String jsonTime = new Gson().toJson(time);
255-
String jsonType = new Gson().toJson(type);
256338

257-
create(this, "storage_text.json", jsonText);
258-
create(this, "storage_time.json", jsonTime);
259-
create(this, "storage_type.json", jsonType);
260-
*/
339+
public String getJSONFromUrl(String ConversationID) {
340+
SharedPreferences settings = getApplication().getSharedPreferences("myPrefs", 0);
341+
String tokenOK = settings.getString("token", ""/*default value*/);
342+
String result ="";
343+
try {
344+
//Connect
345+
// cache problema .... + "?_=" + System.currentTimeMillis()
346+
HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://chat-ipg-04.azurewebsites.net/api/chat/"+ConversationID+ "?_=" + System.currentTimeMillis()).openConnection());
347+
// urlConnection.setDoOutput(false);
348+
urlConnection.setRequestMethod("GET");
349+
urlConnection.setUseCaches(false);
350+
351+
urlConnection.setRequestProperty("Content-Type", "application/json");
352+
urlConnection.setRequestProperty("Accept", "application/json");
353+
urlConnection.setRequestProperty("Authorization", tokenOK);
354+
355+
urlConnection.connect();
356+
urlConnection.setConnectTimeout(10000);
357+
358+
359+
//Read
360+
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
361+
String line = null;
362+
StringBuilder sb = new StringBuilder();
363+
while ((line = bufferedReader.readLine()) != null) {
364+
sb.append(line);
365+
}
366+
bufferedReader.close();
367+
result = sb.toString();
368+
urlConnection.disconnect();
369+
370+
} catch (UnsupportedEncodingException e){
371+
return result;
372+
// e.printStackTrace();
373+
} catch (IOException e) {
374+
return result;
375+
// e.printStackTrace();
376+
}
261377

262-
/*
263-
String storagejsonText = read(this, "storage_text.json");
264-
String[] text = storagejsonText.substring(1, storagejsonText.length()-1).split("\",\""); //remove [ and ] , then split by ','
265-
String storagejsonTime = read(this, "storage_time.json");
266-
String[] time = storagejsonTime.substring(1, storagejsonTime.length()-1).split("\",\"");//remove [ and ] , then split by ','
267-
String storagejsonType = read(this, "storage_type.json");
268-
String[] type = storagejsonType.substring(1, storagejsonType.length()-1).split("\",\""); //remove [ and ] , then split by ','
378+
return result;
269379

380+
}
270381

271382

272-
for (int i=0; i<text.length; i++){
273-
ChatData item = new ChatData();
274-
item.setType(type[i]);
275-
item.setText(text[i]);
276-
item.setTime(time[i]);
277-
data.add(item);
278-
}
279-
*/
280-
// ler
281-
return data;
383+
public String sendReplyToConversation(String ConversationID, String msg) {
384+
SharedPreferences settings = getApplication().getSharedPreferences("myPrefs", 0);
385+
String tokenOK = settings.getString("token", ""/*default value*/);
282386

283-
}
387+
String result ="";
388+
try {
389+
//Connect
390+
HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://chat-ipg-04.azurewebsites.net/api/chat/"+ConversationID).openConnection());
391+
urlConnection.setDoOutput(true);
392+
urlConnection.setRequestProperty("Accept", "application/json");
393+
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
394+
urlConnection.setRequestMethod("POST");
395+
urlConnection.setRequestProperty("Authorization", tokenOK);
396+
397+
String params = "composedMessage="+msg;
398+
urlConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
399+
400+
urlConnection.connect();
401+
urlConnection.setConnectTimeout(10000);
402+
403+
//Write
404+
OutputStream outputStream = urlConnection.getOutputStream();
405+
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
406+
writer.write(params);
407+
writer.close();
408+
outputStream.close();
409+
410+
//Read
411+
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
412+
String line = null;
413+
StringBuilder sb = new StringBuilder();
414+
while ((line = bufferedReader.readLine()) != null) {
415+
sb.append(line);
416+
}
417+
bufferedReader.close();
418+
result = sb.toString();
284419

285420

286-
@Override
287-
public boolean onCreateOptionsMenu(Menu menu) {
288-
MenuInflater inflater = getMenuInflater();
289-
inflater.inflate(R.menu.menu_userphoto, menu);
290-
return true;
291-
}
292421

422+
} catch (UnsupportedEncodingException e){
423+
return result;
424+
// e.printStackTrace();
425+
} catch (IOException e) {
426+
return result;
427+
// e.printStackTrace();
428+
}
429+
return result;
293430

431+
}
294432

295433

296434
}

0 commit comments

Comments
 (0)