I am trying to send a canvas PNG to a java servlet using ajax.
Here is my javascript code:
function sendToServer(image){
$.ajax({
type: "POST",
url: "SaveAnnotation",
data: {
annotationImage: image
},
success: function(msg)
{
alert(msg);
},
error: function()
{
alert("Error connecting to server!");
}
});
}
function save() {
var dataURL = canvas.toDataURL();
sendToServer(dataURL);
}
And the java servlet doPost():
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
try{
String img64 = request.getParameter("annotationImage");
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64);
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
File outputfile = new File("saved_annotations/saved.png");
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
out.print("Success!");
}catch(IOException e){
out.print(e.getMessage());
}
}
The problem is that getParameter("annotationImage") returns null, and I can't understand why: using browser debugger I can see annotationImageand its value between the request parameters, so I am sure it is not null, but for some reason the parameter is not received by the Java Servlet.
I found out the reasons why it didn't work.
To avoid parsing JSON I send the data to the server without setting any parameter, writing data: image instead of JSON formatted data: {annotationImage: image} to avoid JSON parsing in the servlet.
In the java servlet I get the entire request body, remove the content-type declaration and finally decode and save the image. Here is the code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
String img64 = jb.toString();
//check if the image is really a base64 png, maybe a bit hard-coded
if(img64 != null && img64.startsWith("data:image/png;base64,")){
//Remove Content-type declaration
img64 = img64.substring(img64.indexOf(',') + 1);
}else{
response.setStatus(403);
out.print("Formato immagine non corretto!");
return;
}
try{
InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(img64.getBytes()));
BufferedImage bfi = ImageIO.read(stream);
String path = getServletConfig().getServletContext().getRealPath("saved_annotations/saved.png");
File outputfile = new File(path);
outputfile.createNewFile();
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
response.setStatus(200);
out.print("L'immagine e' stata salvata con successo!");
}catch(IOException e){
e.printStackTrace();
response.setStatus(500);
out.print("Errore durante il salvataggio dell'immagine: " + e.getMessage());
}
}
Related
I am trying to use httpurlconnection to post parameters to URL. The httpurlconnection seems to be posting fine when posting values without spaces however the issue appears when something like submit=Login Accountwhich contains a space. I have tried to use a plus symbol and %20 instead of the space however I have been unsuccessful submitting the form.
String requestParameters =“password=test123&confirm=test123&id=2869483&submit=Login Account”;
posting function
public static String postURL(String urlString, String parameters, int timeout, Proxy proxy, String accept, String acceptEncoding, String userAgent, String acceptLanguage) throws IOException {
URL address = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) address.openConnection(proxy);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Accept", accept);
httpConnection.addRequestProperty("Accept-Encoding", acceptEncoding);
httpConnection.addRequestProperty("User-Agent", userAgent);
httpConnection.addRequestProperty("Accept-Language", acceptLanguage);
httpConnection.addRequestProperty("Connection", "keep-alive");
httpConnection.setDoOutput(true);
httpConnection.setConnectTimeout(timeout);
httpConnection.setReadTimeout(timeout);
DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
httpConnection.disconnect();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
String result = response.toString();
in.close();
return result;
}
request to post using posting function
*
ArrayList<unlock> ns = new ArrayList<>();
try {
ns = methods.UnlockRequest("register#test.com");// gets urls from database.
} catch (IOException e) {
e.printStackTrace();
}
String s = ns.get(0).toString(); // gets first url in list
url=s; // sets url to s
String[] st= url.split("id="); // splits url to get id
System.out.println(url);
System.out.println(st[1]);
System.out.println("accounts class reached");
String requestParameters = null;
requestParameters = "password=test123&confirm=test123&id=2869483&submit=Login Account”;
System.out.println(requestParameters);
ConnectionSettings connectionSettings = Variables.get().getConnectionSettings();
String creation = "";
System.out.println(Variables.get().getCaptchaSolution());
try {
if (connectionSettings.isProxyCreation()) {
creation = HTTPRequests.postURL(url, requestParameters, 30000, connectionSettings.getProxy(), connectionSettings.getAcceptCriteria(), connectionSettings.getAcceptEncoding(),
connectionSettings.getUserAgent(), connectionSettings.getAcceptLanguage());
}
} catch (FileNotFoundException e) {
System.out.println(ColoredText.criticalMessage("Error: Your IP is banned from requesting. Ending script."));
Variables.get().setStopScript(true);
} catch (IOException e) {
e.printStackTrace();
Variables.get().setStopScript(true);
}
*
I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}
I am trying to add parameter and redirect to a page that only accepts request in post method. I am using this code in my servlet and it is not forwarding me to the url.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "http://www.thisone.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("User", "xyz");
method.addParameter("Name", "abc");
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode != -1) {
response.sendRedirect(response.encodeRedirectURL(url));
in = method.getResponseBodyAsStream();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think it's possible to redirect with post method using this approach. what you can do is get the response to the client and therefore set the location header in response. Implementation for the same is given below:
Once your condition is satisfied:
response.setStatus(307);
response.addHeader("Location", "<url>");
also check out the significance of 307 status code.
Here is the javascript code, which starts with an ajax request and hit a servlet to fetch the desired URL, once it receives the URL, creates a HTML form object, sets values and submits the form...
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callURL(this.responseText);
}
};
xhttp.open("GET", "TestServlet", true);
xhttp.send();
function callURL(url){
var form = document.createElement("form");
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
form.setAttribute('id', 'frmProduct');
form.style.display = 'none';
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'name');
i.setAttribute('value', 'Neeraj');
form.appendChild(i);
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();
}
</script>
Below is the implementation of my Testservlet
#WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://www.thisone.com";
PrintWriter out = response.getWriter();
out.print(url);
}
}
You can make use of automatic form submit using POST method to do the same.
Please find below sample code:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
private void sendPOSTRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
String postURL = "url to send data";
String value1 = "value for name1";
String value2 = "value for name2";
String content = "<html><body onload='document.forms[0].submit()'><form action=\"" + postURL + "\" method=\"POST\">"
+ "<INPUT TYPE=\"hidden\" NAME=\"name1\" VALUE=\"" + value1 + "\"/>"
+ "<INPUT TYPE=\"hidden\" NAME=\"name2\" VALUE=\"" + value2 + "\"/>"
+ "</form></body></html>";
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write(content);
}
I have a problem with my created zip file. I am using Java 8. I tried to create a zip file out of a byte array, which contains two or more Excel files. . So, I thought everything is alright. I do an ajax call for create and download my file but i don't have the popup for download my zip and i don't have error.
This is my javascript:
function getFile() {
$.ajax({
type: "POST",
url: "/support-web/downloadCSV",
dataType: "json",
contentType: 'application/json;charset=UTF-8',
data: jsonfile,
success: function (data) {
console.log("in sucess");
window.location.href="/support-web/downloadCSV/"+data
},
error:function (xhr, ajaxOptions, thrownError){
console.log("in error")
}
});
}
This is my Controller:
#Controller
#RequestMapping(value = "/downloadCSV")
public class DownloadCSVController {
private static final int BUFFER_SIZE = 4096;
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public void downloadCSV(HttpServletRequest request, HttpServletResponse response, #RequestBody String json)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
int i = 0;
for (String url : parts) {
i++;
URL uri = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) uri.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 9, disposition.length());
}
} else {
// extracts file name from URL
fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
ZipEntry entry = new ZipEntry(fileName + i + ".csv");
int length = 1;
zos.putNextEntry(entry);
byte[] b = new byte[BUFFER_SIZE];
while ((length = inputStream.read(b)) > 0) {
zos.write(b, 0, length);
}
zos.closeEntry();
inputStream.close();
System.out.println("File downloaded");
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
// this is the zip file as byte[]
int size = baos.toByteArray().length;
byte[] reportContent = baos.toByteArray();
// Write file to response.
OutputStream output = response.getOutputStream();
output.write(reportContent);
output.close();
response.setContentType("application/force-download");
response.setContentLength((int)size);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"test.zip\"");//fileName)
System.out.println("FIN TELECHARGEMENT");
}
}
Problem:
The Browser not should open a download box
The response isn't handled in the error or in the success (ajax)
So what do I wrong or what is the proper way to do this?
In my navigator you can see the response with my file but download box not should open
You need to do two things:
Set headers before writing anything to response stream.
Remove output.close(); you should not do that. Stream is opened and closed by container.
Second point actually not affecting your problem, its just an advice. You can read more about it here Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?.
In my app, I have created web server which is hosting a web app. All the files of web app are placed in assets folder.
Now, i start the web server by running my application and then from crome brower, I try to run my web app by calling index.html file. The html, css part of the page is getting loaded properly but the images are not getting loaded in the page:
Here is my HttpRequestHandlerCode:
public class HomePageHandler implements HttpRequestHandler {
private Context context = null;
private static final Map<String, String> mimeTypes = new HashMap<String, String>() {
{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xhtml", "text/xhtml");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("svg", "image/svg+xml");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
put("m3u8", "application/vnd.apple.mpegurl");
put("ts", " video/mp2t");
}
};
public HomePageHandler(Context context){
this.context = context;
}
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
//String contentType = "text/html";
//Log.i("Sushill", "..request : " + request.getRequestLine().getUri().toString());
final String requestUri = request.getRequestLine().getUri().toString();
final String contentType = contentType(requestUri);
String resp = Utility.openHTMLStringFromAssets(context, "html" + requestUri);
writer.write(resp);
writer.flush();
// }
}
});
((EntityTemplate) entity).setContentType(contentType);
response.setEntity(entity);
}
}
/**
* Get content type
*
* #param fileName
* The file
* #return Content type
*/
private String contentType(String fileName) {
String ext = "";
int idx = fileName.lastIndexOf(".");
if (idx >= 0) {
ext = fileName.substring(idx + 1);
}
if (mimeTypes.containsKey(ext)) {
//Log.i("Sushill", "...ext : " + ext);
return mimeTypes.get(ext);
}
else
return "application/octet-stream";
}
To handle image, I tried this but it did not work :
if(contentType.contains("image")) {
InputStream is = Utility.openImageFromAssets(context, "html" + requestUri);
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can someone please help me in figuring out how to load the images also in my browser.
Thanks for any help
Do away with BufferedReader(new InputStreamReader' so you do away with UTF-8 too. Use only InputStream 'is'. Do away with writer. You are not showing what 'writer' is but do away with it. Use the OutputStream of the http connection. Keep the buffer and the loop where you read in the buffer and write from the buffer.