I'm making a small app for accessing gmail and getting messages with attachments.
Properties props = System.getProperties();
props.put("mail.user", login);
props.put("mail.host", pop3Host);
props.put("mail.debug", "false");
props.setProperty("mail.store.protocol", "imaps");
// set this session up to use SSL for IMAP connections
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// don't fallback to normal IMAP connections on failure.
props.setProperty("mail.imap.socketFactory.fallback", "false");
// use the simap port for imap/ssl connections.
props.setProperty("mail.imap.socketFactory.port", settings.getPop3Port().toString());
props.setProperty("mail.imap.partialfetch", "false");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", settings.getSmtpAuth().toString());
Session session=null;
session = Session.getInstance(props, new GMailAuthenticator(login, password));
Store store = null;
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
SearchTerm st = new AndTerm(new SubjectTerm(subjectSubstringToSearch), unseenFlagTerm);
// Get some message references
Message [] messages = inbox.search(st);
System.out.println(messages.length + " -- Messages amount");
//Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
ArrayList<String> attachments = new ArrayList<String>();
LinkedList<MessageBean> listMessages = getPart(messages, attachments);
for(String s :attachments) {
System.out.println(s);
}
inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
BufferedReader reader = new BufferedReader (
new InputStreamReader(System.in));
for (int i=0, j=messages.length; i<j; i++) {
messages[i].setFlag(Flags.Flag.SEEN, true);
}
inbox.close(true);
store.close();
return listMessages;
}
private static LinkedList<MessageBean> getPart(Message[] messages, ArrayList<String> attachments) throws MessagingException, IOException {
LinkedList<MessageBean> listMessages = new LinkedList<MessageBean>();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Message inMessage : messages) {
attachments.clear();
if (inMessage.isMimeType("text/plain")) {
MessageBean message = new MessageBean(inMessage.getMessageNumber(), MimeUtility.decodeText(inMessage.getSubject()), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) inMessage.getContent(), false, null);
listMessages.add(message);
System.out.println("text/plain");
} else if (inMessage.isMimeType("multipart/*")) {
System.out.println("multipart");
Multipart mp = (Multipart) inMessage.getContent();
MessageBean message = null;
System.out.println(mp.getCount());
for (int i = 0; i < mp.getCount(); i++) {
Part part = mp.getBodyPart(i);
if ((part.getFileName() == null || part.getFileName() == "") && part.isMimeType("text/plain")) {
System.out.println(inMessage.getSentDate());
message = new MessageBean(inMessage.getMessageNumber(), inMessage.getSubject(), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) part.getContent(), false, null);
} else if (part.getFileName() != null || part.getFileName() != "") {
if ((part.getDisposition() != null) && (part.getDisposition().equals(Part.ATTACHMENT))) {
System.out.println(part.getFileName());
attachments.add(saveFile(MimeUtility.decodeText(part.getFileName()), part.getInputStream()));
if (message != null) {
message.setAttachments(attachments);
}
}
}
}
listMessages.add(message);
}
}
return listMessages;
}
//method for saving attachment on local disk
private static String saveFile(String filename, InputStream input) {
String strDirectory = "D:\\temp\\attachments";
try{
// Create one directory
boolean success = (new File(strDirectory)).mkdir();
if (success) {
System.out.println("Directory: "
+ strDirectory + " created");
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
String path = strDirectory+"\\" + filename;
try {
byte[] attachment = new byte[input.available()];
input.read(attachment);
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
out.write(attachment);
input.close();
out.close();
return path;
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
MessageBean:
public class MessageBean implements Serializable {
private String subject;
private String from;
private String to;
private Date dateSent;
private String content;
private boolean isNew;
private int msgId;
private ArrayList<String> attachments;
public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
this.subject = subject;
this.from = from;
this.to = to;
this.dateSent = dateSent;
this.content = content;
this.isNew = isNew;
this.msgId = msgId;
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Date getDateSent() {
return dateSent;
}
public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean aNew) {
isNew = aNew;
}
public int getMsgId() {
return msgId;
}
public void setMsgId(int msgId) {
this.msgId = msgId;
}
public ArrayList<String> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<String> attachments) {
this.attachments = new ArrayList<String>(attachments);
}
}
I can connect to my mail account and see amount of unseen messages, but it seems that MessageBean doesn't get populated with attachments.
The biggest problem is that i develop my app on a computer that doesn't have an Internet connection. So i build jar, go to computer that has inet, java -jar it and stare at NullPointer exception. I can't debug this crap. Could someone, please, spot where is my mistake.
EDIT
This code works for gmail pop, with another connection obviously.
becuase your list is null when you get elements from it, so you can make new ArrayList object inside MessageBean, and then copy the elements
private List<String> attachments= new ArrayList<String>();
public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
this.subject = subject;
this.from = from;
this.to = to;
this.dateSent = dateSent;
this.content = content;
this.isNew = isNew;
this.msgId = msgId;
this.attachments.addAll(attachments);
}
The JavaMail FAQ has debugging tips as well as tips for using Gmail.
What value are you using for pop3host? Hopefully it's "imap.gmail.com" and not "pop.gmail.com".
Note that you can remove all those socket factory properties, you don't need them.
package com.thread.test;
import java.io.File;
import java.util.Properties;
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 ReadMailThread implements Runnable{
private Thread readMailThread;
private String threadName;
public ReadMailThread() {
readMailThread = new Thread(this);
readMailThread.start();
}
public ReadMailThread(String s) {
threadName = s;
System.out.println("creating thread :: "+threadName);
}
#Override
public void run() {
System.out.println("Thread Started "+threadName);
String saveDirectory = "D:/Ganga/attachment";
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "******#gmail.com", "******");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
/* Message msg = inbox.getMessage(inbox.getMessageCount());
System.out.println("Message Size is "+msg.getSize()/1024 +" KB");
System.out.println("Message Size is "+msg.getSize()/1024*1024 +" MB");
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());*/
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
String contentType = messages[i].getContentType();
String messageContent = "";
String attachFiles = "";
if (contentType.contains("multipart")) {
Multipart multiPart = (Multipart) messages[i].getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String fileName = part.getFileName();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = messages[i].getContent();
if (content != null) {
messageContent = content.toString();
}
}
/*System.out.println(messages[i].getSize() + " bytes long.");
System.out.println(messages[i].getSize()/1024 + " KB long.");
System.out.println(messages[i].getSize()/1024*1024 + " MB long.");
System.out.println(messages[i].getLineCount() + " lines.");
String disposition = messages[i].getDisposition();
if (disposition == null){
//Do Nothing
}else if (disposition.equals(Part.INLINE)) {
System.out.println("This part should be displayed inline");
} else if (disposition.equals(Part.ATTACHMENT)) {
System.out.println("This part is an attachment");
String fileName = messages[i].getFileName();
System.out.println("The file name of this attachment is " + fileName);
}
String description = messages[i].getDescription();
if (description != null) {
System.out.println("The description of this message is " + description);
}*/
}
inbox.close(false);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public void start(){
if(readMailThread == null){
readMailThread = new Thread(this, threadName);
readMailThread.start();
}
}
}
package com.thread.test;
public class MailTest {
public MailTest() {
}
public static void main(String[] args) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
ReadMailThread rmt1=new ReadMailThread("remoteThread1");
ReadMailThread rmt2=new ReadMailThread("remoteThread2");
ReadMailThread rmt3=new ReadMailThread("remoteThread3");
ReadMailThread rmt4=new ReadMailThread("remoteThread4");
ReadMailThread rmt5=new ReadMailThread("remoteThread5");
ReadMailThread rmt6=new ReadMailThread("remoteThread6");
ReadMailThread rmt7=new ReadMailThread("remoteThread7");
ReadMailThread rmt8=new ReadMailThread("remoteThread8");
ReadMailThread rmt9=new ReadMailThread("remoteThread9");
ReadMailThread rmt10=new ReadMailThread("remoteThread10");
rmt1.start();
rmt2.start();
rmt3.start();
rmt4.start();
rmt5.start();
rmt6.start();
rmt7.start();
rmt8.start();
rmt9.start();
rmt10.start();
}
}
package com.equinix.gse.apps.me.tas.app.ec.process.snmp.fivemins;
import com.equinix.gse.apps.me.tas.app.ec.dao.snmp.Snmp5MinsDatabaseReadThread;
import com.equinix.gse.apps.me.tas.core.TasException;
import com.equinix.gse.apps.me.tas.core.util.TasConstants;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* User: vreddy
*/
#Service
public class Snmp5MinsCache {
private static final Logger logger = Logger.getLogger(Snmp5MinsCache.class);
private static final String CLASS_NAME="Snmp5MinsCache";
private static final String SNMP5MINSDATABASEREADTHREAD="snmp5MinsDatabaseReadThread";
#Autowired
private ApplicationContext ac;
public Map<String,Long> getCache() throws TasException{
ExecutorService executor = Executors.newFixedThreadPool(TasConstants.THREAD_POOL_SIZE);
int startCounter = 1;
int endCounter = TasConstants.SNMP_EXDB_BATCH_SIZE;
StringBuilder query = new StringBuilder();
query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME from (" );
query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, ");
query.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW ");
query.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null and ");
StringBuilder countQuery = new StringBuilder();
countQuery.append("select count(*) from (" );
countQuery.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, ");
countQuery.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW ");
countQuery.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null");
Map<String,Long> map = new ConcurrentHashMap<String, Long>();
BasicDataSource dataSource = (BasicDataSource)ac.getBean(TasConstants.DATA_SOURCE);
int recordCount = 0;
Connection conn = null;
ResultSet resultSet = null;
try {
conn = dataSource.getConnection();
resultSet = conn.createStatement().executeQuery(countQuery.toString());
resultSet.next();
recordCount = resultSet.getInt(1);
int timeToExecute= recordCount>0?(recordCount/TasConstants.SNMP_EXDB_BATCH_SIZE)+1:0;
for (int i = 0; i < timeToExecute ; i++) {
StringBuilder prepareWhereClass = new StringBuilder();
prepareWhereClass.append(" r >= ");
prepareWhereClass.append(startCounter);
prepareWhereClass.append(" and r <= ");
prepareWhereClass.append(endCounter);
Snmp5MinsDatabaseReadThread dbRead = (Snmp5MinsDatabaseReadThread) ac.getBean(SNMP5MINSDATABASEREADTHREAD);
((Snmp5MinsDatabaseReadThread)dbRead).setMap(map);
((Snmp5MinsDatabaseReadThread)dbRead).setQuery(query.toString() + prepareWhereClass.toString());
((Snmp5MinsDatabaseReadThread)dbRead).setDataSource(dataSource);
Runnable worker = dbRead;
executor.execute(worker);
startCounter = endCounter + 1;
endCounter = endCounter + TasConstants.SNMP_EXDB_BATCH_SIZE;
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e);
} finally {
try {
resultSet.close();
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage(),e);
throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
logger.info("Waiting to process all the thread");
}
logger.info("SNMP 5 mins cache size "+map.size());
return map;
}
}
===========================================
package com.equinix.gse.apps.me.tas.app.ec.process.snmp.fivemins;
import com.equinix.gse.apps.me.tas.app.ec.dao.snmp.Snmp5MinsDatabaseReadThread;
import com.equinix.gse.apps.me.tas.core.TasException;
import com.equinix.gse.apps.me.tas.core.util.TasConstants;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* User: vreddy
*/
#Service
public class Snmp5MinsCache {
private static final Logger logger = Logger.getLogger(Snmp5MinsCache.class);
private static final String CLASS_NAME="Snmp5MinsCache";
private static final String SNMP5MINSDATABASEREADTHREAD="snmp5MinsDatabaseReadThread";
#Autowired
private ApplicationContext ac;
public Map<String,Long> getCache() throws TasException{
ExecutorService executor = Executors.newFixedThreadPool(TasConstants.THREAD_POOL_SIZE);
int startCounter = 1;
int endCounter = TasConstants.SNMP_EXDB_BATCH_SIZE;
StringBuilder query = new StringBuilder();
query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME from (" );
query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, ");
query.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW ");
query.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null and ");
StringBuilder countQuery = new StringBuilder();
countQuery.append("select count(*) from (" );
countQuery.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, ");
countQuery.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW ");
countQuery.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null");
Map<String,Long> map = new ConcurrentHashMap<String, Long>();
BasicDataSource dataSource = (BasicDataSource)ac.getBean(TasConstants.DATA_SOURCE);
int recordCount = 0;
Connection conn = null;
ResultSet resultSet = null;
try {
conn = dataSource.getConnection();
resultSet = conn.createStatement().executeQuery(countQuery.toString());
resultSet.next();
recordCount = resultSet.getInt(1);
int timeToExecute= recordCount>0?(recordCount/TasConstants.SNMP_EXDB_BATCH_SIZE)+1:0;
for (int i = 0; i < timeToExecute ; i++) {
StringBuilder prepareWhereClass = new StringBuilder();
prepareWhereClass.append(" r >= ");
prepareWhereClass.append(startCounter);
prepareWhereClass.append(" and r <= ");
prepareWhereClass.append(endCounter);
Snmp5MinsDatabaseReadThread dbRead = (Snmp5MinsDatabaseReadThread) ac.getBean(SNMP5MINSDATABASEREADTHREAD);
((Snmp5MinsDatabaseReadThread)dbRead).setMap(map);
((Snmp5MinsDatabaseReadThread)dbRead).setQuery(query.toString() + prepareWhereClass.toString());
((Snmp5MinsDatabaseReadThread)dbRead).setDataSource(dataSource);
Runnable worker = dbRead;
executor.execute(worker);
startCounter = endCounter + 1;
endCounter = endCounter + TasConstants.SNMP_EXDB_BATCH_SIZE;
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e);
} finally {
try {
resultSet.close();
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage(),e);
throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
logger.info("Waiting to process all the thread");
}
logger.info("SNMP 5 mins cache size "+map.size());
return map;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class MailProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
private Message message;
public MailProcessor() {
}
public void run() {
System.out.println("Starting processing a message with thread id"
+ Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finished processing a message with thread id"
+ Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
processMessageBody(message);
System.out.println("--------------------------------");
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println(content);
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) {
InputStream inStream = null;
FileOutputStream outStream = null;
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Text = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)) {
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
inStream = bodyPart.getInputStream();
outStream = new FileOutputStream(new File(downloadDirectory
+ fileName));
byte[] tempBuffer = new byte[4096];// KB
int numRead = 0;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public MailProcessor setMessage(Message message) {
this.message = message;
return this;
}
}
===========================================================================
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Message;
public class MailServer {
public static void start(int threadCount,
int frequencyInSecondsToListenMail) {
long lastFinished = System.currentTimeMillis();
do {
if ((System.currentTimeMillis() - lastFinished) / 1000 >= frequencyInSecondsToListenMail) {
readMails(threadCount);
}
} while (true);
}
private static void readMails(int threadCount) {
List<Message> recentMessages = MailUtility.readMessages();
ExecutorService executorService = Executors
.newFixedThreadPool(threadCount);
if(recentMessages == null || recentMessages.isEmpty()){
System.out.println("No messages found.");
}
for (Message message : recentMessages) {
executorService
.execute(new MailProcessor().setMessage(message));
}
executorService.shutdown();
}
public static void main(String[] args) {
MailServer.start(2, 2);
}
}
=======================================================================
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
public final class MailUtility {
public static List<Message> readMessages() {
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "");
properties.setProperty("mail.transport.protocol", "imaps");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
String username = mailServerProperties
.getProperty("username");
String password = mailServerProperties
.getProperty("password");
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Store store;
try {
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
List<Message> result = new ArrayList<Message>();
for(Message message : messages){
result.add(new MimeMessage((MimeMessage)message));
}
inbox.close(false);
store.close();
return result;
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
==========================================================================
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Flags.Flag;
public class MessagesProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
private List<Message> messages;
public MessagesProcessor() {
}
public void run() {
System.out.println("Starting processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finished processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
for (Message message : messages) {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
processMessageBody(message);
System.out.println("--------------------------------");
message.setFlag(Flag.SEEN, true);
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println(content);
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) {
InputStream inStream = null;
FileOutputStream outStream = null;
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Text = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)) {
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
inStream = bodyPart.getInputStream();
outStream = new FileOutputStream(new File(downloadDirectory
+ fileName));
byte[] tempBuffer = new byte[4096];// KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public MessagesProcessor setMessages(List<Message> messages) {
this.messages = messages;
return this;
}
}
============================================================================
import java.io.IOException;
import java.util.Properties;
public final class PropertyFileReader {
public static Properties getProperties(String filename) {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
Properties properties = new Properties();
try {
properties.load(contextClassLoader.getResourceAsStream(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return properties;
}
}
for(int i=0; i < timeToExecute; i++){
for(int j=0;j<5;j++){
Runnable runner = null;
if(i+1 == timeToExecute){
endIndex = count;
runner = new TaskPrint(startIndex, endIndex, inbox);
} else {
runner = new TaskPrint(startIndex, endIndex, inbox);
}
executor.execute(runner);
startIndex = endIndex + 1;
endIndex = endIndex + 200;
i++;
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DAOUtils {
public static void createTable(){
String createSql = "CREATE TABLE MAILBOX " +
" from VARCHAR(255), " +
" sentDate VARCHAR(255), " +
" subject VARCHAR(255), " +
" message VARCHAR(255)";
Connection con = DBConnection.getInstance().getConnection();
Statement stmt;
try {
stmt = con.createStatement();
stmt.executeUpdate(createSql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void insertRow(MailInfo mes){
Connection conn = DBConnection.getInstance().getConnection();
String sql = "INSERT INTO MAILBOX (from, sentDate, subject, message)" +
"VALUES (?, ?, ?, ?)";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, mes.getFrom());
preparedStatement.setString(2, mes.getSentDate());
preparedStatement.setString(3, mes.getSubject());
preparedStatement.setString(4, mes.getMessageContent());
preparedStatement.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
}
}
===========================================================================
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
private static Connection connect;
private static DBConnection instance;
private DBConnection()
{
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
String username = mailServerProperties
.getProperty("db_username");
String password = mailServerProperties
.getProperty("db_password");
String ip = mailServerProperties
.getProperty("ip");
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://" +ip +"/database",username,password);
}catch(SQLException e)
{
System.err.println(e.getMessage());
}catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
}
public static DBConnection getInstance()
{
if(instance == null) {
instance = new DBConnection();
}
return instance;
}
public static Connection getConnection(){
return connect;
}
}
=========================================================================
public class MailInfo {
private String sentDate;
private String subject;
private String from;
private String messageContent;
public String getSentDate() {
return sentDate;
}
public void setSentDate(String sentDate) {
this.sentDate = sentDate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessageContent() {
return messageContent;
}
public void setMessageContent(String messageContent) {
this.messageContent = messageContent;
}
}
===========================================================================
mail-server.properties
username = hhh60
password = $test123$
db_username = root
db_password = root
ip = localhost:3305
use_db = false
==========================================================================
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Message;
public class MailServer {
public static void start(int messageCountForEachThread, int threadCount) {
List<Message> messages = MailUtility.readMessages();
int messageLength = messages.size();
if (messages == null || messages.size() == 0) {
System.out.println("No messages found");
return;
}
System.out.println("Number of messages found " + messageLength);
if (messageLength <= messageCountForEachThread) {
new Thread(new MessagesProcessor().setMessages(messages)).start();
} else {
ExecutorService executorService = Executors
.newFixedThreadPool(threadCount);
int x = messageLength / messageCountForEachThread;
int remaining = messageLength % messageCountForEachThread;
int i = 1;
while (i <= x) {
int startIndex = (i - 1) * messageCountForEachThread;
int endIndex = startIndex + messageCountForEachThread;
List<Message> messagesForEachThread = messages.subList(
startIndex, endIndex);
executorService.execute(new MessagesProcessor()
.setMessages(messagesForEachThread));
i++;
}
int startIndex = i - 1 * messageCountForEachThread;
int endIndex = startIndex + remaining;
List<Message> messagesForEachThread = messages.subList(startIndex,
endIndex);
executorService.execute(new MessagesProcessor()
.setMessages(messagesForEachThread));
executorService.shutdown();
}
}
public static void main(String[] args) {
MailServer.start(2, 2);
}
}
=======================================================================
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public final class MailUtility {
public static List<Message> readMessages() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
boolean useDb = Boolean.parseBoolean(mailServerProperties.getProperty("use_db"));
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "");
properties.setProperty("mail.transport.protocol", "imaps");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
String username = mailServerProperties
.getProperty("username");
String password = mailServerProperties
.getProperty("password");
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Store store;
try {
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
if(useDb){
DAOUtils.createTable();
}
return Arrays.asList(messages);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
================================================================
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class MessagesProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
boolean useDb;
private List<Message> messages;
public MessagesProcessor() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
useDb = Boolean.parseBoolean(mailServerProperties.getProperty("use_db"));
}
public void run() {
System.out.println("Starting processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Finished processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
for (Message message : messages) {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
processMessageBody(message);
System.out.println("--------------------------------");
if(useDb){
MailInfo info = new MailInfo();
info.setFrom(from[0].toString());
info.setSentDate(message.getSentDate().toString());
info.setSubject(message.getSubject());
info.setMessageContent(message.toString());
DAOUtils.insertRow(info);
}
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println(content);
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) {
InputStream inStream = null;
FileOutputStream outStream = null;
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Text = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)) {
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
inStream = bodyPart.getInputStream();
File f = new File(downloadDirectory + fileName);
if(!f.exists()){
System.out.println("Downloading file : " + fileName + " .............");
outStream = new FileOutputStream(f);
byte[] tempBuffer = new byte[4096];// KB
int numRead = 0;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
System.out.println("Download completed");
} else {
System.out.println("Given file name already exists");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public MessagesProcessor setMessages(List<Message> messages) {
this.messages = messages;
return this;
}
}
==================================================================
import java.io.IOException;
import java.util.Properties;
public final class PropertyFileReader {
public static Properties getProperties(String filename) {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
Properties properties = new Properties();
try {
properties.load(contextClassLoader.getResourceAsStream(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return properties;
}
}
package Test.TestArtifact;
import java.time.LocalDate;
import java.util.Date;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
public class TaskPrint implements Runnable{
private Message messages;
private Date startDate;
public TaskPrint(Date startDate, Message messages){
this.startDate = startDate;
this.messages = messages;
}
public void run() {
try {
if(messages.getSentDate().after(startDate) && messages.getSentDate().before(startDate)){
Address[] in = messages.getFrom();
String contentType = messages.getContentType();
String messageContent = "";
String attachFiles = "";
if(contentType.contains("multiport")){
Multipart multipart = (Multipart) messages.getContent();
int noOfParts = multipart.getCount();
for(int partCount =0; partCount < noOfParts; partCount++){
MimeBodyPart mime = (MimeBodyPart) multipart.getBodyPart(partCount);
if(Part.ATTACHMENT.equalsIgnoreCase(mime.getDisposition())){
String fileName = mime.getFileName();
attachFiles += fileName + ",";
if(fileName.endsWith("=")){
mime.saveFile("C:\\tmp\\downloads" + fileName);
} else {
messageContent = mime.getContent().toString();
}
}
if(attachFiles.length() > 1){
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
} else if(contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = messages.getContent();
if(content != null){
messageContent = content.toString();
}
}
}
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
package Test.TestArtifact;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class ExecutorServiceExample {
public static void main(String[] args) throws MessagingException {
ExecutorServiceExample eService = new ExecutorServiceExample();
Folder inbox = eService.getInboxFolder();
int count = eService.getMailCount();
Message messages = inbox.getMessage(count);
System.out.println("Total Mail count = " + count);
ExecutorService executor = Executors.newFixedThreadPool(5);
int waitTime = 1000000;
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate;
Date endDate;
try {
startDate = formatter.parse("2015-10-01");
endDate = formatter.parse("2015-10-31");
while(startDate.before(endDate)){
for(int j=0;j<5;j++){
Runnable runner = new TaskPrint(startDate,messages);
executor.execute(runner);
}
}
} catch (ParseException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(waitTime);
executor.shutdown();
executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
private Folder getInboxFolder() throws MessagingException{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("", "", "");
store.getFolder("INBOX").open(Folder.READ_ONLY);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
return inbox;
}
private int getMailCount() throws MessagingException{
int count = getInboxFolder().getMessageCount();
return count;
}
}
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class ExecutorServiceExample {
public static void main(String[] args) throws MessagingException {
ExecutorServiceExample eService = new ExecutorServiceExample();
Folder inbox = eService.getInboxFolder();
Message[] messages = inbox.getMessages();
System.out.println("Total Mail count = " + messages.length);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
for(Message message: messages){
Runnable runner = new TaskPrint(message);
executor.execute(runner);
}
System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
executor.shutdown();
try {
Thread.sleep(1000);
executor.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Folder getInboxFolder() throws MessagingException{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props,null);
Store store = session.getStore();
store.connect("imap.gmail.com", "aaa#gmail.com", "aaaaa");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
return inbox;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class TaskPrint implements Runnable{
private Message message;
public TaskPrint(Message message){
this.message = message;
}
public void run() {
try {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
bodyPart.getFileName() != null) {
continue; // dealing with attachments only
}
System.out.println("Message subject " + message.getSubject());
InputStream is = bodyPart.getInputStream();
File f = new File("c:/tmp/" + bodyPart.getFileName());
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while((bytesRead = is.read(buf))!=-1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(MessagingException e){
e.printStackTrace();
}
}
}
Related
I'm quite new to java and unsure how to fix this java.io.NotSerializableException error.
I'm trying to use an add button on the GUI to add an object to an array list
Then write that object to a file so I am able to read it back.
Here is the code I'm using for the Branch class which implement Java Serializable:
import java.io.Serializable;
public class Branch implements Serializable{
private String branch_name;
private String branch_address;
public Branch(String Bname, String Baddress) {
this.branch_name = Bname;
this.branch_address = Baddress;
public String getbranch_name(){
return branch_name;
}
public String getbranch_address(){
return branch_address;
}
public void show_branch_details() {
System.out.println( " The branch name is : " + getbranch_name()
+ " branch address :"+ getbranch_address()
}
}
}
Here is the code for the add button:
ArrayList<Branch> BranchList = new ArrayList<Branch>();
JButton AddBranch = new JButton("ADD BRANCH");
AddBranch.setBounds(10, 35, 161, 23);
AddBranch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Bname = branchNameField.getText();
String Baddress = branchAddressField.getText();
Branch A = new Branch(Bname, Baddress);
BranchList.add(A);
for (int i = 0; i < BranchList.size(); i++) {
displayInfo.append(BranchList.get(i).getbranch_name() +);
}
System.out.println("The ArrayList has " + BranchList.size());
for (int i = 0; i < BranchList.size(); i++) {
System.out.println(BranchList.get(i).getbranch_name());
}
try {
FileOutputStream fos = new FileOutputStream("branch.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//oos.writeObject(BranchList);
for (int b = 0; b < BranchList.size(); b++) {
oos.writeObject(BranchList.get(b));
}
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("branch.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
//BranchList = (ArrayList<Branch>)ois.readObject();
Branch obj = null;
while ((obj = (Branch) ois.readObject()) != null) {
System.out.println("Name:" + obj.getbranch_name() + ", Address:"
+ obj.getbranch_address());
}
ois.close();
} catch (IOException ex) {
System.out.println(" IOE ERROR");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("class ERROR");
ex.printStackTrace();
}
}
});
Please use this as Branch class :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class Branch implements Serializable{
private String branch_name;
private String branch_address;
public Branch(String Bname, String Baddress) {
this.branch_name = Bname;
this.branch_address = Baddress;
}
public String getbranch_name(){
return branch_name;
}
public String getbranch_address(){
return branch_address;
}
public void show_branch_details() {
System.out.println( " The branch name is : " + getbranch_name()
+ " branch address :"+ getbranch_address());
}
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Branch A= new Branch("TestA","Add_A");
Branch B= new Branch("TestB","Add_B");
ArrayList<Branch> BranchList = new ArrayList<>();
BranchList.add(A);
BranchList.add(B);
FileOutputStream fos = new FileOutputStream("branch.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(BranchList);
oos.flush();
oos.close();
ArrayList<Branch> OutputBranchList = new ArrayList<>();
FileInputStream fis = new FileInputStream("branch.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
OutputBranchList = (ArrayList) ois.readObject();
for(Branch branch : OutputBranchList) {
System.out.println(branch.getbranch_name()+" "+ branch.getbranch_address());
}
ois.close();
}
}
I'm making an application with Google SpeechClient that has the requirements to set a GOOGLE_APPLICATION_CREDENTIALS environment variable that, once set, you can use the voice to text api.
My application is required to run in linux and windows. In linux it runs perfectly, however, on windows, when running the project, it throws an exception com.google.api.gax.rpc.UnavailableException: "io.grpc.StatusRuntimeException: UNAVAILABLE: Credentials failed to obtain metadata" when trying to run this thread
package Controller.Runnables;
import Controller.GUI.VoxSpeechGUIController;
import Model.SpokenTextHistory;
import com.google.api.gax.rpc.ClientStream;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.speech.v1.*;
import com.google.protobuf.ByteString;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import java.io.IOException;
import java.util.ArrayList;
public class SpeechRecognizerRunnable implements Runnable{
private VoxSpeechGUIController controller;
public SpeechRecognizerRunnable(VoxSpeechGUIController voxSpeechGUIController) {
this.controller = voxSpeechGUIController;
}
#Override
public void run() {
MicrofoneRunnable micrunnable = MicrofoneRunnable.getInstance();
Thread micThread = new Thread(micrunnable);
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver =
new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
public void onStart(StreamController controller) {}
public void onResponse(StreamingRecognizeResponse response) {
try {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
// There can be several alternative transcripts for a given chunk of speech. Just
// use the first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
String transcript = alternative.getTranscript();
System.out.printf("Transcript : %s\n", transcript);
String newText = SpokenTextHistory.getInstance().getActualSpeechString() + " " + transcript;
SpokenTextHistory.getInstance().setActualSpeechString(newText);
controller.setLabelText(newText);
}
catch (Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public void onComplete() {
}
public void onError(Throwable t) {
System.out.println(t);
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("pt-BR")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig =
StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();
StreamingRecognizeRequest request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build(); // The first request in a streaming call has to be a config
clientStream.send(request);
try {
// SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
// bigEndian: false
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info targetInfo =
new DataLine.Info(
TargetDataLine.class,
audioFormat); // Set the system information to read from the microphone audio
// stream
if (!AudioSystem.isLineSupported(targetInfo)) {
System.out.println("Microphone not supported");
System.exit(0);
}
// Target data line captures the audio stream the microphone produces.
micrunnable.targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
micrunnable.targetDataLine.open(audioFormat);
micThread.start();
long startTime = System.currentTimeMillis();
while (!micrunnable.stopFlag) {
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= 55000) {
clientStream.closeSend();
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build();
startTime = System.currentTimeMillis();
} else {
request =
StreamingRecognizeRequest.newBuilder()
.setAudioContent(ByteString.copyFrom(micrunnable.sharedQueue.take()))
.build();
}
clientStream.send(request);
}
} catch (Exception e) {
System.out.println(e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've been working hard for hours and have not found a solution that solves my problem.
It is worth mentioning that the environment variable is being set correctly.
Has anyone ever had this problem with Google? What should I do to fix this?
This is my envirounment variable creator:
PS: I`ve already tried use all google alternatives to validate credentials, but all return me errors.
package Controller.Autentication;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GoogleAuthentication {
private static final String GOOGLE_APPLICATION_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS";
private static final String VoxSpeechFolder = ".vox";
private static final String GoogleAuthenticationJsonFile = "VoxAuthentication.json";
public static void setupGoogleCredentials() {
String directory = defaultDirectory();
directory += File.separator+VoxSpeechFolder;
File voxPath = new File(directory);
if (!voxPath.exists()) {
voxPath.mkdirs();
}
ClassLoader classLoader = new GoogleAuthentication().getClass().getClassLoader();
File srcFile = new File(classLoader.getResource(GoogleAuthenticationJsonFile).getFile());
if(srcFile.exists()){
try {
String voxDestPath = defaultDirectory() + File.separator + VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
File destFile = new File(voxDestPath);
copyFile(srcFile,destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Map<String,String> googleEnv = new HashMap<>();
String path = defaultDirectory() +File.separator+ VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
googleEnv.put(GOOGLE_APPLICATION_CREDENTIALS, path);
setGoogleEnv(googleEnv);
} catch (Exception e) {
e.printStackTrace();
}
}
static void copyFile(File sourceFile, File destFile)
throws IOException {
InputStream inStream ;
OutputStream outStream ;
System.out.println(destFile.getPath());
if(destFile.createNewFile()){
inStream = new FileInputStream(sourceFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
}
static String defaultDirectory()
{
String OS = getOperationSystem();
if (OS.contains("WIN"))
return System.getenv("APPDATA");
else if (OS.contains("MAC"))
return System.getProperty("user.home") + "/Library/Application "
+ "Support";
else if (OS.contains("LINUX")) {
return System.getProperty("user.home");
}
return System.getProperty("user.dir");
}
static String getOperationSystem() {
return System.getProperty("os.name").toUpperCase();
}
protected static void setGoogleEnv(Map<String, String> newenv) throws Exception {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
String genv = System.getenv(GOOGLE_APPLICATION_CREDENTIALS);
System.out.println(genv);
}
}
I am trying to import configuration sbconfig.jar in OSB using java for automated tests. Before that I implemented FindAndReplace operation using Orcale help in java.
But in сase importing configuration from the same Article, when I run presented code - I get an error.
What I am trying to do
Connect to OSB(Oracle Service Bus 11.1)
Read file
Create session
Import prepared file
Activate session
On fourth item i got an error:
Cannot import to deployed configuration
Maybe someone has already implemented such a thing?
I would be grateful for help
package update.configuration.osb;
import com.bea.wli.config.Ref;
import com.bea.wli.config.customization.FindAndReplaceCustomization;
import com.bea.wli.config.env.EnvValueQuery;
import com.bea.wli.config.importexport.ImportResult;
import com.bea.wli.config.resource.Diagnostics;
import com.bea.wli.sb.management.configuration.*;
import com.bea.wli.sb.util.EnvValueTypes;
import com.bea.wli.config.customization.Customization;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import javax.management.*;
import javax.management.remote.*;
import javax.naming.Context;
import weblogic.management.jmx.MBeanServerInvocationHandler;
import weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean;
import com.bea.wli.sb.management.importexport.ALSBJarInfo;
import com.bea.wli.sb.management.importexport.ALSBImportPlan;
import java.util.Map;
public class OSBConfigUpdateNew {
private static JMXConnector initConnection(String hostname, int port,
String username, String password) throws IOException,
MalformedURLException {
JMXServiceURL serviceURL = new JMXServiceURL("t3", hostname, port,
"/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME);
Hashtable<String, String> h = new Hashtable<String, String>();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
"weblogic.management.remote");
return JMXConnectorFactory.connect(serviceURL, h);
}
static private void simpleImportExport(String importFileName, String host, int port,
String username, String password) {
JMXConnector conn = null;
SessionManagementMBean sm = null;
File importFile = new File(importFileName);
byte[] bytes = readBytes(importFile);
String sessionName = "newsession";
String statusmsg = "";
try {
conn = initConnection(host, port, username, password);
MBeanServerConnection mbconn = conn.getMBeanServerConnection();
DomainRuntimeServiceMBean domainService = (DomainRuntimeServiceMBean) MBeanServerInvocationHandler
.newProxyInstance(mbconn, new ObjectName(
DomainRuntimeServiceMBean.OBJECT_NAME));
sm = (SessionManagementMBean) domainService.findService(
SessionManagementMBean.NAME, SessionManagementMBean.TYPE,
null);
sm.createSession(sessionName);
ALSBConfigurationMBean alsbSession = getConfigMBean(sessionName, conn);
// ALSBConfigurationMBean alsbSession = (ALSBConfigurationMBean) domainService.findService(ALSBConfigurationMBean.NAME + "." + "newsession", ALSBConfigurationMBean.TYPE, null);
try {
alsbSession.uploadJarFile(bytes);
ALSBJarInfo jarInfo = alsbSession.getImportJarInfo();
ALSBImportPlan importPlan = jarInfo.getDefaultImportPlan();
ImportResult result = alsbSession.importUploaded(importPlan);
if (result.getImported().size() > 0) {
System.out.println("The following resources have been successfully imported.");
for (Ref ref : result.getImported()) {
System.out.println("\t" + ref);
}
}
if (result.getFailed().size() > 0) {
System.out.println("The following resources have failed to be imported.");
for (Map.Entry<Ref, Diagnostics> e : result.getFailed().entrySet()) {
Ref ref = e.getKey();
Diagnostics d = e.getValue();
System.out.println("\t" + ref + ". reason: " + d);
}
System.out.println("Discarding the session.");
sm.discardSession(sessionName);
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
sm.activateSession(sessionName, "description");
ALSBConfigurationMBean alsbcore = getConfigMBean(null, conn);
byte[] contentsProj = alsbcore.exportProjects(Collections.singleton(Ref.makeProjectRef("Project")), null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception ex) {
if (null != sm) {
try {
sm.discardSession(sessionName);
} catch (Exception e) {
System.out.println("Able to discard the session");
}
}
statusmsg = "Not able to perform the operation";
ex.printStackTrace();
} finally {
if (null != conn)
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static ALSBConfigurationMBean getConfigMBean(String sessionName, JMXConnector conn) throws Exception {
MBeanServerConnection mbconn = conn.getMBeanServerConnection();
DomainRuntimeServiceMBean domainService =
(DomainRuntimeServiceMBean) MBeanServerInvocationHandler.newProxyInstance(
mbconn, new ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME));
return (ALSBConfigurationMBean) domainService.findService(
ALSBConfigurationMBean.NAME,
ALSBConfigurationMBean.TYPE, null);
}
private static byte[] readBytes(File importFile) {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(importFile);
int read = 0;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
// private static Ref constructRef(String refType, String serviceuri) {
// Ref ref = null;
// String[] uriData = serviceuri.split("/");
// ref = new Ref(refType, uriData);
// return ref;
// }
public static void main(String[] args) {
simpleImportExport("C:\\sbconfig.jar", "127.0.0.1",
7001, "user", "password");
}
}
Serializing data through
try {
FileOutputStream fileOut = new FileOutputStream(
"C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(r);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reg.ser");
pr.println("Registered Successfully ");
} catch (IOException i) {
i.printStackTrace();
}
and while Deserializing not getting entire file objects only getting single object i.e starting object only .
FileInputStream fileIn = new FileInputStream("C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser");
ObjectInputStream in = null;
while (fileIn.available() != 0) {
in = new ObjectInputStream(fileIn);
while (in != null && in.available() != 0) {
r = (Registration) in.readObject();
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
if (r.u.equals(ur) && r.p.equals(ps)) {
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
pr.println("Display");
}
}
}
I have created the working sample for you .
My POJO serializable class will be ,
import java.io.Serializable;
public class Pojo implements Serializable{
String name;
String age;
String qualification;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
My main class will be,
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Serialization {
/**
* #param args
*/
public static final String FILENAME = "F:\\test\\cool_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
//ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(FILENAME);
//oos = new ObjectOutputStream(fos);
/* for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}*/
for(int i=0;i<10;i++){
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pojo pojo = new Pojo();
pojo.setName("HumanBeing - "+i);
pojo.setAge("25 - "+i);
pojo.setQualification("B.E - "+i);
oos.writeObject(pojo);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
//ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILENAME);
//ois = new ObjectInputStream(fis);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
for (int i=0; i<results.size()-1; i++) {
System.out.println(((Pojo)results.get(i)).getName()+ " "+((Pojo)results.get(i)).getAge()+ " "+((Pojo)results.get(i)).getQualification());
}
}
}
Hope it helps.
I am trying to execute a command (eg. ps -ef | grep apache) using ProcessBuilder and Process. The code works as long as the output of 'ps -ef' is small. But if the output is too big, the program hangs. Is there a way to fix this? Here is my code based on [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
#### Program.java ####
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class Program {
private List<String> command;
public Program(String commandString) throws IOException {
this(commandString, null);
}
public List<String> getCommand() {
return this.command;
}
private void setCommand(String filename, String location, String commandString, List<String> parameters) throws IOException {
if(filename != null) {
commandString = new File(location, filename).getCanonicalPath();
}
this.command =
Collections.synchronizedList(new ArrayList<String>());
this.command.add(commandString);
if (parameters != null) {
for (String arg: parameters) {
command.add(arg);
}
}
}
public String[] run() throws IOException, InterruptedException {
return this.run(null);
}
public String[] run(String input) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(this.command);
List<String> commandList = processBuilder.command();
Process process = processBuilder.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(process.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
process.getOutputStream().close();
Gobbler outGobbler = new Gobbler(process.getInputStream());
Gobbler errGobbler = new Gobbler(process.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = process.waitFor();
System.out.println("PROCESS WAIT FOR: " + exitVal);
List<String> output = outGobbler.getOuput();
return output.toArray(new String[output.size()]);
}
}
#### CommandExecutor.java ####
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CommandExecutor {
public List<List<Object>> programs;
public static void main(String[] args) {
try {
CommandExecutor ce = new CommandExecutor(args[0]);
String output = ce.run();
System.out.println("Command: " + args[0]);
System.out.println("Output: " + output);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getLocalizedMessage());
e.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.out.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public CommandExecutor(String command) throws IOException {
this.setPrograms(command);
}
private void setPrograms(String command) throws IOException {
this.programs = new ArrayList<List<Object>>();
//String cmdstring = "";
String[] commands = command.split("\\s*;\\s*");
for(String c: commands) {
//String subcmdstr = "";
String file = null;
String[] chainedCommands = c.split("\\s*\\|\\s*");
String lastCmd = chainedCommands[chainedCommands.length-1];
String[] fileCmd = lastCmd.split("\\s*>\\s*");
if(fileCmd.length > 1) {
chainedCommands[chainedCommands.length-1] = fileCmd[0];
file = fileCmd[1];
}
List<Object> l = new ArrayList<Object>();
for(String p: chainedCommands) {
/*if(subcmdstr.equals("")) {
subcmdstr = p;
}
else {
subcmdstr += " redirects to " + p;
}*/
String[] cmdparams = p.split(" ");
String cmd = cmdparams[0];
List<String> params = new ArrayList<String>();
for(int j = 1; j < cmdparams.length; j++) {
params.add(cmdparams[j]);
}
Program prog = new Program(cmd, params);
l.add(prog);
}
if(file != null) {
//subcmdstr += " redirects to file: " + file;
l.add(file);
}
this.programs.add(l);
//cmdstring += "new command: " + subcmdstr + "\n";
}
//System.out.println("Actual Command: " + command);
//System.out.println("Command String:\n" + cmdstring);
}
public String run() throws IOException, InterruptedException {
String output = "";
for(List<Object> l: this.programs) {
String[] out = new String[0];
int count = 0;
boolean filenotfound = true;
for(Object o: l) {
if(o instanceof Program) {
Program p = (Program) o;
if(count == 0) {
out = p.run();
}
else {
out = p.run(CommandExecutor.arrayToString(out));
}
}
else if(o instanceof String) {
PrintWriter f = new PrintWriter(new File((String)o));
f.print(CommandExecutor.arrayToString(out));
f.close();
filenotfound = false;
}
count++;
}
if(filenotfound) {
output += CommandExecutor.arrayToString(out);
}
}
return output;
}
public static String arrayToString(String[] strArray) {
String str = "";
for(String s: strArray) {
str += s;
}
return str;
}
}
Thanks,
Quadir
Ok, I got it working. Below is the code, given a list of commands, it pipes the output of one command to the next.
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Don't print it as a String but give the CommandExecuter an optional OutputStream (in your Case you pass System.out as the argument) and write it to that stream.
In your current program the Main Method will execute the program and won't print anything (hang) until your run method returns something.