I cant seem to figure out how to get this code to work properly. Am I doing something wrong? the program fails on the Record[] records = lookup.run(); line.
import java.util.Iterator;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.TXTRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
Lookup lookup;
try {
lookup = new Lookup("google.com", Type.ANY);
Record[] records = lookup.run();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
String responseMessage = null;
String listingType = null;
for (int i = 0; i < records.length; i++) {
if (records[i] instanceof TXTRecord) {
TXTRecord txt = (TXTRecord) records[i];
for (Iterator j = txt.getStrings().iterator(); j.hasNext();) {
responseMessage += (String) j.next();
}
} else if (records[i] instanceof ARecord) {
listingType = ((ARecord) records[i]).getAddress()
.getHostAddress();
}
}
}
}catch (TextParseException e) {
e.printStackTrace();
}
What do you mean by it does not work? Please paste any exception trace as requested earlier. I was able to run the code just fine, I added output to the records so as to see the result. Here is the code:
import java.util.Iterator;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.TXTRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
public class DNS {
public static void main(String[] args) {
try {
Lookup lookup = new Lookup("google.com", Type.ANY);
Record[] records = lookup.run();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
String responseMessage = null;
String listingType = null;
for (int i = 0; i < records.length; i++) {
if (records[i] instanceof TXTRecord) {
TXTRecord txt = (TXTRecord) records[i];
for (Iterator j = txt.getStrings().iterator(); j
.hasNext();) {
responseMessage += (String) j.next();
}
System.out.println("TXRecord " + responseMessage);
} else if (records[i] instanceof ARecord) {
listingType = ((ARecord) records[i]).getAddress()
.getHostAddress();
System.out.println("ARecord address : " + listingType);
}
}
}
} catch (TextParseException e) {
e.printStackTrace();
}
}
}
And here is the output:
ARecord address : 74.125.224.49
ARecord address : 74.125.224.51
ARecord address : 74.125.224.52
ARecord address : 74.125.224.48
ARecord address : 74.125.224.50
TXRecord nullv=spf1 include:_netblocks.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all
Related
I need to modify class PrimeFactors so that it extends HashMap<Integer,ArrayList> and implements Serializable.
Let x be a number and y be an ArrayList containing the prime factors of x: add all <x,y> pairs to PrimeFactors and serialize the object into a new file.
Then write a method that de-serializes the PrimeFactors object from the file and displays the <x,y> pairs.
Right now, I am completely stuck and unsure how to continue. Any help would be greatly appreciated as I am very unfamiliar with this situation.
Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.ObjectOutputStream;
public class PrimeFactors2 extends HashMap<Integer,ArrayList<Integer>> implements Serializable {
public static void findFactor(int n) {
System.out.print("Factors for the number " + n + " is: ");
for (int i = n; i >= 1; i--) {
if (n % i == 0)
System.out.print(i + " ");
}
}
public static boolean checkForPrime(int number) {
boolean isItPrime = true;
if (number <= 1) {
isItPrime = false;
return isItPrime;
} else {
for (int i = 2; i <= number / 2; i++) {
if ((number % i) == 0) {
isItPrime = false;
break;
}
}
return isItPrime;
}
}
public static void main(String[] args) {
String path = "/Users/benharrington/Desktop/primeOrNot.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<Integer> list = new ArrayList<Integer>();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
int i = Integer.parseInt(str);
boolean isItPrime = checkForPrime(i);
if (isItPrime)
System.out.println(i + " is Prime");
else
System.out.println(i + " is not Prime");
if (isItPrime == false) {
list.add(i);
}
}
for (int k : list) {
System.out.println(" ");
findFactor(k);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What you did in your code is simply reading a file and parsing it.
If you want to serialize and se-derialize an object, it can be done with the following code:
PrimeFactors2 primeFactors2 = // you object creation code here;
// i.e:
// PrimeFactors2 primeFactors2 = new PrimeFactors2();
// primeFactors2.setX1(2);
// primeFactors2.setX2(3);
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/obj.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(primeFactors2);
out.close();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, in some context (same or another) in the same moment (or whenvever after you created the .ser object), you may de-serialize it with the following code:
try {
FileInputStream fileIn = new FileInputStream("/tmp/obj.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
PrimeFactors2 primeFactors2 = (PrimeFactors2) in.readObject();
// YAY!!! primeFactors2 is an object with the same values you created before
// i.e: primeFactors.getX1() is 2
// primeFactors.getX2() is 3
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}
I have text file data like :
2,2,1
data1,123,89,1
data2,124,90,2
data3,125,91,3
data4,126,92,4
data5,127,93,5
data6,128,94,6
data7,129,95,7
data8,130,96,8
data9,131,97,9
data10,132,98,10
The first line 2,2,1 indicate 2 lines from 1st set of lines and store it in nodeFile, 2 lines from 2nd set of lines store it in linkFile and 1 line from 3rd set of lines store it in moduleFile. However for example purpose I have shows small number of lines but its a larger file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
static int a[];
public static void main(String[] args) {
File file11 = new File("/home/madhu/Desktop/node.txt");
Scanner scAll = null;
try {
scAll = new Scanner(file11);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] numberOfLines = (scAll.nextLine()).split(",");
int flag = 0;
int counter = 1;
while (scAll.hasNext()) {
if (flag == 0 && "\\n\\n".equals(scAll.nextLine()) && counter <= Integer.parseInt(numberOfLines[0].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[0].trim()); i++) {
System.out.println(scAll.nextLine());
nodeFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[0].trim())) {
flag = 1;
counter = 1;
}
} else if (flag == 1 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[1].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[1].trim()); i++) {
System.out.println(scAll.nextLine());
linkFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[1].trim())) {
flag = 2;
counter = 1;
}
} else if (flag == 2 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[2].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[2].trim()); i++) {
System.out.println(scAll.nextLine());
moduleFile.add(scAll.nextLine());
counter++;
}
} else {
continue;
}
}
scAll.close();
}
}
I have written the above code, but this code gets terminated during execution. How to get the desired result? Please help.
Hopefully I am not misunderstanding, but this is what I'd do.
I didn't check to see if this is fully working example, but it should work more or less.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class ReadFile {
// basically just do what you did
static List<String> nodeFile;
static List<String> linkFile;
static List<String> moduleFile;
public static void main(String[] args) throws FileNotFoundException {
final File file = new File("/home/madhu/Desktop/node.txt");
final Scanner scanner = new Scanner(file);
// make it a little better for indexing
final List<Integer> selections = Arrays
.stream(scanner.nextLine().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
// this is the meat of the code
// basically each split up block of lines is a block
final List<List<String>> blocks = new ArrayList<>();
while (scanner.hasNextLine()) {
List<String> lines = new ArrayList<>();
String line;
while (!(line = scanner.nextLine()).equals("\n")) {
lines.add(line);
}
if (!lines.isEmpty()) {
blocks.add(lines);
}
}
// allocate your files now
nodeFile = blocks.get(0).subList(0, selections.get(0));
linkFile = blocks.get(1).subList(0, selections.get(1));
moduleFile = blocks.get(2).subList(0, selections.get(2));
scanner.close();
}
}
try this code , i use BufferedReader because its more cleaner :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
public static void main(String[] args) {
File file = new File("/home/madhu/Desktop/node.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String data[] = reader.readLine().split(",");
String s;
int nbline=0, i=0,block =0;
while ((s = reader.readLine())!=null && block < data.length) {
if(s.equals("")){
block++;
nbline = Integer.parseInt(data[block-1]);
i = 0;
}
for(;i<nbline;i++){
s = reader.readLine();
if(s == null) break;
else if(s.equals("")){
block++;
break;
}
switch(block){
case 1 :
nodeFile.add(s);
break;
case 2:
linkFile.add(s);
break;
default: moduleFile.add(s);
}
}
}
} catch (IOException | NumberFormatException ex) {
System.err.println(ex.getStackTrace());
}
finally{
closeReader(reader);
}
System.out.println("nodeFile : "+nodeFile);
System.out.println("linkFile : "+linkFile);
System.out.println("moduleFile : "+moduleFile);
}
public static void closeReader(BufferedReader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
output :
nodeFile : [data1,123,89,1, data2,124,90,2]
linkFile : [data5,127,93,5, data6,128,94,6]
moduleFile : [data8,130,96,8]
i have following code for comparing the md5 hash values for two folder but i need to show the list of files and the hash value of each file. can anyone please help me out with this. i just need to get hash value for one folder only.
package com.example;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Compare
{
//This can be any folder locations which you want to compare
File dir1 = new File("/Users/Samip/Desktop/crypto");
File dir2 = new File("/Users/Samip/Desktop/crypto1");
public static void main(String ...args)
{
Compare compare = new Compare();
try
{
compare.getDiff(compare.dir1,compare.dir2);
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
public void getDiff(File dirA, File dirB) throws IOException
{
File[] fileList1 = dirA.listFiles();
File[] fileList2 = dirB.listFiles();
Arrays.sort(fileList1);
Arrays.sort(fileList2);
HashMap<String, File> map1;
if(fileList1.length < fileList2.length)
{
map1 = new HashMap<String, File>();
for(int i=0;i<fileList1.length;i++)
{
map1.put(fileList1[i].getName(),fileList1[i]);
}
compareNow(fileList2, map1);
}
else
{
map1 = new HashMap<String, File>();
for(int i=0;i<fileList2.length;i++)
{
map1.put(fileList2[i].getName(),fileList2[i]);
}
compareNow(fileList1, map1);
}
}
public void compareNow(File[] fileArr, HashMap<String, File> map) throws IOException
{
for(int i=0;i<fileArr.length;i++)
{
String fName = fileArr[i].getName();
File fComp = map.get(fName);
map.remove(fName);
if(fComp!=null)
{
if(fComp.isDirectory())
{
getDiff(fileArr[i], fComp);
}
else
{
String cSum1 = checksum(fileArr[i]);
String cSum2 = checksum(fComp);
if(!cSum1.equals(cSum2))
{
System.out.println(fileArr[i].getName()+"\t\t"+ "different");
}
else
{
System.out.println(fileArr[i].getName()+"\t\t"+"identical");
}
}
}
else
{
if(fileArr[i].isDirectory())
{
traverseDirectory(fileArr[i]);
}
else
{
System.out.println(fileArr[i].getName()+"\t\t"+"only in "+fileArr[i].getParent());
}
}
}
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext())
{
String n = it.next();
File fileFrmMap = map.get(n);
map.remove(n);
if(fileFrmMap.isDirectory())
{
traverseDirectory(fileFrmMap);
}
else
{
System.out.println(fileFrmMap.getName() +"\t\t"+"only in "+ fileFrmMap.getParent());
}
}
}
public void traverseDirectory(File dir)
{
File[] list = dir.listFiles();
for(int k=0;k<list.length;k++)
{
if(list[k].isDirectory())
{
traverseDirectory(list[k]);
}
else
{
System.out.println(list[k].getName() +"\t\t"+"only in "+ list[k].getParent());
}
}
}
public String checksum(File file)
{
try
{
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do
{
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++)
{
strDigest += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
}
catch (Exception e)
{
return null;
}
}
}
In you main method, instead using Compare.getDiff(dir1, dir2) you want to
Get a file listing of your target directory
Invoke Compare.checksum(file) on each file and print the result
Looks like you have all the code, you just need to reshape it a little.
Consider this example. The hash-generating code has been taken from your previous question - same goes for the file-iteration code. You just replace that folder to match your.
import java.io.*;
import java.security.MessageDigest;
public class PrintChecksums {
public static void main(String[] args) {
String sourceDir = "/Users/Jan/Desktop/Folder1";
try {
new PrintChecksums().printHashs(new File(sourceDir));
} catch (Exception e) {
e.printStackTrace();
}
}
private void printHashs(File sourceDir) throws Exception {
for (File f : sourceDir.listFiles()) {
String hash = createHash(f); // That you almost have
System.out.println(f.getAbsolutePath() + " / Hashvalue: " + hash);
}
}
public String createHash(File datafile) throws Exception {
// SNIP - YOUR CODE BEGINS
MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(datafile);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest();
// convert the byte to hex format
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
// SNAP - YOUR CODE ENDS
return sb.toString();
}
}
Please have a look at the below code. I have added a function printCheckSum() which iterates though directory, scans each file and prints its hash value.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Compare
{
//This can be any folder locations which you want to compare
File dir1 = new File("D:\\dir1");
File dir2 = new File("D:\\dir2");
public static void main(String ...args)
{
Compare compare = new Compare();
try
{
compare.printCheckSum(compare.dir1);
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
public void getDiff(File dirA, File dirB) throws IOException
{
File[] fileList1 = dirA.listFiles();
File[] fileList2 = dirB.listFiles();
Arrays.sort(fileList1);
Arrays.sort(fileList2);
HashMap<String, File> map1;
if(fileList1.length < fileList2.length)
{
map1 = new HashMap<String, File>();
for(int i=0;i<fileList1.length;i++)
{
map1.put(fileList1[i].getName(),fileList1[i]);
}
compareNow(fileList2, map1);
}
else
{
map1 = new HashMap<String, File>();
for(int i=0;i<fileList2.length;i++)
{
map1.put(fileList2[i].getName(),fileList2[i]);
}
compareNow(fileList1, map1);
}
}
public void compareNow(File[] fileArr, HashMap<String, File> map) throws IOException
{
for(int i=0;i<fileArr.length;i++)
{
String fName = fileArr[i].getName();
File fComp = map.get(fName);
map.remove(fName);
if(fComp!=null)
{
if(fComp.isDirectory())
{
getDiff(fileArr[i], fComp);
}
else
{
String cSum1 = checksum(fileArr[i]);
String cSum2 = checksum(fComp);
if(!cSum1.equals(cSum2))
{
System.out.println(fileArr[i].getName()+"\t\t"+ "different");
}
else
{
System.out.println(fileArr[i].getName()+"\t\t"+"identical");
}
}
}
else
{
if(fileArr[i].isDirectory())
{
traverseDirectory(fileArr[i]);
}
else
{
System.out.println(fileArr[i].getName()+"\t\t"+"only in "+fileArr[i].getParent());
}
}
}
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext())
{
String n = it.next();
File fileFrmMap = map.get(n);
map.remove(n);
if(fileFrmMap.isDirectory())
{
traverseDirectory(fileFrmMap);
}
else
{
System.out.println(fileFrmMap.getName() +"\t\t"+"only in "+ fileFrmMap.getParent());
}
}
}
public void traverseDirectory(File dir)
{
File[] list = dir.listFiles();
for(int k=0;k<list.length;k++)
{
if(list[k].isDirectory())
{
traverseDirectory(list[k]);
}
else
{
System.out.println(list[k].getName() +"\t\t"+"only in "+ list[k].getParent());
}
}
}
public String checksum(File file)
{
try
{
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do
{
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++)
{
strDigest += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
}
catch (Exception e)
{
return null;
}
}
public void printCheckSum(File dir) throws IOException{
File[] fileList = dir.listFiles();
for(File file : fileList){
if(file.isDirectory()){
printCheckSum(file);
}else
System.out.println(file.getName() +"\t :: \t" + checksum(file));
}
}
}
Hope this helps. Cheers!
I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?
I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.
EDIT: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to read attachments from received mail.
Cheers,
Don
Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading.
The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths.
Focus on the doEMailDownload method.
/**
* Copyright (c) 2008 Steven M. Cherry
* All rights reserved.
*/
package utils.scheduled;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import glob.ActionLogicImplementation;
import glob.IOConn;
import glob.log.Log;
import logic.utils.sql.Settings;
import logic.utils.sqldo.EMail;
import logic.utils.sqldo.EMailAttach;
/**
* This will connect to our incoming e-mail server and download any e-mails
* that are found on the server. The e-mails will be stored for further processing
* in our internal database. Attachments will be written out to separate files
* and then referred to by the database entries. This is intended to be run by
* the scheduler every minute or so.
*
* #author Steven M. Cherry
*/
public class DownloadEMail implements ActionLogicImplementation {
protected String receiving_host;
protected String receiving_user;
protected String receiving_pass;
protected String receiving_protocol;
protected boolean receiving_secure;
protected String receiving_attachments;
/** This will run our logic */
public void ExecuteRequest(IOConn ioc) throws Exception {
Log.Trace("Enter");
Log.Debug("Executing DownloadEMail");
ioc.initializeResponseDocument("DownloadEMail");
// pick up our configuration from the server:
receiving_host = Settings.getValue(ioc, "server.email.receiving.host");
receiving_user = Settings.getValue(ioc, "server.email.receiving.username");
receiving_pass = Settings.getValue(ioc, "server.email.receiving.password");
receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol");
String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure");
receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments");
// sanity check on the parameters:
if(receiving_host == null || receiving_host.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no host defined.
}
if(receiving_user == null || receiving_user.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no user defined.
}
if(receiving_pass == null || receiving_pass.length() == 0){
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
return; // no pass defined.
}
if(receiving_protocol == null || receiving_protocol.length() == 0){
Log.Debug("EMail receiving protocol not defined, defaulting to POP");
receiving_protocol = "POP";
}
if(tmp_secure == null ||
tmp_secure.length() == 0 ||
tmp_secure.compareToIgnoreCase("false") == 0 ||
tmp_secure.compareToIgnoreCase("no") == 0
){
receiving_secure = false;
} else {
receiving_secure = true;
}
if(receiving_attachments == null || receiving_attachments.length() == 0){
Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/");
receiving_attachments = "./email/attachments/";
}
// now do the real work.
doEMailDownload(ioc);
ioc.SendReturn();
ioc.Close();
Log.Trace("Exit");
}
protected void doEMailDownload(IOConn ioc) throws Exception {
// Create empty properties
Properties props = new Properties();
// Get the session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore(receiving_protocol);
store.connect(receiving_host, receiving_user, receiving_pass);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
try {
// Get directory listing
Message messages[] = folder.getMessages();
for (int i=0; i < messages.length; i++) {
// get the details of the message:
EMail email = new EMail();
email.fromaddr = messages[i].getFrom()[0].toString();
Address[] to = messages[i].getRecipients(Message.RecipientType.TO);
email.toaddr = "";
for(int j = 0; j < to.length; j++){
email.toaddr += to[j].toString() + "; ";
}
Address[] cc;
try {
cc = messages[i].getRecipients(Message.RecipientType.CC);
} catch (Exception e){
Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage());
cc = null;
}
email.cc = "";
if(cc != null){
for(int j = 0; j < cc.length; j++){
email.cc += cc[j].toString() + "; ";
}
}
email.subject = messages[i].getSubject();
if(messages[i].getReceivedDate() != null){
email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());
} else {
email.received_when = new Timestamp( (new java.util.Date()).getTime());
}
email.body = "";
Vector<EMailAttach> vema = new Vector<EMailAttach>();
Object content = messages[i].getContent();
if(content instanceof java.lang.String){
email.body = (String)content;
} else if(content instanceof Multipart){
Multipart mp = (Multipart)content;
for (int j=0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
Log.Debug("Mime type is plain");
email.body += (String)mbp.getContent();
} else {
Log.Debug("Mime type is not plain");
// Special non-attachment cases here of
// image/gif, text/html, ...
EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = File.createTempFile("emailattach", ".atch", savedir );
ema.path = savefile.getAbsolutePath();
ema.size = part.getSize();
vema.add(ema);
ema.size = saveFile(savefile, part);
}
} else if ((disposition != null) &&
(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) )
){
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
Log.Debug("Mime type is plain");
email.body += (String)mbp.getContent();
} else {
Log.Debug("Save file (%s)", part.getFileName() );
EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = File.createTempFile("emailattach", ".atch", savedir );
ema.path = savefile.getAbsolutePath();
ema.size = part.getSize();
vema.add(ema);
ema.size = saveFile( savefile, part);
}
}
}
}
// Insert everything into the database:
logic.utils.sql.EMail.insertEMail(ioc, email);
for(int j = 0; j < vema.size(); j++){
vema.get(j).emailid = email.id;
logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );
}
// commit this message and all of it's attachments
ioc.getDBConnection().commit();
// Finally delete the message from the server.
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages.
store.close();
} catch (Exception e){
folder.close(true); // true tells the mail server to expunge deleted messages.
store.close();
throw e;
}
}
protected int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while( (ret = is.read(buff)) > 0 ){
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
protected String decodeName( String name ) throws Exception {
if(name == null || name.length() == 0){
return "unknown";
}
String ret = java.net.URLDecoder.decode( name, "UTF-8" );
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
}
I worked Steven's example a little bit and removed the parts of the code specific to Steven. My code won't read the body of an email if it has attachments. That is fine for my case but you may want to refine it further for yours.
package utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
public class IncomingMail {
public static List<Email> downloadPop3(String host, String user, String pass, String downloadDir) throws Exception {
List<Email> emails = new ArrayList<Email>();
// Create empty properties
Properties props = new Properties();
// Get the session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore("pop3");
store.connect(host, user, pass);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
try {
// Get directory listing
Message messages[] = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
Email email = new Email();
// from
email.from = messages[i].getFrom()[0].toString();
// to list
Address[] toArray = messages[i] .getRecipients(Message.RecipientType.TO);
for (Address to : toArray) { email.to.add(to.toString()); }
// cc list
Address[] ccArray = null;
try {
ccArray = messages[i] .getRecipients(Message.RecipientType.CC);
} catch (Exception e) { ccArray = null; }
if (ccArray != null) {
for (Address c : ccArray) {
email.cc.add(c.toString());
}
}
// subject
email.subject = messages[i].getSubject();
// received date
if (messages[i].getReceivedDate() != null) {
email.received = messages[i].getReceivedDate();
} else {
email.received = new Date();
}
// body and attachments
email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String) {
email.body = (String) content;
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
// Plain
email.body += (String) mbp.getContent();
}
} else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition .equals(Part.INLINE))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
email.body += (String) mbp.getContent();
} else {
EmailAttachment attachment = new EmailAttachment();
attachment.name = decodeName(part.getFileName());
File savedir = new File(downloadDir);
savedir.mkdirs();
// File savefile = File.createTempFile( "emailattach", ".atch", savedir);
File savefile = new File(downloadDir,attachment.name);
attachment.path = savefile.getAbsolutePath();
attachment.size = saveFile(savefile, part);
email.attachments.add(attachment);
}
}
} // end of multipart for loop
} // end messages for loop
emails.add(email);
// Finally delete the message from the server.
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages
store.close();
} catch (Exception e) {
folder.close(true); // true tells the mail server to expunge deleted
store.close();
throw e;
}
return emails;
}
private static String decodeName(String name) throws Exception {
if (name == null || name.length() == 0) {
return "unknown";
}
String ret = java.net.URLDecoder.decode(name, "UTF-8");
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
private static int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(saveFile));
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while ((ret = is.read(buff)) > 0) {
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
}
You also need these two helper classes
package utils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Email {
public Date received;
public String from;
public List<String> to = new ArrayList<String>();
public List<String> cc = new ArrayList<String>();
public String subject;
public String body;
public List<EmailAttachment> attachments = new ArrayList<EmailAttachment>();
}
and
package utils;
public class EmailAttachment {
public String name;
public String path;
public int size;
}
I used this to test the above classes
package utils;
import java.util.List;
public class Test {
public static void main(String[] args) {
String host = "some host";
String user = "some user";
String pass = "some pass";
String downloadDir = "/Temp";
try {
List<Email> emails = IncomingMail.downloadPop3(host, user, pass, downloadDir);
for ( Email email : emails ) {
System.out.println(email.from);
System.out.println(email.subject);
System.out.println(email.body);
List<EmailAttachment> attachments = email.attachments;
for ( EmailAttachment attachment : attachments ) {
System.out.println(attachment.path+" "+attachment.name);
}
}
} catch (Exception e) { e.printStackTrace(); }
}
}
More info can be found at http://java.sun.com/developer/onlineTraining/JavaMail/contents.html
Here is an error:
else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT)
|| disposition.equals(Part.INLINE) )
it should be:
else if ((disposition.equalsIgnoreCase(Part.ATTACHMENT)
|| disposition.equalsIgnoreCase(Part.INLINE))
Thanks #Stevenmcherry for your answer
I used Apache Commons Mail for this task:
import java.util.List;
import javax.activation.DataSource;
import javax.mail.internet.MimeMessage;
import org.apache.commons.mail.util.MimeMessageParser;
public List<DataSource> getAttachmentList(MimeMessage message) throws Exception {
msgParser = new MimeMessageParser(message);
msgParser.parse();
return msgParser.getAttachmentList();
}
From a DataSource object you can retrieve an InputStream (beside name and type) of the attachment (see API: http://docs.oracle.com/javase/6/docs/api/javax/activation/DataSource.html?is-external=true).
Thus far, I've only used the JavaMail APIs (and I've been reasonably happy with them for my purposes). If the full JavaMail package is too heavy for you, the underlying transport engine can be used without the top layers of the package. The lower you go in the SMTP, POP3 and IMAP stacks, the more you have to be prepared to do for yourself.
On the bright side, you'll also be able to ignore the parts that aren't required for your application.
import java.io.IOException;
import java.io.InputStream;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
#Controller
#RequestMapping("/sendEmail.do")
public class SendEmailAttachController {
#Autowired
private JavaMailSender mailSender;
#RequestMapping(method = RequestMethod.POST)
public String sendEmail(HttpServletRequest request,
final #RequestParam CommonsMultipartFile attachFile) {
// Input here
final String emailTo = request.getParameter("mailTo");
final String subject = request.getParameter("subject");
final String yourmailid = request.getParameter("yourmail");
final String message = request.getParameter("message");
// Logging
System.out.println("emailTo: " + emailTo);
System.out.println("subject: " + subject);
System.out.println("Your mail id is: "+yourmailid);
System.out.println("message: " + message);
System.out.println("attachFile: " + attachFile.getOriginalFilename());
mailSender.send(new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mimeMessage, true, "UTF-8");
messageHelper.setTo(emailTo);
messageHelper.setSubject(subject);
messageHelper.setReplyTo(yourmailid);
messageHelper.setText(message);
// Attachment with mail
String attachName = attachFile.getOriginalFilename();
if (!attachFile.equals("")) {
messageHelper.addAttachment(attachName, new InputStreamSource() {
#Override
public InputStream getInputStream() throws IOException {
return attachFile.getInputStream();
}
});
}
}
});
return "Result";
}
}
I am currently working on a project for my computer science class, and I was trying to figure out how to retrieve and print certain values from a file in excel. Such as, how would I go about printing the integer in column J, row 6?
Better yet, is there a way for me to return the row number of a string in column 1? Such as, if I had a string "Phone" in column 1, could I use a command to return the row number of the first instance of "phone"?
I have looked at other questions, none of which sufficiently answered my own.
Here you go refer to this class file for iterating over an excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
private static final String FILE_NAME = "/users/developer/Documents/myFile.xlsx";
public void employeesUpload() {
String fName = "";
String lName = "";
String phoneNumber = "";
String email = "";
String gender = "";
String employeeCode = "";
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
int rowIndex = 0;
DataFormatter formatter = new DataFormatter();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
if (rowIndex > 0) {
Iterator<Cell> cellIterator = currentRow.iterator();
employeeCode = fName = lName = phoneNumber = email = gender = "";
int cellIndex = 0;
while (cellIndex <= 5) {
Cell currentCell = currentRow.getCell(cellIndex);
if (cellIndex == 4) {
employeeCode = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 1) {
fName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 2) {
lName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 0) {
email = formatter.formatCellValue(currentCell);
email = email.trim().toLowerCase();
}
if (cellIndex == 3) {
phoneNumber = formatter.formatCellValue(currentCell).trim();
}
cellIndex++;
}
Cell resultCell = currentRow.getCell(7);
if (resultCell == null) {
resultCell = currentRow.createCell(7);
}
Cell employementIdCell = currentRow.getCell(8);
if (employementIdCell == null) {
employementIdCell = currentRow.createCell(8);
}
if (true) {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
employementIdCell.setCellValue("Success");
resultCell.setCellValue(email);
} else {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
resultCell.setCellValue("Error");
}
}
rowIndex++;
}
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ParseException, UnsupportedEncodingException {
Test employeesBulkUpload = new Test();
employeesBulkUpload.employeesUpload();
}
}
Hope this helps :)
user https://github.com/jueyue/easypoi this jar
use annotion to easy read excel
public class ExcelImportNewDateTest {
#Test
public void importTest() {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
long start = new Date().getTime();
List<NewDateEntity> list = ExcelImportUtil.importExcel(
new File(FileUtilTest.getWebRootPath("import/ExcelNewDateTest.xlsx")), NewDateEntity.class, params);
System.out.println(new Date().getTime() - start);
Assert.assertEquals(list.size(), 100);
System.out.println(list.size());
System.out.println(ReflectionToStringBuilder.toString(list.get(1)));
}
}