How to post data and redirect to another page using GWT? - 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
}

Related

How to recognize whether is it successfully find the values for the 'asserEquals' in Selenium(POM)?

Here mentioned code successfully passed by the test run.But it was not showed the login button click and the logged-user name.(I have try to print the messages by try-catch ).but result shows as passed without those messages.
I just wanted to why can't I see the button click and assertEqual messages?
is there any coding issue or practice should be able to use to overcome this?
I have used the xml file to send the browser type.Further,I pasted only the relevant code sections.
1.TestCommands.java
public class TestCommands {
public void assertText(By locator,WebDriver driver,String expectedValue){
try {
WebElement element = driver.findElement(locator);
assertEquals(element.getText(), expectedValue);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("Not equal");
}
System.out.println("Equal");
System.out.println("captured web element: "+ locator);
System.out.println("captured expectedValue: "+ expectedValue);
}
}
2.LoginPage.java
public class LoginPage extends TestCommands{
public void loginToApplication(WebDriver driver,String userName,String password,String loggedUser){
type(userName(),driver,userName);
type(password(),driver,password);
click(loginButton(),driver);
selectByVisibleText(loggedUser(),driver,loggedUser);
}
3.TC_LoginToTest.java
public class TC_LoginToTest {
WebDriver driver ;
String baseUrl;
LoginPage login = new LoginPage();
#Parameters("browser")
#BeforeMethod
public void beforeMethod(String browser) {
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "drivers\\geckodriver.exe");
driver = new FirefoxDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
driver = new ChromeDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
}
#DataProvider
public Object[][] tc001() {
return new Object[][] {
new Object[] {"nadee","12345678","Testnadee"},
};
}
#Test(dataProvider="tc001")
public void tc001(String userName , String password ,String loggedUser) {
login.openApplication("https://test.com", driver);
login.loginToApplication(driver, userName, password, loggedUser);
}
}

How to solve the java.lang.IllegalStateException: Only one connection receive subscriber allowed

I used spring-cloud-gateway to build the gateway service, but when the service receives the POST request, this exception occurs: "java.lang.IllegalStateException: Only one connection receives subscriber allowed". How to solve this? Below is my code. Thank you.
#Override
public GatewayFilter apply(Object config) {
return ((exchange, chain) -> {
URI uri = exchange.getRequest().getURI();
URI ex = UriComponentsBuilder.fromUri(uri).build(true).toUri();
ServerHttpRequest request = exchange.getRequest().mutate().uri(ex).build();
if ("POST".equalsIgnoreCase(request.getMethodValue())) {
Flux<DataBuffer> body = request.getBody();
AtomicReference<String> bodyRef = new AtomicReference<>(); //used for cache request body
//Cache request
body.subscribe(dataBuffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
DataBufferUtils.release(dataBuffer);
bodyRef.set(charBuffer.toString());
});
//generate bodyFlux
String bodyStr = bodyRef.get();
System.out.println(bodyStr);
DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
// generate request by bodyFlux
request = new ServerHttpRequestDecorator(request) {
#Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
};
}
return chain.filter(exchange.mutate().request(request).build());
});
}
// Generated DataBuffer from String
protected DataBuffer stringBuffer(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
buffer.write(bytes);
return buffer;
}
This looks like the following issue: https://github.com/spring-cloud/spring-cloud-gateway/issues/541
As a temporary workaround, you can define this bean in your application:
#Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new HiddenHttpMethodFilter() {
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange);
}
};
}
This is fixed as of "Greenwich.M1".

Get post data from ByteArrayResource

I send data over post request to path which mount to:
public class AJAXPostPort extends ByteArrayResource implements IResource {
...
#Override
protected byte[] getData(Attributes attributes) {
attributes.getRequest().getPostParameters(); <- EMPTY
...
}
...
}
and can't get it :(. Request from client side is correct and catching from PHP.
Could you help me? how to catch post request from wicket module?
It was easy:
#Override
protected byte[] getData(Attributes attributes) {
HttpServletRequest request;
request = (HttpServletRequest)attributes.getRequest().getContainerRequest();
String data=null;
try {
data = IOUtils.toString( req.getInputStream()); <- GET REAL POST DATA
} catch ( IOException e ) {
e.printStackTrace();
}
...
}

formpanel.submit does not submit the file on GWT server

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
}

RequestFactory and offline clients

I'm trying to create an application which is able to work even when network is down.
The idea is to store data returned from RequestFactory on the localStorage, and to use localStorage when network isn't available.
My problem - I'm not sure exactly how to differentiate between server errors(5XX, 4XX, ...) and network errors.
(I assume that on both cases my Receiver.onFailure() would be called, but I still don't know how to identify this situation)
Any help would be appreciated,
Thanks,
Gilad.
The response code when there is no internet connection is 0.
With RequestFactory to identify that the request was unsuccessful because of the network the response code has to be accessed. The RequestTransport seems like the best place.
Here is a rough implementation of an OfflineAwareRequestTransport.
public class OfflineAwareRequestTransport extends DefaultRequestTransport {
private final EventBus eventBus;
private boolean online = true;
public OfflineAwareRequestTransport(EventBus eventBus) {
this.eventBus = eventBus;
}
#Override
public void send(final String payload, final TransportReceiver receiver) {
// super.send(payload, proxy);
RequestBuilder builder = createRequestBuilder();
configureRequestBuilder(builder);
builder.setRequestData(payload);
builder.setCallback(createRequestCallback(receiver, payload));
try {
builder.send();
} catch (RequestException e) {
}
}
protected static final int SC_OFFLINE = 0;
protected RequestCallback createRequestCallback(final TransportReceiver receiver,
final String payload) {
return new RequestCallback() {
public void onError(Request request, Throwable exception) {
receiver.onTransportFailure(new ServerFailure(exception.getMessage()));
}
public void onResponseReceived(Request request, Response response) {
if (Response.SC_OK == response.getStatusCode()) {
String text = response.getText();
setOnline(true);
receiver.onTransportSuccess(text);
} else if (response.getStatusCode() == SC_OFFLINE) {
setOnline(false);
boolean processedOk = processPayload(payload);
receiver.onTransportFailure(new ServerFailure("You are offline!", OfflineReceiver.name,
"", !processedOk));
} else {
setOnline(true);
String message = "Server Error " + response.getStatusCode() + " " + response.getText();
receiver.onTransportFailure(new ServerFailure(message));
}
}
};
}