I have written a servlet for approval of leaves. In this servlet I have also written code to send a mail. Due to this, it shows HTTP 405 error. If I remove the code which sends a mail, then it does not show the error, but I need the mail code.
package mis;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.jdo.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class approve extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try{
HttpSession session = req.getSession(true);
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery(Leave_bal.class);
query1.setFilter("emp_Id == emp");
query1.declareParameters("String emp");
List<Leave_bal> results1 = (List<Leave_bal>)query1.execute(session.getAttribute("emp_Id").toString());
String plan="";
String unplan="";
String planleave_result="" ;
String unplanleave_result="";
for (Leave_bal e : results1)
{
plan=e.getplan_leave();
resp.getWriter().println("Planned_Leave"+plan);
unplan=e.getunplan_leave();
resp.getWriter().println("Unplanned:"+unplan);
}
int plan_leave=Integer.parseInt(plan);
int unplan_leave=Integer.parseInt(unplan);
String ID=req.getParameter("id");
resp.getWriter().println(ID);
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Leave_detail.class);
query.setFilter("id == ID");
query.declareParameters("String ID");
List<Leave_detail> results = (List<Leave_detail>)query.execute(ID);
String plan_detail="";
String duration="";
for (Leave_detail e : results)
{
plan_detail=e.getLeave_Type();
duration=e.getdurtn();
//f=e.getfrom();
//t=e.getto();
}
resp.getWriter().println("duration "+duration);
resp.getWriter().println("Planned_selected "+plan_detail);
int duration_integer=Integer.parseInt(duration);
resp.getWriter().println("duration "+duration_integer);
//String duration=req.getParameter("date");
// resp.getWriter().println("diffrence:"+duration);
//int workingdays=Integer.parseInt(duration);
//String Leave = req.getParameter("a");
// resp.getWriter().println("planned:"+Leave);
if(plan_detail.equals("UNPLAN"))
{
unplan_leave=unplan_leave-duration_integer;
unplanleave_result=String.valueOf(unplan_leave);
planleave_result=plan;
resp.getWriter().println("Planned After Change"+unplanleave_result);
//st="Applied";
}
if(plan_detail.equals("PLAN"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("LWP"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("Onduty"))
{
planleave_result=plan;
unplanleave_result=unplan;
}
Leave_detail status_update = pm.getObjectById(Leave_detail.class,ID);
status_update.setstatus("Approved");
pm.makePersistent(status_update);
Leave_bal ed1=new Leave_bal(session.getAttribute("emp_Id").toString(),planleave_result,unplanleave_result);
pm.makePersistent(ed1);
//code for mail
RequestDispatcher dispatcher = getServletConfig ( ) .getServletContext ().getRequestDispatcher("/MailServiceapply");
dispatcher.forward (req, resp) ;
pm.close();
}
catch(Exception a )
{
resp.getWriter().println(a .getMessage());
} finally{
}
resp.sendRedirect("hr.jsp#LMS");
}
}
This thread on Java Forums provides some hints for this error, like
HTML form invokes POST operation and servlet doesn't implement doPost (direct link)
Inital HTML form not declared in web.xml file (or misspelled) (direct link)
At the bottom of this servlet you're forwarding the request to another servlet:
RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/MailServiceapply");
dispatcher.forward(req, resp);
This is not only a poor approach, certainly because you've written data to the HTTP response before in the servlet and you thus risk IllegalStateException (writing to the response should take place in a JSP), but doing so also requires that the servlet in question also implements doGet(). The error which you're facing suggests that this mail service servlet has only the doPost() implemented.
You need to add a doGet() method to the mail service servlet and use RequestDispatcher#include() to invoke it.
dispatcher.include(req, resp);
Needless to say that this is still a poor approach. You'd rather like to refactor the mail code logic into a standalone Java class which you then import and invoke in both servlets and put all the presentation logic in a JSP.
Related
/*I have passed session cookies manually in below code.when i pass the session cookies in post man its working fine but in eclipse it giving 401 HTTP error.I am very new to rest assured.please let me know if anything is wrong with the code.I have attached the error aswell */
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.security.cert.CertificateException;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.testng.annotations.Test;
import com.sun.net.ssl.SSLContext;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
public class getart {
#Test
public void Test1()
{
// TODO Auto-generated method stub
//baseURL or Host
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI="https://localhost";
given().
param("Cookie","JSESSIONID=B1FAC334FF60F7182D4C552ABE01A700; hi.session.co.entity=1838-PROD1; hi.session.id.identifier=xHmvClBuIBcSKAEiVP~~AAAESADWaUjq; hi.session.client.identifier=1838Viewer").
when().
get("/hi-prod/3.1.12/al/api/articles")
.then().assertThat().statusCode(200).
body("status",equalTo("OK")).log().body();
}
}
param() is used to add a query parameter to the URL - which is not something you want for setting the cookies. Cookies have to be set in the Request Header.
Instead you should be using cookie() or cookies(). The rest-assured wiki has a section on how to set the cookies. Note that you will need to set four cookies according to your example.
EDIT: Added as per comment,
Approach 1
Cookie cookie1 = Cookie.Builder("JSESSIONID", "B1FAC334FF60F7182D4C552ABE01A700").build();
Cookie cookie2 = Cookie.Builder("hi.session.co.entity", "1838-PROD1").build();
Cookie cookie3 = Cookie.Builder("hi.session.id.identifier", "xHmvClBuIBcSKAEiVP~~AAAESADWaUjq").build();
Cookie cookie4 = Cookie.Builder("hi.session.client.identifier", "1838Viewer").build();
Cookies cookies = new Cookies(cookie1, cookie2, cookie3, cookie4);
given().cookies(cookies)
.when().get("/hi-prod/3.1.12/al/api/articles")
Approach 2
given().header("Set-Cookie", "JSESSIONID=B1FAC334FF60F7182D4C552ABE01A700; hi.session.co.entity=1838-PROD1; hi.session.id.identifier=xHmvClBuIBcSKAEiVP~~AAAESADWaUjq; hi.session.client.identifier=1838Viewer"")
.when().get("/hi-prod/3.1.12/al/api/articles")
In our application we have couple of webservices.i need to get the userids(means who has loged in and webservice name) for auditing purpose i need to store.
Could anyone suggest which will be either filter chain or Interceptors and how to get the webservice name.
You can use PreSecurityInterceptor for doing this ,request from client will first goto it and there you can log the data in db or file .
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
/**
* This interceptor verify the method name and log the details
* */
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
//import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
#Provider
#ServerInterceptor
public class PreSecurityInterceptor implements PreProcessInterceptor {
#Context HttpServletRequest req;
#Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
System.out.println("********************************************* pre process *****************************");
System.out.println(new Date() + " Method : " + method.getMethod().getName() + " being called from "
+ req.getRemoteHost()+":"+req.getLocalPort()+": Remote Port "+req.getRemotePort());
if ( "defaultMethod".equalsIgnoreCase(method.getMethod().getName())) {
return null; // normal flow continues
} else {
System.out.println(new Date() + " Method : " + method.getMethod().getName() + " Precondition failed ");
return (ServerResponse) Response
.status(Response.Status.PRECONDITION_FAILED).entity("invalid method details provided !!").build();
}
}
}
I want to get current country name in java . I use this code.
private HttpServletRequest request;
Locale currentCountry = request.getLocale();
System.out.println(currentCountry.getDisplayCountry());
But it through an NullPointerException like Caused by: java.lang.NullPointerException. at 2nd line. Please Help me anyone.
The snippet of code is not enough to tell why you got the Null Pointer. I assume you are use servlet on server side.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HttpServletBean;
public class MyServlet extends HttpServletBean {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Locale userlocale = request.getLocale();
out.println("Your Country : " + userlocale.getCountry());
out.println();
out.println("");
}
}
i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)
Easy way to write servlet that returns table data in xml format - ?
Data comes from a database table.
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;
public class TableServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/xml");
PrintWriter writer = response.getWriter();
writer.println("<?xml version=\"1.0\"?>");
writer.println("<table>");
writer.println("<style>");
writer.println("<finish>polished</finish>");
writer.println("<material>oak</material>");
writer.println("</style>");
writer.println("<legs>4</legs>");
writer.println("</table>");
writer.flush();
}
}
You may found jersey useful it works for XML, also supports JSON . Here is a good tutorial (Look section 4) .