error 500 on google app engine - java

I am trying to create a servlet on the Google App Engine. I have done this sucsessfully a few times in the past, but now I get an "Internal Server Error" when running it from the cloud.
It works on Eclipse on development mode, though.
My servlet is called AsyncServer and the code is:
public class AsyncServer extends HttpServlet {
static final long serialVersionUID=0L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.write("Hello");
writer.flush();
writer.close();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}
I use the following address to call it on the local development server:
http://127.0.0.1:8888/test4/AsyncServer
and I get "Hello", as expected.
When deployed to the Google servers under the ID fa100-1130
I use the following address
http://fa100-1130.appspot.com/test4/AsyncServer
I get an http error 500

Currently entering the URL mentioned in your question and returns an affirmative respesta:
http://fa100-1130.appspot.com/test4/AsyncServer
run the development and performs deploy again
bye :) #locoalien

Related

How to mock RequestDispatcher so that it goes to the .jsp file?

I am trying to write the JUnit test case for the code:
In SearchController class
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<AlbumSimplified> items = spotifyService.searchAlbum(searchName);
request.setAttribute("items", items);
request.getRequestDispatcher("searchResult.jsp").forward(request, response);
}
as
public void SearchControllerTesting() throws ServletException, IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
//mocked myalbums
when(searchServiceMock.searchAlbum(anyString())).thenReturn(myalbums); when(request.getRequestDispatcher(anyString())).thenReturn(request.getRequestDispatcher("searchResult.jsp"));
searchController.doGet(request, response);
}
The error I am facing is:
java.lang.NullPointerException: Cannot invoke "jakarta.servlet.RequestDispatcher.forward(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)" because the return value of "jakarta.servlet.http.HttpServletRequest.getRequestDispatcher(String)" is null
I believe that it is due to the fact that the uri is not identified for the request and so, it is not able to find the "searchResult.jsp" located at "/app/src/main/webapp/searchResult.jsp" where app is the root of the project directory.
Hence I tried to set the
when(request.getRequestedURI()).thenReturn("app/search"), which is the URL of the request in the browser for non-testing usage.
However, I am not able to move ahead and solve the issue.
I want the items in the request to go to the searchResult.jsp, and return me a response of type "text/html".
Thanks.

how to prevent servlet from being invoked directly through browser

I was working on a web project using java servlet and jsp pages. In one of the servlet we have RequestDispatcher method and which is calling another servlet.
#WebServlet("/Demo")
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.sendRedirect("testing"); //calling other servlet
}
}
#WebServlet("/testing")
public class TestingServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
So, now I wanted to prevent contextRoot/testing from being invoked directly from the browser but instead only let it invoked from the other servlet(Demo)
Please suggest me if there is any way to do that.
Couple of techniques exist:
Look at writing a HTTP Request Filter. You can then inspect the incoming request and the url and reject it if the pattern matches the servlet paths that you do not want to be invoked directly.
Another mechanism is to use the security constraints in your web.xml to allow access to various paths in your application only to authorized users/roles. Look at <security-constraint> tag in web.xml
Answer given by "Romin" is correct. You have to use Filters for this. what you can do is, you can set a new session variable whenever "/Demo" url is accessed and in the filter check for the condition that session exists, if it exists allow the url or else throw error. You could do something similar like this. In "Demo" servlet
#WebServlet("/Demo")
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = request.getSession() //get new session
res.sendRedirect("testing"); //calling other servlet
}
}
In Filter class add the below code
#WebFilter("/login")
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpRequest request = (HttpRequest) req;
HttpResponse respone = (HttpResponse) res;
HttpSession session = request.getSession(false) //get the existing session object
if(null != session) {
chain.doFilter(req, resp);
} else {
"redirect to some error page or home page"
}
}
public void destroy() {}
}
One approach is to check the caller's ip using ServletRequest.getRemoteAddr() and rejects it if it's not called locally
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
if(!req.getRemoteAddr().equals("127.0.0.1")) { // reject }
}
However this method wouldn't work legitimate caller (eg: proxy) is also using the same ip.

Java Servlet return error 405 (Method Not Allowed) for POST request

My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)
Here is my code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class init extends HttpServlet {
public init() { }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
out.print("POST");
}
}
This happened to me when my method call
"super.doGet(req, resp)" or "super.doPost(req, resp)" .
After i removed above super class calling from the doGet and doPost it worked fine.
Infact those super class calling codes were inserted by the Eclipse IDE template.
Are you sure that you actually override the doPost Method?
The signature looks like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
but you specify it like this:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, IllegalStateException
I am not sure whether this is allowed:
Overriding Java interfaces with new checked exceptions
Try the following steps:
Add the #Override Annotation
Remove the throws IllegalStateException (shouldn't be a problem as it is a runtime exception)

Cause of IllegalStateException: Cannot forward after response has been committed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java.lang.IllegalStateException: Cannot forward after response has been committed
What is the usual cause of this kind of error:
com.mycompany.myapp.servlet.TxnDetailsServlet doRequest
ERROR: View failed
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:312)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at com.mycompany.myapp.servlet.TxnDetailsServlet.doRequest(TxnDetailsServlet.java:82)
at com.mycompany.myapp.servlet.TxnDetailsServlet.doGet(TxnDetailsServlet.java:131)
The servlet process the request (i.e set attributes) then call:
private void doRequest(HttpServletRequest request) throws IOException, ServletException {
// Code omitted
getServletContext().getRequestDispatcher("/Some.jsp").forward(this.request, this.response);
// Code omitted
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
doRequest(request);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
doRequest(request);
}
The servlet does not do anything in reponse.
to add to what others said, response need not be transferred to client(browser) in a single shot. Instead it can be transferred to client in multiple shots as, whenever you call a response.flushBuffer . Once the response starts transferring data to client, you cant do anything that changes response state(setStatus, forward etc)
Don't write to the response output stream if you forward to another servlet/jsp.

Authenticate Google App users with Google OAuth2 API

I'm wondering if I can use the google client api (java) to authenticate the users of a google apps domain to my application.
The target application is a web application using a REST backend (jersey).
The documentation isn't very clear (or I misunderstood it), and the samples in the documentation refers to deprecated classes... Does someone knows if it's possible and the best way to do it.
A code sample would be appreciate.
Google Apps accounts should work fine with the APIs.
The only exception to this is if the service is disabled by the domain administrator. For example, if the Google+ feature is disabled by the domain administrator, you're not going to be able to access that user's Google+ data.
No code change is necessary, so you should be able to use the code from any of the samples in the client library repository or the product specific samples like this one for Google+.
The Google+ starter project implements the OAuth flow first by extending AbstractAuthorizationCodeServlet in com.google.api.sample.OAuth2AuthorizationCodeServlet
public class OAuth2AuthorizationCodeServlet
extends AbstractAuthorizationCodeServlet {
/**
* If the user already has a valid credential held in the
* AuthorizationCodeFlow they are simply returned to the home page.
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("/");
}
/**
* Returns the URI to redirect to with the authentication result.
*/
#Override
protected String getRedirectUri(HttpServletRequest request)
throws ServletException, IOException {
return ConfigHelper.REDIRECT_URI;
}
/**
* Returns the HTTP session id as the identifier for the current user.
* The users credentials are stored against this ID.
*/
#Override
protected String getUserId(HttpServletRequest request)
throws ServletException, IOException {
return request.getSession(true).getId();
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws ServletException,
IOException {
return Util.getFlow();
}
}
And then by completing the flow in com.google.api.sample.Oauth2CallbackServlet by extending AbstractAuthorizationCodeCallbackServlet:
public class OAuth2CallbackServlet
extends AbstractAuthorizationCodeCallbackServlet {
#Override
protected void onSuccess(HttpServletRequest request,
HttpServletResponse response, Credential credential)
throws ServletException, IOException {
response.sendRedirect("/");
}
#Override
protected void onError(HttpServletRequest req, HttpServletResponse resp,
AuthorizationCodeResponseUrl errorResponse)
throws ServletException, IOException {
resp.sendError(SC_INTERNAL_SERVER_ERROR, "Something went wrong :(");
}
#Override
protected String getRedirectUri(HttpServletRequest request)
throws ServletException, IOException {
return ConfigHelper.REDIRECT_URI;
}
#Override
protected AuthorizationCodeFlow initializeFlow()
throws IOException {
return Util.getFlow();
}
#Override
protected String getUserId(HttpServletRequest request) throws ServletException, IOException {
return request.getSession(true).getId();
}
}

Categories