I'm developing an application for sending bulk emails from multiple senders in a continuous loop. Sender email-ID's are stored in a csv file and I am reading that in ReadFile class and calling it in servlet class where I am also calling an email utility class which have email sending functions.
ReadFile.java
CsvReader senders;
public List<String> read(){
ArrayList<String> al=new ArrayList<String>();
try {
senders = new CsvReader("C:/Users/dc/Documents/Senderlist.csv");
senders.readHeaders();
while (senders.readRecord()) {
String SenderID = senders.get("SenderID");
// perform program logic here
System.out.println("Sender ID is: "+SenderID );
al.add(SenderID);
}
senders.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return al;
}
Servlet.java:
public class MailController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String ExchangeIP;
private String port;
ReadFile rf;
/**
* #throws IOException
* #see HttpServlet#HttpServlet()
*/
public MailController() throws IOException {
rf=new ReadFile();
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
ExchangeIP = context.getInitParameter("ExchangeIP");
port = context.getInitParameter("port");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
String resultMessage = ""; //null
try {
List sendersInput = rf.read();
// print all the elements in the list
Iterator itr = sendersInput.iterator();
while(itr.hasNext()) {
EmailUtility.sendEmail(ExchangeIP, port, itr.next(), recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail has been sent successfully";
}
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext()
.getRequestDispatcher("/Result.jsp")
.forward(request, response);
}
}
}
While running this I am getting an error:
java.lang.ClassNotFoundException: com.csvreader.CsvReader
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at com.project.util.ReadFile.read(ReadFile.java:20)
at com.project.controller.MailController.doPost(MailController.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
How to resolve this error.
You're missing the opencsv.jar library.
Specify it in your java command with
java -cp opencsv.jar:...
By adding servlet-api.jar from apache tomcat library in to projects->properties->java build path, Solved the error.
Related
I use the doGet method to get the parameter and then process it. When the reply is sent, it contains the status data. Also, when the second client connects, the answer contains the data from frist client.
I want the send new the data after the second client is connected. Reset buffer and send new data to second client the data, or after restoring the page send new data.
Its not working. The client retrieves the page again and sends me a old and new data. I need only new data to be sent to client.
class HttpTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HttpTest() {
super();
// TODO Auto-generated constructor stub
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println(request.getQueryString());
String[] parameters = request.getQueryString().split(";");
String out_data="";
/*
* algorithm for generate out data
*/
out.println(out_data);
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
try this might help
private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try (PrintWriter writer = response.getWriter()) {
System.out.println(request.getQueryString());
String[] parms = request.getQueryString().split(";");
String outData = "";
/*
* algorithm for generate out data
*/
writer.println(outData);
}
}
I have created an application which reads & writes into a remote file. I have different files (A.properties, B.properties, C.properties) in different directories (folder-1, folder-2, folder-3). Each directory has the same filename with different data.
I have implemented concurrency in my application by using the LockRegistry provided by this other answer. The issue is that if a thread is accessing A.properties while another thread accesses B.properties, the propertyMap displayed to the end user will contain both data from property files. How can I resolve this issue?
My code:
public class UDEManager
{
private Map<String, String> propertyMap = new TreeMap<>();
HttpSession session = null;
public UDEPropertyManager()
{
super();
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Code for calling thread for read/write operations into remote
// file and fill the propertyMap
}
}
class WebAppProperty implements Runnable
{
private WebApp webapp; // folder-1
private String propertyFile; // A.properties
private String keyValue; //messages-title=Messages
private LockType mode;
public String getPropertyFile()
{
return propertyFile;
}
public void setPropertyFile(String propertyFile)
{
this.propertyFile = propertyFile;
}
#Override
public void run()
{
try {
LockRegistry.INSTANCE.acquire(propertyFile, mode);
if (this.mode == LockType.WRITE) {
writeToPropertyFile();
} else if (this.mode == LockType.READ) {
getProperty(this.webapp, this.propertyFile);
}
} catch (Exception ie) {
sysoutAndLog("Thread is Interrupted");
ie.printStackTrace();
} finally {
LockRegistry.INSTANCE.release(propertyFile, mode);
}
}
private boolean getProperty(WebApp webapp, String property)
{
try {
// read from file and put it into Map instance variable
// of calling class (UDEManager)
propertyMap.put(key, value);
} catch(Exception e) {
sysoutAndLog("Error while reading property ");
e.printStackTrace();
}
return false;
}
private void writeToPropertyFile()
{
try {
// Write data into remote file
} catch (Exception e) {
sysoutAndLog("exception while writing to file.");
e.printStackTrace();
}
}
}
You should associate the properties map with the user session or request
I'm been writing a small login servlet. The login part works just fine, but when I press logout submit button - nothing happens.
Servlet code down bellow:
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7638796169158385551L;
private Database database = Database.getInstance();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.write("<html><head><title>Login form</title></head>");
if (!database.connected) {
outLoginForm(out);
} else {
out.write("Hello " + database.getLoginName() + "!");
outLogoutForm(out);
}
out.write("</body></html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("loginsub") != null) {
if (isParameterEmpty(request, "login")
|| isParameterEmpty(request, "pass")) {
response.getWriter().write("Some fields are empty");
doGet(request, response);
}
try {
database.connect(request.getParameter("login"),
request.getParameter("pass"));
} catch (ExceptionInInitializerError ex) {
response.getWriter().write("Login or password is incorrect");
}
} else if (request.getParameter("logoutsub") != null) {
database.disconnect();
}
doGet(request, response);
}
private boolean isParameterEmpty(HttpServletRequest request,
String parameter) {
if (request.getParameter(parameter).isEmpty())
return true;
return false;
}
protected void outLoginForm(PrintWriter out) {
out.write("<FORM method =\"POST\">");
out.write("Login:<input type=\"text\"name=\"login\"><br>");
out.write("Password:<input type=\"password\"name=\"pass\"><br>");
out.write("<input type=\"submit\"name=\"loginsub\" value=\"Login\"/><br>");
out.write("</FORM><br>");
}
protected void outLogoutForm(PrintWriter out) {
out.write("<FORM method =\"POST>\">");
out.write("<input type=\"submit\"name=\"logoutsub\" value=\"Logout\"/><br>");
out.write("</FORM><br>");
}
}
Can anyone help me find out what's wrong? I'm new to JSP and java servlets.
There is one problem is below line (one extra > after POST
out.write("<FORM method =\"POST>\">");
replace it with
out.write("<FORM method =\"POST\">");
I am calling a Servlet using its URL address. This is the URL I am typing
http://localhost:7001/ryan/olympics?action=selectCatalog&id=1
This is the Servlet's URL for sure; if I change the address I get
page not found
This is the code for the Servlet.
public class Servlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("*** initializing controller servlet.");
super.init(config);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("selectCatalog")) {
String categoryId = request.getParameter("id");
ProductModelDAO dao4 = new ProductModelDAOImpl("jpac");
if (categoryId != null && !categoryId.trim().equals("")) {
CategoryDAO dao1 = new CategoryDAOImpl("jpac");
try {
Category category = dao1.getCategoryName(categoryId);
request.setAttribute("category", category);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
#SuppressWarnings("unchecked")
List<Product> products = dao4
.getProductsByCategory(categoryId);
request.setAttribute("products", products);
} catch (Exception e) {
e.printStackTrace();
}
url = "SelectCatalog.jsp";
RequestDispatcher requestDispatcher =
getServletContext().getRequestDispatcher(url);
requestDispatcher.forward(request, response);
I get the NullPointerException pointing to the RequestDispatcher's line. Any help?
Try changing "SelectCatalog.jsp" to "/SelectCatalog.jsp", because, as I understand, You want to use an absolute path.
If you want to use a relative path you have to use:
request.getRequestDispatcher(url);
in place of:
getServletContext().getRequestDispatcher(url);
request.getParameter("action");
code is written in doPost method. Are you invoking this servlet from doPost method of calling servlet? URL parameters will not be used by doPost method.
I have login code in one servlet:LoginGtalkServlet..
XMPPConnection connection;
//#see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(userName);
System.out.println(password);
//ProxyInfo proxyInfo = new
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
connection = new XMPPConnection(config);
config.setSASLAuthenticationEnabled(false);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
boolean status=connection.isAuthenticated();
if(status==true)
{
System.out.println("Success");
response.sendRedirect("GetRoster");
}
else
{
response.sendRedirect("Loginfailed.html");
}
And my GetRosterServlet has the code for retreving the roster list
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry r : entries) {
String user = r.getUser();
String name = r.getName();
System.out.println(name + user);
}
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String>
// addresses) {}
public void entriesDeleted(Collection<String> addresses) {
}
public void entriesUpdated(Collection<String> addresses) {
}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom()
+ " " + presence);
}
#Override
public void entriesAdded(Collection<String> arg0) {
}
});
}
Now the isssue is my GetRosterServlet is not informed that I haved logged into Gtalk..i.e LoginGtalkServlet is not communicating with GetRosterServlet and hence connection.getRoster() is throwing Null pointer exception...
How do I let the roster servlet know that the user is logged into gtalk and hence get the friends list
Note that I'm not familiar with XMPP/GTalk.
When you log in to it in LoginGtalkServlet, is it possible for you to be handed back some sort of session ID? If so, you could put that into the redirect URL as a query parameter or in a POST body and then GetRosterServlet could extract the session ID from request and use it to Gtalk via that session ID.
(Note: the edit I just made was just to fix some bad grammar. No substantive changes.)
You can save the connection object in the session attribute.
session .setAttribute("connection", connectionObj);
And can get by using session.getAttribute("connection");