export to excel from web application is not working - java

I am having a very wierd issue and I'm hoping you can help me out
At work, we use a web application made with the framework GWT, and all the sales reports have an option to export the data to excel. It usually works fine, but the days that the report has more than about 15-20 thousand rows, the excel file only opens with the word "null" on the first cell.
Within the code, we use a JSP to send the data as html and a StringBuffer object to append all the text of the html. Here es the method that sends the html:
public void export(final String psFormat) {
manageStartOfCall();
String lsFileName = "resources/system/excel_file.jsp";
final DynamicForm loForm = new DynamicForm();
loForm.setAction(lsFileName);
loForm.setMethod(FormMethod.POST);
loForm.setCanSubmit(true);
final TextAreaItem loDataToExport = new TextAreaItem("psExcelData");
final Window loExcelWindow = new Window();
loExcelWindow.setWidth(5);
loExcelWindow.setHeight(5);
loExcelWindow.addItem(loForm);
addChild(loExcelWindow);
new Timer() {
public void run() {
cancel();
loDataToExport.setValue(moHeader.getHeaderAsExcel() + "<br><br>" + moReportGrid.getDataAsHTML());
loForm.setFields(loDataToExport);
new Timer() {
public void run() {
cancel();
manageEndOfCall();
loForm.submit();
loExcelWindow.destroy();
}
}.schedule(200);
}
}.schedule(200);
}
I've already debugged the getDataAsHTML method and the string that it returns is fine, it contains the correct HTML, however when I call the method getParameter in the JSP y returns a null value. Here the code of the JSP:
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=eYumReport.xls");
String msDataToExcel = request.getParameter("psExcelData");
%>
<html>
<head>
<title>Data to excel</title>
</head>
<body>
<%=msDataToExcel %>
</body>
</html>
I may have to mention I am using this on Firefox 26, GWT 2.1, smartGWT 2.4, Windows 7 Professional and the Web application is on Windows Server 2008, mounted on Apache 6.
Any ideas why this is happening??

Related

How to create a web service in Java that keeps push video binary data to a web page?

I have been doing researches on how to real-time stream video from a camera using Java and OpenCV. I could real-time stream the video with Java JFrame application.
Now I want to real-time stream the video on a web page. I have done researches on that. It seems that using <video> tag of HTML5 with src="blob:http://domain.name/codeabcxxxxx" is a good option.
So I've created a web service with Spring MVC framework. Below is the web service controller that handles the AJAX requests, captures the video frames from the camera and sends the AJAX response with the video frames in binary data.
import ...;
#RestController
public class GreetingController {
final static int CV_CAP_DSHOW = 700;
final static int CAMERA_ID = 0;
VideoCapture videoCapture;
Mat m;
public GreetingController() {
System.load( "C:\\opencv\\build\\java\\x64\\" + Core.NATIVE_LIBRARY_NAME + ".dll");
videoCapture = new VideoCapture(CAMERA_ID, CV_CAP_DSHOW);
m = new Mat();
videoCapture.read(m);
}
#GetMapping("/streaming")
public byte[] streaming() {
while (true) {
if (videoCapture.isOpened() && videoCapture.read(m)) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage image = new BufferedImage(m.width(), m.height(), type);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
final byte[] targetPixels = dataBuffer.getData();
m.get(0, 0, targetPixels);
return targetPixels;
}
}
}
}
Besides that, I've created an index.html web page as following.
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<video id="second-video" controls autoplay muted></video>
<video id="third-video" controls autoplay muted></video>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const secondVideo = document.getElementById("second-video");
const thirdVideo = document.getElementById("third-video");
const url = "http://localhost:8080/streaming";
axios.get(url).then(res => {
const content = res.data;
// Try URL.createObjectURL
const url = URL.createObjectURL(new Blob([content], {type: "video/H264"}));
secondVideo.src = url;
// Try MediaSource
const mediaSourceA = new MediaSource(url);
thirdVideo.srcObject = mediaSourceA ;
});
</script>
</html>
The client (JavaScript on the web page) sends AJAX request to the web service, after getting AJAX response, containing the video frame in binary data, from the web service, it creates an blob object and add the object to the src attribute of the <video> tag. I have tried to use URL.createObjectURL and MediaSource for two different <video> tags. Nothing works!
Result: No video showing in the <video> tags and the web service does not keep sending next video frames, due to the return statement inside the while-loop.
I miss the following knowledge:
Does the client need to keep sending AJAX requests to the web service for each video frame continuously?
or
The client sends only one AJAX request and the web service keeps sending responses with new video frames continuously?
If the client needs to keep sending AJAX requests, how does the client do that?
If the client needs to send only one AJAX request, how can the web service keeps sending responses continuously? Because with my code above, the while-loop stops due to the return statement and the streaming() method needs to use the return statement.
I kind of miss some understanding, please help me! Thanks!

Multipart POST request doesn't contain the file uploaded

I want to extend an existing application with a drag and drop file upload feature. The application is built upon Jetty + Wicket. DropzoneJS seems a good way to go. Dropzone provides all front-end work, I just have to wire it up to the back-end.
More easily said than done, as it turns out. First, I created a test application with the Wicket quickstart. I added dropzone to the HomePage:
<!DOCTYPE html>
<html>
<head>
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">
</head>
<body>
<form action="/upload" class="dropzone"></form>
</body>
</html>
Dropzone is simply included from its repository. On the server, I mounted a resource reference at /upload:
public class FileUploadResourceReference extends ResourceReference
{
public FileUploadResourceReference(String name)
{
super(FileUploadResourceReference.class, name);
}
#Override
public IResource getResource()
{
return new FileUploadResource();
}
}
FileUploadResource will handle processing of uploaded files:
public class FileUploadResource extends AbstractResource
{
#Override
protected ResourceResponse newResourceResponse(Attributes attributes)
{
ServletWebRequest request = (ServletWebRequest) attributes.getRequest();
try
{
MultipartServletWebRequest multipartRequest = request
.newMultipartWebRequest(Bytes.megabytes(100), "ignored");
Map<String, List<FileItem>> files = multipartRequest.getFiles();
List<FileItem> fileItems = files.get("file");
for (FileItem fileItem : fileItems)
{
saveFile(fileItem);
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
return null;
}
private void saveFile(FileItem fileItem)
{
// not implemented
}
}
Now here's the problem, when uploading files, Dropzone sends a POST-request to my http://localhost:8080/upload. The request is recognized as a multipart request, but the file parameter is absent. A null pointer exception is thrown entering the for-loop:
java.lang.NullPointerException
at com.test.FileUploadResource.newResourceResponse(FileUploadResource.java:31) ~[classes/:?]
at org.apache.wicket.request.resource.AbstractResource.respond(AbstractResource.java:629) ~[wicket-core-7.4.0.jar:7.4.0]
at org.apache.wicket.request.handler.resource.ResourceRequestHandler.respond(ResourceRequestHandler.java:105) ~[wicket-core-7.4.0.jar:7.4.0]
at org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler.respond(ResourceReferenceRequestHandler.java:108) ~[wicket-core-7.4.0.jar:7.4.0]
I can't figure out what's going on here. According to the Dropzone website, the form declaration should be fine. A bug in Dropzone perhaps? Seems unlikely. Some Jetty configuration parameter that is denying multipart form requests? Seems highly unlikely, at least I've never heard of it.
You can find full source code of my test app on GitHub.
You miss one method call - multipartRequest.parseFileNames().
You need to do it before #getFiles().
See http://wicketinaction.com/2012/11/uploading-files-to-wicket-iresource/

Can't display applet from html using javascript code in Eclipse

I've tried to run a java applet using the javascript code in Eclipse IDE as shown in the web page Embedding Java Applet into .html file. But the output page shows error. My code to use applet is
<script src="//www.java.com/js/deployJava.js"></script>
in the head section and
<script>
var attributes = {
codebase : '../src/',
code : 'transfol.Main.class',
//archive: 'my-archive.jar',
width : '800',
height : '500'
};
var parameters = {
java_arguments : '-Xmx256m'
}; // customize per your needs
var version = '1.5'; // JDK version
deployJava.runApplet(attributes, parameters, version);
</script>
in the body section.
The way I've saved them is shown in the Navigator as
Main.class inside the package transfol which is in src folder (in Eclipse) and index.jsp in the web content
where Main.class is the applet and index.jsp is the file from which applet is being called.
I'm almost sure that the problem is in the codebase or code attributes where the path has to be specified, when I click on more information on applet, I get exception as:
The folloing exception has occured. For more information, try to launch the browser from the command line and examine the output.
For even more information you can visit http://icedtea.classpath.org/wiki/IcedTea-Web and follow the steps described there on how to obtain necessary information to file bug
Additional information may be available in the console or logs. Even more information is available if debugging is enabled.
Another available info:
IcedTea-Web Plugin version: 1.5 (1.5-1ubuntu1)
26/5/15 5:56 PM
Exception was:
net.sourceforge.jnlp.LaunchException: Fatal: Initialization Error: Could not initialize applet. For more information click "more information button".
at net.sourceforge.jnlp.Launcher.createApplet(Launcher.java:746)
at net.sourceforge.jnlp.Launcher.getApplet(Launcher.java:675)
at net.sourceforge.jnlp.Launcher$TgThread.run(Launcher.java:908)
Caused by: java.lang.ClassNotFoundException: Can't do a codebase look up and there are no jars. Failing sooner rather than later
at net.sourceforge.jnlp.Launcher.createApplet(Launcher.java:716)
... 2 more
This is the list of exceptions that occurred launching your applet. Please note, those exceptions can originate from multiple applets. For a helpful bug report, be sure to run only one applet.
1) at 26/5/15 5:47 PM
net.sourceforge.jnlp.LaunchException: Fatal: Initialization Error: Could not initialize applet. For more information click "more information button".
at net.sourceforge.jnlp.Launcher.createApplet(Launcher.java:746)
at net.sourceforge.jnlp.Launcher.getApplet(Launcher.java:675)
at net.sourceforge.jnlp.Launcher$TgThread.run(Launcher.java:908)
Caused by: java.lang.ClassNotFoundException: Can't do a codebase look up and there are no jars. Failing sooner rather than later
at net.sourceforge.jnlp.Launcher.createApplet(Launcher.java:716)
... 2 more
Try below code
<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
</APPLET>
OR
<object width="400" height="400" data="helloworld.class"></object>
Try this
Java applet
package cdig;
import java.applet.Applet;
import java.security.AccessController;
import java.security.PrivilegedAction;
public class CDigApplet extends Applet
{
private static final long serialVersionUID = 1L;
String ret;
CDigApplet applet = this;
#SuppressWarnings({ "rawtypes", "unchecked" })
public String signFile(String fileID, String pin, String token)
{
AccessController.doPrivileged(new PrivilegedAction()
{
#Override
public Object run()
{
try
{
System.out.println("Iniciando processo de assinatura.");
}
catch (Exception e)
{
String sl = "{\"success\":false," + "\"message\":\"" + e.getMessage() + "\"}";
ret = sl;
System.out.println(sl);
}
return null;
}
});
return ret;
}
public void init(){
}
public void destroy(){
}
}
HTML
<script>
<!-- applet id can be used to get a reference to the applet object -->
var attributes = { id:'cdigApplet', code:'cdig.CDigApplet', archive:'cdig-applet-1.0.jar', width:1, height:1, classloader_cache:'false'} ;
var parameters = {persistState: false, cache_option:'no' } ;
deployJava.runApplet(attributes, parameters, '1.8');
</script>
Call via javascript
var res = document.getElementById("cdigApplet").signFile(Id, '', token);
Don't forget to sign your applet and to not run your app with a URL with underscores '_' like this.

NanoHTTPD how to present variable from app

I play NanoHTTPD and WebServer based on it. To update any object in my code (application) I can use GET/POST method. But how can I create dynamic pages? For example I have html page on disc and it should present current temperature:
<html>
<head>
<title>My page</title>
</head>
<body>
<p style="text-align: center">Temperature: [temperature variable] </p>
</body>
</html>
How can I pass "variable temperature" from my application based on NanoHTTPD to html file and present it in browser?
You have to read the template from your disk, and replace the [temperature variable] substring with the value you want to include.
To read the file, you can use the Files class:
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
String templ = new String(data, StandardCharsets.UTF_8);
To insert your temperature:
double temperature = 22.3;
String html = templ.replace("[temperature variable]", Double.toString(temperature));
And finally to send this as the response with NanoHTTPD:
return new NanoHTTPD.Response(html);
The complete program:
Foreword: Exceptions are not handled, this is just for demonstration purposes.
public class TemperatureServer extends NanoHTTPD {
// Loaded and cached html template
private static String templ;
// Value of this variable will be included and sent in the response
private static double temperature;
public TemperatureServer () {
super(8080);
}
#Override
public Response serve(IHTTPSession session) {
String html = templ.replace("[temperature variable]",
Double.toString(temperature));
return new NanoHTTPD.Response(html);
}
public static void main(String[] args) throws Exception {
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
templ = new String(data, StandardCharsets.UTF_8);
ServerRunner.run(TemperatureServer.class);
}
}
For more advanced examples check out the Samples package of the NanoHttpd Github site.

Running Javascript in WebView when using LoadData

I am very new to Android Dev and I am developing what I thought would be a simple app. I have some HTML code that is stored is the raw resources folder - the code includes some Javascript. When I run the code in Google Chrome it runs fine - however when I load it into the webview using the loadData function it doesn't run the Javascript.
I have enabled javascript with:
mWebView.getSettings().setJavaScriptEnabled(true);
I need to be able to run this Javascript within the browser - any help?
Try this:
webView.loadDataWithBaseURL("blarg://ignored", getData(), "text/html",
"utf-8", "");
Try call JS function from code. Like this:
mWebView.loadUrl("javascript:myFunction()");
What does the loaded HTML data look like? In my case, the raw HTML data I generated was in the format:
<html>
<head>
<style>..</style>
<script>..</script>
</head>
<body>...</body>
</html>
Testing in a normal browser, things worked as expected. However, once I had used WebView.loadData, the CSS seemed to be recognized but I found that the Javascript was not working.
What found that worked for me was moving the Javascript to external files (more specifically I put the scripts I needed to assets/ using content providers.
<html>
<head>
<link rel="stylesheet" type="text/css" href="content://PATHTOSTYLESHEET" />
<script src="content://PATHTOJS"></script>
</head>
<body>...</body>
</html>
According to What is the difference between Android webview's loadData and loadDataWithBaseURL it sounds even more simple if you set a proper base URL which your style/scripts are stored - using the appropriate file:// for anything you store locally.
I am following up on #Cobaia's answer above, with another (I think) useful feature:
Since I need to keep changing the embedded HTML while testing and debugging, I decided to grab the raw page from my local web server during the development of the page and pass it to the webView as follows:
String url, str;
str = getFromURL(url);
webView.loadDataWithBaseURL("blarg://ignored", str, "text/html", "UTF-8", "");
where getFromURL() is defined as:
public String getFromURL(String urlToRead) {
URL url;
HttpURLConnection conn;
BufferedReader rd;
String result = "";
char[] chunk = new char[8192];
int blen = chunk.length;
int amt;
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((amt = rd.read(chunk, 0, blen)) > 0) {
result += new String(chunk, 0, amt);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Note that I had to create a special controller (I'm using CodeIgniter) to allow downloading the file as a text file from the server.
Hope this hint helps others too!
The above solutions did not work for me because I was loading a string that held the HTML instead of a separate HTML file. The HTML in the string referenced JavaScripts that were in assets/www/. What worked was to use mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);
See below for a full example. The example create a webview, loads the HTML from the string, and then calls a function in a separate JavaScript file. The function simply shows an alert.
public class MainActivity extends Activity{
private WebView mWv;
private static final String HTML_AS_STRING =
"<!DOCTYPE html>" +
"<html>" +
"<head>" +
"</head>" +
"<body>" +
"<p>Just some text in a paragraph.</p>" +
"<div align=\"center\" style=\"color:#0000FF\">" +
"<h3>This is a heading in a div element</h3>" +
"<p>This is some text in a div element.</p>" +
"</div>" +
"<font size=\"4\" color=\"0000FF\">" +
"This is some sized and colored text." +
"</font>"
+
"<script src=\"index.js\"></script>" +
"</body>" +
"</html>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mWv = (WebView)findViewById(R.id.webview);
mWv.getSettings().setJavaScriptEnabled(true);
mWv.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
mWv.loadUrl("javascript:showAlert()");
}
});
mWv.setWebChromeClient(new WebChromeClient());
mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);
}
}
index.js (A separate file in assets/www/):
function showAlert() {
alert("A simple alert!");
}

Categories