JavaScript alerts ???? for UTF-8 with spring? - java

I am doing a sample application for UTF-8 with Spring to support multi-language .
This is my JSP with Script ,
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Test</h1>
<input type="text" id="hide" />
<input type="text" id="message"/>
<button id="button">test</button>
<div id="messageDisplayArea"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var contexPath = "<%=request.getContextPath() %>";
</script>
<script>
$('#button').on('click', sendMessage);
function sendMessage() {
var intxnId = $("#hide").val();
var message = $("#message").val();
alert("send : \n intxnId : " + intxnId + "\nmessage : " + message);
$.ajax({
type: "POST",
cache: false,
url: contexPath + "/test.html",
async: true,
data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
//dataType: "json",
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8",
success: function(response) {
alert(response);
alert(response.message);
if (response !== null && response !== "" && response !== "null") {
var txt = '{"data":[' + response + ']}';
var json = eval("(" + txt + ")");
for (i = 0; i < json.data.length; i++) {
var data = json.data[i];
var name = data.name;
var message = data.message;
var time = data.time;
alert("Name : " + name + "\nMessage : " + message + "\ntime : " + time);
var createHTML = send(name, message, time);
$("#messageDisplayArea").append(createHTML);
}
;
}
},
error: function(e) {
alert('Error: ' + e);
},
});
function send(name , message , time){
var user = "<div id='user' class='fontStyle'>"+name+"</div>";
var msg = "<div id='msg' class='fontStyle'>"+message+"</div>";
var timeStamp = "<div id='time' class='fontStyle'>"+time+"</div>";
var row = "<div id='msgSet' >"+ user + msg + timeStamp +"</div>";
return row;
}
}
</script>
</body>
</html>
My Spring controller will be ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
String contentType = "application/json; charset=utf-8";
response.setContentType(contentType);
try {
// request.setCharacterEncoding("utf-8");
request.setCharacterEncoding("application/json; charset=utf-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
My Controllers prints ,
Send Message UTF-8 ----------------- தமிழ் அரிச்சுவடி
Send Message :::::::: : {"message":"தமிழ் அரிச்சுவடி","time":"time","name":"test"}
In this my controller prints the local language . But in the JQuery success alert , I got message as ???? . I need to append the local language text in my JSP .
Hope our stack members will help me.

Following piece of code should solve your issue.
#RequestMapping(value="<your path>",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(#RequestParam String intxnId, #RequestParam String message) {
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
This will produce UTF-8 ajax response.
Add mimeType:"application/json; charset=UTF-8" in jQuery.

I got the solution by changing the Controller as ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public ResponseEntity<String> sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

Related

How can I develop two call ajax by clicking two different button of same JSP page where controller is different?

I am developing an employee registration form in spring. I have used two ajax call, one is for employee information and other one is for upload e file(image)and store them in a specific folder in single jsp page and single controller.Here is my jsp page:
function onuploadCall(){
var file = $('[name="file"]');
console.log(file);
var filename = $.trim(file.val());
console.log(filename);
//var imgContainer = $('#imgContainer');
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
$.ajax({
url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
type: "POST",
async:true,
data: formData,
enctype: "multipart/form-data",
processData: false,
modelAttribute:'uploadedFile',
contentType: true,
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
/* }).done(function(data) {
// imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
alert("success");
// imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
}); */
}
function madeAjaxCall(){
array();
var gender = $('#gender').val();
var blood = $('#blood').val();
$.ajax({
type: "post",
url: "http://localhost:8080/EmployeeRegistrationForm/employee",
cache: false,
async:false,
data:'name=' + $("#name").val()
+"&fname=" + $("#fname").val()
+"&mname=" + $("#mname").val()
+"&nid=" + $("#nid").val()
+"&age=" + $("#age").val()
+"&blood=" + blood
+"&gender=" + gender
+"&caddress=" + $("#caddress").val()
+"&paddress=" + $("#paddress").val()
+"&paddress=" + $("#paddress").val()
+"&pdegree=" + $("#pdegree").val()
+"&puniversity=" + $("#puniversity").val()
+"&pyear="+ $("#pyear").val()
+"&presult=" + $("#presult").val()
+"&mdegree=" + $("#mdegree").val()
+"&muniversity=" + $("#muniversity").val()
+"&mresult=" + $("#mresult").val()
+"&myear=" + $("#myear").val()
+"&bdegree=" + $("#bdegree").val()
+"&buniversity=" + $("#buniversity").val()
+"&bresult=" + $("#bresult").val()
+"&byear=" + $("#byear").val()
+"&hdegree=" + $("#hdegree").val()
+"&college=" + $("#college").val()
+"&hresult=" + $("#hresult").val()
+"&hyear=" + $("#hyear").val()
+"&sdegree=" + $("#sdegree").val()
+"&school=" + $("#school").val()
+"&sresult=" + $("#sresult").val()
+"&syear=" + $("#syear").val()
+"&date=" + $("#date").val()
+"&department=" + $("#department").val()
+"&location=" + $("#location").val()
+"&company=" + company
+"&from=" + from
+"&to=" + to
+"&year=" + year
+"&organization=" + organization
+"&topic=" + topic
+"&duration=" + duration,
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
}
Here is my controller:
#Controller
public class imageUploadController {
#RequestMapping(value = "/echofile",method = RequestMethod.POST)
public #ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response , #ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile multipartFile = request.getFile("file");
MultipartFile file = upldfile.getFile();
String fileName = multipartFile.getOriginalFilename();
System.out.println("vcvvvvvvvv"+fileName);
upldfile.setFile(file);
Long size = file.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
inputStream = file.getInputStream();
File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
// byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
But this shows the error:
EVERE: Servlet.service() for servlet [dispatcher] in context with path
[/EmployeeRegistrationForm] threw exception [Request processing
failed; nested exception is
org.springframework.web.bind.annotation.support.HandlerMethodInvocationException:
Failed to invoke handler method [public java.util.HashMap
EmployeeRegistrationForm.controller.imageUploadController.echoFile(org.springframework.web.multipart.MultipartHttpServletRequest,javax.servlet.http.HttpServletResponse,EmployeeRegistrationForm.model.UploadedFile)
throws java.lang.Exception]; nested exception is
java.lang.IllegalStateException: Current request is not of type
[org.springframework.web.multipart.MultipartHttpServletRequest]:
org.apache.catalina.connector.RequestFacade#618dfe29] with root cause
java.lang.IllegalStateException: Current request is not of type
[org.springframework.web.multipart.MultipartHttpServletRequest]:
org.apache.catalina.connector.RequestFacade#618dfe29
Here is my dispatch-servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="EmployeeRegistrationForm.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
Why it shows this error???When I input text data, it has been called an ajax call in controller /employee, it works.but when I am trying to upload a file and call ajax by clicking upload button in same jsp page and in same controller /echofile-it shows this error. Where is the problem?
Here is full jsp page
I have changed few things on my project. On jquery:
function uploadImage() {
var file = $('[name="file"]');
//var imgContainer = $('#imgContainer');
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
type: "POST",
data: new FormData(document.getElementById("fileForm")),
//data: formData,
enctype: 'multipart/form-data',
processData: false,
aync: false,
modelAttribute:'uploadedFile',
headers: {'Content-Type': 'multipart/form-data'},
contentType: false,
/* }).done(function(data) {
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
alert("success");
}).fail(function(jqXHR, textStatus) {
alert('File upload failed ...');
}); */
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
}
and my controller is:
#RequestMapping(value = "/echofile",method = RequestMethod.POST)
public #ResponseBody HashMap<String, Object> echoFile(HttpServletRequest request,
HttpServletResponse response , #ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
if(request instanceof MultipartHttpServletRequest){
InputStream inputStream = null;
OutputStream outputStream = null;
// MultipartFile multipartFile = request.getFile("file");
MultipartFile file = upldfile.getFile();
String fileName = file.getOriginalFilename();
System.out.println("vcvvvvvvvv"+fileName);
upldfile.setFile(file);
Long size = file.getSize();
String contentType = file.getContentType();
InputStream stream = file.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
inputStream = file.getInputStream();
File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] byt = new byte[1024];
while ((read = inputStream.read(byt)) != -1) {
outputStream.write(byt, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map;
}
This is my full jsp page

Spring MVC storing files at RestService

Hi I am struggling in storing files at server I am new to spring MVC. Can anyone point me if I am doing it right or wrong.
What I have to do is take some files (text or binary) and store those in the storage device using Restservice.
public #ResponseBody String storeFiles(#RequestBody List<File> filenames, #PathVariable String dirname)
throws Exception {
// TODO Auto-generated method stub
Gson gson = new Gson();
String jsonList = gson.toJson(storeFiles.storeFilesToHitachi(filenames, dirname));
return jsonList;
}public Map<String, Integer> storeFilesToHitachi(List<File> filenames,String dirname) throws Exception{
Map<String, Integer> resultStored = new HashMap<String, Integer>();
if(checkDirAvailable(dirname) || createDirectoryAtHitachi(dirname)){
resultStored = storeFilenamesAtHitachi(filenames, dirname);
}
return resultStored;
}
public boolean createDirectoryAtHitachi(String dirname){
boolean isDirCreated = false;
try{
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCreateDir(dirname);
httpPutRequest.setURI(hitachiURI);
HttpResponse httpCreateDirResp = httpClient.execute(httpPutRequest);
int responseCode = httpCreateDirResp.getStatusLine().getStatusCode();
if(responseCode == 201) {
isDirCreated = true;
logger.info("A directory by the name "+ dirname +" has been created" );
}
logger.info(responseCode);
}
catch(Exception e){
logger.error("Unable to create directory:" + dirname + e.getMessage());
}
return isDirCreated;
}
public boolean checkDirAvailable(String dirname){
boolean dirAvailable = false;
try{
httpGetRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCheckDir(dirname);
httpGetRequest.setURI(hitachiURI);
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
int respCode = httpResponse.getStatusLine().getStatusCode();
if (respCode == 200){
dirAvailable = true;
logger.info("A directory named "+dirname +" is avaliable");
}
logger.info(respCode);
}
catch(Exception e){
logger.error("An exception occured while checking for "+dirname + e.getMessage());
}
return dirAvailable;
}
public Map<String, Integer> storeFilenamesAtHitachi(List<File> filenames,String dirname){
Map<String,Integer> resultMap = new HashMap<String, Integer>();
try{
File filename=null;
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
Iterator<File> iter = filenames.iterator();
while(iter.hasNext()){
filename = iter.next();
hitachiURI = constructURLForStorFilesAtHitachi(dirname, filename);
httpPutRequest.setURI(hitachiURI);
receivedFile = new FileInputStream(filename);
httpPutRequest.setEntity(new InputStreamEntity(receivedFile, -1));
HttpResponse httpPutResponse = httpClient.execute(httpPutRequest);
int respCode = httpPutResponse.getStatusLine().getStatusCode();
resultMap.put(filename.getName(), respCode);
logger.info(resultMap);
logger.info("Response code is :"+respCode +" while saving " +filename +" in directory " +dirname);
}
}
catch(Exception e){
logger.error("Got the following exception while storing files:" +e.getMessage());
}
return resultMap;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Error 415--Unsupported Media Type</TITLE>
</HEAD>
<BODY bgcolor="white">
<FONT FACE=Helvetica><BR CLEAR=all>
<TABLE border=0 cellspacing=5><TR><TD><BR CLEAR=all>
<FONT FACE="Helvetica" COLOR="black" SIZE="3"><H2>Error 415--Unsupported Media Type</H2>
</FONT></TD></TR>
</TABLE>
<TABLE border=0 width=100% cellpadding=10><TR><TD VALIGN=top WIDTH=100% BGCOLOR=white><FONT FACE="Courier New"><FONT FACE="Helvetica" SIZE="3"><H3>From RFC 2068 <i>Hypertext Transfer Protocol -- HTTP/1.1</i>:</H3>
</FONT><FONT FACE="Helvetica" SIZE="3"><H4>10.4.16 415 Unsupported Media Type</H4>
</FONT><P><FONT FACE="Courier New">The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.</FONT></P>
</FONT></TD></TR>
</TABLE>
</BODY>
</HTML>
My goal is to take list of files and store in particular directory at server.

Register a Facebook user on Parse

I'm implementing facebook login on my webapp.
I receive the access token, I know the email and everything is fine.
But I can't register the user on Parse database.
I made a java bean which has userId, userName, userEmail and token.
I put these in a form, that should be sent to Parse.
/*--------------------------FORM FACEBOOK ----------------------------*/
final TextField<String> userId = new TextField<>("userId");
final TextField<String> userName = new TextField<>("userName");
final TextField<String> userEmail = new TextField<>("userEmail");
final TextField<String> token = new TextField<>("token");
model = new CompoundPropertyModel<>(new FacebookLoginForm());
form = new Form<FacebookLoginForm>("tokenForm", model)
{
#Override
protected void onSubmit()
{
ParseUser pu = new ParseUser();
pu.setUsername(model.getObject().getUserName());
pu.setEmail(model.getObject().getUserEmail());
/*METHOD FOR PARSE*/
curlParse(model.getObject().getToken(), model.getObject().getUserId());
}
};
add(form);
form.add(userId);
form.add(token);
form.add(userName);
form.add(userEmail);
Parse curlParse():
public void curlParse(String token, String id)
{
try
{ Date exp = new Date();
exp.setTime(exp.getTime()+7200000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd'T'HH:MM:ss.SSS'Z'"); /*2012-02-28T23:49:36.353Z Data format*/
String sExp = sdf.format(exp);
Request.Post("https://api.parse.com/1/users")
.addHeader("X-Custom-header", "stuff")
.bodyString(
"{"
+ " \"authData\": { "
+ " \"facebook\": {"
+ " \"id\": \""+ id +"\","
+ "\"access_token\": \""+ token +"\","
+ " \"expiration_date\": \""+sExp+"\""
+ " }"
+ "}"
+ "}", ContentType.APPLICATION_JSON
)
.execute().returnContent().asString();
} catch (IOException ex)
{
Logger.getLogger(Login2.class.getName()).log(Level.SEVERE, null, ex);
}
}
Since I need an absolute path to login user via facebook, I cannot use debug and there aren't any exceptions in the log(Tomcat) file.
I tried to translate from the cURL to java, but it doesn't seem to work.
Where is my mistake?
Thank you.
On html
<form id="tokenForm" wicket:id="tokenForm" >
<input type="text" id="token" wicket:id="token" name="token"/>
<input type="text" id="userId" wicket:id="userId" name="userId"/>
<input type="text" id="userName" wicket:id="userName"
<input type="text" id="userEmail" wicket:id="userEmail" name="userEmail"/>
<input type="submit"id="facebookSubmit" wicket:id="facebookSubmit" name="facebookSubmit">
</form>
On js:
function login() {
openFB.login(
function (response) {
if (response.status === 'connected') {
getInfo();
document.getElementById("token").value = response.authResponse.token;
} else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
function getInfo() {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
document.getElementById("userId").value = data.id;
document.getElementById("userEmail").value = data.email;
document.getElementById("userName").value = data.first_name;
document.getElementById("userSurname").value = data.last_name;
document.getElementById("facebookSubmit").click();
},
error: errorHandler});
}
on java:
public void curlParse(String token, String id)
{
try
{
Date exp = new Date();
exp.setTime(exp.getTime() + 7200000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); /*2012-02-28T23:49:36.353Z */
String sExp = sdf.format(exp);
String resp = Request.Post("https://api.parse.com/1/users")
.addHeader("X-Parse-Application-Id", CWSApplication.getParseDotComApplicationID())
.addHeader("X-Parse-REST-API-Key", CWSApplication.getParseDotComApplicationKey())
.addHeader("Content-Type", "application/json")
.bodyString(
"{"
+ " \"authData\": { "
+ " \"facebook\": {"
+ " \"id\": \"" + id + "\","
+ "\"access_token\": \"" + token + "\","
+ " \"expiration_date\": \"" + sExp + "\""
+ " }"
+ "}"
+ "}", ContentType.APPLICATION_JSON
)
.execute().returnContent().asString();
/*System.out.println(ResponseParse);*/
CWSSession session = (CWSSession) getSession();
ParseUser loggedUser = new ParseUser();
/*questo con la libreriagson ci legge il JSON che ha i dati che ci servono da mettere su Parse*/
try
{
JsonReader reader = new JsonReader(new StringReader(resp));
reader.beginObject();
while (reader.hasNext())
{
String name = reader.nextName();
if (name.equals("objectId"))
{
loggedUser.setObjectId(reader.nextString());
} else if (name.equals("sessionToken"))
{
loggedUser.setSessionToken(reader.nextString());
} else
{
reader.skipValue(); //avoid some unhandle events
}
}
reader.endObject();
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
}

How to write PDF to client using JSON

I'm trying to write a PDF to the client dynamically using servlet/JSP and jquery. Here is what I have so far:
SERVLET
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static MimetypesFileTypeMap mtp = new MimetypesFileTypeMap();
public IndexServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Sysout of doGet from IndexServlet");
////INIT OF VARs
int pdfNum,
pdf;
String[] currentBatch;
String
mimeType = null,
fileID = null,
rtn = null,
docSelect = null,
docNumber = null,
docType = null,
batchName = null,
event = request.getParameter("EVENT"),
pendDir = "\\\\****\\****\\****\\****\\****\\****\\****";
///////////////////
if(event.equals("LOAD")){
System.out.println("You're now in the LOAD portion of the doGet");
PdfInit p = new PdfInit();
Batch b = p.getBatch();
currentBatch = b.pdfFiles;
batchName = b.batchName;
pdfNum = b.pdfNum;
Gson gson = new Gson();
String json = gson.toJson(b);
System.out.println(json);
response.setContentType("application/json");
response.getWriter().write(json);
}else if(event.equals("GETPDF")){
System.out.println("You're now in the GETPDF portion of the doGet");
PdfInit p = new PdfInit();
Batch b = p.getBatch();
currentBatch = b.pdfFiles;
batchName = b.batchName;
pdfNum = b.pdfNum;
pdf = Integer.parseInt(request.getParameter("id"));
String fileName = pendDir + "\\" + batchName + "\\" + currentBatch[pdf];
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayDataSource bais = new ByteArrayDataSource(bis, mimeType);
byte [] pdfArray = bais.toByteArray();
String encoded = DatatypeConverter.printBase64Binary(pdfArray);
Gson gson = new Gson();
String json = gson.toJson(encoded);
response.setContentType("application/json");
response.getWriter().write(json);
response.getOutputStream().flush();
response.getOutputStream().close();
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO- 8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="/Indexer/_js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/Indexer/_js/jquery.form.js"></script>
</head>
<body>
<input type="button" value="Load Batch" id="LoadBatchBtn">
<p id="batchName"><b>Batch Name:</b> </p>
<p>Click on a document to view it.</p>
<ol id="pdfList"></ol>
<div id="pdfDiv"></div>
</body>
</html>
<script>
$(document).ready(function(){
$("#LoadBatchBtn").click(function(){
$.getJSON("IndexServlet", {"EVENT": "LOAD"}, function(data) {
$("#batchName").append(data.batchName);
for(var i = 0; i < data.pdfNum; i++ )
{
$("#pdfList").append("<li id=" + i + ">" + data.pdfFiles[i] + "</li>");
}
$("li").click(function(){
$("#pdfDiv").hide();
$.getJSON("IndexServlet", {id: this.id, "EVENT":"GETPDF"}, function(data){
var decodedData = window.atob(data);
$("#pdfDiv").html(decodedData).show();
});
});
});
});
});
</script>
Right now I am not getting anything at all on the JSP. However in the console I can see the base64 string being passed without issue. I know I most likely need to take this one step further, but I am not sure where to go from here.
EDIT
Okay now I am getting string output in the div. How can I turn this into data that the browser reads as a PDF?

Phonegap Plugin Behaving in a strange manner

I have implemented Phonegap Plugins for v1.0.0.
Please have a look at my HTML code
/**** HTML FILE ****/
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum- scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="system.js"></script>
<script type="text/javascript">
var uname = "User1"; //------------- 2
var System = function() {};
System.prototype.func = function(funcname,funcdata) {
//alert("In the list function");
return PhoneGap.exec(
null, //Success callback from the plugin
null, //Error callback from the plugin
'SystemPlugin', //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
funcname, //Tell plugin, which action we want to perform
funcdata); //Passing list of args to the plugin
};
PhoneGap.addConstructor(
function() {
PhoneGap.addPlugin("system", new System());
}
);
var _anomFunkMap = {};
var _anomFunkMapNextId = 0;
function anomToNameFunk(fun)
{
var funkId = "f" + _anomFunkMapNextId++;
var funk = function()
{
fun.apply(this,arguments);
_anomFunkMap[funkId] = null;
delete _anomFunkMap[funkId];
}
_anomFunkMap[funkId] = funk;
return "_anomFunkMap." + funkId;
}
function GetFunctionName(fn)
{
if (typeof fn === "function") {
var name= fn.name;
if (!name) {
var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
name= m && m[1];
}
if (name && (window[name] === fn)) {
return name;
} else {
return anomToNameFunk(fn);
}
}else {
return null;
}
}
function post_sync_data(url, urlparam, param, requestheader, callback){
//alert("In post_sync_data");
if(undefined == callback){
if(undefined == requestheader){
var fnname = GetFunctionName(param);
var dataArray = [fnname, fnname, url, urlparam];
}
else{
var fnname = GetFunctionName(requestheader);
//Note : the param is optional parameter or request header
var dataArray = [fnname, fnname, url, urlparam, param];
}
}
else{
var fnname = GetFunctionName(callback);
var dataArray = [fnname, fnname, url, urlparam, param, requestheader];
}
//alert("Calling plugin function post with \r\n"+dataArray);
var r = window.plugins.system.func("post",dataArray);
//alert("r is :\r\n"+r); ------------- 3
return r;
}
function validate(){
//Make a webservice call for the Omnesys Token
post_sync_data(url,urlparam,uname,postDataCB);
}
function postDataCB(token,name){
//Here uname is undefined.
alert("In postDataCB()\r\nuname: "+uname+"\r\nuname from C Func: "+name+"\r\n\r\ntoken: "+token);
return;
}
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
function onDeviceReady()
{
// do your thing!
navigator.notification.alert("PhoneGap is working")
document.getElementById('d1').style.visibility = "visible";
}
</script>
</head>
<body onload="onBodyLoad()">
<div id="d1" style="visibility:hidden">
<form> <!-- 1 -->
<button onclick="javascript:validate()">Submit</button><br />
</form>
</div>
</body>
</html>
My Phonegap Plugin File.
/*** My PhoneGap Plugin.xml File ***/
<?xml version="1.0" encoding="utf-8"?>
<plugins>
<plugin name="App" value="com.phonegap.App"/>
<plugin name="Geolocation" value="com.phonegap.GeoBroker"/>
<plugin name="Device" value="com.phonegap.Device"/>
<plugin name="Accelerometer" value="com.phonegap.AccelListener"/>
<plugin name="Compass" value="com.phonegap.CompassListener"/>
<plugin name="Media" value="com.phonegap.AudioHandler"/>
<plugin name="Camera" value="com.phonegap.CameraLauncher"/>
<plugin name="Contacts" value="com.phonegap.ContactManager"/>
<plugin name="Crypto" value="com.phonegap.CryptoHandler"/>
<plugin name="File" value="com.phonegap.FileUtils"/>
<plugin name="Network Status" value="com.phonegap.NetworkManager"/>
<plugin name="Notification" value="com.phonegap.Notification"/>
<plugin name="Storage" value="com.phonegap.Storage"/>
<plugin name="Temperature" value="com.phonegap.TempListener"/>
<plugin name="FileTransfer" value="com.phonegap.FileTransfer"/>
<plugin name="Capture" value="com.phonegap.Capture"/>
<plugin name="SystemPlugin" value="com.phonegap.test.SystemPlugin" />
</plugin>
And my JAVA Class
/** Plugin Code **/
public class SystemPlugin extends Plugin {
#Override
public PluginResult execute(String funcname, JSONArray funcargs, String jscallbackid){
//Get the success and failure call back functions
try{
SuccessCallBack = funcargs.getString(0);
FailureCallBack = funcargs.getString(1);
}
catch (JSONException jsonEx) {
return null;
}
if(funcname.equals("post")){
try{
url = funcargs.getString(2);
urlparam = funcargs.getString(3);
}
catch (JSONException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
try {
conn = new URL(url).openConnection();
conn.setDoOutput(true);
} catch (MalformedURLException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
if(requestheader == null){
//Default Request Property
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
else{
String Headers[] = requestheader.split("\r\n");
for(i=0; i < Headers.length; i++){
String hReq[] = Headers[i].split(":");
if(hReq.length == 2){
conn.setRequestProperty(hReq[0], hReq[1]);
}
}
}
try {
//Blank String
String data="";
String param[] = urlparam.split("&");
for(i=0; i < param.length; i++){
String keyval[] = param[i].split("=");
if(keyval.length == 2){
data += URLEncoder.encode(keyval[0], "UTF-8") + "=" + URLEncoder.encode(keyval[1], "UTF-8") + "&";
}
}
//remove the unwanted & at the end of the string
data = data.substring(0,data.length()-1);
ro = new OutputStreamWriter(conn.getOutputStream());
ro.write(data);
//Close the connection
ro.close();
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
try{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
//Close the connection
rd.close();
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
SendJS = "javascript:" + SuccessCallBack + "('" + JSONObject.quote(sb.toString());
if(jObj != null)
SendJS += "','" + jObj + "')";
else if(StringParam != null)
SendJS += "','" + StringParam + "')";
else
SendJS += "')";
sendJavascript(SendJS);
return null;
}
else{
return null;
}
}
}
Now in the first code you can see numerals 1 2 3
1 - the form element
2 - is a global variable
3 - is the plugin alert
Now if i remove 1. everything works fine. But if i keep the form, the global variable cannot hold its value. It becomes undefined and the alert also gives undefined
Can someone guide me what the issue is ?
This is a Form issue. The form was not as per the standard form format
Rectifying this fixed the issue.

Categories