Restful Web Service Error - java

I use Javax Restfull web service. I can return String from mobile app. but I cant return Model class.
I want to return Employee model. I give a error;
Full Error:
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/CafeSiparis] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError
at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findSerializer(AnnotationIntrospector.java:1148)
at org.codehaus.jackson.map.ser.BasicSerializerFactory.findSerializerFromAnnotation(BasicSerializerFactory.java:362)
at org.codehaus.jackson.map.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:252)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createUntypedSerializer(StdSerializerProvider.java:782)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createAndCacheUntypedSerializer(StdSerializerProvider.java:735)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findValueSerializer(StdSerializerProvider.java:344)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findTypedValueSerializer(StdSerializerProvider.java:420)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:601)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:527)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at controls.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:31)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2440)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2429)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My class:
Employee Model:
package model;
/**
*
* #author cengizhan
*/
public class Employee {
private String name;
private String surname;
private int id;
public Employee(int id, String name, String surname){
this.id = id;
this.name=name;
this.surname =surname;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the surname
*/
public String getSurname() {
return surname;
}
/**
* #param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
Web Service Class:
package ws;
import helper.UrunHelper;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import model.Employee;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Path("/WSLogin")
public class WSLogin implements Serializable {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/returnModel")
public Employee returnModel() {
Employee emp = new Employee(1, "Jack", "Jason");
return emp;
}
}
SimpleCORSFilter:
package controls;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author cengizhan
*/
public class SimpleCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
Web.xml:
<!-- Web Service -->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ws</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- /Web Service -->
Thank you :)

Looks like you are mixing dependency versions.. try using jersey-server-1.8 and jersey-json-1.8 (and adjust their dependencies versions)
Maven could help you out on this..
EDIT: Try using the following jars

Related

cannot Inject Named bean into javax.ws.rs class while #EJB could be used

I try to inject a named bean into a class using javax.ws.rs.* and got the result of :
javax.servlet.ServletException: A MultiException has 1 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=UserBean,parent=NameCheckREST,qualifiers={},position=-1,optional=false,self=false,unqualified=null,903092946)
root cause
So I can guess the dependency injection failed. After I comment the #inject and related methods, it works. My question is why I cannot inject the named bean into javax REST class while my teacher uses #EJB to inject ejb and it succeeds.
Is this kind of design mechanism? You can refer to the code below:
#inject failed:
package restServices;
import java.text.DecimalFormat;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import beans.UserBean;
#Path("checkname")
public class NameCheckREST {
#SuppressWarnings("unused")
#Context
private UriInfo context;
#Inject
private UserBean userBean;
/**
* Default constructor.
*/
public NameCheckREST() {
// TODO Auto-generated constructor stub
}
// /**
// * Retrieves representation of an instance of NameCheckREST
// * #return an instance of String
// */
// #GET
// #Produces("application/json")
// public String getJson() {
// // TODO return proper representation object
// throw new UnsupportedOperationException();
// }
/**
* Retrieves representation of an instance of HelloWorld
* #return an instance of String
*/
#GET
#Produces("text/html")
public String getHtml() {
// TODO return proper representation object
//DecimalFormat df = new DecimalFormat("0.00");
return "<html><body><h1>" + "Web resources for CMS" + "</h1> </body></html>";
//throw new UnsupportedOperationException();
}
/**
* PUT method for updating or creating an instance of NameCheckREST
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/json")
public void putJson(String content) {
}
#POST
#Path("user")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.APPLICATION_JSON)
public JsonArray checkUsername(#FormParam("account") String account) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
objectBuilder.add("account", account);
if(userBean.searchUserByAccount(account) == null) {
objectBuilder.add("exist", false);
}else {
objectBuilder.add("exist", true);
}
arrayBuilder.add(objectBuilder);
return arrayBuilder.build();
}
}
named user bean:
package beans;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.util.logging.Level;
import java.util.logging.Logger;
import entity.NormalUser;
//import entity.User;
import repository.UserRepository;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
UserRepository userRepository;
//default constructor
public UserBean() {
}
public List<NormalUser> getAllUsers(){
try {
List<NormalUser> users = userRepository.getAllUsers();
//System.out.print("users:" + users.size());
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, "users:" + users.size());
return users;
} catch(Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public boolean addUser(NormalUser user) {
try {
userRepository.addUser(user);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean removeUser(String account) {
try {
userRepository.deleteUser(account);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean editUser(NormalUser user) {
try {
userRepository.updateUser(user);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public NormalUser searchUserByAccount(String account) {
try {
NormalUser user = userRepository.searchUser(account);
return user;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
#EJB succeed:
package helloworld;
import java.text.DecimalFormat;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import calculator.LoanBean;
#Path("greeting")
public class HelloWorld {
#SuppressWarnings("unused")
#Context
private UriInfo context;
#EJB
private NameStorageBean nameStorage;
#EJB
private LoanBean loanBean;
/**
* Default constructor.
*/
public HelloWorld() {
// TODO Auto-generated constructor stub
}
/**
* Retrieves representation of an instance of HelloWorld
* #return an instance of String
*/
#GET
#Produces("text/html")
public String getHtml() {
// TODO return proper representation object
DecimalFormat df = new DecimalFormat("0.00");
return "<html><body><h1>Hello " + nameStorage.getName() + ", the monthly payment is " + df.format(loanBean.calculate()) +"!</h1> </body></html>";
//throw new UnsupportedOperationException();
}
#POST
#Consumes("application/x-www-form-urlencoded")
public void setPostName( #FormParam("name") String content) {
nameStorage.setName(content);
}
#POST
#Path("loan")
#Consumes("application/json")
public void setPostLoan(Loan loan) {
loanBean.setPrinciple(loan.getPrinciple());
loanBean.setInterestRate(loan.getInterestRate());
loanBean.setNumberOfYears(loan.getNumberOfYears());
loanBean.setMonthlyPayment(loanBean.calculate());
// ELContext context
// = FacesContext.getCurrentInstance().getELContext();
// WebServiceBean currentWebBean = (WebServiceBean) FacesContext.getCurrentInstance().getApplication()
// .getELResolver().getValue(context, null, "webServiceBean");
// currentWebBean.setMonthlyPayment(loanBean.calculate());
}
/**
* PUT method for updating or creating an instance of HelloWorld
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("text/html")
public void putHtml(String content) {
}
}
about web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>CMS-war</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<!-- <context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</param-value>
</context-param> -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<security-constraint>
<display-name>AdminContstraint</display-name>
<web-resource-collection>
<web-resource-name>WebResource</web-resource-name>
<url-pattern>/faces/admin/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>DELETE</http-method>
<http-method>PUT</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint>
<description>Administrator</description>
<role-name>Admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<display-name>NormalContstraint</display-name>
<web-resource-collection>
<web-resource-name>WebResource</web-resource-name>
<url-pattern>/faces/normal/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>DELETE</http-method>
<http-method>PUT</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint>
<description>NormalUser</description>
<role-name>Normal</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>cms_security</realm-name>
<form-login-config>
<form-login-page>/faces/login.xhtml</form-login-page>
<form-error-page>/faces/error.xhtml</form-error-page>
</form-login-config>
</login-config>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<security-role>
<description>Administrator</description>
<role-name>Admin</role-name>
</security-role>
<security-role>
<description>NormalUser</description>
<role-name>Normal</role-name>
</security-role>
</web-app>
So is there anything I did not pay attention to or I just cannot inject named bean but ejb into javax-rest class.

SAPUI5 to Java HttpServletRequest.getUserPrincipal() returns null

I'm trying to authenticate users in my java backend. I'm trying to connect to my backend with SAPUI5. I added two roles in the SCP Portal and I want to access them in Java. I'm using HttpServletRequest.getUserPrincipal() to get the user, but it keeps returning null. Any ideas on how to solve this? Did I forget something in SAPUI5?
package be.amista.filters;
import java.io.IOException;
import java.security.Principal;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sap.security.um.service.UserManagementAccessor;
import com.sap.security.um.user.User;
import com.sap.security.um.user.UserProvider;
#WebFilter("/*")
public class UserFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(UserFilter.class);
private static Set<String> userRoles;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (httpServletRequest.getUserPrincipal() != null) {
try {
// UserProvider provides access to the user storage
UserProvider users = UserManagementAccessor.getUserProvider();
// Read the currently logged in user from the user storage
User user = users.getUser(httpServletRequest.getUserPrincipal().getName());
userRoles = user.getRoles();
} catch (Exception e) {
// Handle errors
logger.error(e.getMessage());
}
}
// pass the request along the filter chain
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
public static Set<String> getUserRoles() {
return userRoles;
}
}
I found a solution myself. I added this piece of code to the web.xml and it worked.
<resource-ref>
<res-ref-name>user/Provider</res-ref-name>
<res-type>com.sap.security.um.user.UserProvider</res-type>
</resource-ref>
<resource-ref>
<res-ref-name>connectivityConfiguration</res-ref-name>
<res-type>com.sap.core.connectivity.api.configuration.ConnectivityConfiguration</res-type>
</resource-ref>
<login-config>
<auth-method>FORM</auth-method>
</login-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Everyone</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<description>All SAP Cloud Platform users</description>
<role-name>Everyone</role-name>
</security-role>

Sending email on button click in Java EE servlet with tomcat

I am new to JAVA EE, and I am working by myself on a project. Now, I want to deploy sending email function on a button click. In detail, I want my customer to submit their information and when they click on submit button, an email of receipt should be sent to their email. I will show my coding below.
First of all, here are my source files that are related to what I am doing.
EmailUtility.java
package com.jason;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
And here is my PaymentServlet.java
package com.jason;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import com.jason.storeServlet.Command;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Authenticator;
/**
* Servlet implementation class paymentServlet
*/
#WebServlet("/paymentServlet")
public class paymentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
int quantity;
String color;
double size;
double price;
String productId;
double totalPrice;
double tax;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
public enum Command {Buy,Submit,Confirm}
private String host;
private String port;
private String user;
private String pass;
public void init() {
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String action = request.getParameter("action");
Command command = Command.valueOf(action);
System.out.println(action);
System.out.println("get");
switch(command) {
case Buy:
this.buynow(request, response);
break;
case Submit:
this.submit(request, response);
break;
case Confirm:
this.confirm(request, response);
break;
default:
break;
}
}
private void confirm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
HttpSession session = request.getSession();
response.sendRedirect(request.getContextPath() + "/receipt.jsp");
session.setAttribute("date", date());
Email(request, response);
}
private String date(){
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
return sdf.format(new Date());
}
protected void Email(HttpServletRequest request, HttpServletResponse response){
String recipient = "some email";
String subject = "Receipt for your order";
String content = "We thank you for your purchase.";
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
}
}
}
And here is web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>some email</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>some password</param-value>
</context-param>
</web-app>
So the way it should work is that when a customer clicks on Confirm button it should deploy the confirm method which calls email method.
Here is the error I am getting:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.jason.paymentServlet] in context with path [/Practice4_Shopping] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: javax.mail.Authenticator
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
at com.jason.paymentServlet.Email(paymentServlet.java:256)
at com.jason.paymentServlet.confirm(paymentServlet.java:239)
at com.jason.paymentServlet.doGet(paymentServlet.java:84)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1374)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

Jersey Client API - authentication error using jersey rest api

I have created one authorization filter before calling rest API but i am getting 404 error message. Below is classes which I have created.
--RestAuthenticationFilter
package com.sms.Security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RestAuthenticationFilter implements javax.servlet.Filter {
public static final String AUTHENTICATION_HEADER = "Authorization";
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authCredentials = httpServletRequest
.getHeader(AUTHENTICATION_HEADER);
// better injected
AuthenticationService authenticationService = new AuthenticationService();
boolean authenticationStatus = authenticationService
.authenticate(authCredentials);
if (authenticationStatus) {
filter.doFilter(request, response);
} else {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse
.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
--AuthenticationService
package com.sms.Security;
import java.io.IOException;
import java.util.Base64;
import java.util.StringTokenizer;
public class AuthenticationService {
public boolean authenticate(String authCredentials) {
if (null == authCredentials)
return false;
// header value format will be "Basic encodedstring" for Basic
// authentication. Example "Basic YWRtaW46YWRtaW4="
final String encodedUserPassword = authCredentials.replaceFirst("Basic"
+ " ", "");
String usernameAndPassword = null;
try {
byte[] decodedBytes = Base64.getDecoder().decode(
encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(
usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
// we have fixed the userid and password as admin
// call some UserService/LDAP here
boolean authenticationStatus = "admin".equals(username)
&& "admin".equals(password);
return authenticationStatus;
}
}
--Web.xml file
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.sms.presentationT</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/pages/rest/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.sms.Security.RestAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/pages/rest/*</url-pattern>
</filter-mapping>
</web-app>
--Login API
package com.sms.presentationT;
import java.io.Serializable;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import com.sms.userServices.*;
import com.sms.Registrations.Regitration;
import com.sms.persistenceT.*;
import com.sms.persistenceT.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sms.Security.*;
#Path("/user-servicesLogincheck1")
public class Check implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#POST
#Path("/LoginPagecheck1")
//#Consumes("application/json")
//#Produces("application/json")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Regitration loginUserInfo(#FormParam("logusertype") String logUserType,
#FormParam("userNAME") String UserNAME,
#FormParam("PassWORD") String PAssWORD) throws ParseException
{
System.out.println(logUserType+UserNAME+PAssWORD);
CustomApplication CA = new CustomApplication();
CA.getApplication();
LoginUserServiceCheck LUS = new LoginUserServiceCheck();
JSONObject jobj2 = new JSONObject();
jobj2 = LUS.LoginInputDatacheck(logUserType,UserNAME, PAssWORD);
System.out.println("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
System.out.println("Presentation jobj"+jobj2);
String jsonText = jobj2.toJSONString();
System.out.println(jsonText);
JSONParser parser = new JSONParser();
JSONObject newJObject = null;
try {
newJObject = (JSONObject) parser.parse(jsonText);
} catch (ParseException e) {
e.printStackTrace();
}
//System.out.println(LUS.loginresponse);
//System.out.println(LUS.resultStatus);
/*
if(LUS.resultStatus)
{
System.out.println(LUS.loginresponse);
return LUS.loginresponse;
//return "UserName is valid";
}
else
{
return LUS.loginresponse;
}
*/
System.out.println(newJObject.get("Name"));
System.out.println(newJObject.get("Email"));
Regitration rg = new Regitration();
rg.setUserType(logUserType);
rg.setName((String)newJObject.get("Name"));
rg.setEmail((String)newJObject.get("Email"));
rg.setUserName((String)newJObject.get("userName"));
rg.setPassword((String)newJObject.get("password"));
rg.setConfirmPasssword((String)newJObject.get("password"));
rg.setBirthDay((String)newJObject.get("birthday"));
rg.setGender((String)newJObject.get("Gender"));
rg.setMobileNo((String)newJObject.get("mobileNo"));
rg.setCurrentAddress((String)newJObject.get("currentAddress"));
rg.setPermenantAddress((String)newJObject.get("PermenantAddress"));
rg.setCountry((String)newJObject.get("Country"));
rg.setState((String)newJObject.get("state"));
rg.setCity((String)newJObject.get("City"));
rg.setLandmark((String)newJObject.get("Landmark"));
rg.setZipCode((String)newJObject.get("ZipCode"));
return rg;
}
}
-- Error message
Mar 27, 2017 1:44:58 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2836 ms
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
Mar 27, 2017 1:44:59 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter AuthenticationFilter
java.lang.ClassNotFoundException: com.sms.Security.RestAuthenticationFilter
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:269)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:424)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
It looks like the RestAuthenticationFilter is not available in the classpath, hence the ClassNotFoundException. Please double check if you are compiling it and putting it in the classpath.

Cannot create JDBC driver of class using MySQL

This Question has been asked multiple times..but still doesn't solve my problem,i am not able to find my mistake.
I am trying to create Dynamic Web Project using STS. I got the following stacktrace
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at actions.OneServlet.doGet(OneServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:315)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
... 25 more
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ServletConnectionPool</display-name>
<resource-ref>
<description>MySQL Connection</description>
<res-ref-name>jdbc/MySQLDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
<description>
</description>
<display-name>OneServlet</display-name>
<servlet-name>OneServlet</servlet-name>
<servlet-class>actions.OneServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OneServlet</servlet-name>
<url-pattern>/OneServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
My Context.xml is
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/MySQLDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100"
maxIdle="30" maxWaitMillis="10000" username="root" password="-----"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/hcq"/>
</Context>
My Connection Pools class is
package actions;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DSource {
public static DataSource getDataSource() {
DataSource ds=null;
Context initCtx,envCtx;
initCtx=envCtx=null;
try {
initCtx=new InitialContext();
envCtx=(Context)initCtx.lookup("java:comp/env");
ds=(DataSource)envCtx.lookup("jdbc/MySQLDB");
}
catch(NamingException e) {
e.printStackTrace();
}
return ds;
}
}
My main Servlet is
package actions;
import actions.DSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
/**
* Servlet implementation class OneServlet
*/
public class OneServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public OneServlet() {
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
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Details of Employee");
PreparedStatement stmt;
ResultSet rset;
DataSource ds=DSource.getDataSource();
System.out.println(ds);
if(ds!=null) {
try(Connection con=ds.getConnection()) {
stmt=con.prepareStatement("select * from Employee");
rset=stmt.executeQuery();
while(rset.next()) {
out.println("<br>"+rset.getString(1)+"\t"+rset.getString(2));
}
}
catch(SQLException e) {
e.printStackTrace();
}
} else {
out.println("Connection Failed");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
The mysql-connector jar is available in both WEB-INF/lib and Libraries/apachetomcat
I am not able to find my error.

Categories

Resources