// CLIENT SOURCE
while(!isStop){
try{
Object ob = mc.getOis().readObject();
try{
message = (String) ob;
} catch (ClassCastException e){
try {
user = (User) ob;
mc.user = (User) ob;
message = "none";
} catch ( ClassCastException ee ) {
Room room = (Room) ob;
mc.setRoom(room);
System.out.println("room come in");
for (int i = 0; i<mc.room.userlist.size(); i++ )
{
System.out.println("ThreadUserNum:" + room.userlist.get(i).getPlayer_Num());
}
mc.roomidimg();
message = "none";
}
}
}
}
// SERVER SOURCE
public void roombroodcast ( Room msg, int room_id) throws IOException{
if (room_id == 1){
for( ServerThread ct : sv.getroom1list() ){
for( int i = 0; i<msg.getUserlist().size(); i++){
System.out.println(i + "broodcast:" + msg.getUserlist().get(i).getUser_Id());
}
ct.send( msg );
}
} else {
for( ServerThread ct : sv.getroom2list() ){
ct.send( msg );
}
}
}
We are making a game but we have some problems.
The first user, who entered the game first, cannot get the other user's room
class broadcasting.
I mean, the other user or another user can get the room class broadcasting but the first one cannot get the updated room information.
How can I update the room class broadcasting problem?
We are using sockets to communicate.
You are always sending the same object, so serialization will not actually re-send it: it economizes, as described in the Object Serialization Specification. So updating it and sending it again will not affect the object received at the receiver.
You need to investigate ObjectOutputStream.reset() or ObjectOutputStream.writeUnshared().
Related
I have come across a few posts, none of which has really answered my question, I have also been in the process of raising the question but putting it off only to research more dead ends...
So here is the issue, using j2ssh libraries to make ssh connections :
#OnMessage
public String handleOpen(Session usersession) {
System.out.println("Client is now connected.")
properties = new SshConnectionProperties();
properties.setHost(host)
properties.setPort(sshPort)
ssh.connect(properties, new IgnoreHostKeyVerification())
int result=0
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient()
pwd.setUsername(username)
pwd.setPassword(password)
result = ssh.authenticate(pwd)
if(result == 4) {
isAuthenticated=true
}
// Evaluate the result
if (isAuthenticated) {
session = ssh.openSessionChannel()
SessionOutputReader sor = new SessionOutputReader(session)
if (session.requestPseudoTerminal("gogrid",80,24, 0 , 0, "")) {
if (session.startShell()) {
ChannelOutputStream out = session.getOutputStream()
session.getOutputStream().write("${usercommand} \n".getBytes())
println "--------------------------------authenticated user"
handleMessage(session.getInputStream(),usersession)
}
}
}
}
#OnMessage
public void handleMessage(InputStream stream, Session usersession) {
try {
usersession.getBasicRemote().sendText('SOMETHING')
usersession.getBasicRemote().sendObject(stream)
//return stream
} catch (IOException e) {
}
}
What I would like to do is for handleMessage to return the entire inputStream
Then within the javascript on the client's webpage to recieve that input stream :
...
webSocket.onmessage=function(message) {processMessage(message);};
var THRESHOLD = 10240;
...
function processMessage(message) {
//webSocket.send(textMessage.value);
//textMessage.value="";
messagesTextarea.value +=" woot woot woot\n";
if(message.data instanceof ArrayBuffer) {
var wordarray = new Uint16Array(message.data);
for (var i = 0; i < wordarray.length; i++)
{
console.log(wordarray[i]);
wordarray[i]=wordarray[i]+1;
}
messagesTextarea.value +=""+wordarray.buffer+"\n"
}else{
messagesTextarea.value +=""+message.data+"\n"
}
/*
setInterval( function() {
//messagesTextarea.value +=" Receive from Server ===> "+ message.data +"\n";
if (webSocket.bufferedAmount < THRESHOLD) {
if ((message.data != null)&&(message.data !="")) {
messagesTextarea.value +=" got from Server ===> ("+message.data+")";
}
} }, 5000);
*/
}
The objective is to launch ssh connection (no input really required - although with input would be of benefit for further client calls...
Once connected to run
handleMessage(session.getInputStream(),usersession)
This then returns the stream from the connection back to the javascript frontend.
At the moment I can see a connection to handleMessage but nothing is being returned to javascript frontend...
So I guess its related to how do you stream inputstreams via a javascript frontend.....
Ive actually got it working - up for lots of testing at the momemnt:
Java Endpoint:
#OnMessage
public void handleMessage(String message, Session usersession) {
InputStream input=session.getInputStream()
byte[] buffer=new byte[255]
int read;
int i=0
def pattern = ~/^\s+$/
while((read = input.read(buffer)) > 0) {
String out1 = new String(buffer, 0, read)
def m=pattern.matcher(out1).matches()
if (m==false) {
usersession.getBasicRemote().sendText(out1)
}
}
}
Front end Java script (note the call is not hitting array if call )
function processMessage(message) {
if(message.data instanceof ArrayBuffer) {
var wordarray = new Uint16Array(message.data);
for (var i = 0; i < wordarray.length; i++) {
console.log(wordarray[i]);
wordarray[i]=wordarray[i]+1;
}
messagesTextarea.value +=""+wordarray.buffer+"\n"
}else{
messagesTextarea.value +=""+message.data+"\n"
}
}
Firstly, yes I'm calling this from a web browser. It's quite a long piece of code but I've tried shortening it as much as possible.
Basically, I need to wait let's say 1 second for every iteration in the loop. Tried pretty much everything (.sleep() etc.) but it just doesn't seem to be pausing. The reason why I need to do this is because the SimpleSocketClient is calling a socket which has a low limit per second allowed.
#Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
String forwardToJsp = null;
HttpSession session = request.getSession();
String allUrls = request.getParameter("domains");
ArrayList domainList = new ArrayList<String>();
Scanner sc = new Scanner(allUrls);
while (sc.hasNextLine()) {
String line = sc.nextLine();
domainList.add(line);
// process the line
}
sc.close();
String pageHtml = null;
String domain = "";
String status = "";
String registrant = "";
String dates = "";
String tag = "";
String email = "";
ArrayList domains = new ArrayList<Domain>();
Domain theDomain;
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
for (int i = 0; i < domainList.size(); i++) {
//NEED TO WAIT 1 SECOND HERE / ANYWHERE IN LOOP
String singleDomain = domainList.get(i).toString();
SimpleSocketClient tester = new SimpleSocketClient(singleDomain,ipAddress);
pageHtml = tester.getResult();
try {
String whoIs2 = ipAddress + " " + ipAddress + " " + singleDomain + "\r\n";
byte[] data = whoIs2.getBytes();
//details of each domain
//domain name
domain = singleDomain;
//status
status = "FTR";
//registrant
registrant = "N/A";
//dates
dates = "N/A";
//tag
tag = "N/A";
//email
email = "N/A";
}
} catch (Exception e) {
Logger.getLogger("ip is " + ipAddress + bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, e);
forwardToJsp = "index.jsp";
return forwardToJsp;
}
//single one
theDomain = new Domain(domain,status,registrant,dates,tag,email);
//now add to arrayList
domains.add(theDomain);
// try {
// Thread.sleep(230000);
// } catch (InterruptedException ex) {
// Logger.getLogger(bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, ex);
// }
// try {
// pause.poll(100 * 300, TimeUnit.MILLISECONDS);
// } catch (InterruptedException ex) {
// Logger.getLogger(bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, ex);
// }
}
EDIT - Friend recommended to use ajax to poll updates but surely there's a way of just using java.
Your can try to set a while-loop in the while-loop, to pause it. Should like this:
while(!done)
{
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < 1000L){}
}
Didn't test it but the approach counts. I had the idea to do a combination of both. So every time Thread.Sleep() crashes, you have to take the loop. Something like this:
while(!done)
{
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println(e);
}
while(System.currentTimeMillis() - start < 1000L){}
}
When Thread.Sleep() worked it just get called once. Otherwise you need some CPU time. Could be the cpu economical version.
I am currently having issues in attempting to display data (i.e. itemSummaries with a certain ContainerType) for sites that are ISP, as an example, www.telstra.com.au from Australia
Logging into the site works fine, and the credentials for the site work fine (in other words, it does a refresh which succeeds), however there doesn't appear to be a way to display the itemSummary data
The soap command getItemSummaries, doesn't display data for the item (it displays item data from financial institutions fine). Upon examining the sample code provided by Yodlee for the java soap api, you are meant to use the getItemSummaries1 along with setting ContainerTypes using a SummaryRequest
The problem is that this returns a CoreExceptionFaultMessage. The getItemSummaries1 command is causing the CoreExceptionFaultError. Using different ContainerTypes with different combinations (i.e. ISP, Telephone, Bills) didn't alleviate the issue
The same error message is returned in Yodlees own sample code, i.e. java_soap_example (run the com.yodlee.sampleapps.accountsummary.DisplayBillsData main method and provide the Yodlee login info as command line arguments)
As a reference, the code that is provided by Yodlee sample app is below
Running the getItemSummaries1 command
public void displayBillsData (UserContext userContext)
{
/*SummaryRequest sr = new SummaryRequest(
new String[] {ContainerTypes.BILL, ContainerTypes.TELEPHONE},
new DataExtent[] { DataExtent.getDataExtentForAllLevels(),DataExtent.getDataExtentForAllLevels() }
);*/
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(new String[] {ContainerTypesHelper.BILL, ContainerTypesHelper.TELEPHONE});
sr.setContainerCriteria(list);
Object[] itemSummaries = null;
List itemSummariesList = null;
try {
itemSummariesList = dataService.getItemSummaries1(userContext, sr);
if (itemSummariesList != null){
itemSummaries = itemSummariesList.getElements();
}
} catch (StaleConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (InvalidConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (CoreExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentTypeExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentValueExceptionFault e) {
e.printStackTrace();
} catch (InvalidUserContextExceptionFault e) {
e.printStackTrace();
} catch (IllegalDataExtentExceptionFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if (itemSummaries == null || itemSummaries.length == 0) {
System.out.println ("No bills data available");
return;
}
for (int i = 0; i < itemSummaries.length; i++) {
ItemSummary is = (ItemSummary) itemSummaries[i];
displayBillsDataForItem(is);
// Dump the BillsData Object
// dumpBillsDataForItem(is);
}
}
Printing the item data
public void displayBillsDataForItem (ItemSummary is)
{
String containerType = is.getContentServiceInfo ().
getContainerInfo ().getContainerName ();
System.out.println("containerType = " + containerType );
if (!(containerType.equals(ContainerTypesHelper.BILL ) || containerType.equals(ContainerTypesHelper.TELEPHONE)
|| containerType.equals(ContainerTypesHelper.MINUTES))) {
throw new RuntimeException ("displayBillsDataForItem called with " +
"invalid container type: " + containerType);
}
DisplayItemInfo displayItemInfo = new DisplayItemInfo ();
System.out.println("DisplayItemInfo:");
displayItemInfo.displayItemSummaryInfo (is);
System.out.println("");
ItemData id = is.getItemData();
if(id == null){
System.out.println("ItemData == null");
}else{
List accountsList = id.getAccounts();
Object[] accounts = null;
if (accountsList != null){
accounts = accountsList.getElements();
}
if (accounts == null || accounts.length == 0) {
System.out.println ("\tNo accounts");
}else {
for (int accts = 0; accts < accounts.length; accts++) {
BillsData billsData = (BillsData) accounts[accts];
System.out.println("\tAccount Holder: " + billsData.getAccountHolder() );
System.out.println("\tAccount Id: " + billsData.getAccountId());
System.out.println("\tItemAccountId: " + billsData.getItemAccountId() );
System.out.println("\tAccountName: " + billsData.getAccountName() );
System.out.println("\tAccountNumber: " + billsData.getAccountNumber() );
System.out.println("");
// Get List of Bill Objects
List billsList = billsData.getBills();
Object[] bills = null;
if (billsList != null){
bills = billsList.getElements();
}
if (bills == null || bills.length == 0) {
System.out.println ("\t\tNo Bill objects");
}else {
for (int b = 0; b < bills.length; b++) {
Bill bill = (Bill) bills[b];
System.out.println("\t\tBill Account Number: " + bill.getAccountNumber() );
System.out.println("\t\tBill Acct Type: " + bill.getAcctType() );
System.out.println("\t\tBill Due Date: " + Formatter.formatDate(bill.getDueDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Date: " + Formatter.formatDate(bill.getBillDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Past Due: "
+ (bill.getPastDue() != null ? bill
.getPastDue().getAmount() : 0.0));
System.out
.println("\t\tBill Last payment: "
+ (bill.getLastPayment() != null ? bill
.getLastPayment()
.getAmount()
: 0.0));
System.out.println("\t\tBill Amount Due: "
+ (bill.getAmountDue() != null ? bill
.getAmountDue().getAmount() : 0.0));
System.out
.println("\t\tBill Min Payment: "
+ (bill.getMinPayment() != null ? bill
.getMinPayment()
.getAmount()
: 0.0));
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = bill.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\t\tNo AccountUsageData objects");
}else {
for (int usage = 0; usage < acctUsageData.length; usage++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usage];
System.out.println("\t\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = billsData.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\tNo AccountUsageData objects");
}else {
for (int usageData = 0; usageData < acctUsageData.length; usageData++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usageData];
System.out.println("\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
}
}
EDIT2:
I have updated the getItemSummaries1 command to look like this
ContainerCriteria bills = new ContainerCriteria();
ContainerCriteria telephone = new ContainerCriteria();
ContainerCriteria isp = new ContainerCriteria();
ContainerCriteria utilities = new ContainerCriteria();
bills.setContainerType(ContainerTypesHelper.BILL);
telephone.setContainerType(ContainerTypesHelper.TELEPHONE);
isp.setContainerType(ContainerTypesHelper.ISP);
utilities.setContainerType(ContainerTypesHelper.UTILITIES);
Object[] containerList = {
bills,telephone,isp,utilities
};
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(containerList);
sr.setContainerCriteria(list);
The command now executes and works correctly, however its returning a list of 0 elements (using DataExtents with different values didn't change anything). My suspicion is that Telstra.com.au site is broken on Yodlee's end (when a full refresh is done on the Telstra site, Yodlee returns a null for refreshing that specific site).
So far I can see some deviation, so do modify your container criteria as mentioned below
object[] list = {
new ContainerCriteria { containerType = "bills" },
new ContainerCriteria { containerType = "telephone" }
};
sr.containerCriteria = list;
You may additionally provide data extent as follows
DataExtent de = new DataExtent();
dataExtent.startLevel = 0; //as per your needs
dataExtent.endLevel = 0; //as per your needs
object[] list = {
new ContainerCriteria { containerType = "bills", dataExtent = de },
new ContainerCriteria { containerType = "telephone", dataExtent = de }
};
sr.containerCriteria = list;
This should solve your issue. If not then try to get the detail which is is node in the response for the CoreExceptionFaultMessage, this detail may help to diagnose the accurate issue.
To get data for any of the container first you need to add an account for the site belonging to that container. Once you have added the account successfully then only you will be able to pull in the data for such container. Also you can check the tag returned in the getItemSummaries API which has and once this statusCode = 0 then only you have data present for that account.
You can do testing by using the Dummy account which yodlee provides. Please refer to Yodlee Dummy account generator page for more info on Dummy accounts.
I need to communicate a Java application and a C process via POSIX message queue, and I would like to do it using JNA.
After some research, reading and your help, I started with a simple Java application which tries to create a message queue.
/** Simple example of JNA interface mapping and usage. */
public class HelloJNAWorld {
// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.
public interface IPCLibrary extends Library {
IPCLibrary INSTANCE = (IPCLibrary)
Native.loadLibrary("c",IPCLibrary.class);
int msgget(NativeLong key, int msgflg);
}
public static void main(String[] args) {
int id = IPCLibrary.INSTANCE.msgget(new NativeLong(12500), 0600|1);
if(id<0){
System.out.println("Error creating message queue. Id:"+id);
System.out.println(Native.getLastError());
}else{
System.out.println("Message queue id:" + idCola);
}
}
}
I thought msgctl was the simplest method to map because it's just int msgget(key_t key, int msgflag);. I have assumed that I could map key_t as a NativeLong but msget is returning -1. So I've checked lastError and the value returned is 2, which means "No such file or
directory" according to errno codes.
Could you help me with this? Maybe key_t should be mapped in another way? Maybe I need more libraries or something like that?
Since no one answer this question, and some could need the help I needed those days, I'm posting my test class code here. :-)
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.Structure;
/** Simple example of JNA interface mapping and usage. */
public class HelloJNAWorld {
// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)
Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),CLibrary.class);
void printf(String format, Object... args);
}
public interface IPCLibrary extends Library {
IPCLibrary INSTANCE = (IPCLibrary)
Native.loadLibrary("c",IPCLibrary.class);
class WaitQueue extends Structure{
}
// mapping msqid_ds structure
class MsqidDs extends Structure{
long msg_stime; /* last msgsnd time */
long msg_rtime; /* last msgrcv time */
long msg_ctime; /* last change time */
short msg_cbytes;
short msg_qnum;
short msg_qbytes; /* max number of bytes on queue */
short msg_lspid; /* pid of last msgsnd */
short msg_lrpid; /* last receive pid */
}
// END mapping msqid_ds structure
class MsgBuf extends Structure{
NativeLong mtype; /* type of message */
byte mtext[] = new byte[1];
}
class MyMsgBuf extends MsgBuf{
public NativeLong messageKind;
public byte[] contenido = new byte[1024];
}
// Initialize queue, or if it exists, get it
int msgget(NativeLong key, int msgflg);
// Send messages to queue
// int msgsnd(int msqid, struct msgbuf *ptrkey, int length, int flag);
int msgsnd(int msqid, MsgBuf ptrkey, int msgsz, int msgflg);
// Receive messages from queue
// int msgrcv(int msqid, struct msgbuf *ptrkey, int length, long msgtype, int flag);
int msgrcv(int msqid, MsgBuf ptrkey, int length, long msgtype, int flag);
}
public static void main(String[] args) {
int idCola = IPCLibrary.INSTANCE.msgget(new NativeLong(12500), 0);
if(idCola<0){
System.out.println("The queue can't be created. IdCola:"+idCola);
System.out.println("Error msgget: " + Native.getLastError());
}else{
System.out.println("Queue with id:" + idCola + "has been recovered");
// Send message
IPCLibrary.MyMsgBuf mensaje = new IPCLibrary.MyMsgBuf();
mensaje.tipoMensaje = new NativeLong(1);
mensaje.contenido = "Sending message".getBytes();
int devSend = IPCLibrary.INSTANCE.msgsnd(idCola, mensaje, mensaje.contenido.length, 1);
if(devSend != 0){
System.out.println("Send response: "+devSend);
System.out.println("Error value: " + Native.getLastError());
}
}
// Receiving message
IPCLibrary.MyMsgBuf mensajeRecibido = new IPCLibrary.MyMsgBuf();
int bytesRecibidos = IPCLibrary.INSTANCE.msgrcv(idCola, mensajeRecibido, mensajeRecibido.contenido.length, 1234, 0);
if(bytesRecibidos > 0){
System.out.println("C message has been received: " + new String(mensajeRecibido.contenido));
}else{
System.out.println("msgrcv error: " + Native.getLastError());
}
// Send closing message
IPCLibrary.MyMsgBuf mensajeCierre = new IPCLibrary.MyMsgBuf();
mensajeCierre.tipoMensaje = new NativeLong(2);
mensajeCierre.contenido = "Closing queue".getBytes();
int devSend = IPCLibrary.INSTANCE.msgsnd(idCola, mensajeCierre, mensajeCierre.contenido.length, 1);
if(devSend != 0){
System.out.println("Send response: "+devSend);
System.out.println("Error value: " + Native.getLastError());
}
}
}
I really hope this can help someone else.
I cleaned up your code and got it running.
You need two tasks . one to send and one to receive.
just replace the main() in your previous post with the main()'s below. It worked for me. Thanks for posting your efforts for me to start with.
Also see kirk.c and spock.c for a good c example http://beej.us/guide/bgipc/output/html/multipage/mq.html
public static void main(String[] args) {
double SLEEP_MINUTES = 0.1;
int IPC_CREAT = 01000; // starts with 0 so its octal or 512
int IPC_EXCL = 02000;
int IPC_NOWAIT = 04000;
int MSG_EXCEPT = 020000;
int MSG_NOERROR = 010000; // truncate the message if its to big
int msgflg_msgrcv = MSG_NOERROR; // truncate the message if its to big
int msgflg_msgget = 0666 | IPC_CREAT;
int msgflg_msgsnd = 0;
int msgtype_msgrcv = 0; // read them all
NativeLong msgtype_msgsnd = new NativeLong(1); // just needs to be a positive number
NativeLong msgkey = new NativeLong(12500);
int msqid = IPCLibrary.INSTANCE.msgget(msgkey, msgflg_msgget);
if(msqid<0)
{
System.out.println("The queue can't be created. msqid:"+msqid);
System.out.println("Error msgget: " + Native.getLastError());
System.exit(0);
}
System.out.println("Queue with id:" + msqid + "has been found or created");
for(int i=0;i<100;i++)
{
// Send message
IPCLibrary.MyMsgBuf message = new IPCLibrary.MyMsgBuf();
message.messagetype = msgtype_msgsnd;
message.content = ("Sending message"+i+'\0').getBytes(); // add 1 for the '\0'
int devSend = IPCLibrary.INSTANCE.msgsnd(msqid, message, message.content.length+1,
msgflg_msgsnd);
if(devSend != 0)
{
System.out.println("Send response: "+devSend);
System.out.println("Error value: " + Native.getLastError());
System.exit(0);
}
System.out.println("Sent "+i);
try
{
Thread.sleep((long)(SLEEP_MINUTES*60.0*1000.0));
}
catch (InterruptedException e)
{
System.out.println("InterruptedException while writing");
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
// found these in /usr/include/bits/*.h
int IPC_CREAT = 01000; // remember if it starts with a '0' its octal or 512
int IPC_EXCL = 02000;
int IPC_NOWAIT = 04000;
int MSG_EXCEPT = 020000;
int MSG_NOERROR = 010000; // truncate the message if its to big
int msgflg_msgrcv = MSG_NOERROR; // truncate the message if its to big
int msgflg_msgget = 0666 | IPC_CREAT; // create the queue if its not there , let everybody read and write
int msgtype_msgrcv = 0; // read them all
NativeLong msgtype_msgsnd = new NativeLong(1); // just needs to be a positive number
NativeLong msgkey = new NativeLong(12500);
int msqid = IPCLibrary.INSTANCE.msgget(msgkey, msgflg_msgget);
if(msqid<0)
{
System.out.println("The queue can't be created. msqid:"+msqid);
System.out.println("Error msgget: " + Native.getLastError());
System.exit(0);
}
System.out.println("Queue with id:" + msqid + "has been found or was created");
for(int i=0;i<100;i++)
{
IPCLibrary.MyMsgBuf message = new IPCLibrary.MyMsgBuf();
int ret = IPCLibrary.INSTANCE.msgrcv(msqid, message, message.content.length,
msgtype_msgrcv,msgflg_msgrcv);
if(ret > 0)
{
System.out.println("message has been received: " + ret);
System.out.println(new String(message.content));
}
else
{
System.out.println("msgrcv error: " + Native.getLastError());
}
}
}
}
i know how can we retrive the mails from INBOX folder...but now i want to retrieve mails from SENT ITEMS folder...i am using imap to retrieve the data...
Let me know what parameter i should pass in this function to get mails from SENT ITEMS folder
Folder folder=store.getFolder("inbox");i should change the inbox as some stirng i want to know that string...
There is not a standard name here. The IMAP spec requires that the inbox be called "INBOX", but no other folders are specifically defined. It's just a name of a folder after all - some providers will use "Sent", some will use "Sent Items" and you might even see some other variants about.
I'd recommend listing the folders that the server knows about, and selecting the appropriate one from there (either interactively, or perhaps grepping for "sent" in the name if running headless). A better option overall might be to make this a configurable parameter (if your application already has a properties file).
Of course, if this is a throwaway project you could just hard-code the value for the specific server in question. But if you want to do it properly, you'll need to be flexible.
I found the solution for my problem....
i used this code to list out the folders from mail server
and pass those values in getFolder() function...it's working fine..
Folder[] folderList = store.getDefaultFolder().list();
for (int i = 0; i < folderList.length; i++) {
System.out.println(folderList[i].getFullName());
}
Gmail stores sent mails under a folder called Sent Mail inside [Gmail] folder. So I was able to get the sent mail folder through this;
Folder sentMail = store.getFolder( "[Gmail]" ).getFolder( "Sent Mail" );
This code will retrieve all mails and will print the contents and store in local if have any attachment
public class MailReader {
Folder inbox;
public MailReader() {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "username",
"password");
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : "
+ inbox.getMessageCount() + " "
+ inbox.getUnreadMessageCount());
/* Open the inbox using store. */
inbox.open(Folder.READ_ONLY);
/*
* Get the messages which is unread in the Inbox Message messages[]
* = inbox.search(new FlagTerm( new Flags(Flag.SEEN), false));
*/
Message messages[] = inbox.getMessages();
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception {
for (int i = 0; i < msgs.length; i++) {
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
/* Print the envelope(FromAddress,ReceivedDate,Subject) */
public void printEnvelope(Message message) throws Exception {
Address[] a;
// FROM
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg) {
try {
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
dumpPart(mp.getBodyPart(i));
}
} catch (Exception ex) {
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception {
// Dump input stream ..
if (p.getFileName() == null) {
return;
}
System.out.println("filename:" + p.getFileName());
System.out.println(p.ATTACHMENT);
InputStream is = p.getInputStream();
File file = new File(p.getFileName());
FileOutputStream fout = null;
fout = new FileOutputStream(p.getFileName());
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1) {
fout.write(c);
}
if (fout != null) {
fout.close();
}
}
public static void main(String args[]) {
new MailReader();
}
}