How to call the html from the java servlet - java

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..

Related

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

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
}

HttpRequest from asp.net client to java server which has error "the request was rejected because no multipart boundary was found"

asp.net client
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Image_Identify.aspx.cs"
Inherits="WebApplication.iva.Image_Identify" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<div>
<asp:Button ID="Button_Post" runat="server" Text="submit" OnClick="Button_PostWebRequest" />
</div>
</form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
namespace WebApplication.iva
{
public partial class Image_Identify : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string postUrl = "http://xxx/WebUploadHandleServlet";
string paramData = "E:\\1111.jpg";
string ret = string.Empty;
Encoding dataEncode = Encoding.UTF8;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "multipart/mixed";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button_PostWebRequest(object sender, EventArgs e)
{
}
}
}
java server
#WebServlet(asyncSupported = true, urlPatterns = { "/WebUploadHandleServlet" })
public class WebUploadHandleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final long MAXSize = 1024 * 1024 * 4 * 2L;// 4*2MB
private String filedir = null;// before
private String resdir = null;// after
/**
* #see HttpServlet#HttpServlet()
*/
public WebUploadHandleServlet() {
super();
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init...");
JNIDispatcher.getInstance();
filedir = config.getServletContext().getRealPath("WEB-INF/original_images");
resdir = config.getServletContext().getRealPath("WEB-INF/result_images");
File file1 = new File(filedir);
File file2 = new File(resdir);
if (!file1.exists() && !file2.exists()) {
System.out.println("create dir");
file1.mkdir();
file2.mkdir();
System.out.println("create success");
}
System.out.println("filedir=" + filedir);
System.out.println("resdir=" + resdir);
super.init(config);
}
/**
* #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 {
System.out.println("receive request");
double begin_time = System.currentTimeMillis();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//FileUpload upload = new FileUpload(factory);20161005
upload.setSizeMax(-1);
upload.setHeaderEncoding("utf-8");
ImageDispose disposer = new ImageDispose(filedir, resdir);
// response.setContentType("text/html");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String respondResult = null;
String filename = null;
try {
List<FileItem> items = upload.parseRequest(request);
if (items != null && !items.isEmpty()) {
System.out.println("items size:" + items.size());
double start_time = System.currentTimeMillis();
for (FileItem fileItem : items) {
filename = fileItem.getName();
String filepath = filedir + File.separator + filename;
System.out.println("file save path:" + filepath);
InputStream inputStream = fileItem.getInputStream();
respondResult = disposer.process(inputStream, filename);
inputStream.close();
fileItem.delete();
}
double end_time = System.currentTimeMillis();
System.out.println("JNI handle" + filename + "time:" + (end_time - start_time) + "ms");
System.out.println("total time:" + (end_time - begin_time));
}
out.write(respondResult);
} catch (Exception e) {
e.printStackTrace();
out.write("文件" + filename + "upload fail:" + e.getMessage());
}
System.out.println("finish!");
}
#Override
public void destroy() {
System.out.println("release JNI...");
JNIDispatcher.getInstance().releaseJNI();
super.destroy();
}
}
I have printed the result as below.
It seems that java server has received the http request but cannot resolve.
Hope for help!

servlet getParts() in uploading file

I have implemented drag & drop file uploading in jsp and servlet, but I have a problem. Here is a part of my upload.jsp code:
function dropUpload(event) {
var files = event.dataTransfer.files;
upload(files);
}
function upload(files) {
var formData = new FormData();
for (var i in files) {
formData.append('file[]', files[i]);
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.open("POST", "UploadServlet");
xhr.send(formData);
}
I use the getParts() method in my UploadServlet.java code to get the files that the user uploads, like below:
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath = "D:\\TEST";
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
response.getWriter().println(request.getParts().size());
for (Part part : request.getParts()) {
if(part.getContentType() == null) {
continue;
}
response.getWriter().println("Part name: " + part.getName());
response.getWriter().println("Size: " + part.getSize());
response.getWriter().println("Content Type: " + part.getContentType());
String fileName = extractFileName(part, response);
response.getWriter().println(fileName);
part.write(savePath + File.separator + fileName);
response.getWriter().println("already upload file:" + fileName);
response.getWriter().println("=============================================");
}
}
private String extractFileName(Part part,HttpServletResponse response) throws IOException {
String contentDisp = part.getHeader("content-disposition");
//response.getWriter().println(contentDisp);
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
But I can't understand that if I upload 2 files with upload.jsp,
the value of getParts().size() is 4; it means that I always have 2 more files than exactly what I upload, and the 2 external files name and contentType will be null, and it will cause an error in part.write().
My solution is use the if statement
if(part.getContentType() == null) {
continue; }
to ignore the null file.
Can somebody tell me why this happens?

NullPointer trying to retrieve an Integer value

I have a problem when retrieving data (an Integer value) between servlets, when I want to multiply the value retrieved. I have this function in my first servlet,
private int totalNumberOf(Map<String,Integer> cart) {
int counter = 0;
for (String key : cart.keySet())
counter += cart.get(key);
return counter;
}
And I also have the attribute for it (placed at the end of the doGet() method)...
req.setAttribute("quantity", new Integer(totalNumberOf(cart)));
, a function that gives me the total number of products that are in the cart, which updates the value every time I add something to the cart so when I finish buying I can get an updated value of the number of products that are currently in the cart.
The problem comes now, when I try to do the fictional checkout (because I just have a generic price for every type of product) and I have to multiply the number of items by the generic price (here's where the NullPointer shows up).
Here's the code of my second servlet,
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity;
int toPay;
int genericValue = 20;
quantity = (Integer) req.getAttribute("quantity");
toPay = quantity.intValue() * genericValue; // NullPointer
}
I've tried everything in every way but I can't get rid of that ugly NullPointer. Hope you can help me a bit with this...
UPDATE Servlet1
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida = "";
Map<String,Integer> carrito = null;
String articuloElegido = req.getParameter("producto");
HttpSession session = req.getSession();
if (session.isNew()) {
session.invalidate();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
dispatcher.forward(req, res);
}
else {
String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
if (session.getAttribute("carrito") == null) {
carrito = new HashMap<String,Integer>();
session.setAttribute("carrito",carrito);
mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
}
else {
carrito = (Map<String,Integer>) session.getAttribute("carrito");
mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
}
insertarEnCarrito(carrito, articuloElegido);
}
req.setAttribute("mensaje", mensajeBienvenida);
req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
req.setAttribute("cantidad", numeroTotalLibros(carrito));
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
dispatcher.forward(req, res);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
if (carrito.get(articulo) == null){
carrito.put(articulo, new Integer(1));
}
else {
int numeroArticulos = (Integer)carrito.get(articulo).intValue();
carrito.put(articulo, new Integer(numeroArticulos+1));
}
}
private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
String cestaEnHTML = "";
for (String key : carrito.keySet())
cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
return cestaEnHTML;
}
private int numeroTotalLibros(Map<String,Integer> carrito) {
int counterLibro = 0;
for (String key : carrito.keySet())
counterLibro += carrito.get(key);
return counterLibro;
}
}
Servlet2
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida;
String cestaDeLaCompraEnHTML;
mensajeBienvenida = (String) req.getAttribute("mensaje");
cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY>" + mensajeBienvenida + "<br>");
out.println(cestaDeLaCompraEnHTML + "<br>");
out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
out.println("Seguir comprando!</BODY></HTML>");
out.println("Anular Compra</BODY></HTML>");
out.println("Pagar Compra</BODY></HTML>");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Servlet3
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer cantidadLibro;
int pagar;
int valorLibro = 20;
Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
Usuario usuario = (Usuario) session.getAttribute("user");
cantidadLibro = (Integer) req.getAttribute("cantidad");
if (cantidadLibro == null){
cantidadLibro = 0;
} else {
cantidadLibro = (Integer) req.getAttribute("cantidad");
}
// pagar = cantidadLibro.intValue() * valorLibro;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
out.println("<br><p>Total a pagar por su compra - " + "<br>");
out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
out.println("<br><p>User ID - " + usuario.getId() + "<br>");
session.invalidate();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Besides the refactoring and optimisation that your code might need, the problem you are refering to is that your are setting the attribute "cantidad" to the request instead of the session.
In Servlet1, replace this
req.setAttribute("cantidad", numeroTotalLibros(carrito));
with this
session.setAttribute("cantidad", numeroTotalLibros(carrito));
And in Servlet3, replace this
cantidadLibro = (Integer) req.getAttribute("cantidad");
with this
cantidadLibro = (Integer) session.getAttribute("cantidad");
The reason is that you are forwarding your request from Servlet1 to Servlet2, and so in Servlet2 you can access the "forwarded" request and all its attributes, BUT Serlvet3 is called independently at a later stage. I guess that is when you press "Pagar" in the rendered HTML page. Therefore, you can no longer access those attributes via the request because it is a different request. You can instead access them via the session if you stored them there previously.
Hope this helps.
Have you ever heard about debugging tools?
Your quantity variable has null value, it could be because of abscense attribute quantity in request. That is why you got NPE: null * (primitive numeric constant) -> NullPointerException.
From your code it it looks like "quantity.intValue()" throws your null pointer because quantity is null. Try this:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity = 0;
int toPay;
int genericValue = 20;
if (req.getAttribute("quantity") != null) {
quantity = (Integer) req.getAttribute("quantity");
}
toPay = quantity.intValue() * genericValue;
}
Notice not only do I initialize quantity with a value of 0 (so that it is not null) I also add a null check to "req.getAttribute("quantity")" so that you do not assign null to quantity in the case where .getAttribute returns null.
It's likely that your getAttribute function returned null. Remember to do null checking in code. I suggest a if (quantity != null) check before you call .intValue()
Another possible solution would be to check what .getAttribute() returned instead of checking what quantity was set to. You could also give quantity a default value.
if (req.getAttribute("quantity") == null) {
quantity = 0;
} else {
quantity = (Integer) req.getAttribute("quantity");
}

Sending an XML Object via HTTP POST

We are students.
In our project,we want to send xml block,basically saml assertion,from one server to another server via http post method.
Can anyone help us out in sending the XML object from one servlet to another servlet where each servlet resides on two different computers in java.
/* here we are trying to send xml object(root) from one servlet to another servlet which resides on different pc... but dispatcher method isnt working in this case.*/
public class sp1serv extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,java.io.IOException
{
Connection c=null;
Statement s= null;
ResultSet rs = null;
String d=null;
int flag=0;
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Response response=null;
XMLObject root=null;
HttpSession session1=req.getSession();
System.out.println(session1.getAttribute("sAccessLevel"));
System.out.println(session1.getAttribute("sUserId"));
String eid=session1.getAttribute("sUserId").toString();
String[] str1 = {"response","attr",session1.getAttribute("sAccessLevel").toString(), session1.getAttribute("sUserId").toString() };
String filename= eid.concat(".xml");
try {
response=SAMLProtocol.passResponse(str1);
root=SAMLSignature.passSignature(response,filename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.setAttribute("SP1",root);
String abc="http://169.254.229.232:8080/sp_response_handler";
RequestDispatcher rd=getServletContext().getRequestDispatcher(abc);
rd.forward(req, resp);
break;
}
}
}
}}
/* this servlet is used for retrieving xml object(root) and parsing it..on another server.*/
public class sp1_response_handler extends HttpServlet {
private static final long serialVersionUID = 1L;
public sp1_response_handler() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Response resp=null;
//XMLObject resp=null;
resp=(Response) request.getAttribute("SP1");
int result=0;
//SAMLSignature verification=null;
try {
result=SAMLSignature.verify(resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(result==1){
List attributeStatements = resp.getAssertions().get(0).getAttributeStatements();
for (int i = 0; i < attributeStatements.size(); i++)
{
List attributes = ((AttributeStatement) attributeStatements.get(i)).getAttributes();
for (int x = 0; x < attributes.size(); x++)
{
String strAttributeName = ((XMLObject) attributes.get(x)).getDOM().getAttribute("Name");
List<XMLObject> attributeValues = ((Attribute) attributes.get(x)).getAttributeValues();
for (int y = 0; y < attributeValues.size(); y++)
{
String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
System.out.println(strAttributeName + ": " + strAttributeValue);
}
}
}
response.sendRedirect("SP1.jsp");
}
else
{
System.out.println("NOT a Valid Signature");
}
}}
If you are using spring, you can use RestTemplate. From the docs:
String uri = "http://example.com/hotels/1/bookings";
PostMethod post = new PostMethod(uri);
// create booking request content
String request = post.setRequestEntity(new StringRequestEntity(request));
httpClient.executeMethod(post);
if (HttpStatus.SC_CREATED == post.getStatusCode()) {
Header location = post.getRequestHeader("Location");
if (location != null) {
System.out.println("Created new booking at :" + location.getValue());
}
}
Something like that should work (with the parameters being a Map<String,String>):
StringBuffer data = new StringBuffer();
if (parameters != null && parameters.size() > 0) {
for (Entry<String, String> e : parameters.entrySet()) {
if (data.length() > 0) {
data.append('&');
}
data.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
}
}
String parametersAsString = data.toString();
// Send data
URL local_url = new URL(url);
URLConnection conn = local_url.openConnection();
conn.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(parametersAsString);
wr.flush();
break;

Categories