Reading all new messages from my gmail using javamail - java

I have an application which contains a GUI, it is using Javamail. When i open this Jframe I have to see messages that are sent to my mail on a jTextArea.
The problem is when i wrote my code it only shows just the last message sent.
How do I display all new messages in my inbox?
This is my code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "mymail#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymail#gmail.com", "mypassword");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "mymail#gmail.com", "mypaswword");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_ONLY);
Message[] msg = fldr.getMessages();
Address[] address;
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
fldr.close(true);
store.close();
} catch (Exception e) {
System.out.println(e);
}

You repeatedly set the text of the jTextArea1 to the same contents in your loop over messages here:
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
You should build a StringBuilder with all the messages and then set the contents of the jTextArea1
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < msg.length; i++) {
sb.append("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
jTextArea1.setText(sb.toString());
You can then make this a lot more legible by using an enhanced for loop and using the append method of the StringBuilder.
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());

final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());

Related

How to parse JSON File to Object

I have below item, how to parse the nested object into java variable. I am using JSON document but not sure how to parse the sub object. Please see the JSON item and java code
JSON:
{
"_id" : "328",
"website" : "www.abc.com",
"addresses" : [
{
"addressType" : "PRIMARY",
"address" : "102 Yonge Street",
"city" : "Toronto",
"postalCode" : "M2N 6T6",
"state" : {
"code" : "ON",
"name" : "Ontario",
"countryCode" : "CA"
},
"country" : "Canada"
},
{
"addressType" : "SECONDARY",
"address" : "180 Yonge Street",
"city" : "Toronto",
"postalCode" : "L6P 6T7",
"state" : {
"code" : "ON",
"name" : "Ontario",
"countryCode" : "CA"
},
"country" : "Canada"
}
],
"phoneNumber" : "123456"
}
Java Code:
DynamicMappingFile objDynoMapping = new DynamicMappingFile();
ConfigReader objConfigReader = new ConfigReader();
public String strSQL(String strFullDocument)
{
String sqlInsertStatement = "";
System.out.println("Value of strFullDocument is " + strFullDocument);
String lstrInsertColumnStatement ="";
String charAfterColumnStatement = ")";
String lstrInsertValuesStatement ="values (";
String lstrColumnValues = "";
String lstrBSONDocValue = "";
String lstrColumnName;
int columnIndex = 0;
int documentLength = BsonDocument.parse(strFullDocument).size();
final BufferedReader br;
String lstrMySQLColumneName="";
String MySQLColumnNames = "";
String lstrMongoandMySQLDBFields="";
int lstrBSONDoubleValue = 0;
try {
br = new BufferedReader(new FileReader("./Configuration/MongoMySQLMapping.csv"));
lstrInsertColumnStatement = lstrInsertColumnStatement.concat("Insert into " + objConfigReader.mySQLTable + " (");
System.out.println("Value of Insert statement is : " + lstrInsertColumnStatement);
while(br.ready()){
lstrMongoandMySQLDBFields = br.readLine(); //Skip the header line
System.out.println(lstrMongoandMySQLDBFields);
objDynoMapping.add(objDynoMapping.new MapFields(lstrMongoandMySQLDBFields));
}
}
catch(Exception errBuff) {
System.out.println(errBuff.toString());
}
System.out.println("Length of Document is " + documentLength);
lstrColumnName = BsonDocument.parse(strFullDocument).keySet().toString().replace("[", "").replace("]", "");
System.out.println("value of lstrcolumnname");
Set<String> setKeys = BsonDocument.parse(strFullDocument).keySet();
Iterator<String> itr = setKeys.iterator();
System.out.println("Value of keys");
while(itr.hasNext())
{
System.out.println("Inside while");
String keys = (String) itr.next();
lstrMySQLColumneName = objDynoMapping.lsMapFields.get(keys).keySet().toString().replace("[", "").replace("]", "");
System.out.println("lstrMySQLColumneName" + lstrMySQLColumneName);
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Inside object id");
lstrBSONDocValue = (String)BsonDocument.parse(strFullDocument).get(keys).asObjectId().getValue().toString();
System.out.println("lstrBSONDocValue is" + lstrBSONDocValue);
}
else if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
// details[i] = BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Inside else of string");
lstrBSONDocValue = (String)BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Value is " + lstrColumnValues);
// System.out.println("Value of details is " + details[i]);
}
else if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
// details[i] = BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Inside int value");
lstrBSONDocValue = String.valueOf(BsonDocument.parse(strFullDocument).get(keys).asInt32().getValue());
System.out.println("Value is " + lstrBSONDoubleValue);
// System.out.println("Value of details is " + details[i]);
}
if(columnIndex!=documentLength-1)
{
System.out.println("insode column index");
MySQLColumnNames = MySQLColumnNames.concat(lstrMySQLColumneName + ",");
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat(String.valueOf(lstrBSONDocValue) + ",");
System.out.println("After is " + lstrColumnValues);
}
}
else
{
System.out.println("Insode else column");
MySQLColumnNames = MySQLColumnNames.concat(lstrMySQLColumneName);
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\"");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat(String.valueOf(lstrBSONDocValue));
System.out.println("After is " + lstrColumnValues);
}
//
// System.out.println("lstrColumnValues 1 is " + lstrColumnValues);
}
columnIndex++;
}
sqlInsertStatement = sqlInsertStatement.concat(lstrInsertColumnStatement + MySQLColumnNames + charAfterColumnStatement + lstrInsertValuesStatement + lstrColumnValues + ")");
System.out.println("Final Value of Insert is " + sqlInsertStatement);
return sqlInsertStatement;
}

How to get LAC and Cell id for LTE Network

i am using GsmCellLocation to get LAC and cell id for 3G network with below code :
mCid = gmsCellLocation.getCid() & 0xffff;
mLac = gmsCellLocation.getLac();
and is there any library or formula how to get/calculate the correct LAC and cell id for LTE network (4G) ? Thanks.
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> cellInfoList = telephonyManager.getAllCellInfo();
for (int i = 0; i < cellInfoList.size(); i++) {
if (cellInfoList.get(i) instanceof CellInfoLte) {
CellInfoLte cellInfoLte = (CellInfoLte) cellInfoList.get(i);
mCid = cellInfoLte.getCellIdentity().getCi();
mLac = cellInfoLte.getCellIdentity().getTac();
}
}
Note the method name, it is getCi for LTE. Also, getTac for LTE instead of getLac. See this answer for more.
I hope this might help you :
public class MobileInfoRecognizer {
public String getCellInfo(CellInfo cellInfo) {
String additional_info;
if (cellInfo instanceof CellInfoGsm) {
CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo;
CellIdentityGsm cellIdentityGsm = cellInfoGsm.getCellIdentity();
additional_info = "cell identity " + cellIdentityGsm.getCid() + "\n"
+ "Mobile country code " + cellIdentityGsm.getMcc() + "\n"
+ "Mobile network code " + cellIdentityGsm.getMnc() + "\n"
+ "local area " + cellIdentityGsm.getLac() + "\n";
} else if (cellInfo instanceof CellInfoLte) {
CellInfoLte cellInfoLte = (CellInfoLte) cellInfo;
CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
additional_info = "cell identity " + cellIdentityLte.getCid() + "\n"
+ "Mobile country code " + cellIdentityLte.getMcc() + "\n"
+ "Mobile network code " + cellIdentityLte.getMnc() + "\n"
+ "physical cell " + cellIdentityLte.getPci() + "\n"
+ "Tracking area code " + cellIdentityLte.getTac() + "\n";
} else if (cellInfo instanceof CellInfoWcdma){
CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo;
CellIdentityWcdma cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
additional_info = "cell identity " + cellIdentityWcdma.getCid() + "\n"
+ "Mobile country code " + cellIdentityWcdma.getMcc() + "\n"
+ "Mobile network code " + cellIdentityWcdma.getMnc() + "\n"
+ "local area " + cellIdentityWcdma.getLac() + "\n";
}
return additional_info;
}
}

Output on new line WITHOUT for loop

I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.

When i want add a object from request json in an ArrayList

Well, I consult a JSON object by url , I get the object and add it to a string, there all right, the problem is when I add it to the ArrayList this line is skipped and not executed when we add , anyone know why?
public void consult(String val_user){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
"http://"+ippref+":8080/Activo/webresources/activo.entities.historialactivos/consulta/"+val_user+"", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String item = "";
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
item += "Actividad: " + obj.getString("actividad") + "\r\n";
item += "Activo NS: " + obj.getString("activo") + "\r\n";
item += "Fecha: " + obj.getString("fecha") + "\r\n";
item += "Id Activo: " + obj.getString("idActivo") + "\r\n";
item += "Id Historial: " + obj.getString("idHistorialActivo") + "\r\n";
item += "Id Incidencia: " + obj.getString("idIncidencia") + "\r\n";
item += "Id Usuario: " + obj.getString("idUsuario") + "\r\n";
item += "Incidencia: " + obj.getString("incidencia") + "\r\n";
item += "Observaciones: " + obj.getString("observaciones") + "\r\n";
item += "Oficina: " + obj.getString("oficina") + "\r\n";
item += "Tipo de movimiento: " + obj.getString("tipoMovimiento") + "\r\n";
item += "Usuario: " + obj.getString("usuario" + "\r\n");
array.add(item);
item = "";
} catch (JSONException ex) {
ex.printStackTrace();
}
metodo_adapter();
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
In array.add(item) when I do execute the debug skip the line of code.
array.add(item);
item = ""; // This line is causing issue.
Don't make your item string empty like this because String is a reference based variable and if you will do like this you will end up storing " " in your array.
Better define your String item = ""; inside try block
only problem because you put
String item = "";
outside for loop ,, this mean all array list look to single object , mean only last one will be have data
solution must do this
for (int i = 0; i < response.length(); i++) {
try {
String item = "";
JSONObject obj = response.getJSONObject(i);
item += "Actividad: " + obj.getString("actividad") + "\r\n";
item += "Activo NS: " + obj.getString("activo") + "\r\n";
item += "Fecha: " + obj.getString("fecha") + "\r\n";
item += "Id Activo: " + obj.getString("idActivo") + "\r\n";
item += "Id Historial: " + obj.getString("idHistorialActivo") + "\r\n";
item += "Id Incidencia: " + obj.getString("idIncidencia") + "\r\n";
item += "Id Usuario: " + obj.getString("idUsuario") + "\r\n";
item += "Incidencia: " + obj.getString("incidencia") + "\r\n";
item += "Observaciones: " + obj.getString("observaciones") + "\r\n";
item += "Oficina: " + obj.getString("oficina") + "\r\n";
item += "Tipo de movimiento: " + obj.getString("tipoMovimiento") + "\r\n";
item += "Usuario: " + obj.getString("usuario" + "\r\n");
array.add(item);
item = "";
} catch (JSONException ex) {
ex.printStackTrace();
}
metodo_adapter();
adapter.notifyDataSetChanged();
}
will solve your problem

appendFile into textfile that dont overwrite

Im loosing on append method.
I have a program that inputs an information then printing in a text file.
The problem is, I want to append the new input of information into text file too without overwriting, it means that if I rerun the program the information that I encoded will be in the textfile together with the encoded on the last run of the program.
Please help me. Here is the program:
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
System.out.println("STUDENT INFORMATION");
System.out.println("-------------------");
System.out.println("Full Name : ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("\nCourse and Year : ");
String yearcourse = sc.nextLine();
System.out.println("\nStudent Number : ");
String studentnumber = sc.nextLine();
System.out.println("\nE-mail Address : ");
String eadd = sc.nextLine();
System.out.println("\nCellphone Number : ");
String cpnumber = sc.nextLine();
System.out.println("\nGender : ");
String gender = sc.nextLine();
System.out.println("\nAge : ");
String age = sc.nextLine();
System.out.println("\nDate of Birth : ");
String dob = sc.nextLine();
System.out.println("\nCivil Status : ");
String status = sc.nextLine();
System.out.println("\nAddress : ");
String address = sc.nextLine();
System.out.println("\n\n________________________________________________");
System.out.println("STUDENT INFORMATION");
System.out.println("\nName : " + name + "");
System.out.println("Year and Course : " + yearcourse + "");
System.out.println("Student Number : " + studentnumber + "");
System.out.println("E-mail Address : " + eadd + "");
System.out.println("Cellphone Number : " + cpnumber + "");
System.out.println("Gender : " + gender + "");
System.out.println("Age : " + age + "");
System.out.println("Date of Birth : " + dob + "");
System.out.println("Civil Status : " + status + "");
System.out.println("Address : " + address + "");
System.out.println("");
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)){
BufferedWriter bufferWritter = new BufferedWriter(writer);
writer.println("\nSTUDENT INFORMATION:");
writer.println("--------------------");
writer.println("Name : " + name + "");
writer.println("Year and Course : " + yearcourse + "");
writer.println("Student Number : " + studentnumber + "");
writer.println("E-mail Address : " + eadd + "");
writer.println("Cellphone Number : " + cpnumber + "");
writer.println("Gender : " + gender + "");
writer.println("Age : " + age + "");
writer.println("Date of Birth : " + dob + "");
writer.println("Civil Status : " + status + "");
writer.println("Address : " + address + "");
writer.flush();
}
}
}
In this. if I rerun the program, the text file will just overwrite with the new encoded information. They said to use append bufferwriter. but I'm really lost.
Try to change your code to something like this:
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println("\nSTUDENT INFORMATION:");
out.println("--------------------");
out.println("Name : " + name + "");
out.println("Year and Course : " + yearcourse + "");
out.println("Student Number : " + studentnumber + "");
out.println("E-mail Address : " + eadd + "");
out.println("Cellphone Number : " + cpnumber + "");
out.println("Gender : " + gender + "");
out.println("Age : " + age + "");
out.println("Date of Birth : " + dob + "");
out.println("Civil Status : " + status + "");
out.println("Address : " + address + "");
}catch (IOException e) {
// Handle IO exception.
}
This part of the code:
new FileWriter(file,true)
tells it to append when it's set to true, as you can see on the docs.
Or you could change your line:
PrintWriter writer = new PrintWriter(file);
To this:
PrintWriter writer = new PrintWriter(new FileWriter(file,true));
instead of this
PrintWriter writer = new PrintWriter(file);
try this
PrintWriter writer= new PrintWriter(new BufferedWriter(new FileWriter(file, true));
See Also
How to append content to file in Java
How to append text to an existing file in Java

Categories

Resources