Incorrect string value - JOOQ - Java - java

I am trying to upload csv into my mysql db using jooq how ever i am getting following error.I tried various solutions suggested on net but cant fix it
Error: org.jooq.exception.DataAccessException: SQL [insert into `Test`.`testtable` <mydata> Incorrect string value: '\xEF\xBF\xBD15 ...' for column 'colum_Name' at row 1
How I am uploading csv to jooq
create.loadInto(Tables.TableName)
               .onErrorIgnore()
               .loadCSV(new File("/tmp/uploaded-files/" + fileName), "UTF-8").<fields>.execute();
I ensure file is in utf-8 however when ever there is UTF-8 character record is failing to save in DB and throwing above error.I ensured using
file -i <filename>
front end ajax:
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: fileUploadUrl,
data: dataforFileUpload,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (message) {
console.log(message);
alert(message);
console.log("upload done "+ new Date());
},
error: function (e) {
console.log("ERROR : ", e.responseText);
alert("ERROR : "+ e.responseText);
}
});
I am getting file from my front end reading it via java rest
InputStream inputStream = listingFilePart.getBody(InputStream.class, null);
and writing file recursively in local system before passing to jooq
PrintWriter fop = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8));
I set my DB to accept utf-8 and I verified the same

I found the issue.Issue is on ajax call.
I need to send charset with enctype like
$.ajax({
type: "POST",
enctype: 'multipart/form-data;charset=UTF-8',
url: fileUploadUrl,
data: dataforFileUpload,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (message) {
console.log(message);
alert(message);
console.log("upload done "+ new Date());
},
error: function (e) {
console.log("ERROR : ", e.responseText);
alert("ERROR : "+ e.responseText);
}
});

Related

How to decode the special characters sent from the url in Java?

I am sending the the value from my jsp to my servlet in url parsing.
The value contains the special character (), but when I am receiving the value it is &#40 and &#41.
How to decode this back to ()?
jsp code
var devicename=document.getElementById('s_loc_1').value;
var param=devicename;
param=encodeURIComponent(devicename);
var updatedevsaturl="http://"+window.location.host+"/services/PCEquipmentDevice?productid={}&action=updatePCDeviceStatus&reqby={}&param="+param;
var productId=document.getElementById('pid').value;
updatedevsaturl=sustituteParameter(updatedevsaturl,productId);
updatedevsaturl=sustituteParameter(updatedevsaturl,userUpi);
alert(updatedevsaturl);
$.ajax({
type : "GET",
timeout:20000,
url : updatedevsaturl,
async: false,
dataType : "xml",
success: function(data) { }, error: function (xhr, ajaxOptions, thrownError) {
alert('Service Unavailable - VPU List');
}
});
java code to decode
if(action.equals("updatePCDeviceStatus")){
System.out.println("param: "+param);
//String decodeparam3 = new String(param.getBytes("UTF-8"),"ASCII");
//String decodeparam3 =URLDecoder.decode(param, "UTF-8");
String decodeparam3= URLDecoder.decode(param, "ISO-8859-1");
System.out.println("decodeparam132 "+ decodeparam3);
I tried all the ways give on net but didnt workenter code here
input at jsp 2-in-1 Laptop (12.5 inches)
output at servlet 2-in-1 Laptop &#4012.5 inches&#41
This is ASCII code for "(". Look at this answer Java: How to unescape HTML character entities in Java? . You have to create a char from that html entity.

Jquery unescape response text from java servlet not working properly

java code
pResponse.setHeader("content-type", "text/plain;chartset=UTF-8");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.write(escapedJsonString);
The purpose to escape the return text is because there are some accented character in 'resultsJson' and even though I set charset=UTF-8, I still get garbled text from ajax. check this question from me ajax garbled text
ajax code
var option = {
type : 'POST',
url : $('#csrOrderExportform').attr('action'),
data : $('#csrOrderExportform').serialize(),
beforeSend : preAjaxReqest,
dataType:'text',
error : function(data, statustext, error){
$(".searchSubmitBtn").removeAttr("disabled");
setErrorMessage('No Records Found!');
},
success : function(data){
if (data) {
alert(unescape(data));}
}
};
$.ajax(option);
response text
[{\"orderNumber\":\"S301020000\",\"customerFirstName\":\"\u5F20\u79D1\",\"customerLastName\":\"\u5F20\u79D1\",\"orderStatus\":\"PENDING_FULFILLMENT_REQUEST\",\"orderSubmittedDate\":\"May 13, 2015 1:41:28 PM\"}]
after unescape the text from jquery, I am getting the same text.
expected output
[{"orderNumber":"S301020000","customerFirstName":"张科","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}]
This should work:-
pResponse.setContentType("application/json");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.println(escapedJsonString);

ajax POST cannot send data to servelet

I am working on a simple tomcat web application. The client side just send the username data in json to server side and server side return if this username is already registered.
Here is my code.
ajax part:
var udata = new Array();
udata.push({ name: uname});
$.ajax({
url: '/TestProj/Controller?action=checkuname',
type: 'POST',
dataType: 'json',
data: udata,
//contentType:'application/json, charset=utf-8',
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
servlet part:
I am using a controller to dispatch the request to checkname servlet.
String username = request.getParameter("name");
if (checkuser(username)){
status = "false";
}else{
status = "true";
}
response.setContentType("application/json");
PrintWriter o = response.getWriter();
o.println("{\"status\":\""+status+"\"}");
//o.println("{\"status\":\""+username+"\"}");
I try print out the content of "status" and "username", but they are both null. Does it mean that I did not successfully send out the data via ajax to servlet. I may mess up the json data part.
Any help will be appreciated.
Updated:
I change the ajax part to this and it works. Can someone let me know how to do it in the json way?
ajax part:
var udata = new Array();
udata.push({ name: uname});
$.ajax({
url: '/TestProj/Controller?action=checkuname&uname='+uname,
type: 'POST',
dataType: 'json',
data: udata,
//contentType:'application/json, charset=utf-8',
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
It doesn't really make sense to use a JSON object for such a simple thing as posting a username to a servlet. Just use a simple request parameter and save yourself a lot of trouble. But if you must do it with JSON, there are a few problems you'll need to resolve.
Unless you're handling multiple users at the same time, a javascript array is not a good choice of data type. A simple object would be better.
var udata = {name: uname};
Your post data should be a string, not a javascript object (array or otherwise). Use JSON.stringify() as in your error function.
$.ajax({
url: '/TestProj/Controller',
type: 'POST',
dataType: 'json',
data: 'action=checkuname&jsonObject=' + JSON.stringify(udata),
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
However, udata is such a simple javascript object that you might as well stringify it yourself, as the native JSON object is not going to be available in older browsers.
var udata = '{name:"'+uname+'"}';
$.ajax({
url: '/TestProj/Controller',
type: 'POST',
dataType: 'json',
data: 'action=checkuname&jsonObject=' + uname,
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
Also, although it may boil down to personal preference, the action parameter is better off in the post body rather in the query string. This is a post, after all.
request.getParameter() is not going to help you inspect a JSON string. It can only get the value of request parameters. So
String json = request.getParameter("jsonObject")
// this variable will have a value like "{name: 'somedude'}"
You'll need to parse this JSON string on the server. You could try to do this yourself with String methods, by a library like Gson is a much better option. You could obtain the username value like this:
String username = (String)(new Gson().fromJson(json, Map.class).get("name"));

how to read parsed json data in ajax success call

On Ajax success call, I'm getting already parsed data in JSON format from a Controller.
I want to read that data, so while I'm doing below one, I am getting undefined as an error.
How can I solve this?
success : function(response) {
alert(response.operatorId);
},
Here is an example of working code
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('' + topic.link_text + "");
});
}
It appears that the response coming into success function is not a JSON object. COuld you check if you have following set in your ajax call.
dataType: 'json',
contentType : 'application/json'
Alternatively, you may use the following to parse the json string to json object and then use dot notation to access the properties
success : function(response) {
var jsonData = $.parseJSON(response)
alert(jsonData.operatorId);
},

Does jQuery have a built in function to do long polling?

I am doing Java Chat application .
I will call the pingAction() in my external Jquery when my application get initiated.
I used this site for reference of long polling with JQUERY - http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
The Jquery pingAction will be ,
function pingAction(){
$.ajax(
{
type: "post",
url: "PingAction",
async: false,
data : "userId="+encodeURIComponent(userId)+"&secureKey="+encodeURIComponent(secureKey)+"&sid="+Math.random() ,
cache:false,
complete: pingAction,
timeout: 5000 ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8" ,
dataType: "html",
error: function (xhr, ajaxOptions, thrownError) {
alert("xhr.status : "+xhr.status);
if(xhr.status == 12029 || xhr.status == 0){
//alert("XMLHttp status : "+xhr.status);
$("#serverMsg").css("backgroundColor" , "yellow");
$("#serverMsg").text("Your Network connection is failed !");
$("#serverMsg").show();
}
//setTimeout('pingAction()', 5000);
xhr.abort();
},
success: function( responseData , status){
if($("#serverMsg").text() == "" || $("#serverMsg").text() == "Your Network connection is failed !"){
disableServerMessage();
}
if(responseData != "null" && responseData.length != 0 && responseData != null){
var stringToArray = new Array;
stringToArray = responseData.split("<//br//>");
var len = stringToArray.length;
for(var i=0;i<len-1;i++){
getText(stringToArray[i]);
}
}
//setTimeout('pingAction()', 5000);
}
}
);
}
Before using the Long Poling , I will call the pingAction() in javaScript for every 5 seconds using the setTimeInterval().
Now I need to use the LONG POLLING concept in the Chat application (Wait until the server gives the new messages).So I modified my Jquery pinAction() what you have seeing above.
Is there any built in method to do the Long polling in JQUERY ?
No, there is no built in method in jQuery to do long polling. You will have to either develop your own or find existing code that solves your problem.
If you're looking for ideas, you can start with a Google search for "long polling in jQuery". There are plenty of examples to learn from.

Categories

Resources