session.getDefaultInstance() is giving me noClassDefFound? - java

I've been constructing a software that will send an email verification code, however when ever I try to run it I get an error on this line ' newSession = Session.getInstance(properties,null);'
Does anyone knows why this is happening, and would also be willing to give me some pointers in how I could fix this?
public void emailVerification()
{
int min = 0;// sets a minimum number for range
int max = 9;//sets maximum number for range
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);// generates a random number
int random_int2 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates another random number
int random_int3 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates another random number
int random_int4 = (int)Math.floor(Math.random()*(max-min+1)+min);// generates the final random number
String randomDigit1 = random_int+"";
String randomDigit2 = random_int2+"";
String randomDigit3 = random_int3+"";
String randomDigit4 = random_int4+"";
allDigits = randomDigit1+randomDigit2+randomDigit3+randomDigit4;
Session newSession = null;
MimeMessage mimeMessage = null;
Properties properties = new Properties();
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.port","547");
String emailHost = ("smtp.gmail.com");
String myAccountEmail = ("**********#*****.com");
String myAccountPassword = ("*******");
newSession = Session.getInstance(properties,null);
String[] emailRecipients ={signUpAccount};
String emailSubject = "Verification Code";
String emailBody = allDigits;
mimeMessage = new MimeMessage(newSession);
for(int i =0; i<emailRecipients.length;i++)
{
try
{
mimeMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(emailRecipients[i]));
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
}
try
{
mimeMessage.setSubject(emailSubject);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
try
{
multipart.addBodyPart(bodyPart);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
try
{
mimeMessage.setContent(multipart);
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
try
{
Transport transport = newSession.getTransport("smtp");
try
{
transport.connect(emailHost, myAccountEmail, myAccountPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
JOptionPane.showInputDialog("The verification Email has been sent");
}
catch (javax.mail.MessagingException me)
{
me.printStackTrace();
}
}
catch (javax.mail.NoSuchProviderException nspe)
{
nspe.printStackTrace();
}
}

Related

What would be the error of the email method?

The previous settings of port, authentication, and protocol are correct for you sending the email.
And as a result i get a message like the one in the image.
Without a message and without attachment, I just get the signature by default in the mail.
thanks;
#Autowired
public Session emailSession;
#Override
public JsonObject sendEmail(final JsonObject json) throws CommunicationsException {
final JsonObject response = new JsonObject();
final String receiver = (String) json.get(RECEIVER);
final String subject = (String) json.get(SUBJECT);
final String messageBody = (String) json.get(MESSAGE_BODY);
final String attachment = (String) json.get(ATTACHMENT);
try {
MimeMessage msg = new MimeMessage(emailSession);
msg.setFrom(new InternetAddress(MAIL_USER_FROM));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
msg.setSubject(subject);
Multipart emailContenido = new MimeMultipart();
// Text
MimeBodyPart textoBodyPart = new MimeBodyPart();
textoBodyPart.setText(messageBody);
// Att
MimeBodyPart adjunto = new MimeBodyPart();
adjunto.attachFile("C:/hola.txt");
// Parts email
emailContenido.addBodyPart(textoBodyPart);
emailContenido.addBodyPart(adjunto);
msg.setContent(emailContenido);
Transport.send(msg);
System.out.println("Message ok");
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}

How to make a asnychron REST Server with communication to external hardware

I am currently working on a REST server in Spring Boot that also communicates with external hardware via USB or TCP/IP. A command is sent to the external device, then I wait 2 seconds for the response and return it to the RestController.
For the USB communication I am currently using jSerialComm. For the TCP/IP communication I use sockets.
The whole thing also works so far when I use Thread.sleep. However, I would prefer it to be more dynamic, i.e. without the sleep, because TCP/IP can cause delays.
For me Java and REST are still new. Is there a way to let the server communicate asynchronously with the hardware?
#RestController
#RequestMapping("/api/v1")
public class CommController {
#GetMapping("/Version")
public String getVersion() {
Serial serial = new Serial();
String s_response = null;
s_response = serial.getVersion();
return s_response;
}
#GetMapping("/VersionTCPIP")
public String getVersionTCPIP() {
Serial serial = new Serial();
String s_response = null;
s_response = serial.getVersionTCPIP();
return s_response;
}
}
USB/serial-class:
public class Serial {
private static SerialPort port;
private static List<Byte> l_readBuffer;
private static final class MessageListener implements SerialPortDataListener
{
#Override
public int getListeningEvents()
{
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
#Override
public void serialEvent(SerialPortEvent event)
{
if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
return;
byte[] newData = new byte[port.bytesAvailable()];
int numRead = port.readBytes(newData, newData.length);
for (int i = 0; i < numRead; i++)
{
l_readBuffer.add(newData[i]);
}
System.out.println("Read " + numRead + " bytes.");
}
}
public String getVersion() {
SerialPort[] ports = SerialPort.getCommPorts();
port = null;
for (SerialPort currentPort :
ports)
{
if (currentPort.getDescriptivePortName().contains("XXX"))
{
port = currentPort;
break;
}
}
Objects.requireNonNull(port).setBaudRate(9600);
port.setParity(SerialPort.NO_PARITY);
port.setNumStopBits(SerialPort.ONE_STOP_BIT);
port.setNumDataBits(8);
port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
//port.clearRTS();
port.setComPortTimeouts(SerialPort.LISTENING_EVENT_DATA_AVAILABLE, 5000, 5000);
port.openPort();
MessageListener listener = new MessageListener();
port.addDataListener(listener);
l_readBuffer = new ArrayList<>();
byte[] sendBuffer = new byte[5];
// fill sendBuffer
port.writeBytes(sendBuffer, sendBuffer.length);
try
{
Thread.sleep(2000);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Data raw: " + l_readBuffer.toString());
byte[] ba_responseBuffer = new byte[l_readBuffer.size()];
for (int i = 0; i < l_readBuffer.size(); i++)
{
ba_responseBuffer[i] = l_readBuffer.get(i);
}
String s_version = new String(ba_responseBuffer);
System.out.println("Version: " + s_version);
port.removeDataListener();
port.closePort();
return s_version;
}
public String getVersionTCPIP()
{
Socket socket;
String s_versionString = null;
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(s_hostnameTCPIP, i_port), 1000);
byte[] ba_sendBuffer = new byte[1024];
Arrays.fill(ba_sendBuffer, (byte) 0x00);
// fill sendBuffer
// send data
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.write(ba_sendBuffer); // write the message
dOut.writeInt(i_sendLength); // write length of the message
dOut.flush();
try
{
Thread.sleep(2000);
} catch (Exception e)
{
e.printStackTrace();
}
byte[] ba_responseBuffer = new byte[0];
if (socket.isConnected())
{
try
{
InputStream inFromServer = socket.getInputStream();
DataInputStream dIn = new DataInputStream(inFromServer);
synchronized (dIn)
{
int length = dIn.available();
ba_responseBuffer = new byte[length];
// receive data
dIn.readFully(ba_responseBuffer);
}
} catch (IOException ex)
{
ex.printStackTrace();
}
String s_version = new String(ba_responseBuffer);
System.out.println("Version: " + s_version);
s_versionString = s_version;
socket.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
return s_versionString;
}
}

Reading Error in Mail JAVA

I am reading email from gmail.com. i have read some of the mail successfully but after a while i got this,
java.lang.ClassCastException:
javax.mail.internet.MimeMultipart cannot be cast to java.lang.String
at emailIngestion.EmailIngestion.check(EmailIngestion.java:66)
at emailIngestion.EmailIngestion.main(EmailIngestion.java:106).
Actually my requirement is to store content into a variable and then store it in arraylist and then again write it to a file... i have implemented it using this code so if any better ideas are there please share me.
public class EmailIngestion {
static ArrayList<EmailModel> contentList=new ArrayList<EmailModel>();
static ArrayList<EmailModel> metaDataList= new ArrayList<EmailModel>();
public static void check(String host, String storeType, String user,
String password) throws IOException
{
FileWriter fw= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_metadata.csv",true);
FileWriter fw1= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_content.txt",true);
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
int emailNumber;
String mailContent = null,from = null,to = null,mailContentType = null,subject = null;
Date recievedDate= new Date();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Subject is"+message.getSubject());
subject = message.getSubject();
from = message.getFrom()[0].toString();
mailContentType=message.getContentType();
recievedDate=message.getSentDate();
to=InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
emailNumber=message.getMessageNumber();
metaDataList.add(new EmailModel(from, to, subject, mailContentType, recievedDate,emailNumber));
fw.write(emailNumber+"\001"+from+"\001"+subject+"\001"+recievedDate+mailContentType+"\001"+" \n");
fw.flush();
if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
mailContent=(String) bodyPart.getContent();
System.out.println(mailContent);
}
}
else{
mailContent=(String) message.getContent();
System.out.println(message.getContent());
}
contentList.add(new EmailModel(mailContent, emailNumber));
fw1.write(emailNumber+","+mailContent+"\n");
}
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "abcd#gmail.com";// change accordingly
String password = "******";// change accordingly
check(host, mailStoreType, username, password);
}
}
Thanks in advance
If the services are fluctuating then its definitely not stable. Which version of 1.3 you are using? As you are using one node make sure that you have master and worker services are installed and running. This you can see from your cluster manager. The info from logs is not informative enough to nail down the issue.

Javamail, Transport.send() very slow

I have written a method for sending emails in bulk but it is very very slow (around 3 mails every 10 seconds). I want to send thousands of mails. Is there any way to do this much more faster?
I am using gmail now but only for test, finally I want to send using my own SMTP server.
Here is the code:
public boolean sendMessages()
{
try
{
Session session = Session.getInstance(this._properties, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(this.getFrom()));
message.setSubject(this.getSubject());
message.setText(this.getBody());
for (int i = 0, c = this._addresses.size(); i < c; i++)
{
message.setRecipient(Message.RecipientType.TO, new InternetAddress(this._addresses.get(i)));
Transport.send(message);
}
return true;
}
catch(AuthenticationFailedException e) {
e.printStackTrace();
return false;
}
catch(MessagingException e) {
e.printStackTrace();
return false;
}
}
Ok, thank you for your suggestions.
My solution is:
Transport transport = session.getTransport("smtp");
transport.connect(this._properties.getProperty("mail.smtp.host"),
Integer.parseInt(this._properties.getProperty("mail.smtp.port")),
this._properties.getProperty("mail.smtp.user"),
this._properties.getProperty("mail.smtp.password"));
Address[] addr = new Address[this._addresses.size()];
for (int i = 0, c = this._addresses.size(); i < c; i++)
{
addr[i] = new InternetAddress(this._addresses.get(i));
}
transport.sendMessage(message, addr);

Getting remote device file list via BT in Java/Android

I'm trying to get the remote device folder listing using OBEX; i'm trying to connect using
String btUrl=btgoep://"+mac_address+":10;authenticate=false;encrypt=false;master=false"
but i get Not supported yet error when i call
ClientSession conn = (ClientSession) Connector.open(btURL);
Can anyone help me?
The port may be incorrect. You should get connection addres via service search in DiscoveryListener. In jsr82 it looks like this:
private final UUID L2CAP_UUID = new UUID(0x1106);
public String getOBEXURL(RemoteDevice dev) {
DiscoveryAgent discoveryAgent = null;
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
}
catch (Exception e) {
return null;
}
try {
discoveryAgent.searchServices(null, new UUID[]{L2CAP_UUID}, dev, this);
} catch (Exception e) {
return null;
}
synchronized (this) {
try { wait(); }
catch (Exception e) {}
}
switch (respCode) {
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
ps.println("Remote device could not be reached");
break;
case SERVICE_SEARCH_ERROR:
ps.println("The service search was terminated with error");
break;
case SERVICE_SEARCH_NO_RECORDS:
ps.println("No services found on device");
break;
case SERVICE_SEARCH_TERMINATED:
ps.println("The service search has been canceled by the application and did not complete");
break;
}
return obexURL;
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
obexURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
}
public void serviceSearchCompleted(int transID, int respCode) {
this.respCode = respCode;
synchronized (this) { notify(); }
}
Try this.
private void GetFileNamesViaBTFTP(UUID UUID3)
{
try
{
mBtSocket = mBtDevice.createInsecureRfcommSocketToServiceRecord(UUID3);
}
catch (Exception e)
{
//e.printStackTrace();
}
Thread thread=new Thread(new Runnable() {
public void run()
{
UUID uuid=UUID.fromString("F9EC7BC4-953C-11D2-984E-525400DC9E09");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
byte [] bytes=bb.array();
Operation putOperation=null;
Operation getOperation=null;
//ArrayUtils.reverse(bytes);
try
{
// 소켓을 연결한다
mBtSocket.connect();
mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));
HeaderSet headerset = new HeaderSet();
headerset.setHeader(HeaderSet.TARGET, bytes);
headerset = mSession.connect(headerset);
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
{
mConnected = true;
}
else
{
mSession.disconnect(headerset);
}
// Send a file with meta data to the server
final byte filebytes[] = "[CLIENT] Hello..".getBytes();
final HeaderSet hs = new HeaderSet();
hs.setHeader(HeaderSet.NAME, "test.txt");
hs.setHeader(HeaderSet.TYPE, "text/plain");
hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));
putOperation = mSession.put(hs);
mOutput = putOperation.openOutputStream();
mOutput.write(filebytes);
mOutput.close();
putOperation.close();
//In order to go the desired folder the OBEX SETPATH command is
//being used
//Prepare the header for the SETPATH command
HeaderSet header = new HeaderSet();
//folder_name is set to the name of the desired folder
//if left blank the root folder will be used
//header.setHeader(HeaderSet.NAME, "");
//Send the SETPATH command
/*result =*/ mSession.setPath(header, false, false);
final HeaderSet geths = new HeaderSet();
//geths.setHeader(HeaderSet.NAME, null);
geths.setHeader(HeaderSet.TYPE, "x-obex/folder-listing");
//hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));
getOperation = mSession.get(geths);
InputStreamReader din = new
InputStreamReader(getOperation.openInputStream(), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(din);
String tmp2=new String();
String line = bufferedReader.readLine();
while (line != null)
{
tmp2 += line;//System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
getOperation.close();
/*
mInput=getOperation.openInputStream();
// Retrieve the length of the object being sent back
int length = (int) getOperation.getLength();
// Create space for the object
byte[] obj = new byte[length];
// Get the object from the input stream
DataInputStream in = getOperation.openDataInputStream();
in.read(obj);
// End the transaction
in.close();
*/
final String ftmp=tmp2;
runOnUiThread(new Runnable(){
#Override
public void run()
{
//String s=new String(ftmp, "UTF-16");
deviceTextEdit.setText(ftmp);
}
});
Xml xml;
}
catch (Exception e)
{
//e.printStackTrace();
}
finally
{
try
{
mOutput.close();
putOperation.close();
mSession.disconnect(null);
}
catch (IOException e)
{}
//updateStatus("[CLIENT] Connection Closed");
}
}
});
thread.start();
}
Now your work is to parse XML data of obexfolder listing.

Categories