formpanel.submit does not submit the file on GWT server - gwt

i want to send a file from client to server.
My code:
Client side:
private FormPanel getFormPanel() {
if (formPanel == null) {
formPanel = new FormPanel();
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
formPanel.setWidget(getFlexTable_1());
System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet");
}
return formPanel;
}
In getFlexTable_1()
flexTable.setWidget(1, 1, getFileUpload());
In getFileUpload()
private FileUpload getFileUpload() {
if (fileUpload == null) {
fileUpload = new FileUpload();
fileUpload.setName("upload");
}
return fileUpload;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
formPanel.submit();
}
});
}
return addButton;
}
On server side
public class CmisFileUpload extends HttpServlet implements Servlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
byte[] buffer = new byte[115200];//
String fileName = null;
String mimetype = null;
String majorVersion = null;
InputStream stream = null;
System.out.println("ServletWorking Fine");
}
Now when i Choose a file and click on ADD button i cant see the output on server side for this code System.out.println("ServletWorking Fine");
The outPut of System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet"); on client side is
http://127.0.0.1:8888/UploadFileServlet
and when i use this url directly on browser i get server side output for System.out.println("ServletWorking Fine");**
Edited
I created one more web application for file upload
public class Uploadfile implements EntryPoint {
FormPanel uploadForm = new FormPanel();
public void onModuleLoad() {
HorizontalPanel horizontalPanel = new HorizontalPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
horizontalPanel.add(uploadForm);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
uploadForm.setWidget(panel);
FlexTable flexTable = new FlexTable();
panel.add(flexTable);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
flexTable.setWidget(2, 3, upload);
// panel.add(upload);
// Add a 'submit' button.
Button uploadSubmitButton = new Button("Submit");
panel.add(uploadSubmitButton);
uploadSubmitButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
uploadForm.submit();
}
});
uploadForm.addFormHandler(new FormHandler() {
public void onSubmit(FormSubmitEvent event) {
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
RootPanel.get().add(horizontalPanel);
}
}
Server
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
System.out.println("working fine" );
}
This code is working fine
According to me there is no difference between the codes.
Plz tell me why the formpanel.submit is not working properly.
Plz help.

Is hide() method is closing the window??? If Yes then
remove move code hide(); after formPanel.submit();
for hide() use FormHandler. for eg
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
hide();
}
public void onSubmit(FormSubmitEvent event) {
}
});
reason: The FormPanel must not be detached (i.e. removed from its parent until the submission is complete. Otherwise, notification of submission will fail.

Why you have mapped for GET method for file upload. The GET request method is serving for the url entered in browser. Remove the GET Request Map, it will work.
For the POST request map, you can use MultipartFile for RequestParam as below
protected void uploadFileAndReconcilePayout1(#RequestParam("documentUpload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
//code for file working
}

Related

Asynchronous GET on REST with okhttp3

I am trying to perform an asynchronous GET-request on my openHAB-project. I have done it before and reused parts of my code to create a new Android app, but it is not working.
In theory I want the state of the "GastSwitch"-item to be written into a String (gastSwitchState) to then be used as a trigger for opening a different activity. If the result of the request is "OFF" the app is supposed to keep running, but stay in the MainActivity.
When debugging it seems like the getGastSwitchState-method is jumped entirely after the enqeue-Method is called. Can someone explain to me, why my code seems to leave out half of the method?
I know that this way of doing it should work, but I can't find where I went wrong.
//connect with REST-API in openHAB :
// GET Status GastSwitch: if Switch = "ON" go to MeetingActivity
//Timer to GET the GastSwitch-status every 30 seconds:
TimerTask gastSwitchTimerTask = new TimerTask() {
public void run() {
try {
getGastSwitchState("myURLforOpenHABGastSwitchState", new Callback() {
#Override
public void getParameter(String string) {
if (gastSwitch.equals("ON")) {
Intent activityIntent = new Intent(getApplicationContext(), MeetingActivity.class);
startActivity(activityIntent);
}
}
});
} catch (IOException e) {
e.printStackTrace();
tvLog.setText(e.toString());
}
}
};
// Timer for GETting the GastSwitch-state every 30 seconds
long emergencyDelay = 1000 * 30 * 1;
Timer gastSwitchTimer = new Timer();
gastSwitchTimer.schedule(gastSwitchTimerTask, 0, emergencyDelay);
}
//Method for GETting the GastSwitch-state from REST-API:
void getGastSwitchState(String url, final Callback callback) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.method("GET", null)
.addHeader("AuthToken", "")
.build();
client.newCall(request)
.enqueue(new okhttp3.Callback() {
#Override
public void onResponse(#NotNull okhttp3.Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String res = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
gastSwitch = res;
tvLog.setText(gastSwitch);
callback.getParameter(gastSwitch);
}
});
}
}
#Override
public void onFailure(#NotNull okhttp3.Call call, #NotNull IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
});

Twitter object is always null I have taken example from twitter4j

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
TwitterFactory twitterFac = new TwitterFactory();
Twitter twitter = twitterFac.getInstance();
twitter.setOAuthConsumer("key", "secret");
request.getSession().setAttribute("twitter", twitter);
try
{
RequestToken requestToken = twitter.getOAuthRequestToken("http://local.your-domain.com:8080/sign-in-with-twitter/callback");
request.getSession().setAttribute("requestToken", requestToken);
System.out.println(requestToken.getAuthenticationURL());
response.sendRedirect(requestToken.getAuthenticationURL());
} catch (TwitterException e)
{
throw new ServletException(e);
}
}
}
****Then the twitter page redirects to a page of my application (CallbackServlet). All this is performed correctly.****
Then the CallbackServlet has the following doGet method:
public class CallbackServlet extends HttpServlet {
private static final long serialVersionUID = 1657390011452788111L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("oauth_token");
String verifier = request.getParameter("oauth_verifier");
try {
twitter.getOAuthAccessToken(requestToken, verifier);
request.getSession().removeAttribute("requestToken");
} catch (TwitterException e) {
throw new ServletException(e);
}
response.sendRedirect(request.getContextPath() + "/");
}
}
=============================
The CallbackServlet tries to get the twitter and requestToken saved in the LoginServlet (using the method getSession().getAttribute()). This is where the problem is: the twitter object is always null!
plz sort it out

Issue with UploadServlet in GWT Project - empty MultiPart

I'm developing a web-app using GWT, and I need to upload a file to the server.
I've written this servlet (which I found here on stackoverflow)
public class ImageUploadService extends HttpServlet {
private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;
#Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) {
wlog("INFO: LA SERVLET é PARTITA");
boolean isMultipart = /* ServletFileUpload.isMultipartContent(request); */true;
if (isMultipart) {
wlog("INFO: IL CONTENUTO é MULTIPART");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
try {
List<FileItem> items = upload.parseRequest(request);
wlog("INFO: LISTA PARTI " + Arrays.toString(items.toArray()));
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
wlog("INFO: SALVATO FILE SU DISCO");
}
}
wlog("FINE SERVLET");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void wlog(String s) {
System.out.println("UPLOAD SERVLET " + s);
}
}
This servlet is correctly invoked, and the method doPost executes when I perform form.submit() on the client, but the problem is, upload.parseRequest always returns an empty list.
As I seached here on SO the solution, I found that the main cause for this behaviour is that the request has already been parsed before, but, as you can see from the code I posted, I never parse the request before .parseRequest().
I'm really getting mad tryng to understand where the problem stands, as all the solutions suggested so far haven't worked.
Thanks to everyone who will help spot the error..
(If it helps, I may post the client-side code, although I don't think that the issue lies there)
EDIT: inserted client code
private void inserisciSegnalazioneOK() {
final PopupPanel inserisciSegnalazionePopup = new PopupPanel();
VerticalPanel inseriscisegnalazioneholder = new VerticalPanel();
final FormPanel textform = new FormPanel();
final FormPanel uploadform = new FormPanel();
Button inseriscisegnalazionebtn = new Button("INSERISCI SEGNALAZIONE");
VerticalPanel textholder = new VerticalPanel();
VerticalPanel uploadholder = new VerticalPanel();
final Segnalazione segnalazione = new Segnalazione();
final ListBox lbcat = new ListBox();
for (String s : listaCategorie)
lbcat.addItem(s);
final TextBox descrizione = new TextBox();
final GoogleSuggestBox gsb = new GoogleSuggestBox();
final FileUpload fu = new FileUpload();
textholder.add(new Label("scegli la categoria della segnalazione"));
textholder.add(lbcat);
textholder.add(new Label("inserisci una descrizione testuale"));
textholder.add(descrizione);
textholder.add(new Label("inserisci l'indirizzo della segnalazione"));
textholder.add(gsb);
uploadholder.add(new Label(
"se puoi, allega una foto della segnalazione"));
uploadholder.add(fu);
textform.add(textholder);
uploadform.add(uploadholder);
inseriscisegnalazioneholder.add(textform);
inseriscisegnalazioneholder.add(uploadform);
inseriscisegnalazioneholder.add(inseriscisegnalazionebtn);
inserisciSegnalazionePopup.setWidget(inseriscisegnalazioneholder);
inseriscisegnalazionebtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
segnalazione.setCategoria(lbcat.getItemText(lbcat
.getSelectedIndex()));
segnalazione.setDescrizione(descrizione.getText());
segnalazione.setIndirizzo(gsb.getText());
segnalazione.setUtente(username);
log("INFO: upload del file " + fu.getFilename());
textform.submit();
uploadform.submit();
}
});
uploadform.setAction(GWT.getModuleBaseURL() + "imageUpload");
uploadform.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadform.setMethod(FormPanel.METHOD_POST);
uploadform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
if (fu.getFilename().length() == 0) {
Window.alert("Non hai eseguito l'upload di nessuna immagine");
event.cancel();
}
}
});
textform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
dataLayerService.inserisciSegnalazione(segnalazione,
new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated
// method stub
caught.printStackTrace();
}
#Override
public void onSuccess(Boolean result) {
// TODO Auto-generated
// method stub
if (result) {
Window.alert("Inserimento avvenuto con successo");
inserisciSegnalazionePopup.hide();
gc.getLatLng(segnalazione.getIndirizzo(),
new LatLngCallback() {
#Override
public void onFailure() {
// TODO
// Auto-generated
// method
// stub
}
#Override
public void onSuccess(
LatLng point) {
// TODO
// Auto-generated
// method
// stub
Marker m = new Marker(point);
map.addOverlay(m);
listaMarker.add(m);
}
});
} else
Window.alert("L'inserimento ha avuto esito negativo");
}
});
}
});
inserisciSegnalazionePopup.setAutoHideEnabled(true);
inserisciSegnalazionePopup.setGlassEnabled(true);
inserisciSegnalazionePopup.center();
}
You have to set a name to your FileUpload if you want the field to be sent out to the server.
BTW, why are you using a FormPanel for your "data" form? Why aren't you simply calling the RPC from the submit button's click? or alternatively, why aren't you putting everything in the same uploadForm and processing it all at once (data and uploaded file) on the server in your upload servlet?

GWT Create JAVAscriptObject form string

I have a model such as bellow.
public class ColumnDtoWrapper extends JavaScriptObject{
protected ColumnDtoWrapper() {}
public final native JsArray<ColumnDto> getfields() /*-{
return this.fields;
}-*/;
public final native void gettable() /*-{
return this.table;
}-*/;
public final native JavaScriptObject getHasMany() /*-{
return this.hasmany;
}-*/;
}
I Make server call like
RequestBuilder build = new RequestBuilder(RequestBuilder.POST, URL);
try {
Request request = build.sendRequest(null, new RequestCallback(){
#Override
public void onResponseReceived(Request request, Response response) {
if(200== response.getStatusCode()){
}
}
#Override
public void onError(Request request, Throwable exception) {
Window.alert("error : " + exception.getLocalizedMessage());
}
});
} catch (Exception e) {
Window.alert("try err");
}
When i got success responce in JSON string.
I want to convert that string as ColumnsDtoWrapper.
somthing like ColumnDtoWrapper col = new ColumnDtoWrapper(responce.getText());
but it not works is there any good way to convert string to JavaScriptObject?
Use JsonUtils.safeEval:
ColumnDtoWrapper col = JsonUtils.safeEval(response.getText());

How to post data and redirect to another page using GWT?

When I press a button I post some data to server and there redirect to another page.
I used RequestBuilder but it is waiting the response, and of course get it. And nothing happens, same page stays. I see RequestBuidler shouldn't be used here... What should I use to post data and be able to redirect?
In Spring
#RequestMapping(method=RequestMethod.POST, value="/ddd")
public ModelAndView processOrder(#RequestBody String orderInString, HttpSession session) throws Exception{
...
return new ModelAndView(new RedirectView("abc"));
}
In GWT
public void postData(final String data, final String url) {
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
try {
builder.sendRequest(data, new RequestCallback() {
public void onError(Request request, Throwable exception) {
...
}
public void onResponseReceived(Request request,
Response response) {
if (200 == response.getStatusCode()) {
..
} else {
..
}
}
});
} catch (RequestException e) {
...
}
return;
}
FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_GET);
Hidden params0 = new Hidden("param1", "value1");
Hidden params1 = new Hidden("param1", "value2");
Hidden params2 = new Hidden("param2", "value3");
FlowPanel panel = new FlowPanel();
panel.add(params0);
panel.add(params1);
panel.add(params2);
form.add(panel);
form.setAction(GWT.getModuleBaseURL() + "../MyServlet");
RootPanel.get().add(form);
form.submit();
Thats it. The code adds FormPanel and sends form.
Add more specifications, code, this is blur.
Since you are using Spring-mvc, you should be having something like this
private static final String newPage = "index2"; //this is resolved with view resolver
#RequestMapping(params = "action=button")
protected String getALPLicense(final RenderRequest request,
final RenderResponse response, final Model model) throws Exception {
try{
}catch{
}
return newPage; //this is your new redirected page
}