I have the following maven dependency:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.5.6</version>
</dependency>
And i have the following servlet:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeoutException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import model.DVD;
/**
* Servlet implementation class LoginServlet
*/
public class IndexServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public IndexServlet()
{
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException
{
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
String QUEUE_NAME = "hello";
try
{
/// some code
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicPublish("", QUEUE_NAME, null, obj.getBytes());
System.out.println(" [x] Sent '" + dvd.getName() + "'");
channel.close();
connection.close();
} catch (IOException | TimeoutException | NumberFormatException exp)
{
exp.printStackTrace();
}
response.sendRedirect("/A3_Producer/");
}
}
I run Maven build with clean install and after that I start the web application in a tomcat server. The welcome page loads, but when I hit the Submit button and enter in this servlet, I get an ClassNotFoundException when trying to make a ConnectionFactory object.
I added the jar too to build path but it didn't fix the problem.
What can I do to fix it?
In order to make this work, you need to place the client jar into the tomcatinstallation/lib lib folder. ($CATALINA_HOME/lib)
Related
I have set cookies in a servlet class and read those cookies values in another servlet class. In another servlet class along with the set cookies values, I am getting some unusual values.
My Home.java servlet class results set ::
first result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello RACHEL
Hello last_name, Hello KIM
second result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello CAIRO
Hello last_name, Hello SENGAL
in both the results I am getting the set cookies values and names but along with them I am getting JSESSIONID and A502A7144AE035ED9B1A2549F5C7B74B. I can't understand from where do these cookies values are appearing? How can I remove this? Why are these values appearing?
My code :
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Authenticate
*/
#WebServlet("/Authenticate")
public class Authenticate extends HttpServlet {
private static final long serialVersionUID = 1L;
public Authenticate() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
out.print("Welcome "+ firstname);
// Create cookies for first and last names.
Cookie f_name = new Cookie("first_name", firstname);
Cookie l_name = new Cookie("last_name", lastname);
// Add both the cookies in the response header.
response.addCookie( f_name );
response.addCookie( l_name );
//creating submit button
out.print("<form action='Home' method='post' >");
out.print("<input type='submit' value='cookie click' />");
out.print("</form>");
out.close();
}
catch(Exception ex)
{
System.out.println("exception occured");
System.out.println(ex.toString());
}
}
}
Code for Home servlet
#WebServlet("/Home")
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Home() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[] = request.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
out.print("Hello " + ck[i].getName() + ", ");
out.print("Hello " + ck[i].getValue());
out.print("<br />");
}
}
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;
/**
* Servlet implementation class IP
*/
public class IP extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public IP() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ipAddress = request.getRemoteAddr();
System.out.println(ipAddress);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//Print out the IP address of the caller
out.println(request.getRemoteAddr());
GeoLocation $gl = javaQueryBundle.createGeoLocation();
System.out.println(ipAddress);
$gl.MAPTargetByIP(ipAddress, "test");
System.out.println($gl.Latitude);
System.out.println($gl.Longitude);
System.out.println($gl.Country);
System.out.println($gl.City);
System.out.println($gl.State);
System.out.println($gl.GoogleMap_URL);
System.out.println($gl.GoogleMap_URL_Bubble);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my code snippest.I am getting IP address of visitor but not location information.
It gives :
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
To tell the java code that all HTTP request should be routed through the proxy use the below snippet:
System.setProperty("http.proxyHost", "proxyHost");
System.setProperty("http.proxyPort", "proxyPort");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("USERNAME","PASSWORD".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
The System.setProperty sets the proxy host and port. The Authenticator should be your corporate username and password. This should work now.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.*;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.MaxMind;
import com.maxmind.geoip2.record.RepresentedCountry;
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;
/**
* Servlet implementation class IP
*/
public class IP extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public IP() {
super();
System.setProperty("http.proxyHost", "proxyHostName");
System.setProperty("http.proxyPort", "proxyPort");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("USERNAME","PASSWORD".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ipAddress = request.getRemoteAddr();
System.out.println(ipAddress);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//Print out the IP address of the caller
out.println(request.getLocalAddr());
GeoLocation $gl = javaQueryBundle.createGeoLocation();
System.out.println($gl.toString().length());
System.out.println("--");
System.out.println($gl.getMACAddressWindows());
$gl.MAPTargetByIP(ipAddress , "test");
System.out.println($gl.Latitude);
System.out.println($gl.Longitude);
System.out.println($gl.Country);
System.out.println($gl.City);
System.out.println($gl.State);
System.out.println($gl.GoogleMap_URL);
System.out.println($gl.GoogleMap_URL_Bubble);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is working fine now.
I am having a bit of problem figuring out whether I can actually call methods of the session bean in a method that doesn't take the HttpServletRequest and HttpServletResponse parameters ?
Having realized that the code works in doGet and doPost methods I have modified a custom made method to take the parameters of request and response, and suddenly it has started working.
My goal is to have the method working (calling session bean methods) without having a request and response in the method parameters.
However here is the code of the problematic version which grants NullPointerException on itemRegistrationSession.openConnection();
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import auction.itemRegistrationRemote;
import auction.userRegistrationRemote;
/**
* Servlet implementation class processItem
*/
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
getCategories();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//ArrayList<String> categories = getCategories(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected ArrayList<String> getCategories() {
System.out.println("Hello from getCategories()");
itemRegistrationSession.openConnection();
System.out.println("Hello2 from getCategories()");
ArrayList<String> categories = itemRegistrationSession.getCategories();
itemRegistrationSession.closeConnection();
return categories;
}
}
package auction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
/**
* Session Bean implementation class itemRegistration
*/
#Singleton
public class itemRegistration implements itemRegistrationRemote {
Connection con;
PreparedStatement prepStat;
ResultSet resultSet;
final String ITEM_NAME = "ITEM_NAME";
final String CATEGORY_NAME = "CATEGORY_NAME";
final String USER_NAME = "USER_NAME";
final String ITEM_MODEL = "ITEM_MODEL";
final String ITEM_DESCRIPTION = "ITEM_DESCRIPTION";
/**
* Default constructor.
*/
public itemRegistration() {
// TODO Auto-generated constructor stub
}
#Override
public void openConnection() {
System.out.println("Openning connection for itemRegistration");
try {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
System.out.println("Openning database connection - Instantiation Exception " + e.getMessage());
} catch (IllegalAccessException e) {
System.out.println("Openning database connection - IllegalAccessException " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Openning database connection - ClassNotFoundException " + e.getMessage());
}
try {
con = DriverManager.getConnection("jdbc:derby:C:/Users/Adrian/MyDB;upgrade=true", "adrian", "testero");
} catch (SQLException e) {
System.out.println("Openning database connection - SQLException " + e.getMessage());
}
} // End of openConnection method
#Override
public void closeConnection() {
try {
resultSet.close();
prepStat.close();
con.close();
} catch (SQLException e) {
System.out.println("Closing database connection - SQLException " + e.getMessage());
}
} // End of closeConnection method
#Override
public ArrayList<String> getCategories() {
ArrayList<String> categories = new ArrayList<String>();
try {
prepStat = con.prepareStatement("SELECT * FROM CATEGORY");
resultSet = prepStat.executeQuery();
int i = 1;
while (resultSet.next()) {
categories.add(resultSet.getString(i));
i++;
}
} catch (SQLException e) {
System.out.println("getCategories SQLException - " + e.getMessage());
}
return categories;
}
}
Sounds like the dependency inject for the
#EJB itemRegistrationRemote itemRegistrationSession
isn't working. Trying adding a log statement showing the value of the itemRegistrationSession object to see if that member got initialized correctly.
You're getting the exception because by the time you call getCategories() the EJBs have not been injected yet.
At constructor invocation time injection hasn't occurred yet, keep in mind that the object is just being created so the container hasn't had time to inject anything, the proper way to do this is by using the #PostConstruct annotation. From the javadoc:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization...
so you need to move the getCategories() invocation to a #PostConstruct annotated method, like this:
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
}
#Postconstruct
void init() {
getCategories();
}...
Hi just wanted to share this servlet it takes 2 arguments ( img-> image name , rot ->rotation of the images) loads the image from the images directory rotates it and outputs it to the servlet stream
you can find it in the answer below
package at.buchinger.mapdisplay;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RotatedImage
*/
public class RotatedImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RotatedImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String img = (String) request.getParameter("img");
String path = getServletContext().getRealPath("image/"+img);
String r;
r=request.getParameter("rot");
if(r==null){
r="0";
}
double rot = Double.parseDouble( r);
BufferedImage image = ImageIO.read(new File(path));
AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(rot), image.getWidth()/2, image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
ServletContext sc = getServletContext();
String filename = getServletContext().getRealPath(path);
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
ServletOutputStream out = response.getOutputStream();
Iterator iter = ImageIO.getImageWritersByMIMEType(mimeType);
ImageIO.write(image, "png", out);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
I need to import contacts to the enable my web app users to send invitation to his/her friends from my site, I am using SocioAuth Open source API to get this done, I have written 2 servlets to get this done I am pasting the code of my servlet. when I deployed the app in my Ec2 instance, I am getting an exception saying "Key in request token is null or blank in the line number 27 of the NewSocialAuthentication,
package com.auth.actions;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
public class NewSocialAuthentication extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of NewSocialApp..");
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
String returnToUrl = "http://ec2-50-19-118-108.compute-1.amazonaws.com/SocialAuthNew6/return";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
}
package com.auth.actions;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.util.*;
public class ReturnServlet extends HttpServlet{
/**
*
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of Return Servlet..");
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");//this the line is rising exception
Profile p = provider.verifyResponse(request);
System.out.println(p.getFirstName());
List<Contact> contactsList = provider.getContactList();
for(int i=0;i<contactsList.size();i++){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println(contactsList.get(i).getFirstName()+" : "+contactsList.get(i).getLastName());
out.println(contactsList.get(i).getFirstName());
out.println(contactsList.get(i).getLastName());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
This is the servlet which redirects to the email service provider
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
/**
* Servlet implementation class NewSocialAuthentication
*/
public class NewSocialAuthentication extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewSocialAuthentication() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
//String returnToUrl = "http://ec2-50-16-183-101.compute-1.amazonaws.com/SocialAuthNew/return";
String returnToUrl = "u r returning url ";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
the return url would look like this I have embedded in the jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Contact" %>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Profile" %>
<%#page import="java.util.*" %>
Insert title here
CONTACT LIST
<%
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");
try{
System.out.println(provider.getContactList());
}
catch(Exception e){
System.out.println("Exception Encountered..");
}
Profile p = provider.verifyResponse(request);
List contactsList = provider.getContactList();
%>
Hello, <%= p.getFirstName() %>
Contact List
First Name
Email
<%
for(int i=0;i
"/><%= contactsList.get(i).getFirstName() %><%= contactsList.get(i).getEmail() %>
<%
}
%>
</table>
<input type="submit" value="GET CONTACTS"/>
</form>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>