Use AuthenticatingSMTPClient and SSL? - java

I need to send an email using SSL (SMTPS) and authentification. In apache Commons Net however there seems to be either AuthenticatingSMTPClient (no SSL, though it extends SMTPSClient?) or SMTPSClient (no authentication?), I need a combination of both (SSL + authentication). Anyone knows how I can do this? Thanks!

I know it is too late to reply to this but for future reference for others, AuthenticatingSMTPClient does provide ssl + authentication as it is extending SMTPSClient. Below is the sample code, one has to do modifications where I have commented with numerals (e.g. //1).
Code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.io.Util;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient.AUTH_METHOD;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
public final class SMTPMail
{
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException
{
String sender, recipient, subject, filename, server;
List<String> ccList = new ArrayList<String>();
FileReader fileReader = null;
Writer writer;
SimpleSMTPHeader header;
AuthenticatingSMTPClient client;
server = "<smtp server>"; // 1
try
{
sender = "<your user name>"; // 2
recipient = "<recipient>"; // 3
subject = "<mail subject>"; // 4
header = new SimpleSMTPHeader(sender, recipient, subject);
filename = "hello.txt"; //This will be the body of your mail //5
try
{
fileReader = new FileReader(filename);
}
catch (FileNotFoundException e)
{
System.err.println("File not found. " + e.getMessage());
}
client = new AuthenticatingSMTPClient("TLS", false);
client.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out), true));
client.connect(server);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode()))
{
client.disconnect();
System.err.println("SMTP server refused connection.");
System.exit(1);
}
client.login("hostname.testing.smtp.api"); //6
if(client.execTLS())
{
if(client.auth(AUTH_METHOD.LOGIN, "<your user name>", "<your password>")) //7
{
client.setSender(sender);
client.addRecipient(recipient);
for (String recpt : ccList) {
client.addRecipient(recpt);
}
writer = client.sendMessageData();
if (writer != null)
{
writer.write(header.toString());
Util.copyReader(fileReader, writer);
writer.close();
client.completePendingCommand();
}
if (fileReader != null ) {
fileReader.close();
}
}
}
client.logout();
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}

Related

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

Why javafx application is crashing while using EventHandler and java.net socket at the same time?

I'm trying to build some Chatting Application with Javafx and java.net networking package. I want the text the User typed in the textfield to be send from the client to the server and from there back to the client and eventually showing up in the textarea of the application. But the application is crashing after I press Enter when I typed in a text in the TextField. So in the "handle"-method of the EventHandler there must be the error. Also the application is crashing before the input-text gets cleared. The application is not responding --> error window pops up.Application is not responding
Client-side Code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.Parent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.*;
public class ChatAppClient extends Application {
private TextArea messages = new TextArea();
private TextField input;
private static String ipAdress = null;
private DataInputStream dis;
private DataOutputStream dos;
private static Socket client;
public Parent mainScene() throws UnknownHostException, IOException {
// Getting IP-Adress from a different file as a String
String userDir = System.getProperty("user.dir");
File file = new File(userDir + "\\..\\IPAdress.txt");
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
raFile.seek(0);
ipAdress = raFile.readLine();
raFile.close();
// Initialising new Socket
client = new Socket(ipAdress, 5000);
System.out.println("Connected to Server.");
// Defining JavaFx Application-Layout
messages.setPrefHeight(220);
input = new TextField();
VBox root = new VBox(20, messages, input);
root.setPrefSize(400, 400);
// Setting up action for Textfield when pressing Enter
input.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
// Defining and initialising Input-String
String message = "Client: ";
message += input.getText();
// Opening OutputStream for String to send it to the server
dos = new DataOutputStream(client.getOutputStream());
// Giving the String to the OutputStream
dos.writeBytes(message);
// Clearing the Textfield from Input-Text
input.clear();
// Setting up InputStream for the Socket to receive the String back from the
// server
dis = new DataInputStream(client.getInputStream());
// Reading String from InputStream
String s = dis.readLine();
// Closing In-and OutputStreams + Socket
dos.close();
// Showing the String in the TextArea "messages"
messages.appendText(s + "\n");
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
return root;
}
public void start(Stage mainStage) {
try {
mainStage.setScene(new Scene(mainScene()));
mainStage.show();
} catch (UnknownHostException uHE) {
uHE.printStackTrace();
} catch (IOException iOE) {
iOE.printStackTrace();
}
}
public static void main(String[] args) {
try {
launch(args);
client.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
}
Server-side Code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatAppServer {
public static void main(String[] args) {
try {
// Defining/ Initialising new ServerSocket
ServerSocket caServerSocket = new ServerSocket(5000);
System.out.println("Waiting for Client...");
Socket nSocket = caServerSocket.accept();
System.out.println("Client connected.");
// Setting up InputStream for the ServerSocket to receive the message String
DataInputStream clientMessages = new DataInputStream(nSocket.getInputStream());
String s = clientMessages.readLine();
// Testing if the Input String got received
System.out.println(s);
// Setting up OutputStream to send back the String
DataOutputStream clientMessagesBack = new DataOutputStream(nSocket.getOutputStream());
clientMessagesBack.writeBytes(s);
caServerSocket.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
}

Java: Simple Client Server message exchange not working

I am new to Java just started yesterday. I wrote a very simple client server java code. Client sends a message to server. The Server should display that message. And the Server should send a message to client after receiving the message. The client should display the message sent by server.
Server Code,
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class CustomServer{
public static void main(String[] args){
final int SERVER_PORT_NUMBER = 8081;
try{
ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER);
Socket clientSocketObj = serverObj.accept();
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()));
if(clientSocketObj != null){
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
// Close Streams
clientOutputStream.close();
clientInputStream.close();
}
serverObj.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Client,
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class CustomClient{
public static void main(String[] args){
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try{
Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER);
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Connecting....");
if(clientSocket != null){
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
// Close Streams
clientInputStream.close();
clientOutputStream.close();
}
clientSocket.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Neither the Server or Client receive the message. Stuck in some loop. Anyone know why?
Start by having a read of the BufferedReader's JavaDocs, which state
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed
BufferedWriter#write is not sending this, so the reader is still waiting.
A simply solution might be to use BufferedWriter#newLine after the write
And don't forget to flush the buffer when you're finished writing to it!
You may also want to take a look at try-with-resources which will provide a better resource management solution
CustomClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class CustomClient {
public static void main(String[] args) {
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try (Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER)) {
try (BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
System.out.println("Connecting....");
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
clientOutputStream.newLine();
clientOutputStream.flush();
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
CustomServer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class CustomServer {
public static void main(String[] args) {
final int SERVER_PORT_NUMBER = 8081;
try (ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER)) {
try (Socket clientSocketObj = serverObj.accept()) {
try (BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()))) {
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
clientOutputStream.newLine();
clientOutputStream.flush();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Avro Communication over TCP Sockets

I am currently working on a project that will involve communication of applications written in C and Java. Therefore, I chose to work with Apache Avro. I have seen on the website that Avro can (de-)serialize objects from files using the DataFileWriter class.
But, in my case I want to use TCP sockets between my applications. Therefore, DataFileWriter class is not going to work for me. After reading the documentation, I have not found any information on how to send objects through TCP sockets.
Any ideas on how to do that? I specifically want to know what kind of Input and Output Streams I should use on the Java Clients.
I have developed the following code for the Java Server:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import middleman.bigpeer.BigPeer;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
public class MiddleManWorker implements Runnable {
private InputStream in;
private OutputStream out;
private Socket clientSocket;
public MiddleManWorker(Socket clientSocket, HashMap<Integer, NodeType> dbNodesDirectory,
HashMap<Integer, NodeType> workersDirectory) {
this.clientSocket = clientSocket;
try {
this.in = clientSocket.getInputStream();
this.out = clientSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
EncoderFactory encoderFactory = new EncoderFactory();
DecoderFactory decoderFactory = new DecoderFactory();
BinaryEncoder binaryEncoder = encoderFactory.binaryEncoder(out, null);
BinaryDecoder binaryDecoder = decoderFactory.binaryDecoder(in, null);
SpecificDatumReader<BigPeer> peerDatumReader = new SpecificDatumReader<BigPeer>(BigPeer.class);
BigPeer bigPeer = null;
SpecificDatumWriter<BigPeer> writer = new SpecificDatumWriter<BigPeer>();
try {
peerDatumReader.read(bigPeer, binaryDecoder);
System.out.println("Received: " + bigPeer.getType());
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.write(bigPeer, binaryEncoder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A sample Java Client is the following:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import middleman.bigpeer.BigPeer;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
public class SystemClient {
public static void connect(String serverIPAddress, Integer serverPort) throws IOException, ClassNotFoundException {
/**
* Create Connection with the server
*/
Socket socket = new Socket(serverIPAddress, serverPort);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
EncoderFactory encoderFactory = new EncoderFactory();
DecoderFactory decoderFactory = new DecoderFactory();
BinaryEncoder binaryEncoder = encoderFactory.binaryEncoder(out, null);
BinaryDecoder binaryDecoder = decoderFactory.binaryDecoder(in, null);
BigPeer bigPeer = new BigPeer();
bigPeer.setType("test");
SpecificDatumReader<BigPeer> reader = new SpecificDatumReader<BigPeer>(BigPeer.class);
SpecificDatumWriter<BigPeer> writer = new SpecificDatumWriter<BigPeer>(BigPeer.class);
System.out.println("Before: " + bigPeer.getType());
writer.write(bigPeer, binaryEncoder);
System.out.println("Waiting for response...");
reader.read(bigPeer, binaryDecoder);
System.out.println("After: " + bigPeer.getType());
}
}
And the server seems to halt on the peerDatumReader.read(bigPeer, binaryDecoder); line of code. Any ideas?
Thank you,
Nick
BinaryEncoder uses an internal buffer for performance reasons. You may need to call flush on the encoder to send the data through the pipe.
See the reference for more information on this behaviour:
The BinaryEncoder implementation returned may buffer its output. Data may not appear on the underlying OutputStream until Flushable.flush() is called. The buffer size is configured with configureBufferSize(int).
If buffering is not desired, and lower performance is acceptable, use directBinaryEncoder(OutputStream, BinaryEncoder)

Java FTP 550 error

I'm getting this error (550 the filename, directory name, or volume label syntax is incorrect. )
I think the url is correct (obviously not though). Any thoughts?
Here is the url:
STOR /images/report/6F81CB22-3D04-4BA3-AC3F-3D34663449E0**9.png
Here is the invocation method:
private void uploadImageToFtp(String location, String imageName) throws Exception{
File imageFile = new File(location);
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("ftp.xxx.com", "user", "password");
ftpUploader.uploadFile(imageFile, imageName, "/images/report/");
imageFile.delete();
ftpUploader.disconnect();
System.out.println("Done");
}
Here is the
ftp class:
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(File file, String fileName, String hostDir)
throws Exception {
try {
InputStream input = new FileInputStream(file);
this.ftp.storeFile(hostDir + fileName, input);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
f.printStackTrace();
}
}
}
}
If the FTP server is running Windows, the '*' characters are the problem. Windows file names may not have asterisks.
Try changing working directory first before uploading
ftp.changeWorkingDirectory(DESTPATH);
It worked for me.

Categories

Resources