Pass x-editable data from JSP to Java Class - java

HTML Code:
Dummy Text
Script Code:
$('#test').editable({
url: '<%=resourceURL.toString() %>',
send: 'always'
});
Java Class Code:
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
String test = ParamUtil.getString(resourceRequest, "test");
System.out.println(test);
}
What happened everytime I change the editable value, there's no data sent from editable ajax.
By the way I'm using Liferay for development.

Related

Java CEF - Is it possible to access DOM document and elements of loaded page?

I've built java-cef from https://bitbucket.org/chromiumembedded/java-cef/overview , but I still can't find any info in docs and javadocs about how to access DOM document and elements of loaded page.
I need to access elements by something like document.getElementsByClassName("example");, document.getElementsByTagName("div");.
Something like in JSoup - https://jsoup.org/cookbook/extracting-data/selector-syntax :
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");
Is there same functional in Java-CEF?
Thank you!
You need to attach a load handler to the CEF Client and call CefBrowser::executeJavaScript(String code) inside the handler, e.g.:
cefClient.addLoadHandler(new LoadHandler());
...
class LoadHandler extends CefLoadHandlerAdapter {
#Override
public void onLoadEnd(CefBrowser browser, int frameId, int status) {
String jscode = "var x = document.getElementsByClassName('example')";
browser.executeJavaScript(jscode);
}
}
UPDATE
Then if you want to receive events from the browser script in your Java code, you need to register a call cefQuery with CefBrowser::executeJavaScript(String code), passing all necessary data in a single argument, and receive it with a message router, e.g:
CefMessageRouter msgRouter = CefMessageRouter.create();
msgRouter.addHandler(new MessageRouterHandler(), true);
cefClient.addMessageRouter(msgRouter);
...
browser.executeJavaScript("cefQuery({request: 'Hello World'})");
...
class MessageRouterHandler extends CefMessageRouterHandlerAdapter {
#Override
public boolean onQuery(CefBrowser browser, long query_id, String request, boolean persistent, CefQueryCallback callback) {
System.out.println(request); // prints "Hello World"
return true;
}
}

Accessing uploaded file in Apache Tapestry page

I'm using Apache Tapestry v5.3.7 and I already use the normal Tapestry upload component in a form. For a better user experience I try now to integrate Dropzone.js in a normal Tapestry page without any form. The JavaScript integration works fine. The uploaded file data are transferred to my server with a post request and I can access the request with all of its parameters.
My question is now how can I access the binary data of the uploaded file (maybe as InputStream) to save them in my system? I already injected the http request but getInputStream returns a empty stream.
Thanks for any suggestions
/** Code snippet of page java part */
...
#Inject
protected HttpServletRequest _request;
public void onActivate (String rowId) {
String fileName=_request.getParameter("file");
try {
InputStream is=_request.getInputStream();
// if I do read from is it returns -1
// :-(
doSomeSaveStuff(is); // dummy code
}
catch(Exception e) {
e.printStackTrace();
}
}
...
Here's one way to do it:
In template:
<t:form t:id="testForm" class="dropzone">
</t:form>
In page.java
#Inject
MultipartDecoder multipartDecoder;
#Component(id = "testForm")
private Form testForm;
#Inject
RequestGlobals requestGlobals;
void onSubmitFromTestForm() throws ManagerException {
System.out.println("test form invoked");
HttpServletRequest r = requestGlobals.getHTTPServletRequest();
UploadedFile u = multipartDecoder.getFileUpload("file");
The uploaded file contains what you uploaded and you can work with it the way you want.
Note: the HttpServletRequest::getParameterMap() , told me that the handle to to the file is called file which is how I know that passing file to getFileUpload makes the decoder correctly parse the multipart/post

Window.open in GWT not open correctly with in a call back function

I have a situation where i need to download a excel file. So i user Window.open for that. The problem is i need to check whether the file is exsist in the server location before call the Window.open. So when user click the download buton below call happens,
public void onClick(Button button, EventObject e) {
final String url = GWT.getModuleBaseURL() + "fileupload/dailyLogReport?param1=param1
openFileDownloadWindow(url,fileName);
}
public void openFileDownloadWindow(final String url,String fileName){
CommonServiceAsync serviceAsyn = CommonService.Util.getInstance();
final AsyncCallback callback = new AsyncCallback() {
public void onSuccess(Object result)
{
isFileExsist = (Boolean)result;
if(isFileExsist){
Window.open( url, "_blank", "status=0,toolbar=0,menubar=0,location=0");
}else{
Window.alert("File not found.");
}
}
public void onFailure(Throwable caught)
{
MessageBox.alert("Error", "Error while getting data"
+ caught.getMessage());
}
};
// calling of the action
serviceAsyn.isDailyLogFileExsists(fileName, callback);
}
But the problem is if i put the Window.open inside the success it just open a Window and getting it close quickly with out download the file. But if i put the Window.open directly in onClick method it successfully open the window pop up and download the file successfully. But Since i have to download the file conditionally by checking whether the file is exists or not I can not put the Window.open inside onClick.
What is the reason Window.open not working properly inside the call back success function?
The problem is popup blocker.
When you click on a element you can open a new window since the browser considers it is a deliberate user action to open the window.
Otherwise, the browser blocks any window.open in asynchronous blocks, because it considers that it could be malicious code run out of the user control.
The best solution, is to open the file in an iframe, but you have to set the appropriate content-disposition header in server side which causes the browser to show the "Save" dialog.
Client Code:
// Create a new iframe
final Frame f = new Frame();
f.setUrl(url_to_my_excel_file");
// Set a size of 0px unless you want the file be displayed in it
// For .html images .pdf, etc. you must configure your servlet
// to send the Content-Disposition header
f.setSize("0px", "0px");
RootPanel.get().add(f);
// Configure a timer to remove the element from the DOM
new Timer() {
public void run() {
f.removeFromParent();
}
}.schedule(10000);
Server Code:
protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
[...]
// Set the appropriate type for your file
resp.setContentType("application/vnd.ms-excel");
// Mandatory if you want the browser open the save dialog
resp.setHeader("Content-Disposition:", "attachment;filename='my_excel_file.xls'");
[...]
}

Connecting a Java Servlet to a Browser

I've tried this question before with little success but that's probably my fault so I'll be as specific as possible!
Part A)
I have a compiled java class which returns a hello world string. The source code for this file is below. After configuring the web.xml setting I am able to get good results from a browser pointing at localhost. This is working exactly as planned.
Part B)
I have an HTML landing page with a single link in it which, when pressed will read a local text file and replace content within it. This is also working exactly as planned.
Part A means I am able to have a client call a server-side java class file and get outputs. Part B means I am able to replace one part of a webpage after a button has been pressed.
My question, from this point is quite straight forward. I would like to merge the two concepts so that when the link from part B is pressed the text updated will reflect the 'hello world' result set from Part A.
Thanks in advance.
Part A Code:
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Part B Code
<p id="mySentence">
Click here to update the page.
When you click the link, this content will be replaced.</p>
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function getNewContent(){
http.open('get','newcontent.txt');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('mySentence').innerHTML = http.responseText;
}
}
</script>

How to get Parameter from Ext.Ajax.request in java controller

I am having one problem in retrieving the parameter which i am passing using Ext.Ajax.request to my JAVA controller class.
I am sending request to my controller using below code
Ext.Ajax.request({
url : 'projecttask/GetprojectTasks.action',
method: 'POST',
jsonData: {
sampledata: record.data
},
type: 'json',
scope: this, // add the scope as the controller
callback : function(options, success, response) {
console.log('RESPONSE FROM SERVER :'+response);
}
});
my java controller method to receive the request is
#RequestMapping(value="/projecttask/GetprojectTasks.action")
public #ResponseBody Map<String, ? extends Object> getprojectTasks(HttpServletRequest request,
HttpServletResponse response,#RequestBody Project project) throws Exception {
try {
System.out.println("PROJECT ::"+project);
System.out.println("RPOJECT DATA ::"+request.getParameter("sampledata"));
Object data = request.getParameter("sampledata");
Project prj = (Project) data;
System.out.println("CREATE TASK DATA IS ::"+prj.getProjectid());
return null;
}catch(Exception e) {
return getModelMapError("Error trying to create contact");
}
}
but it gives me error mentioned below
org.codehaus.jackson.map.JsonMappingException: Unrecognized field "sampledata" (Class com.kintu.projectmgt.model.Project), not marked as ignorable
so what i am doing wrong which not allowed my function to get sampledata passed as parameters. How can i get my Parameters passed value any idea ?
My firebug shows that sampledata contains all values. Please help me to find the problem and solve it as soon as possible.
I am using Ext JS 4.0.2a and JAVA as my serverside technology.
you can use
String postParamsJSON = request.getReader().readLine();
to get the POST data.

Categories