I Want to set the header order of my mime message. I have tried implementing mimemessage and overridden writeTo method. But, im unable to understand how it works. I have sent a sample message but ended up receiving the headers two times. Can anyone please help me get clarity on this. Below is my Message class.
public class MyMessage extends MimeMessage{
private String subject;
private String encodingtype;
public MyMessage(Session session) {
super(session);
this.session=session;
}
#Override
public void writeTo(OutputStream out) throws java.io.IOException, MessagingException{
try{
String replyto = ("\""+displayname+"\" <"+displayfrom+">");
String fromheader = ("\""+displayname+"\" <"+mailfrom+">");
out.write(("Date: "+new Date()+"\r\n").getBytes("UTF-8"));
out.write(("From: "+fromheader+"\r\n").getBytes("UTF-8"));
out.write(("Reply-To: "+replyto+"\r\n").getBytes("UTF-8"));
out.write(("To: "+getAddress(email)+"\r\n").getBytes("UTF-8"));
out.write(("Content-Type: text/html; charset=\"UTF-8\"\r\n").getBytes("UTF-8"));
out.write(("Content-Transfer-Encoding: "+encodingtype+"\r\n").getBytes("UTF-8"));
out.write("\r\n".getBytes("UTF-8"));
out.write("<html><body><h1>HI</h1></body></html>\r\n".getBytes("UTF-8"));
}catch(Exception e){
System.out.println(e);
}
}
}
Thanks in advance.
Um, why do you need to control the header order?
By default, JavaMail will put the well-known headers in the order recommended by the internet RFCs. If you have some legitimate reason to put the headers in a different order, you can subclass MimeMessage and override the createInternetHeaders method to supply your own subclass of the InternetHeaders class that puts the headers in whatever order you want.
Or you can subclass MimeMessage and just override the writeTo method to fetch and output the headers in the order you want. You might find it helpful to look at the MimeMessage source code.
Finally I can able to set the header order. Thanks so much to Bill Shannon. Thanks for the help. Below is my message class.
public MyMessage(Session session, String fromdomain, String format,
String blastid, String listid, String offerid, int blastinstanceid,
String displayname, String displayfrom, String mailfrom, String email, String subject,
String encodingtype, String content) {
super(session);
this.session=session;
this.fromdomain = fromdomain;
this.format = format;
this.blastid = blastid;
this.listid = listid;
this.offerid = offerid;
this.blastinstanceid = blastinstanceid;
this.displayname = displayname;
this.displayfrom = displayfrom;
this.mailfrom = mailfrom;
this.email = email;
this.subject = subject;
this.content = content;
try{
setFrom(getAddress(displayfrom));
setSentDate(new Date());
setRecipients(RecipientType.TO, email);
setSubject(subject);
setReplyTo(getAddress2(mailfrom));
setHeader("Message-Id", getUniqueMessageIDValue(session,
fromdomain, format, blastid, listid, offerid, blastinstanceid));
}catch(Exception e){
System.out.println(e);
}
}
#Override
public void writeTo(OutputStream out, String[] ignoreList) throws
java.io.IOException, MessagingException{
LineOutputStream los = null;
try{
if (!saved)
saveChanges();
String replyto = ("\""+displayname+"\" <"+displayfrom+">");
String fromheader = ("\""+displayname+"\" <"+mailfrom+">");
los = new LineOutputStream(out);
los.writeln("Date: "+getHeader("Date", null));
los.writeln("Message-Id: " +getHeader("Message-Id",null).toString());
los.writeln("From: "+fromheader);
los.writeln("Reply-To: "+replyto);
los.writeln("To: "+getHeader("To",",").toString());
System.out.println("From header is "+getHeader("From",",")+" mail from is "+mailfrom);
//out.write(Message.RecipientType.TO, getAddress(email));
los.writeln("subject: "+getHeader("Subject",null).toString());
Enumeration hdrLines = getNonMatchingHeaderLines(ignoreList);
while (hdrLines.hasMoreElements())
los.writeln((String)hdrLines.nextElement());
los.writeln();
}catch(Exception e){
System.out.println(e);
}finally{
try{
if(los != null) los.flush();
}catch(Exception e){
System.out.println(e);
}
}
}
Related
I don't have much experience with JAVA mail programming and I need help with one task.
I have this code (this is a part of all code where I load attachments; if you need to see whole code, I can send) and I need to write an attachment size to a new variable
I searched the web and found out that size could be get from getSize() function or by counting bytes of file but I don't know how can I write this codes.
Thanks in advance.
private long analyzeAttachment(Metadata metadata, ContentHandler content, DataPipe data, long messageId) throws IOException, MessagingException{
long attid = IdGenerator.getUniqueID();
Logger.getLogger(ImapMailAnalyzer.class.getName()).log(Level.FINE, "Analyzed attachemnt {0} of message {1}", new Object[]{attid, messageId});
String attName = getAttachmentName(metadata);
data.writeRow(attid, "Abrakadabra", attName, messageId);
writeContent(attid, content, data);
return attid;
}
private String getAttachmentName(Metadata metadata){
if(metadata.get("resourceName") != null){
try {
return MimeUtility.decodeText(metadata.get("resourceName"));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
return metadata.get("resourceName");
}
}
return "";
}
The following code uses jakarta.mail-api.
Usually you need to use multipart/xxx content type to send the email with attachments. In this case, you are dealing with javax.mail.internet.MimeMultipart.
So you can get all the body parts and check if they are attachments.
protected void processMimeMultipart(javax.mail.internet.MimeMultipart mimeMultipart) throws Exception {
for(int i = 0; i< mimeMultipart.getCount();i++){
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
int attachmentSize = getAttachmentSize(bodyPart);
}
}
protected int getAttachmentSize(final javax.mail.BodyPart bodyPart) throws Exception {
if(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
return bodyPart.getSize();
}
return -1;
}
I am trying to send sms using JAVA. After googling, I found out that SMPP protocol is to be used for it and stumbled upon the below source code.
public class SendSMS
{
public static void main(String[] args) throws Exception
{
SendSMS obj = new SendSMS();
SendSMS.sendTextMessage("<mobile number>");
}
private TimeFormatter tF = new AbsoluteTimeFormatter();
/*
* This method is used to send SMS to for the given MSISDN
*/
public void sendTextMessage(String MSISDN)
{
// bind param instance is created with parameters for binding with SMSC
BindParameter bP = new BindParameter(
BindType.BIND_TX,
"<user_name>",
"<pass_word>",
"<SYSTEM_TYPE>",
TypeOfNumber.UNKNOWN,
NumberingPlanIndicator.UNKNOWN,
null);
SMPPSession smppSession = null;
try
{
// smpp session is created using the bindparam and the smsc ip address/port
smppSession = new SMPPSession("<SMSC_IP_ADDRESS>", 7777, bP);
}
catch (IOException e1)
{
e1.printStackTrace();
}
// Sample TextMessage
String message = "This is a Test Message";
GeneralDataCoding dataCoding = new GeneralDataCoding(false, true,
MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT);
ESMClass esmClass = new ESMClass();
try
{
// submitShortMessage(..) method is parametrized with necessary
// elements of SMPP submit_sm PDU to send a short message
// the message length for short message is 140
smppSession.submitShortMessage(
"CMT",
TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN,
"<MSISDN>",
TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN,
MSISDN,
esmClass,
(byte) 0,
(byte) 0,
tF.format(new Date()),
null,
new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT),
(byte) 0,
dataCoding,
(byte) 0,
message.getBytes());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
But the problem I encounter with the source code is that it requires specific set of parameters like user_name, pass_word, system_type, SMSC IP address etc which I have no clue of. I have only recently known about the SMPP protocol and so am unaware of how to get this code working to fulfil my usecase of sending sms to my mobile. So can someone please help me get this code to work or guide me to a place where i can learn about doing this?
I've been working on SMPP project recently.
The library I used for SMPP protocol is OpenSMPP.
Here is the example of my class for building and sending SMPP data
public class SmppTransport implements Transport {
#Override
public void send(String url, Map<String, String> map) throws IOException {
int smscPort = Integer.parseInt(map.get("port"));
String smscHost = map.get("send_url");
String smscUsername = map.get("username");
String smscPassword = map.get("password");
String recipientPhoneNumber = map.get("phone_num");
String messageText = map.get("text");
try {
SubmitSM request = new SubmitSM();
// request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
request.setDestAddr(createAddress(recipientPhoneNumber));
request.setShortMessage(messageText);
// request.setScheduleDeliveryTime(deliveryTime); // you can skip this
request.setReplaceIfPresentFlag((byte) 0);
request.setEsmClass((byte) 0);
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
SubmitSMResp response = session.submit(request);
} catch (Throwable e) {
// error
}
}
private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{
if(sessionMap.containsKey(smscUsername)) {
return sessionMap.get(smscUsername);
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
// request.setSystemType(systemType);
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
// connection.setReceiveTimeout(BIND_TIMEOUT);
Session session = new Session(connection);
sessionMap.put(smscUsername, session);
BindResponse response = session.bind(request);
return session;
}
private Address createAddress(String address) throws WrongLengthOfStringException {
Address addressInst = new Address();
addressInst.setTon((byte) 5); // national ton
addressInst.setNpi((byte) 0); // numeric plan indicator
addressInst.setAddress(address, Data.SM_ADDR_LEN);
return addressInst;
}
}
And my operator gave me this parameters for SMPP. There are many configuration options but these are essential
#host = 192.168.10.10 // operator smpp server ip
#port = 12345 // operator smpp server port
#smsc-username = "my_user"
#smsc-password = "my_pass"
#system-type = ""
#source-addr-ton = 5
#source-addr-npi = 0
So if you want to test your code without registering with GSM service provider, you can simulate SMPP server on your computer. SMPPSim is a great project for testing. Download it and run on your computer. It can be configured in multiple ways e.g. request delivery reports from SMPP server, set sms fail ratio and e.t.c. I've tested SMPPSim on linux.
Use following code for single class execution:
public class SmppTransport {
static Map sessionMap=new HashMap<String,String>();
String result=null;
public String send(String url, Map<String, String> map) throws Exception {
int smscPort = Integer.parseInt(map.get("port"));
String smscHost = map.get("send_url");
String smscUsername = map.get("username");
String smscPassword = map.get("password");
String recipientPhoneNumber = map.get("phone_num");
String messageText = map.get("text");
try {
SubmitSM request = new SubmitSM();
// request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
request.setDestAddr(createAddress(recipientPhoneNumber));
request.setShortMessage(messageText);
// request.setScheduleDeliveryTime(deliveryTime); // you can skip this
request.setReplaceIfPresentFlag((byte) 0);
request.setEsmClass((byte) 0);
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
SubmitSMResp response = session.submit(request);
result=new String(response.toString());
} catch (Exception e) {
result=StackTraceToString(e);
}
return result;
}
private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{
if(sessionMap.containsKey(smscUsername)) {
return (Session) sessionMap.get(smscUsername);
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
request.setSystemType("smpp");
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
// connection.setReceiveTimeout(BIND_TIMEOUT);
Session session = new Session(connection);
sessionMap.put(smscUsername, session.toString());
BindResponse response = session.bind(request);
return session;
}
private Address createAddress(String address) throws WrongLengthOfStringException {
Address addressInst = new Address();
addressInst.setTon((byte) 5); // national ton
addressInst.setNpi((byte) 0); // numeric plan indicator
addressInst.setAddress(address, Data.SM_ADDR_LEN);
return addressInst;
}
public String StackTraceToString(Exception err) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
err.printStackTrace(pw);
return sw.toString();
}
public String sendSMS(String Port, String Host,String SMPPUserName,String SMPPPassword,String Phone_Number,String Message) throws Exception {
String response=null;
sessionMap.put("port",Port);
sessionMap.put("send_url",Host);
sessionMap.put("username",SMPPUserName);
sessionMap.put("password",SMPPPassword);
sessionMap.put("phone_num",Phone_Number);
sessionMap.put("text",Message);
Set set=sessionMap.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
}
SmppTransport test =new SmppTransport();
try {
response=test.send("10.50.**.**", sessionMap);
System.out.println(response);
} catch (Exception e) {
response=StackTraceToString(e);
}
return response;
}
public static void main(String[] args) throws Exception
{
SmppTransport sm=new SmppTransport();
String test=sm.sendSMS("80*6", "10.50.**.**", "f***obi", "x***fQ", "+9187965*****", "Testing1");
System.out.println("Data: "+test);
}}
Use this simulator here,
It acts as a service provide, after build and test your application on it you have to change just config parameters(username, password, ip, port, ...) that provided to you by the service provider .
you can find all configurations to connect to this simulator in conf file.
SMPP is a protocol between mobile network operators/carriers and content providers. The fields you specified (username, password, SMSC IP) are provisioned from the operators. Unfortunately, unless you work for a content provider company, or have a deal with an operator, you are unlikely to get these details.
Simulators can let you test out your SMPP code but they will not actually deliver content to your phone.
My best advice if you want to send SMS from your Java app would be to use an SMS API like Twilio's.
My program is laid out so that the main app can send commands to any node connected to it. When a node receives a request, it returns a response and continues to wait for more requests.
When the app is run the node successfully replies to one request, and when a second request is sent the node sees it as a null or does not see it at all. Why does this keep happening?
P.S. I want the connection to the node to stay open, so that it can receive more requests.
Request sending code:
public java.lang.String getTime(server.Node node){
protocol.Message ms = new protocol.Message("<time>","");
node.sendRequestToClient(ms);
node.dos.flush();
java.lang.System.out.println("Sent time request to " + node.ip);
java.lang.String time = null;
try {
time = node.dis.readLine();
} catch (java.io.IOException ex) {
System.out.println("Could not read response.");
}
protocol.Message response = protocol.Message.parseDataToMessage(time);
java.lang.String systime = response.getActionData();
return systime;
}
Response sending code:
public class Client {
public Client(NetworkConnection connection){
this.connectionToServer = connection;
try{
connectionToServer.connect();
responseOutStream = connectionToServer.getPrintWriter();
requestInStream = connectionToServer.getBufferedReader();
}catch(IOException ex){
System.out.println("Could not connect to server." + ex.getMessage() + ex.toString());
}
}
public void beginRequestListener(){
String request;
try {
while((request = requestInStream.readLine())!=""){
System.out.println("Recieved request: " + request + request.length());
Message response = Message.parseDataToMessage(request);
sendResponseToServer(response);
}
} catch (java.io.IOException ex) {
System.out.println("Could not read request stream.");
} catch(NullPointerException e){
e.printStackTrace();
e.getClass();
}
}
public void sendResponseToServer(Message ms){
protocol.Message response = MessageParser.compileResponse(ms);
java.lang.System.out.println("Response to send: "+response);
response.send(responseOutStream);
}
public BufferedReader requestInStream;
public PrintWriter responseOutStream;
public NetworkConnection connectionToServer;
}
MessageParser class:
public class MessageParser {
static public Message compileResponse(Message ms){
Message response = null;
switch(ms.getAction()){
case "<time>":
response = new Message("<time>", String.valueOf(System.currentTimeMillis()));
break;
case "<date>":
SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("IST"));
response = new Message("<date>", date.toString());
break;
default:
break;
}
return response;
}
}
The stack trace and output:
Recieved request: <action><time><action><actionData><actionData>
Response to send: <action><time><action><actionData>1370380854566<actionData>
Recieved request:
java.lang.NullPointerException
at protocol.MessageParser.compileResponse(MessageParser.java:23)
at client.Client.sendResponseToServer(Client.java:67)
at client.Client.beginRequestListener(Client.java:52)
at client.ClientInterface.main(ClientInterface.java:107)
Message class:
public class Message {
public Message(String data){
}
public Message(String action, String actionData){
this.action = action;
this.actionData = actionData;
}
public void send(PrintWriter connection){
try{
connection.println(this.toString());
connection.flush();
//System.out.println(this.toString());
}catch(Exception ex){
System.out.println("Could not send Message.");
}
}
#java.lang.Override
public String toString(){
return
action_marker + action + action_marker +
actionData_marker + actionData + actionData_marker +
eof_marker;
}
public static Message parseDataToMessage(String data){
Message ms = null;
if(data.isEmpty() == false){
int begin_action_marker = data.indexOf("<action>")+8;
int end_action_marker = data.lastIndexOf("<action>");
String action = data.substring(begin_action_marker, end_action_marker);
int begin_actionData_marker = data.indexOf("<actionData>")+12;
int end_actionData_marker = data.lastIndexOf("<actionData>");
String actionData = data.substring(begin_actionData_marker, end_actionData_marker);
ms = new Message(action, actionData);
}
return ms;
}
public void setAction(String action){
this.action = action;
}
public String getActionData(){
return actionData;
}
public String getAction(){
return action;
}
public void setActionData(String action){
this.actionData = action;
}
public String eof_marker = "\r\n";
public String action;
public String action_marker = "<action>";
public String actionData;
public String actionData_marker = "<actionData>";
}
My guess:
you receive an empty request in (request = requestInStream.readLine())
this goes to Message.parseDataToMessage(request); which returns null for empty requests
that generates a NullPointerException in compileResponse
The (likely) solution: change this
while((request = requestInStream.readLine())!=""){
into this:
while(!(request = requestInStream.readLine()).isEmpty())
Why your code does not work: How do I compare strings in Java?
while((request = requestInStream.readLine())!=""){
What's this test for? Are you expecting empty requests? You shouldn't be. If you get one it's a bug at the sender.
However you must test the result of readLine() for null before doing anything else with it. The line should read:
while((request = requestInStream.readLine())!= null){
Attachments need to be added like this
MailMessage.addAttachment(File file, [String fileName])
, but innerly it seems that fileName is only used for MimeBodyPart.setFileName()
I dont find anyway to use the
MimeBodyPart.setContentID("myID") or MimeBodyPart.setHeader("Content-ID", "myID");
feature, so I can use images embeded in mail with
<img src='CID:MyID'>
It seems MailEngine is in the portal jar so only for internal use, and I was not able to find a solution for MailServiceUtil. Does it mean I need to decode all Liferay high-level API stuff from scratch and use Java Mail API?
I don't think there's a way to do that with Liferay (at least not at version 6.2). But I made it work with standard Java approach. The following is pretty similar to Liferay interface.
public void send(TemplateEmailerMailMessage mailMessage) throws UnsupportedEncodingException {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailMessage.getFromEmail(), mailMessage.getFromName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailMessage.getTo()));
message.setSubject(mailMessage.getSubject());
if (mailMessage.isHtmlFormat()) {
message.setText(mailMessage.getBody(), "text/html");
} else {
message.setText(mailMessage.getBody());
}
// create container for attachments and body parts
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getBody(), "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// add attachments one by one
for (File file : mailMessage.getFileAttachments()) {
BodyPart messageAttachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentPart.setDataHandler(new DataHandler(source));
messageAttachmentPart.setFileName(file.getName());
// set Content-ID so it is recognized by <img src="cid: ... ">
messageAttachmentPart.setHeader("Content-ID", "<" + file.getName() + ">");
multipart.addBodyPart(messageAttachmentPart);
}
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
The message object
public class TemplateEmailerMailMessage {
private String fromEmail;
private String fromName;
private String to;
private String body;
private String subject;
private boolean htmlFormat;
private List<File> fileAttachments = new ArrayList<>();
public void addAttachment(File file) {
fileAttachments.add(file);
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public boolean isHtmlFormat() {
return htmlFormat;
}
public void setHtmlFormat(boolean htmlFormat) {
this.htmlFormat = htmlFormat;
}
public List<File> getFileAttachments() {
return fileAttachments;
}
public void setFileAttachments(List<File> fileAttachments) {
this.fileAttachments = fileAttachments;
}
public String getFromEmail() {
return fromEmail;
}
public void setFromEmail(String fromEmail) {
this.fromEmail = fromEmail;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public void setFrom(String fromEmail, String fromName) {
this.fromEmail = fromEmail;
this.fromName = fromName;
}
}
I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.