Unable to find form with id: "credit-card-form" - braintree

I'm trying to use Braintree in my GWT Application.
At the moment I'm loading a form first and get the client token from my server as the user hits this OK button.
This is how I setup braintree:
private static native void setup(String domId, String serverToken) /*-{
braintree.setup(
serverToken,
"custom",
{
id: domId
});
}-*/;
This is the work done in my view:
private final static String CREDIT_CARD_FORM_ID = "credit-card-form";
#Inject
PaymentMethodInfoView(Binder uiBinder) {
this.initWidget(uiBinder.createAndBindUi(this));
this.formCreditCard.getElement().setId(CREDIT_CARD_FORM_ID);
}
#Override
public void setupBraintree(String serverToken) {
BraintreeClient.setupForm(CREDIT_CARD_FORM_ID, serverToken);
}
Here setupBraintree() is called after the user has entered the credit card data and has clicked okay. As you can see I'm setting the id attribute in the constructor of the view.
Still, for some reason I am getting:
Uncaught Error: Unable to find form with id: "credit-card-form"
Any idea what the issue is?
This is my current Braintree client wrapper. I make sure that the static function load() is getting called in my web application bootstrapper.
public class BraintreeClient {
private final static Logger LOGGER = Logger.getLogger(BraintreeClient.class.getName());
private final static String BRAINTREE_JS_URL = "https://js.braintreegateway.com/js/braintree-2.27.0.min.js";
private static JavaScriptObject braintreeJs;
public static void load(OnSuccessCallback<Void> success, OnFailureCallback failure) {
if(braintreeJs == null) {
LOGGER.fine("Loading " + BRAINTREE_JS_URL);
braintreeJs = ScriptInjector.fromUrl(BRAINTREE_JS_URL).setCallback(
new Callback<Void, Exception>() {
#Override
public void onFailure(Exception caught) {
failure.onFailure(caught);
braintreeJs = null;
}
#Override
public void onSuccess(Void result) {
success.onSuccess(result);
}
}).inject();
}
}
public static void setupForm(String domId, String serverToken) {
if(braintreeJs == null) {
throw new RuntimeException("Braintree has not been loaded. Did you call BraintreeClient.load()?");
}
LOGGER.fine("Setting up form " + domId);
setup(domId, serverToken);
}
private static native void setup(String domId, String serverToken) /*-{
braintree.setup(
serverToken,
"custom",
{
id: domId
});
}-*/;
}

It was just a guess but changing
private static native void setup(String domId, String serverToken) /*-{
braintree.setup(
serverToken,
"custom",
{
id: domId
});
}-*/;
to
private static native void setup(String domId, String serverToken) /*-{
braintree.setup(
serverToken,
"custom",
{
container: domId
});
}-*/;
seemed to be the trick here although I've seen an example in the documentation that used id like I did.

Related

Xamarin CameraX OnImageCapturedCallback

I've been working with the "Getting started with CameraX" port to c# https://github.com/venetasoft/Xamarin.CameraX.
The example uses the ImageSaveCallback, but I'd like to use ImageCapturedCallback instead, since I'd like to access the image in memory.
My code is generating the error "cannot convert from 'CameraX.ImageCapturedCallback' to 'AndroidX.Camera.Core.ImageCapture.OnImageCapturedCallback'", so clearly I'm missing something obvious here.
In the ImageSaveCallback example, the code is:
imageCapture.TakePicture(outputOptions, ContextCompat.GetMainExecutor(this), new ImageSaveCallback(
onErrorCallback: (exc) =>
{
var msg = $"Photo capture failed: {exc.Message}";
Log.Error(TAG, msg, exc);
Toast.MakeText(this.BaseContext, msg, ToastLength.Short).Show();
},
onImageSaveCallback: (output) =>
{
var savedUri = output.SavedUri;
var msg = $"Photo capture succeeded: {savedUri}";
Log.Debug(TAG, msg);
Toast.MakeText(this.BaseContext, msg, ToastLength.Short).Show();
}
));
and the callback is:
class ImageSaveCallback : Java.Lang.Object, IOnImageSavedCallback
{
private const string TAG = "CameraXBasic";
private readonly Action<ImageCaptureException> onErrorCallback;
private readonly Action<OutputFileResults> onImageSaveCallback;
public ImageSaveCallback(Action<OutputFileResults> onImageSaveCallback, Action<ImageCaptureException> onErrorCallback)
{
this.onImageSaveCallback = onImageSaveCallback;
this.onErrorCallback = onErrorCallback;
}
public void OnError(ImageCaptureException exc)
{
this.onErrorCallback.Invoke(exc);
}
public void OnImageSaved(OutputFileResults photoFile)
{
this.onImageSaveCallback.Invoke(photoFile);
}
}
My attempt, based on the above:
imageCapture.TakePicture(ContextCompat.GetMainExecutor(this), new ImageCapturedCallback(
onErrorCallback: (exc) =>
{
// handle error
},
onImageCapturedCallback: (output) =>
{
// handle image
}
));
And the callback class:
class ImageCapturedCallback : Java.Lang.Object {
private readonly Action<ImageCaptureException> onErrorCallback;
private readonly Action<IImageProxy> onImageCapturedCallback;
public ImageCapturedCallback(Action<ImageCaptureException> onErrorCallback, Action<IImageProxy> onImageCapturedCallback)
{
onErrorCallback = onErrorCallback;
onImageCapturedCallback = onImageCapturedCallback;
}
public void OnError(ImageCaptureException exc)
{
this.onErrorCallback.Invoke(exc);
}
public void OnCaptureSuccess(IImageProxy proxyImage)
{
this.onImageCapturedCallback.Invoke(proxyImage);
}
}
I found the answer - there's a branch of the example code https://github.com/venetasoft/Xamarin.CameraX/tree/CameraX_Updated.
Based on that code, the ImageCapturedCallback class looks like this:
class ImageCapturedCallback : OnImageCapturedCallback
{
private readonly Action<ImageCaptureException> onErrorCallback;
private readonly Action<Bitmap> onCapturedSuccessCallback;
public ImageCapturedCallback(Action<Bitmap> onCapturedSuccessCallback, Action<ImageCaptureException> onErrorCallback)
{
this.onCapturedSuccessCallback = onCapturedSuccessCallback;
this.onErrorCallback = onErrorCallback;
}
public override void OnError(ImageCaptureException exc)
{
this.onErrorCallback?.Invoke(exc);
}
public override void OnCaptureSuccess(IImageProxy image)
{
var data = ImageUtil.ImageToJpegByteArray(image);
var imageBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length);
this.onCapturedSuccessCallback?.Invoke(imageBitmap);
base.OnCaptureSuccess(image);
image.Close();
}
}

java.net.ProtocolException: Expected ':status' header not present

I just saw a Protocol Exception suddenly in a working app. Starting today all the network calls are failing and getting empty in our application, but the API is working with web browsers.
I updated okHttp & Gson dependencies in my application Gradle but still get the same error. My Server name is nginx .
I also checked same URL in volley and successfully got a response from the server, but I used the same URL and wrote code in Retrofit and it is not working there (no response from server)
Is this related to an android okHttp problem or is it a server-related problem?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
recyclerview.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerview.setLayoutManager(layoutManager);
tabs_adapter = new Tabs_Adapter(MainActivity.this, topTabList);
recyclerview.setAdapter(tabs_adapter);
new AsyncTask<JSONObject, Object, Tabs_Response>() {
#Override
protected Tabs_Response doInBackground(JSONObject... jsonObjects) {
try {
String url = "https://api.bargaincry.com/apurl/deal/get_ApiCategory/41187";
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
strResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Tabs_Response tabs_response = new Gson().fromJson(strResponse,Tabs_Response.class);
return tabs_response;
}
#Override
protected void onPostExecute(Tabs_Response tabs_response) {
if (tabs_response != null && tabs_response.getTopTabs() != null && tabs_response.getTopTabs().size() > 0) {
topTabList = tabs_response.getTopTabs();
tabs_adapter = new Tabs_Adapter(MainActivity.this, topTabList);
recyclerview.setAdapter(tabs_adapter);
}
}
}.execute();
}
Tap_Response.java:
public class Tabs_Response {
#SerializedName("status")
#Expose
private String status;
#SerializedName("top_tabs")
#Expose
private List<TopTab> topTabs = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<TopTab> getTopTabs() {
return topTabs;
}
public void setTopTabs(List<TopTab> topTabs) {
this.topTabs = topTabs;
}
}
TopTab.java:
public class TopTab {
#SerializedName("category_id")
#Expose
private String categoryId;
#SerializedName("category_name")
#Expose
private String categoryName;
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
Tabs_Adapter.java:
public class Tabs_Adapter extends RecyclerView.Adapter {
private Context context;
private List<TopTab> tabList;
private TopTab topTab;
public Tabs_Adapter(Context context, List<TopTab> tabList){
this.context = context;
this.tabList = tabList;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public TopTab topTab;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView)itemView.findViewById(R.id.tabtext_data);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_items,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
topTab = tabList.get(position);
((MyViewHolder)holder).textView.setText(topTab.getCategoryName());
((MyViewHolder)holder).topTab =topTab;
}
#Override
public int getItemCount() {
if (tabList != null){
return tabList.size();
}else {
return 0;
}
}
LogCat:
java.net.ProtocolException: Expected ':status' header not present
02-14 11:38:52.468 12631-19978/com.example.srikanth.toptabs_activity
W/System.err: at
com.squareup.okhttp.internal.http.FramedTransport.readNameValueBlock(FramedTransport.java:197)
02-14 11:38:52.468 12631-19978/com.example.srikanth.toptabs_activity
W/System.err: at
com.squareup.okhttp.internal.http.FramedTransport.readResponseHeaders(FramedTransport.java:104)
02-14 11:38:52.468 12631-19978/com.example.srikanth.toptabs_activity
W/System.err: at
com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:906)
02-14 11:38:52.468 12631-19978/com.example.srikanth.toptabs_activity
W/System.err: at
com.squareup.okhttp.internal.http.HttpEngine.access$300(HttpEngine.java:92)
02-14 11:38:52.468 12631-19978/com.example.srikanth.toptabs_activity
W/System.err: at
com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:891)
Update Retrofit and Okhttp3 libraries to this version.
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
Fixed in current versions of OkHttp. Please upgrade.

Add terminate button to eclipse console

How can I add terminate button to eclipse console toolbar? I create console in this way:
IOConsole console = new IOConsole( name, null, null, true );
ConsolePlugin.getDefault().getConsoleManager().addConsoles( new IConsole[]{console} );
I found solution. Here is the code:
<extension
point="org.eclipse.ui.console.consolePageParticipants">
<consolePageParticipant
class="com.plugin.console.ConsoleActions"
id="com.plugin.console.PageParticipant">
<enablement>
<instanceof value="com.plugin.console.Console"/>
</enablement>
</consolePageParticipant>
</extension>
Console class:
public class Console extends IOConsole {
public Console(String name, ImageDescriptor imageDescriptor) {
super(name, imageDescriptor);
}
public Console(String name, String consoleType, ImageDescriptor imageDescriptor, boolean autoLifeCycle) {
super(name, consoleType, imageDescriptor, autoLifeCycle);
}
}
Console Participant class:
public class ConsoleActions implements IConsolePageParticipant {
private IPageBookViewPage page;
private Action remove, stop;
private IActionBars bars;
private IConsole console;
#Override
public void init(final IPageBookViewPage page, final IConsole console) {
this.console = console;
this.page = page;
IPageSite site = page.getSite();
this.bars = site.getActionBars();
createTerminateAllButton();
createRemoveButton();
bars.getMenuManager().add(new Separator());
bars.getMenuManager().add(remove);
IToolBarManager toolbarManager = bars.getToolBarManager();
toolbarManager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, stop);
toolbarManager.appendToGroup(IConsoleConstants.LAUNCH_GROUP,remove);
bars.updateActionBars();
}
private void createTerminateAllButton() {
ImageDescriptor imageDescriptor = ImageDescriptor.createFromFile(getClass(), "/icons/stop_all_active.gif");
this.stop = new Action("Terminate all", imageDescriptor) {
public void run() {
//code to execute when button is pressed
}
};
}
private void createRemoveButton() {
ImageDescriptor imageDescriptor = ImageDescriptor.createFromFile(getClass(), "/icons/remove_active.gif");
this.remove= new Action("Remove console", imageDescriptor) {
public void run() {
//code to execute when button is pressed
}
};
}
#Override
public void dispose() {
remove= null;
stop = null;
bars = null;
page = null;
}
#Override
public Object getAdapter(Class adapter) {
return null;
}
#Override
public void activated() {
updateVis();
}
#Override
public void deactivated() {
updateVis();
}
private void updateVis() {
if (page == null)
return;
boolean isEnabled = true;
stop.setEnabled(isEnabled);
remove.setEnabled(isEnabled);
bars.updateActionBars();
}
}

GWT application crashes in latest Firefox versions 21 and above

We have a GWT application which crashes in Firefox versions 21 and above, including in the latest version 23.0.1. In earlier versions of Firefox and IE 9, it works fine. This is in deployed mode and not because of the GWT plugin. The situation it crashes is when there are huge number of RPC calls, may be around 300 to 400.
As the application in which it happens is fairly complex, I tried to simulate this issue with a simple prototype. I observed that my prototype crashes when the number of RPC calls reach 100000. But this scenario is very unlikely in my application where RPC calls are around 300-400 as observed using Firebug.
I am trying to find out what else I am missing in my prototype so that it also crashes with 300-400 RPC calls.
GWT version - 2.4
GXT version - 2.2.5
package com.ganesh.check.firefox.client;
public class FirefoxCrash implements EntryPoint {
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
public native static void consoleLog(String text)/*-{
$wnd.console.log(text);
}-*/;
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
final Label countLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
RootPanel.get("count").add(countLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
class MyHandler implements ClickHandler, KeyUpHandler {
private int resultCount = 0;
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
// Then, we send the input to the server.
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
final int loopCount = Integer.parseInt(textToServer);
resultCount=0;
for (int i = 0; i < loopCount; i++) {
greetingService.getResult(textToServer,
new AsyncCallback<ResultBean>() {
public void onFailure(Throwable caught) {
consoleLog(caught.getMessage());
}
public void onSuccess(ResultBean result) {
//countLabel.setText(++resultCount + "");
resultCount++;
if(resultCount==loopCount){
countLabel.setText(resultCount + "");
}
consoleLog("Result returned for "+resultCount);
}
});
}
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public ResultBean getResult(String name) {
ResultBean result = new ResultBean();
Random random = new Random();
int suffix = random.nextInt();
result.setName("Name "+suffix);
result.setAddress("Address "+suffix);
result.setZipCode(suffix);
result.setDoorNumber("Door "+suffix);
return result;
}
public class ResultBean implements Serializable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
private String name;
private String address;
private int zipCode;
private String doorNumber;
}

GWT retrieve list from datastore via serviceimpl

Hi I'm trying to retrieve a linkedhashset from the Google datastore but nothing seems to happen. I want to display the results in a Grid using GWT on a page. I have put system.out.println() in all the classes to see where I go wrong but it only shows one and I don't recieve any errors. I use 6 classes 2 in the server package(ContactDAOJdo/ContactServiceImpl) and 4 in the client package(ContactService/ContactServiceAsync/ContactListDelegate/ContactListGui). I hope someone can explain why this isn't worken and point me in the right direction.
public class ContactDAOJdo implements ContactDAO {
#SuppressWarnings("unchecked")
#Override
public LinkedHashSet<Contact> listContacts() {
PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
String query = "select from " + Contact.class.getName();
System.out.print("ContactDAOJdo: ");
return (LinkedHashSet<Contact>) pm.newQuery(query).execute();
}
}
public class ContactServiceImpl extends RemoteServiceServlet implements ContactService{
private static final long serialVersionUID = 1L;
private ContactDAO contactDAO = new ContactDAOJdo() {
#Override
public LinkedHashSet<Contact> listContacts() {
LinkedHashSet<Contact> contacts = contactDAO.listContacts();
System.out.println("service imp "+contacts);
return contacts;
}
}
#RemoteServiceRelativePath("contact")
public interface ContactService extends RemoteService {
LinkedHashSet<Contact> listContacts();
}
public interface ContactServiceAsync {
void listContacts(AsyncCallback<LinkedHashSet <Contact>> callback);
}
public class ListContactDelegate {
private ContactServiceAsync contactService = GWT.create(ContactService.class);
ListContactGUI gui;
void listContacts(){
contactService.listContacts(new AsyncCallback<LinkedHashSet<Contact>> () {
public void onFailure(Throwable caught) {
gui.service_eventListContactenFailed(caught);
System.out.println("delegate "+caught);
}
public void onSuccess(LinkedHashSet<Contact> result) {
gui.service_eventListRetrievedFromService(result);
System.out.println("delegate "+result);
}
});
}
}
public class ListContactGUI {
protected Grid contactlijst;
protected ListContactDelegate listContactService;
private Label status;
public void init() {
status = new Label();
contactlijst = new Grid();
contactlijst.setVisible(false);
status.setText("Contact list is being retrieved");
placeWidgets();
}
public void service_eventListRetrievedFromService(LinkedHashSet<Contact> result){
System.out.println("1 service eventListRetreivedFromService "+result);
status.setText("Retrieved contactlist list");
contactlijst.setVisible(true);
this.contactlijst.clear();
this.contactlijst.resizeRows(1 + result.size());
int row = 1;
this.contactlijst.setWidget(0, 0, new Label ("Voornaam"));
this.contactlijst.setWidget(0, 1, new Label ("Achternaam"));
for(Contact contact: result) {
this.contactlijst.setWidget(row, 0, new Label (contact.getVoornaam()));
this.contactlijst.setWidget(row, 1, new Label (contact.getVoornaam()));
row++;
System.out.println("voornaam: "+contact.getVoornaam());
}
System.out.println("2 service eventListRetreivedFromService "+result);
}
public void placeWidgets() {
System.out.println("placewidget inside listcontactgui" + contactlijst);
RootPanel.get("status").add(status);
RootPanel.get("contactlijst").add(contactlijst);
}
public void service_eventListContactenFailed(Throwable caught) {
status.setText("Unable to retrieve contact list from database.");
}
}
It could be the query returns a lazy list. Which means not all values are in the list at the moment the list is send to the client. I used a trick to just call size() on the list (not sure how I got to that solution, but seems to work):
public LinkedHashSet<Contact> listContacts() {
final PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
try {
final LinkedHashSet<Contact> contacts =
(LinkedHashSet<Contact>) pm.newQuery(Contact.class).execute();
contacts.size(); // this triggers to get all values.
return contacts;
} finally {
pm.close();
}
}
But I'm not sure if this is the best practice...

Resources