how to use php in gwt - java

it's as it says on the title
First of all, I would like to apologize if this is a dumb question =[
so basically i'm trying to send email through gwt. I have no idea how gwt mail work so instead I tried to use php way (which is more familiar to me) but I have no idea how to get this working.
So.. in my war folder I have my index.html and email.php that I've created. In my index.html, I have a form that calls my email.php.
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "did you make sure to fill everything?";
return false;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\n Message:\n$message";
$headers = "From: noreply#somedomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
above is my php code that I am currently using. However not only eclipse does not recognize php but also when I press my button, it only prints out this code and not running it.
Does this happen to anyone and can anyone please help me?
Thank you =]

What you can do:
Recreate the email form in GWT with FormPanel, or
create your own POST-Request in GWT with RequestBuilder
In both cases: the 'echo' statements that your PHP form returns will not be appended to the HTML page but returned to you as a String. You will have to decide what to do (tell the user? take other action) in your GWT code.
Recreate as form panel:
// create the textboxes of the form with their proper form names
TextBox tbName = new TextBox();
tbName.setName( "name" );
TextBox tbEmail = new TextBox();
tbEmail.setName( "email" );
TextBox tbMessage = new TextBox();
tbMessage.setName( "message" );
// create the form panel
final FormPanel emailFormPanel = new FormPanel();
// TODO: add the form panel to some kind of parent widget / ui object
emailFormPanel.setAction( "/contextRoot/path/to/email.php" );
emailFormPanel.setMethod( "POST" );
// add the textboxes to the form panel
emailFormPanel.add( tbName );
emailFormPanel.add( tbEmail );
emailFormPanel.add( tbMessage );
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
emailFormPanel.submit();
}
} );
// create the formpanel handler for a successful submit
// any error message ("did you forget to ...") will be returned here
emailFormPanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String errorString = event.getResults();
// TODO: decide what to do with a potential non-empty string
}
} );
Create your own POST-Request with RequestBuilder:
// create the textboxes of the form with their proper form names
final TextBox tbName = new TextBox();
final TextBox tbEmail = new TextBox();
final TextBox tbMessage = new TextBox();
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
submitEmailFormRequestBuilder( tbName, tbEmail, tbMessage );
}
} );
// TODO: add textboxes and Submit-Button to the DOM-tree
submit the textbox values:
protected void submitEmailFormRequestBuilder(TextBox name, TextBox email, TextBox message) {
// create the request content in a way that the php script can read it:
// for every textbox the php textbox-name = user-value
StringBuilder requestData = new StringBuilder();
requestData.append( "name=" + name.getValue() );
requestData.append( "&email=" + email.getValue() );
requestData.append( "&message=" + message.getValue() );
// create the REST request callback
RequestCallback callback = new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String errorMessage = response.getText();
// TODO: handle potential error-message
}
#Override
public void onError(Request request, Throwable exception) {
// TODO: handle timeouts and other sending failures like cross-domain posting
}
};
// create the REST request as POST request
RequestBuilder build = new RequestBuilder( RequestBuilder.POST, "/contextRoot/email.php" );
try {
build.sendRequest( requestData.toString(), callback );
}
catch (RequestException e) {
// handle exception
}
}
Otherwise, if index.html is not your GWT starting page where the .nocache.js module is called, then you could include it in your GWT code with an IFrame.

Related

The recipient you have identified is not a valid recipient of the specified envelope

With the following code I am able to read the template from my account and send an email with that template is working.
EnvelopesApi envelopesApi1 = createEnvelopesApi(basePath,
prop.getProperty("authenticationToken"));
EnvelopeDefinition envelope1 = makeEnvelope(signerEmail, signerName);
EnvelopeSummary result = envelopesApi1.createEnvelope(accountId, envelope1);
// session.setEnvelopeId(result.getEnvelopeId());
DoneExample.createDefault("Cusotm title")
.withJsonObject(result)
.withMessage("The envelope has been created and sent!<br/>Envelope ID "
+ result.getEnvelopeId() + ".")
.addToModel(model);
But my application is embedded application, so the approval needs to be done over application Hence I have tried to integrate the same in my embedded application.But I am getting error. My code is below.
// Next, create the top level envelope definition and populate it.
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
envelopeDefinition.setEmailSubject("Please sign this document!!");
envelopeDefinition.setEmailBlurb("this is the custom mail content");
//envelopeDefinition.setDocuments(Arrays.asList(document));
envelopeDefinition.setTemplateId("6fcd32d8-91f6-4f4f-90f8-8b54eb71bfb8");
envelopeDefinition.setTemplateRoles(Arrays.asList(signer1));
// Add the recipient to the envelope object
Recipients recipients = new Recipients();
//recipients.setSigners(Arrays.asList(signer));
//envelopeDefinition.setRecipients(recipients);
envelopeDefinition.setStatus("sent");
// requests that the envelope be created and sent.
// Step 2. Call DocuSign to create and send the envelope
ApiClient apiClient = new ApiClient(basePath);
apiClient.setAccessToken(accessToken, tokenExpirationSeconds);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient);
EnvelopeSummary results = envelopesApi.createEnvelope(accountId, envelopeDefinition);
String envelopeId = results.getEnvelopeId();
// Step 3. The envelope has been created.
// Request a Recipient View URL (the Signing Ceremony URL)
RecipientViewRequest viewRequest = new RecipientViewRequest();
// Set the url where you want the recipient to go once they are done signing
// should typically be a callback route somewhere in your app.
viewRequest.setReturnUrl(baseUrl + "/ds-return");
viewRequest.setAuthenticationMethod(authenticationMethod);
viewRequest.setEmail(signerEmail);
viewRequest.setUserName(signerName);
viewRequest.setClientUserId(clientUserId);
// call the CreateRecipientView API
ViewUrl results1 = envelopesApi.createRecipientView(accountId, envelopeId, viewRequest);
// Step 4. The Recipient View URL (the Signing Ceremony URL) has been received.
// The user's browser will be redirected to it.
String redirectUrl = results1.getUrl();
redirect = new RedirectView(redirectUrl);
redirect.setExposeModelAttributes(false);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return redirect;
}
Here I am getting the below error.
com.docusign.esign.client.ApiException:
Error while requesting server, received a non successful
HTTP code 400 with response Body:
'{"errorCode":"UNKNOWN_ENVELOPE_RECIPIENT",
"message":"The recipient you have identified is not a valid
recipient of the specified envelope."}'
at com.docusign.esign.client.ApiClient.invokeAPI(ApiClient.java:1177)
~[docusign-esign-java-3.2.0.jar:na]
at com.docusign.esign.api.EnvelopesApi.createRecipientView(EnvelopesApi.java:1262)
~[docusign-esign-java-3.2.0.jar:na]
....
There are two ways to solve this problem, one is my below alternate way and the second one is as Larry suggested in the comment just add the clientUserId to the signer recipient when you send the envelope.
For embedded sign we need to go for CompositeTemplate
private EnvelopeDefinition makeEnvelope(String signerEmail, String signerName, String clientUserId, WorkArguments args) throws IOException {
CarbonCopy cc1 = new CarbonCopy();
cc1.setEmail("mail");
cc1.setName("name");
cc1.setRoleName(EnvelopeHelpers.CC_ROLE_NAME);
cc1.setRecipientId("2");
// create a composite template for the server template
CompositeTemplate compTemplate1 = new CompositeTemplate();
compTemplate1.setCompositeTemplateId("1");
ServerTemplate serverTemplates = new ServerTemplate();
serverTemplates.setSequence("1");
serverTemplates.setTemplateId("dafgs345-546sdf4-3546sdfqew");
compTemplate1.setServerTemplates(Arrays.asList(serverTemplates));
// Add the roles via an inlineTemplate object
InlineTemplate inlineTemplate = new InlineTemplate();
inlineTemplate.setSequence("1");
inlineTemplate.setRecipients(EnvelopeHelpers.createRecipients(createSigner(signerEmail,signerName,clientUserId), cc1));
compTemplate1.setInlineTemplates(Arrays.asList(inlineTemplate));
// The signer recipient for the added document with a tab definition
Tabs signer1Tabs = EnvelopeHelpers.createSingleSignerTab("**signature_1**", ANCHOR_OFFSET_Y, ANCHOR_OFFSET_X);
signer1Tabs.textTabs(Arrays.asList(
createText("text", "453", "110","Customized data"),
createText("numbersOnly", "453", "130", "147896")));
Signer signer1AddedDoc = createSigner(signerEmail, signerName,clientUserId);
signer1AddedDoc.setAccessCode("12345");
signer1AddedDoc.setTabs(signer1Tabs);
// Create the HTML document
byte[] htmlDoc = EnvelopeHelpers.createHtmlFromTemplateFile(HTML_DOCUMENT_FILE_NAME, "args", args);
// Create a composite template for the added document and add the recipients via an inlineTemplate
CompositeTemplate compTemplate2 = new CompositeTemplate();
compTemplate2.setCompositeTemplateId("2");
InlineTemplate inlineTemplate2 = new InlineTemplate();
inlineTemplate2.setSequence("2");
inlineTemplate2.setRecipients(EnvelopeHelpers.createRecipients(signer1AddedDoc, cc1));
compTemplate2.setInlineTemplates(Arrays.asList(inlineTemplate2));
compTemplate2.setDocument(EnvelopeHelpers.createDocument(htmlDoc, HTML_DOCUMENT_NAME,
DocumentType.HTML.getDefaultFileExtention(), "1"));
EnvelopeDefinition env = new EnvelopeDefinition();
env.setStatus(EnvelopeHelpers.ENVELOPE_STATUS_SENT);
env.setCompositeTemplates(Arrays.asList(compTemplate1, compTemplate2));
return env;
}
and then we can call the api
EnvelopeDefinition envelope = makeEnvelope(signerEmail, signerName, clientUserId, args);
EnvelopeSummary envelopResults = envelopesApi2.createEnvelope(accountId, envelope);
RecipientViewRequest viewRequest1 = makeRecipientViewRequest(args);
ViewUrl viewUrl = envelopesApi2.createRecipientView(accountId, envelopResults.getEnvelopeId(), viewRequest1);
return new RedirectView(viewUrl.getUrl());

Refresh panel in Wicket with BootstrapDownloadLink

My problem is simple but I have no clue how to solve it. I have a feedbackPanel and I want to show an error message if the BootstrapDownloadLink fails. With a submit I could easily do:
protected void onSubmit(AjaxRequestTarget target) {
...
error("File_not_found"); //Wicket will print this on the feedback panel
target.add(getModalPanel().getFeedbackPanel()); //But i need to refresh it first
}
But the button is inside a panel which I fill with a populateItem and is the only way I know to insert Bootstrap Styles to it. The code of the button:
BootstrapDownloadLink downloadDocument = new BootstrapDownloadLink(IDITEMREPEATER, file) {
#Override
public void onClick() {
File file = (File)getModelObject();
if(file.exists()) {
IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));
} else {
error(getString("error_fichero_no_existe"));
/// ???? need to refresh-> getModalPanel().getFeedbackPanel()
}
}
};
downloadDocument.setIconType(GlyphIconType.clouddownload);
downloadDocument.add(new AttributeModifier("title", getString("documentos.descargar")));
downloadDocument.add(new AttributeModifier("class", " btn btn-info negrita btn-xs center-block"));
downloadDocument.setVisible(Boolean.TRUE);
list.add(downloadDocument);
You could create or extend from an AjaxDownloadLink, for example like here.
The main idea is to have an AjaxBehavior that does the download, and you get a public void onClick(AjaxRequestTarget target) in which you can add the FeedbackPanel
downloadBehavior = new AbstractAjaxBehavior()
{
private static final long serialVersionUID = 3472918725573624819L;
#Override
public void onRequest()
{
[...]
ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(
AjaxDownloadLink.this.getModelObject(), name);
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}
};
And use that behavior in the onclick:
#Override
public void onClick(AjaxRequestTarget aTarget)
{
String url = downloadBehavior.getCallbackUrl().toString();
if (addAntiCache) {
url = url + (url.contains("?") ? "&" : "?");
url = url + "antiCache=" + System.currentTimeMillis();
}
// the timeout is needed to let Wicket release the channel
aTarget.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
}
You can use target.addChildren(getPage(), IFeedback.class). This will add all instances of IFeedback interface in the page to the AjaxRequestTarget.
You can also use FeedbackPanel.class instead of the interface.
Or use getPage().visit(new IVisitor() {...}) to find a specific feedback panel if you don't want to add others which are not related.

Downloading a file with HtmlUnit. Download button has no (seemingly) accessible link

I am new to programming and couldn't find an answer to fit my question, and am unsure where else to turn. As stated in the title, I'm looking to download a file using HtmlUnit in Java, but the download button on the page has no href or onclick I can access. Button follows:
<button class="btn btn-download btn-primary pull-right" id="eta_download" style="display: block;">
<span class="glyphicon glyphicon-download-alt"></span>
</button>
clicking this button causes a normal browser to do some processing and loading for a short amount of time, then open a tab that triggers the download of a gzip file containing a tiff satellite image. I am doing this in a Swing app.
The site I need to download gzipped tiff from
Can anyone help me get this to work?
My code follows:
// Call from whithin new Thread. Get the download
private void getDownload(String latitude, String longitude, String start, String end) throws Exception
{
// Create the browser
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
// Report to user. Loading page...
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading EEFLUX...");
}
});
// Load page
HtmlPage page = webClient.getPage("https://eeflux-level1.appspot.com/");
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Filling in values");
}
});
// Get Latitude, Lomgitude and Date Fields
HtmlInput latitudeField = (HtmlInput) page.getElementById("latitude");
HtmlInput longitudeField = (HtmlInput) page.getElementById("longitude");
HtmlInput date_start_Field = (HtmlInput) page.getElementById("date_start");
HtmlInput date_end_Field = (HtmlInput) page.getElementById("date_end");
// Set the values of fields to that passed into method
latitudeField.setAttribute("value", latitude);
longitudeField.setAttribute("value", longitude);
date_start_Field.setAttribute("value", start);
date_end_Field.setAttribute("value", end);
// Get the Search "Button" then click
HtmlAnchor search = (HtmlAnchor) page.getHtmlElementById("searchForImages");
page = search.click();
// wait for Javascripts jobs to finish
JavaScriptJobManager manager = page.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 7; i++)
{
final int j = i;
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading after Search: " + j);
}
});
Thread.sleep(1000);
}
// Get the list of regions Satellites captured and click to open dropdown
HtmlDivision image_dropdown = (HtmlDivision) page.getElementById("image_dropdown");
image_dropdown.click();
// Get the list of regions
HtmlUnorderedList region_list = (HtmlUnorderedList) image_dropdown.getLastElementChild();
// get iterator for list
Iterator<DomElement> web_list = region_list.getChildElements().iterator();
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Accessing region list");
}
});
// for each Element, download Actual ET image (and later Grass Reference)
while(web_list.hasNext())
{
DomElement region = web_list.next();
System.out.println(region.getTextContent());
HtmlPage page2 = region.click();
// wait for Javascripts jobs to finish
manager = page2.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 2; i++)
{
final int j = i;
// Report to user
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading Image Type page: " + j);
}
});
System.out.println(manager.getJobCount());
Thread.sleep(1000);
}
// Get the Actual ET download Button
HtmlButton ETButton = page2.getHtmlElementById("eta_download");
// Get the Download Page????
HtmlPage page3 = ETButton.click();
UnexpectedPage download_ET = new UnexpectedPage(page3.getWebResponse(), page3.getEnclosingWindow());
// Get the Stream
GZIPInputStream in_ET = (GZIPInputStream) download_ET.getWebResponse().getContentAsStream();
// Try writing the stream (to standard out for now)
try
{
byte[] buffer = new byte[2048];
int len;
while((len = in_ET.read(buffer)) != -1)
{
System.out.write(buffer, 0, len);
}
}
finally
{
// Close the stream
in_ET.close();
}
// just do one till this works
break;
}
}
This is a good start :)
I looked at the request being sent when clicking the button :
As you can see there are several parameters being sent (latitude, longitude, date_end, image_id). In the response, you have the download URL.
This request is generated with some Javascript code, probably this :
function downloadImage(divName,urlProduct){
$(document).ready(function(){
$(divName).on('click', function(){
onlyshowLoading();
$.ajax({
url: urlProduct,
type: "POST",
data: JSON.stringify({
"lat": $('#latitude').val(),
"lng": $('#longitude').val(),
"date_info": $('#date_start').val() + ' to ' + $('#date_end').val(),
'image_id': $("#dropdown:first-child").text().split(" / ")[1],
}),
dataType: 'json',
cache: true,
error: function(){
AjaxOnError();
},
success: function(data){
AjaxOnSuccess();
if (typeof ETa_adjusted == "undefined" || ETa_adjusted == null){
$("#ETrF_adjusted").hide();
$("#EToF_adjusted").hide();
$("#ETa_adjusted").hide();
$("#etrF_adj_download").hide();
$("#etoF_adj_download").hide();
$("#eta_adj_download").hide();
} else{
$("#ETrF_adjusted").show();
$("#EToF_adjusted").show();
$("#ETa_adjusted").show();
$("#etrF_adj_download").show();
$("#etoF_adj_download").show();
$("#eta_adj_download").show();
}
var key = Object.keys(data);
typeName = data[key]
window.open(typeName.url, '_blank');
}
});
});
})
}
So it's possible that HtmlUnit is unable to execute this code, because of Jquery or whatever.
You could create your own WebRequest object, and reproduce the Javascript logic, then you will get the download URL.
It's an interesting subject, if you want to know more I'm in the middle of writing an ebook about web scraping with Java : Java Web Scraping Handbook

JSON response Issue for Jira Rest Client

When I use the following method :
public String getProjectList() {
projNames = new ArrayList<>();
projNames.add("Project1");
projNames.add("Project2");
projNames.add("Project3");
return new Gson().toJson(projNames);
in the following code :
$(document).ready(function() {
$.getJSON('DBDropDown', function(resp) { // on sucess
var $select = $('#someselect');
$select.find('option').remove();
$select.prepend("<option value='Select Project'></option>").val('');
$.each(resp, function(key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
}).fail(function() { // on failure
alert("Request failed.");
});
});
and my JSP call is :
response.getWriter().write(MusicDatabase
.getInstance()
.getProjectList()
I am able to get the dropdown menu. But when I use this method in place of getProjectList I dont get a response when I check chrome developer tools and debug.
public String Names() throws URISyntaxException{
names = new ArrayList<>();
URI uri = new URI("https://jira.xxxxx.com");
JiraRestClientFactory jrcf = new AsynchronousJiraRestClientFactory();
JiraRestClient jrc = jrcf.createWithBasicHttpAuthentication(uri, "xxx", "xxxx");
Iterable<BasicProject> allproject = jrc.getProjectClient().getAllProjects().claim();
for(BasicProject project : allproject){
names.add(project.getName());
}
return new Gson().toJson(names);
}
I am not getting any response and console throws ClassDefNotFound Exception when I already have all the classes needed. Help me if you have gone through this type of issue.
Thanks

ActionListener and combo-box issue

I'm currently having an issue where I am creating a simple web browser and want to write the url of each page visited. Anyway, when the History combo-box is being filled with the URL's the .addItem function is triggering my action listener. Is there any way around this?
Action Listener:
historyList.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
final String url= historyList.getSelectedItem().toString();
addressbar.setText(url); //set the address bar to the url
historyArray[historynum] = url; //add the url to the array which contains the history
historynum = historynum + 1; //move one up the history array
Display(url); //display the url
backplace = 1; //reset the amount of backs a user can take
forwardBtn = false; //not allow the user to go forward again
}
}
);
}
adding URL's from config file to combo:
for (String linehistory : Files.readAllLines(Paths.get("config.history"),Charset.defaultCharset())) {
if (!(linehistory ==null)){
for (String partHistory : linehistory.split("\\s+")) {
String historylines = partHistory;
if( i >6){
if (!(partHistory ==null)){
historyList.addItem(partHistory);
}
}
i = i +1;
}
}
I have noticed this, and I think it may be due to the state of the combo-box being changed, is there a way to change this to onClick? http://imgur.com/aTg9n2E

Categories