How to call the method in Java clicking on a link? - java

This is my servlet:
#WebServlet({ "/Response", "/reportsto" })
public class Response extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Response() {
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
services2 messageservice = new services2();
services3 jiraservice = new services3();
service4 empid = new service4();
String id = request.getParameter("ManagerId");
try {
String name="";
String id1 =empid.getEmpId(id);
System.out.println("id is ===> "+id1);
Map<Object, Object> map=messageservice.getReportees(id1);
Set<Map.Entry<Object,Object>> s1=map.entrySet();
for (Iterator<Map.Entry<Object,Object>> iterator = s1.iterator(); iterator.hasNext();) {
Map.Entry<Object,Object> entry = iterator.next();
Object name1 = entry.getKey();
Object value = entry.getValue();
PrintWriter out=response.getWriter();
out.println("<html><body><table>\r\n" +
"<tr>\r\n" +
"<th>User Id</th>\r\n" +
"<th>Username</th>\r\n" +
"</tr>\r\n" +
"<tr>\r\n" +
"<td>"+value+"</td>\r\n" +
"<td><a href=''>"+name1+"</a></td>\r\n" +
"</tr>\r\n" +
"</table></body></html>");
//how should I pass the object value to getJiras which accepts the strings.
}
I will get the output as:
User Id Username
AR12345 Anagha R
So If I click on Anagha the userid must be passed to the getJiras which has return type as Map Object and then It should process and display the
CHA-3603: Validating Release on the browser in the same page of the above output.
getJiras()
public class services3{
public Map<Object, Object> getJiras(String values) throws Exception {
String api = "https:*****";
String id = values;
String ext= "******";
String url = api+id+ext;
String name = "******";
String password = "********";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
System.out.println("Base64 encoded auth string: " + authStringEnc);
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
//here I am trying to parse the json data.
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(output);
JSONArray jsonarr_1 = (JSONArray) jobj.get("issues");
System.out.println("The total number of issues in validating release are:"+jsonarr_1.size());
Map<Object, Object> map=new HashMap<Object,Object>();
for(int i=0;i<jsonarr_1.size();i++){
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONObject jsonobj_2 = (JSONObject)jsonobj_1.get("fields");
JSONObject status1 = (JSONObject)jsonobj_2.get("status");
JSONObject issuetype = (JSONObject)jsonobj_2.get("issuetype");
Object obj1 = jsonobj_1.get("key");
Object obj2 = status1.get("name");
map.put(obj1, obj2);
}
return map;
}
Also how can I also display the json array size which is being printed in the browser.The problem is getting complicated day by day,Please help to solve this problem.Thanks in advance

You can create another servlet or use same servlet to make one more get request. That request will call to jira service.
Case 1: Create another servlet, it is similar to what you are doing
Case 2: You can custom your current servlet method doGet. Sample code is below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestAction = request.get("action");
if("detail".equals(requestAction)) {
services3 service = new services3();
//get result.
} else if("view".equals(requestAction)){
//your current code
}
//add result to response
}

Related

Calling Java EE REST service through jQuery AJAX by passing the parameters from input text box

I have an html code to create an input text box that accepts the input form user.And the parameters must be passed along with url to rest service.
This is my ajax call code:
$(function() {
var empid = document.getElementById("ManagerId").value;
$('#submit').click(function(){
$.ajax({
crossDomain : true,
type: "GET",
dataType: "json",
url: "http://localhost:8088/JirasTrackingApp/reporter/Reportees?empid="+empid,
success: function(result){
console.log(result);
document.write(empid.value);
}
});
});
This is my Service:
#Path("/Reportees")
public class ReporteesService {
ReporteeList reportee = new ReporteeList();
#GET
#Produces(MediaType.APPLICATION_JSON)
public Map<Object, Object> getList(String empid) throws Exception {
System.out.println("id is"+empid); //when I try to print the empid,it displays nothing
Map<Object, Object> map=reportee.getReportees(empid);
return map;
}
});
This is my getReportees() in ReporteeList class
public class ReporteeList {
public Map<Object, Object> getReportees(String idOfEmp) throws Exception {
System.out.println(idOfEmp);
String msg = "error";
String api = "https://connect.ucern.com/api/core/v3/people/";
String id = idOfEmp;
String ext = "/#reports";
String url = api + id + ext;
String name = "*********";
String password = "*********";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
System.out.println("Base64 encoded auth string: " + authStringEnc);
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
if (resp.getStatus() != 200) {
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
// JSONParser reads the data from string object and break each data into key
// value pairs
JSONParser parse = new JSONParser();
// Type caste the parsed json data in json object
JSONObject jobj = (JSONObject) parse.parse(output);
// Store the JSON object in JSON array as objects (For level 1 array element i.e list)
JSONArray jsonarr_s = (JSONArray) jobj.get("list");
Map<Object, Object> map = new HashMap<Object, Object>(); //error in this line
if (jsonarr_s.size() > 0) {
// Get data for List array
for (int i = 0; i < jsonarr_s.size(); i++) {
JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
JSONObject jive = (JSONObject) jsonobj_1.get("jive");
Object names = jsonobj_1.get("displayName");
Object userid = jive.get("username");
map.put(names, userid);
}
return map;
} else {
map.put("errorcheck", msg);
}
return map;
}
}
The value empid from the ajax call is not being taken by the service. And please tell me how to catch the parameters from the url and pass to the rest services.
You will also have to specify the #QueryParam annotation to your getList method:
#GET
#Produces(MediaType.APPLICATION_JSON)
public Map<Object, Object> getList(#QueryParam("empId") String empid) throws Exception {
System.out.println("id is"+empid); //when I try to print the empid,it displays nothing
Map<Object, Object> map=reportee.getReportees(empid);
return map;
}

How to call the html from the java servlet

Here is my code:
#WebServlet({ "/Response1", "/resp" })
public class Response1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int count=0;
int Number =1;
System.out.println("s val is ==> "+request.getParameter("empidVal"));
String s1 = request.getParameter("empidVal");
System.out.println(s1);
services3 empjiras = new services3();
try {
Map<Object, Object> map1 = empjiras.getJiras(s1);
Object obj3 = map1.get("obj3");
map1.remove("obj3");
System.out.println(obj3);
Collection c=map1.values();
String myvalue="";
for (Iterator iterator = c.iterator(); iterator.hasNext();)
{
myvalue = (String) iterator.next();
count++;
}
System.out.println(count);
int count1 = count;
if(count!=0)
{
Set<Map.Entry<Object,Object>> s2=map1.entrySet();
PrintWriter out1=response.getWriter();
out1.println("<html>"+
"<center><font size=\"20\"><body><h2>JIRA Details</h2></font>"+
//"<table border='1'>"+
"<table width=\"800\" border ='10'>\r\n" +
"<tr>\r\n" +
"<th><font size ='+2'>Number</font></th>"+
"<th><font size ='+2'>JiraNumber</font></th>"+
"<th><font size ='+2'>Jira Status</font></th>" +
"<th><font size = '+2'>EmailId</font></th>\r\n</center>"+
"<button type='ok' value='ok'>OK</button>" +
"<button type='cancel' value='cancel'>cancel</button>");
for (Iterator<Map.Entry<Object,Object>> iterator = s2.iterator(); iterator.hasNext();) {
Map.Entry<Object,Object> entry = iterator.next();
Object name2 = entry.getKey();
Object value2 = entry.getValue();
Object email = obj3;
int num = Number++;
PrintWriter out=response.getWriter();
out.println(
"</tr>\r\n" +
"<tr>\r\n" +
"<tr>\r\n" +
"<td height=\"100\">"+num+"</td>"+
"<td height=\"100\">"+name2+"</td>\r\n" +
"<td height=\"100\">"+value2+"</td>\r\n"+
"<td height=\"100\">"+email+"</td>\r\n"+
"</tr>\r\n");
}
out1.println("</table></body></html>");
}
else
{
PrintWriter out=response.getWriter();
// out.println("count is :"+count1);
out.println("<html><body><h2>no jira issues in validating release</h2></body></html>");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here i am embedding the html code in an servlet which I think is not a good practice,actually I am reading the objects from another servlet and then processing it and displaying it in the browser.But is there any way how to separate this html code from the servlet.
Thanks in advance..

HttpServletRequest.getParamter() return null in CXF Restful service(Post)

I wrote a Web API using Apache CXF. When I use HttpServletRequest.getParamter() in a post method, it return null.Here is the code:
#Path("/")
public class TokenService extends DigiwinBaseService {
private static void printRequest(HttpServletRequest httpRequest) {
System.out.println("\n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\n Parameters");
Enumeration params = httpRequest.getParameterNames();
while (params.hasMoreElements()) {
String paramName = (String) params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
private static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "null";
}
return "null";
}
#POST
#Consumes("application/x-www-form-urlencoded")
public Response Authorize(#FormParam("param") String param,
#FormParam("param2") String param2,#Context HttpServletRequest httpRequest) throws OAuthSystemException {
printRequest(httpRequest);
System.out.println("param:"+param);
System.out.println("param2:"+param2);
return Response.status(HttpServletResponse.SC_OK).entity("OK").build();
}
}
Here is the test code
public class HttpClientTest {
public static void main(String[] args) throws Exception{
String url4 = "/api/services/Test";
String host = "127.0.0.1";
HttpClient httpClient = new HttpClient();
httpClient.getHostConfiguration().setHost(host, 8080, "http");
HttpMethod method = postMethod(url4);
httpClient.executeMethod(method);
String response = method.getResponseBodyAsString();
System.out.println(response);
}
private static HttpMethod postMethod(String url) throws IOException{
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
NameValuePair[] param = {
new NameValuePair("param","param1"),
new NameValuePair("param2","param2"),} ;
post.setRequestBody(param);
post.releaseConnection();
return post;
}
}
Here is the print out :
Headers
content-type = application/x-www-form-urlencoded;charset=gbk
user-agent = Jakarta Commons-HttpClient/3.1
host = 127.0.0.1:8080
content-length = 26
Parameters
Row data
null
param:param1
param2:param2
Why the Parameters is null? How can i get post params using HttpServletRequest.getParamter()
CXF is consuming the POST data to fill the FormParams.
https://issues.apache.org/jira/browse/CXF-2993
The resolution is "won't fix". In the issue, they suggest to use a MultivaluedMap to recover all params, or use only the HttpServletRequest
Option 1
#POST
#Consumes("application/x-www-form-urlencoded")
public Response Authorize( MultivaluedMap<String, String> parameterMap, #Context HttpServletRequest httpRequest) throws OAuthSystemException {
//parameterMap has your POST parameters
Option 2
#POST
#Consumes("application/x-www-form-urlencoded")
public Response Authorize( #Context HttpServletRequest httpRequest) throws OAuthSystemException {
//httpRequest.getParameterMap() has your POST parameters

Unexpected Token L when printing a json object Using advanced rest chrome

Im using a servlet that connects to a database and prints out whether or not you are logged in or not, When using printWriter.write(JsonObject) i get the error in rest Unexpected Token L. I am using a tomcat server to host the data.
public class Login extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/employeedatabase";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
static Connection conn = null;
static Statement stmt = null;
static ResultSet rs;
static PrintWriter out;
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=UTF-8");
out = response.getWriter();
String email = request.getParameter("username");
String password = request.getParameter("password");
String result = "";
if(Validation.validateNull(email) && Validation.validateNull(password)){
if(!Validation.validateEmail(email))
{
result = "Invalid email";
}
if(databaseFuctions.Login(email,password))
{
result = "Login accepted";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
getFromDatabase("manager",email,request,response);
// getFromDatabase("qa",email,request,response);
// getFromDatabase("developer",email,request,response);
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
}
else if(!databaseFuctions.Login(email, password))
{
result = "Login invalid";
}}
else{
result = "No login/password entered";
}
out.write(result);
}
public static void getFromDatabase(String table,String email,HttpServletRequest request, HttpServletResponse response){
JSONObject JObject = new JSONObject();
ResultSet ds;
try {
ds = stmt.executeQuery("SELECT * from "+table+" where email = '"+email+"'");
while(ds.next())
{
int id = ds.getInt("id");
int salary = ds.getInt("salary");
String name = ds.getString("name");
String role = ds.getString("role");
String emailAddress = ds.getString("email");
String phone = ds.getString("phone");
JObject.put("id", id);
JObject.put("salary", salary);
JObject.put("name", name);
JObject.put("role", role);
JObject.put("email", emailAddress);
JObject.put("phone", phone);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
out.print(JObject.toString());
out.flush();
System.out.println(JObject.toString());
}
When printing in the system i get all the correct data, or checking the raw data from rest i get the correct data. But i dont quite understand why the printer is throwing the exception any help is amazing
Ok If the error is in the client is beacuse you are returning a mal formed JSON value, so you are returning something like that: { id: 13, name: "Name"}Login invalid then the first character the L is not valid for the JSON Syntax.
This is becuase you are writing in the response the json string from the method getFromDatabase out.print(JObject.toString()); and after the method call you add to the response the string result = "Login invalid"; out.write(result); that cause you have a invalid JSON.
One way to solve this is return the JSONObject from the method getFromDatabase, and add the put the result method in this object JObject.put("result", result) and the write the object to the response.

Passing value of variable from one method to another

This seems so easy, but I don't know why I'm having such difficulty with it...So in the getURL, I return the String "total". I'm trying to return the SAME value "total" already has in the method handleRequest. Suggestions? Thanks in advance!
public class Multiply implements Controller {
static int product;
private static String total;
public static String getURL(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
String[] item = queryString.split("&");
product = 1;
for (int i = 0; i < item.length; i++) {
String[] s = item[i].split("=");
String name = s[0];
String value = s[1];
int numValue = Integer.parseInt(value);
product = product * numValue;
}
total = "" + product;
return total;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Mess = total;
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}
You have a number of problems with your implementation of this. First, by declaring total static, all instances of this class will have the same value of total. If you're using a framework that creates your controller and reuses it, this could lead to problems because all instances of the class will be referring to and updating the same member field.
What you want is to have your getURL method to return the value of total and then call it from your handleRequest. getURL can be static because it relies on no non-static member fields. You should really rename getURL to getTotal or getTotalFromURL because that is what you're doing. What you're asking getURL to do is actually a side effect, and should be avoided as a practice.
public class Multiply implements Controller {
public static String getURLTotal(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
String[] item = queryString.split("&");
int product = 1;
for (int i = 0; i < item.length; i++) {
String[] s = item[i].split("=");
String name = s[0];
String value = s[1];
int numValue = Integer.parseInt(value);
product = product * numValue;
}
return Integer.toString(product);
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String Mess = Multiply.getURLTotal(request);
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}
total is a member variable to the class Multiply. You should have no problems accessing it from either method. Keep in mind that it is uninitialized. So unless you call getURL before handleRequest then total will not be assigned to any String and will give you an error.
Also, I would watch your capitalization in several areas.
edit: Just for clarification, you technically aren't passing a value from one method to another. You are accessing a shared member variable between two methods.

Categories