I want to write a .jsp (tomcat5.5) that calls a web service (IIS in domain). I get an HTTP Error 401 Unauthorized. It seems that in order to call the web service you have to be a domain user. I want to allow access to the jsp only to domain users. The request.getRemoteUser() in the jsp returns null but not the domain user that calls the jsp.
From a web browser I call the web service and it works fine.
I am a bit confused with this. Can someone tell me how can the issue be resolved?
Do i have to make tomcat make SSO?
Thank you for your time.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter o = response.getWriter();
o.println("sstarting...");
o.println("user.name ".concat(System.getProperty("user.name")));
o.println("request.getRemoteUser() ".concat(request.getRemoteUser()));
try {
GetUserRoles getUserRolesRequest = new GetUserRoles();
getUserRolesRequest.setApplicationId(121);
getUserRolesRequest.setUserName("user");
GetUserRolesResponse getUserRolesResponse;
ServiceStub stub =new ServiceStub() ;
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED,"false");
getUserRolesResponse = stub.getUserRoles(getUserRolesRequest); //IT FAILS HERE 401
String str =getUserRolesResponse.getGetUserRolesResult().toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
o.println(e.getMessage());
}
}
Related
I am trying to include several servlets in the main servlet to get finish some processs and retrieve values. In this example, I am receiving the control from a jsp file to the main servlet. After this servlet send call to the next servlet to carry out an operation related to a Java List and after returns the control to the main servlet. However, I am not able to recover the value of this List. How can I recover values from servlets that I am calling from the main servlet? The part of source code is the next:
(Main Servlet)
DeletePolicy.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
//create an object of RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("GetPolicy");
// send the client data available with req of delete to req of getPolicy with include()
rd.include(request, response);
// To receive the parameter from the second servlet
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
printWriter.print("List of books in Delete: ");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
printWriter.print("I am comming back in Delete to send a request to Delete method");
/*ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
delete(ClientResponse.class,input);
printWriter.print("Delete a policy");*/
}
/* Include solution provided by Jozef Chocholacek: request.setAttribute("policies", policies);
GetPolicy.java(Second Servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
printWriter.println("<u>Searching for current policies...</u><br>");
ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
get(ClientResponse.class);
//ClientResponse rs = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class,input);
/*Transform json to java object*/
String jsonPolicy=rs.getEntity(String.class);
Gson gson = new Gson();
Policy[] PolicyA = gson.fromJson(jsonPolicy, Policy[].class);
List<Policy> policies = Arrays.asList(PolicyA);
for(Policy policy : policies) {
System.out.println(policy.getId()+" "+policy.getMax_books()+", "+policy.getYear_book()+", "+policy.getActivate()+", ");
}
//Send List to the servlet that is calling
request.setAttribute("policies", policies);
/*Display book list in the servlet*/
printWriter.println("<h1>List of Policies</h1>");
if (policies.isEmpty()){
printWriter.println("<html><body>Sorry, we did not have any policy"+"<br>");
}else{
printWriter.println("<html><body>The complete list of policies: <br>");
printWriter.println("<ul>");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
}
printWriter.println("</body></html>");
}
Thank you in advance
Cheers
Well, in your first servlet (DeletePolicy.java) you use
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
but the second servlet (GetPolicies.java) does not store this list into request. You have to add
request.setAttribute("policies", policies);
into your second servlet.
I want to know is there any way to forward servlet request and response from a rest webservice to a servlet..
I have a servlet on remote server from which i am calling webservice to get the request params and then i want it to forward to another servlet from that webservice.I tried some code but it does not work. Please give me suggestions if anyone had worked on it.
this is my rest web code snippet
#GET
#Path("/test")
public void requestToTelkom(#Context HttpServletRequest request,#Context HttpServletResponse response ) {
try {
// the request object is printed successfully
System.out.println(request);
// when i try to forward like this i get exceptions
RequestDispatcher rd = request
.getRequestDispatcher("BypassServlet");
rd.forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got this exception with above code
UT010023: Request io.undertow.servlet.spec.HttpServletRequestImpl#53b21177 was not original or a wrapper
For future visitors looking for a solution. This is what helped me on a jboss eap 7 server..add allow-non-standard-wrappers="true" to your standalone.xml file in the servlet container like this:
<servlet-container name="default" allow-non-standard-wrappers="true">
<jsp-config/>
<websockets/>
</servlet-container>
Am doing the JAVA code found below, to call the servlet doGet() method from JSP page through AJAX call.
Here is my AJAX call..
Am sending the clicked text captured by ng-click of Angular js as a querystring to Servlet's doGet() method .
In my JSP file,
$scope.requestFunc = function (clickData) {
var urlquerystring = clickData;
jQuery.ajax({
type: 'GET',
url: "/Charts/testExecution/"+"?"+ urlquerystring,
dataType: 'html',
success: function(respnsedata)
{
window.location.assign(respnsedata);
}
});
}
In my Servlet's doGet() method,
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.err.println("In TestExecutionESO servlet..");
String teamnametextfield= req.getParameter("teamnametextfield");
System.out.println("Teamname is.."+teamnametextfield);
try {
dcmanager = DataCollectorManager.getInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String selectedteam= req.getQueryString();
String testexeclistofobjectsjson = null;
if(selectedteam!=null)
{
String release=selectedteam.replace("%20"," ").toString();
testexecutionobjlist = dcmanager.getRallyDcMgr().gettestExecutionobjlist(release);
}
Gson gson = new Gson();
testexeclistofobjectsjson = gson.toJson(testexecutionobjlist);
System.out.println(testexecutionobjlist);
System.out.println(testexeclistofobjectsjson);
req.getSession().setAttribute("testexeclistofobjectsjson", testexeclistofobjectsjson);
resp.sendRedirect("TestExecutionESO.jsp");
}
Am getting the querystring perfectly..After the processing, I will do SetAttribute() and redirect to next JSP page..
Redirect is not working..
Here is my error code,
Failed to load resource: net::ERR_TOO_MANY_REDIRECTS..
http://10.112.81.95:9000/Charts/testExecution/TestExecutionESO.jsp.... Failed to load resource: net::ERR_TOO_MANY_REDIRECTS
Please help me resolve the problem..
how to redirect to next JSP page by doing the setAttribute() .??
resp.sendRedirect("TestExecutionESO.jsp");
This is the culprit in your code. when you call sendRedirect(), it will issue a 302 response containing the location-header, URI of the new resource. When the browser sees this header, it will issue a new request for that new URI.
All of this works well for a synchronous request but in case of AJAX calls, we use an XMLHttpRequest, which will not handle redirects so well.
I'd suggest you to use a RequestDispatcher instead to forward to the JSP like this
RequestDispatcher rd = req.getRequestDispatcher("path-to-ur-jsp");
rd.forward(req,res);
I am trying to developing Facebook API using Facebook4J. It is success to get access_token from facebook as flow.
#RequestMapping(value="biztopia.facebook.redirectLogin.do")
public void redirectLogin(ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String code = request.getParameter("code");
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
String oauthCode = request.getParameter("code");
try {
facebook.getOAuthAccessToken(oauthCode);
AccessToken token = facebook.getOAuthAccessToken();
response.sendRedirect("biztopia.facebook.requestUserInfo.do");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#RequestMapping(value="biztopia.facebook.requestUserInfo.do")
public void requestUserInfo(ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
try {
User user = facebook.getMe();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Recieved excetion message as flow
FacebookException{statusCode=400, response=HttpResponse{statusCode=400, responseAsString='{"error":{"message":"API calls from the server require an appsecret_proof argument","type":"GraphMethodException","code":100}}
', is=sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#446f4515, streamConsumed=true}, errorType='GraphMethodException', errorMessage='API calls from the server require an appsecret_proof argument', errorCode=100, errorSubcode=-1}
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93)
at facebook4j.FacebookImpl.get(FacebookImpl.java:2431)
at facebook4j.FacebookImpl.getMe(FacebookImpl.java:105)
at facebook4j.FacebookImpl.getMe(FacebookImpl.java:101)
at biztopia.facebook.web.FacebookController.requestUserInfo(FacebookController.java:292)
I found the solutions.
That is append appsecret_proof parameter at call API as "http://graph.facebook.com/me?access_token={access_token value}$appsecret_proof={appsecret_proof value}.
If you are no want append appsecret_proof parameter then you can change set to no use appsecret_proof paameter on your app management site.
The management site menu is setting>advanced>Require AppSecret Proof for Server API calls -> set to disabled.
I have a web application with a simple upload function. The idea is to allow user select a file and upon successfully upload, redirect to index.jsp.
However, although the file got uploaded, the response.redirect is not working. After a successfully upload, the page doesn't get redirected. It just stays there. The weird thing is that I can see it is processing the index.jsp from the tomcat server log even though it doesn;t get redirected.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
boolean status=false;
if (!ServletFileUpload.isMultipartContent(request)) {
throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
}
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
try {
List<FileItem> items = uploadHandler.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
File file = new File(getServletContext().getRealPath("/WEB-INF/upload"), item.getName());
item.write(file);
writer.write("{\"name\":\"" + item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");
}
}
//redirect to index.jsp if successfully
redirect(request, response);
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
writer.close();
}
}
The redirect method:
private void redirect(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
The file upload plugin is from https://aquantum-demo.appspot.com/file-upload
I used the front-end and developed the upload event handler using java apache fileupload. Everything works fine except the redirect part.
The application.js file which handles the JSON returns:
$(function () {
// Initialize jQuery File Upload (Extended User Interface Version):
$('#file_upload').fileUploadUIX();
// Load existing files:
$.getJSON($('#file_upload').fileUploadUIX('option', 'url'), function (files) {
var options = $('#file_upload').fileUploadUIX('option');
options.adjustMaxNumberOfFiles(-files.length);
$.each(files, function (index, file) {
options.buildDownloadRow(file, options)
.appendTo(options.downloadTable).fadeIn();
});
});
});
Any ideas?
You're attempting to send two responses on a single request. One with JSON data in the response body and one which redirects the response to another request. This is not going to work. You can send only one response back per request. A redirect requires an untouched (uncommitted) response body, otherwise the redirect will just fail with IllegalStateException: response already committed in the server logs.
You need to move the redirect call from the servlet code to JavaScript code. Get rid of the redirect() line in the servlet and add the following line as the last line of the $.getJSON() callback function.
window.location = '/index.jsp';
This way JavaScript will take care of the redirect.