open pdf in new window using spring controlle and ajax - ajax

I want to show the pdf file in new window.
Here is my code.
<c:if test="${noOfOwners>0 && empty isOwner && licenseBean.businessBean.ownershipType==1}">
<c:url value="/auth/newlicense/ownercertification?retailerId=${licenseBean.outletID}" var="ownerCertificationUrl"/>
<p class="label4">Owner Eligibility Certification</p>
<p>For your license application to be approved, you must provide the lottery with a signed Owner Eligibility Certification form. Each owner/officer included on the license application must sign the form, accepting the license eligibility standards, terms and conditions. Instructions on returning the form to the Texas Lottery via mail, fax and email are included on the form. To open a PDF version of the Owner Eligibility form, click on this link /link to form/. A PDF version of the form has also been sent to the email address you provided</p>
</c:if>
<script>
$(document).ready(function() {
$("#ownereligibilityForm").click(function(){
var retailerid = <c:out value='${licenseBean.outletID}'/>;
$.ajax({
url : "ownercertification",
type : "GET",
data : {
"retailerId" : retailerid
},success : function(link){
window.open(link,"_blank");
return false;
},error: function(){
}
});
});
});
</script>
my server side code
#RequestMapping(value = "/ownercertification", method = RequestMethod.GET)
public #ResponseBody String openOwnerEligibilityCertificationForm(HttpServletRequest request,HttpServletResponse response){
File file = new File("/var/lsp/licensing/21/output/"+request.getParameter("retailerId")+"/ownerEligibilityCertificationForm_"+request.getParameter("retailerId")+".pdf");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename="+file);
OutputStream out = null;
try{
byte[] b = new byte[(int)file.length()];
out = response.getOutputStream();
out.write(b);
out.flush();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out.toString();
}
But it is not opening the pdf file. I am getting the below error
HTTP Status 404 - /lsp/auth/newlicense/org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream[delegate=org.apache.catalina.connector.CoyoteOutputStream#266f266f]
Could anyone help me?

Related

What is the callback URL after calling repeat.vsp when using Form Integration?

I'm trying to do repeat payments with Form Integration in Sagepay (now Opayo).
From an earlier problem posted on here, I get that the securitykey is needed but is not returned in the Form call, so an additional call needs to be made to the getTransactionDetails command.
I have the securitykey and can now make a call to https://test.sagepay.com/gateway/service/repeat.vsp to initiate the repeat payment. However, the documentation does not say where the response to that call goes. I assume therefore, that it would go to the NotificationURL that is set up with a payment when using the Server or Direct integrations. Since I'm using Form, this is not set.
The question is, is there any way of capturing the response to the https://test.sagepay.com/gateway/service/repeat.vsp call if the initial payment was created using Form integration?
I suppose the second question is, has anybody successfully made repeat payments work with Sagepay Form integration?
Not sure if this helps you and we didn't do repeat payments; but we are looking at releasing deferred payments and I think it is a similar approach.
How do you make the call to 'https://test.sagepay.com/gateway/service/repeat.vsp'?
Could you use a 'HttpWebRequest' to make the call then capture the direct response in 'HttpWebResponse'?
EG:
private static void DeferredSharedApiCall(Dictionary<string, string> data, string type, string url)
{
string postData = string.Join("&", data.Select(x => $"{x.Key}={HttpUtility.UrlEncode(x.Value)}"));
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (TextWriter tw = new StreamWriter(request.GetRequestStream()))
{
tw.Write(postData);
}
HttpWebResponse response = null;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
//log.Error($"{type} Error, data: {postData}", ex);
}
catch (Exception ex)
{
//log.Error($"{type} Error, data: {postData}", ex);
}
if (response != null)
{
using (TextReader tr = new StreamReader(response.GetResponseStream()))
{
string result = tr.ReadToEnd();
//log.Info($"{type} Response: {Environment.NewLine}{result}");
}
}
}

corrupted PDF file downloaded from spring rest api

I am developing a rest end point to download a existing pdf file. I'm able to download PDF with size, but when I open, getting error as
'Adobe reader couldnot open it is either not supported file type or
because file has been damaged'.
I have noticed that in postman, response header content type is application/pdf;charset=UTF-8. I'm not sure if this is the cause.
With simple spring boot application I'm able to download, but in our project when I implement the same code, it is not working.
#GetMapping( path= "/s3/downloads")
public ResponseEntity<byte[]> downloadFile()
{
InputStream in = getClass().getResourceAsStream("/com/consulting/cloud/filetransfers/rest/template_attendance_en_green_full.pdf");
byte[] generatedCertificate = null;
String downloadFileName = "pdfFile1.pdf";
ResponseEntity<byte[]> responseEntity = ResponseEntity.status( HttpStatus.NO_CONTENT ).body( generatedCertificate );
try {
generatedCertificate = StreamUtils.copyToByteArray(in);
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.setContentType( MediaType.APPLICATION_PDF );
headers.setContentLength( generatedCertificate.length );
headers.setContentDispositionFormData( "attachment", downloadFileName );
responseEntity = ResponseEntity.ok().headers( headers ).body( generatedCertificate );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseEntity;
}
The file is opened as expected.

Server client communication using Javaservlets and JSP

I am trying to understand the aspects to build dynamic web application by referring many resources. I am facing issue while I am trying to communicate and pass the parameter from AJAX to java servlets and to JSP.
Please find the code below:
**HTML Code**:
<button onclick="viewcart()">ViewMyCart</button>
<script>
function viewcart(){
$.ajax({
type:"POST",
url:'./ShowCart',
});
}
</script>
**Servlet (ShowCart):**
try {
System.out.println("In ShowCart code");
LoginDB log=new LoginDB();
Connection con=log.connect();
String SQL="select * from bookname";
PreparedStatement prep=con.prepareStatement(SQL);
ResultSet rs=prep.executeQuery(SQL);
ArrayList<String> bookname=new ArrayList<String>();
while(rs.next()) {
bookname.add(rs.getString("name"));
}
System.out.println("bookname is"+bookname);
request.setAttribute("MyBookNames", bookname);
request.getRequestDispatcher("Display.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
**Display.JSP:**
<h1> Your cart </h1>
<%
ArrayList<String> booknames_list= (ArrayList)request.getAttribute("MyBookNames");
System.out.println("In JSP class Display");
System.out.println(booknames_list);
%>
</body>
</html>
Values are actually in booknames_list . But I wanted to display the values in a separate page. Can you all please guide me in achieving the same?
Thank you

Implement Antibot Captcha with Java Spring MVC using Thymeleaf and JQuery AJAX

I'm trying to implement Captcha with my Spring MVC application. Although there are some examples of how to do that, I couldn't find any where the form is submitted with JQuery AJAX and the template engine is Thymeleaf.
My main source of information is this.
I've added the dependencies and the servlet, but I'm struggling with the template part (where I'm using Thymeleaf and JQuery AJAX to send my form to the controller) and to do the validation in the controller.
I don't necessarily want to use Captcha as my antibot framework, so if you have any ideas using other framework, I would be more than glad to hear them.
Ok, so I ended up using Cage Captcha generator. It can be integrated with Maven and it's fairly easy to be implemented with a Spring MVC application with JQuery AJAX.
/**
* Generates captcha as image and returns the image path
* stores the captcha code in the http session
* and deletes older, unused captcha images.
*/
#RequestMapping(value = "/captcha/generate", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public ResponseEntity<CaptchaRequestData> generateCaptcha(HttpSession session) {
String captchaImageUploadDirectory = environment.getProperty("captcha_image_folder");
String captchaWebAlias = environment.getProperty("captcha_web_alias");
//Creating dir or making new one if it doesn't exist
File file = new File(captchaImageUploadDirectory);
if (!file.exists()) {
try {
file.mkdirs();
} catch(Exception e){}
}
String timeSuffix = DBUtils.getDateTimeAsString();
String fileName = CAPTCHA_IMAGE_PREFIX + timeSuffix + "." + CAPTCHA_IMAGE_EXTENSION;
String fullFilename = captchaImageUploadDirectory + fileName;
//Generating the captcha code and setting max length to 4 symbols
Cage currGcage = new YCage();
String captchaToken = currGcage.getTokenGenerator().next();
if (captchaToken.length() > CAPTCHA_CODE_MAX_LENGTH) {
captchaToken = captchaToken.substring(0, CAPTCHA_CODE_MAX_LENGTH).toUpperCase();
}
//Setting the captcha token in http session
session.setAttribute("captchaToken", captchaToken);
try {
OutputStream os = new FileOutputStream(fullFilename, false);
currGcage.draw(captchaToken, os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
deleteFilesOlderThan(captchaImageUploadDirectory, CAPTCHA_IMAGE_LIFE_MILLISECONDS, CAPTCHA_IMAGE_EXTENSION);
CaptchaRequestData data = new CaptchaRequestData(captchaWebAlias + fileName);
return new ResponseEntity<>(data, HttpStatus.OK);
}
Then when I'm creating the object I check if the given code equals the one, stored in the session:
if (!httpSession.getAttribute("captchaToken").equals(bindingData.getCaptchaCode())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Finally if the provided captcha is incorrect I generate a new one.

How to send email with attachments

I want to send an email with an image attached with it. I am using spring 3 with velocity templates. I am able to do that but for some reasons when I add an extension with the image name I don't get the email delivered.
Following is the code I am using for it:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
Using the code above I could add formstack1 as attachment but it has no extension so I don't get the formstack1.jpg image file. But when I use formstack1.jpg for the name of resource to be attached in helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); as formstack1 changed to formstack1.jpg I don't get even the email delivered. I am using smtp.gmail.com and 25 for port. I do get the email sent successfully message on the console though. But the email
is never delivered.
EDIT: If I keep it like helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); and change the extension from nothing to .jpg while downloading the attached image I do get the desired image.
Could someone help me understand why is it happening and how send email with 1 or more attachments using spring 3.
Thanks.
You should better use Apache Commons HtmlEMail
http://commons.apache.org/email/userguide.html

Resources