Error in Native Interface in codenameone - codenameone

I have added paypal android SDK under native/android package.Created native interface in main project structure(com.mycompany.myapp).Under native/android the implemented class is using the paypal sdk classes.
My implemented class:
package com.mycompany.myapp;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PaymentActivity;
import android.content.Intent;
import android.net.Uri;
import android.app.Activity;
import com.codename1.impl.android.AndroidNativeUtil;
import com.codename1.impl.android.CodenameOneActivity;
import java.math.BigDecimal;
public class MyNativeImpl {
// private static final String TAG = "paymentdemoblog";
/**
* - Set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
*
* - Set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
* from https://developer.paypal.com
*
* - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
* without communicating to PayPal's servers.
*/
// private static final String CONFIG_ENVIRONMENT =
// PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID = "Aeqc2X1rBIEUtDNqsaRNr0h1neFo9QnNmfgmpA3D32uSLaHpGJu9NV1KfMnFmy7O-_hV47I7ST0SXDW2";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
private static Activity activity() {
return com.codename1.impl.android.AndroidNativeUtil.getActivity();
}
public String payPalTest() {
//Activity activity = AndroidNativeUtil.getActivity();
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"HeadSet", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(activity(),PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
activity().startActivityForResult(intent, REQUEST_CODE_PAYMENT);
return "test";
}
public boolean isSupported() {
return false;
}
}
I called the method from main class:
MyNative my = (MyNative)NativeLookup.create(MyNative.class);
if(my!= null){
String aa =my.payPalTest();
System.out.println("result::" + aa);
System.out.println("paypalInt" + my.toString());
}
the apk build successfully but getting below error while trigger the code:
android.content.ActivityNotFound
Exception:Unable to find explicit activity class{com.mycompany.myapp/com.paypal.android.sdk.paymentActivity....
It is searching the paypal sdk classes under main project folder structure.Do I need to add the SDK jar under the said structure?
What I need to do to fix the issue.

The code looks fine, I am guessing this is something in the configuration.
Unable to find explicit activity class Payment activity with PayPal SDK in Xamarin on Android

Related

Rest Client - Can i set connectionPoolSize?

Microprofile allows to define connectionPoolSize from RestClient like this:
io.smallrye.restclient.tests.proxy.HelloClient/property/resteasy.connectionPoolSize = 4
When I set this property in my project, quarkus ignores it. How can i define it?
Create class MyRestClientBuilderListener implements RestClientBuilderListener:
package org.myproject.config
public class MyRestClientBuilderListener implements RestClientBuilderListener {
static final Logger LOG = LoggerFactory.getLogger(MgiRestClientBuilderListener.class);
static final String CONNECTION_POOL_SIZE_PROP = "config.restclient.connectionPoolSize";
#Override
public void onNewBuilder(RestClientBuilder builder) {
Config cfg = ConfigProvider.getConfig();
Integer poolSizeConnection = cfg.getValue(CONNECTION_POOL_SIZE_PROP, Integer.class);
if(poolSizeConnection == null) {
poolSizeConnection = 50;//default
}
builder.property("resteasy.connectionPoolSize", poolSizeConnection);
}
}
Create file with name org.eclipse.microprofile.rest.client.spi.RestClientBuilderListener in META-INF\services with content:
org.myproject.config.MyRestClientBuilderListener
If your configured client is #RegisterRestClient(configKey="myClient"), to set the pool size use:
quarkus.rest-client.myClient.connection-pool-size: 5
(...and not myClient/mp-rest/connectionPoolSize)

Integration testing flink job

I've written a small flink application. I has some input, and enriches it with data from an external source. It's an RichAsyncFunction and within the open method I construct a http client to be used for the enrichment.
Now I want to write an integration test for my job. But since the http client is created within the open method I have no means to provide it, and mock it in my integration test. I've tried to refactor it providing it within the constructor, but I'm always getting serialisation errors.
This is the example I'm working from:
https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/asyncio.html
Thanks in advance :)
This question was posted over a year ago but I'll post the answer in-case anyone stumbles upon this in the future.
The serialization exception you are seeing is likely this
Exception encountered when invoking run on a nested suite. *** ABORTED *** (610 milliseconds)
java.lang.NullPointerException:
at java.util.Objects.requireNonNull(Objects.java:203)
at org.apache.flink.streaming.runtime.streamrecord.StreamElementSerializer.<init>(StreamElementSerializer.java:64)
at org.apache.flink.streaming.api.operators.async.AsyncWaitOperator.setup(AsyncWaitOperator.java:136)
at org.apache.flink.streaming.api.operators.SimpleOperatorFactory.createStreamOperator(SimpleOperatorFactory.java:77)
at org.apache.flink.streaming.api.operators.StreamOperatorFactoryUtil.createOperator(StreamOperatorFactoryUtil.java:70)
at org.apache.flink.streaming.util.AbstractStreamOperatorTestHarness.setup(AbstractStreamOperatorTestHarness.java:366)
at org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness.setup(OneInputStreamOperatorTestHarness.java:165)
...
The reason is that your test operator needs to know how to deserialize the DataStream input type. The only way to provide this is by supplying it directly while initializing the testHarness and then passing it to the setup() method call.
So to test the example from the Flink docs you linked you can do something like this (my implementation is in Scala but you can adapt it to Java as well)
import org.apache.flink.api.common.ExecutionConfig
import org.apache.flink.api.java.typeutils.TypeExtractor
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.datastream.AsyncDataStream.OutputMode
import org.apache.flink.streaming.api.operators.async.AsyncWaitOperator
import org.apache.flink.streaming.runtime.tasks.{StreamTaskActionExecutor, TestProcessingTimeService}
import org.apache.flink.streaming.runtime.tasks.mailbox.{MailboxExecutorImpl, TaskMailboxImpl}
import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness
import org.scalatest.{BeforeAndAfter, FunSuite, Matchers}
/**
This test case is written using Flink 1.11+.
Older versions likely have a simpler constructor definition for [[AsyncWaitOperator]] so you might have to remove the last two arguments (processingTimeService and mailboxExecutor)
*/
class AsyncDatabaseRequestSuite extends FunSuite with BeforeAndAfter with Matchers {
var testHarness: OneInputStreamOperatorTestHarness[String, (String, String)] = _
val TIMEOUT = 1000
val CAPACITY = 1000
val MAILBOX_PRIORITY = 0
def createTestHarness: Unit = {
val operator = new AsyncWaitOperator[String, (String, String)](
new AsyncDatabaseRequest {
override def open(configuration: Configuration): Unit = {
client = new MockDatabaseClient(host, post, credentials); // put your mock DatabaseClient object here
}
},
TIMEOUT,
CAPACITY,
OutputMode.UNORDERED,
new TestProcessingTimeService,
new MailboxExecutorImpl(
new TaskMailboxImpl,
MAILBOX_PRIORITY,
StreamTaskActionExecutor.IMMEDIATE
)
)
// supply the TypeSerializer for the "input" type of the operator
testHarness = new OneInputStreamOperatorTestHarness[String, (String, String)](
operator,
TypeExtractor.getForClass(classOf[String]).createSerializer(new ExecutionConfig)
)
// supply the TypeSerializer for the "output" type of the operator to the setup() call
testHarness.setup(
TypeExtractor.getForClass(classOf[(String, String)]).createSerializer(new ExecutionConfig)
)
testHarness.open()
}
before {
createTestHarness
}
after {
testHarness.close()
}
test("Your test case goes here") {
// fill in your test case here
}
}
Here is the solution in Java
class TestingClass {
#InjectMocks
ClassUnderTest cut;
private static OneInputStreamOperatorTestHarness<IN, OUT> testHarness; // replace IN, OUT with your asyncFunction's
private static long TIMEOUT = 1000;
private static int CAPACITY = 1000;
private static int MAILBOX_PRIORITY = 0;
private long UNUSED_TIME = 0L;
Driver driverRef;
public void createTestHarness() throws Exception {
cut = new ClassUnderTest() {
#Override
public void open(Configuration parameters) throws Exception {
driver = mock(Driver.class); // mock your driver (external data source here).
driverRef = driver; // create external ref to driver to refer to in test
}
};
MailboxExecutorImpl mailboxExecutorImpl = new MailboxExecutorImpl(
new TaskMailboxImpl(), MAILBOX_PRIORITY, StreamTaskActionExecutor.IMMEDIATE
);
AsyncWaitOperator operator = new AsyncWaitOperator<>(
gatewayEnrichment,
TIMEOUT,
CAPACITY,
ORDERED,
new TestProcessingTimeService(),
mailboxExecutorImpl
);
testHarness = new OneInputStreamOperatorTestHarness<IN, OUT>(
operator,
TypeExtractor.getForClass(IN.class).createSerializer(new ExecutionConfig())
);
testHarness.setup(TypeExtractor.getForClass(OUT.class).createSerializer(new ExecutionConfig()));
testHarness.open();
}
#BeforeEach()
void setUp() throws Exception {
createTestHarness();
MockitoAnnotations.openMocks(this);
}
#AfterEach
void tearDown() throws Exception {
testHarness.close();
}
#Test
public void test_yourTestCase() throws Exception {
}
}

Build Server: 'Error! Failed to transfer some classes!'

I wanted to test my App on my phone, so I send it to the Build server (Android). Instead of the expected, successfull build, I got an error:
Error! Failed to transform some classes
java.lang.RuntimeException: java.lang.ClassNotFoundException: com.private.container.projectDetailsContainer.top.center.progCircle.ProgressCircle
at net.orfjackal.retrolambda.lambdas.BackportLambdaInvocations.loadClass(BackportLambdaInvocations.java:116)
at net.orfjackal.retrolambda.lambdas.BackportLambdaInvocations.access$100(BackportLambdaInvocations.java:16)
at net.orfjackal.retrolambda.lambdas.BackportLambdaInvocations$InvokeDynamicInsnConverter.backportLambda(BackportLambdaInvocations.java:101)
at net.orfjackal.retrolambda.lambdas.BackportLambdaInvocations$InvokeDynamicInsnConverter.visitInvokeDynamicInsn(BackportLambdaInvocations.java:94)
at net.orfjackal.retrolambda.asm.ClassReader.readCode(ClassReader.java:1452)
at net.orfjackal.retrolambda.asm.ClassReader.readMethod(ClassReader.java:1017)
at net.orfjackal.retrolambda.asm.ClassReader.accept(ClassReader.java:693)
at net.orfjackal.retrolambda.asm.ClassReader.accept(ClassReader.java:506)
at net.orfjackal.retrolambda.Transformers.lambda$transform$4(Transformers.java:106)
at net.orfjackal.retrolambda.Transformers$$Lambda$8/636718812.accept(Unknown Source)
at net.orfjackal.retrolambda.Transformers.transform(Transformers.java:120)
at net.orfjackal.retrolambda.Transformers.transform(Transformers.java:106)
at net.orfjackal.retrolambda.Transformers.backportClass(Transformers.java:46)
at net.orfjackal.retrolambda.Retrolambda.run(Retrolambda.java:72)
at net.orfjackal.retrolambda.Main.main(Main.java:26)
Caused by: java.lang.ClassNotFoundException: com.private.container.projectDetailsContainer.top.center.progCircle.ProgressCircle
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at net.orfjackal.retrolambda.NonDelegatingClassLoader.loadClass(NonDelegatingClassLoader.java:27)
at net.orfjackal.retrolambda.lambdas.BackportLambdaInvocations.loadClass(BackportLambdaInvocations.java:114)
... 14 more
What am I doing wrong?
Notice
I already used the App on my mobile device and there was no problem with it
The App has no problems running in the simulator
EDIT 1
As you asked for it, here is the way I use the class (the only time I use it):
package com.companyname.mobile.container.projectDetailsContainer.top.center.progCircle;
import java.util.HashMap;
import com.codename1.ui.Container;
import com.codename1.ui.Label;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.GridLayout;
import com.companyname.mobile.renderer.projectListitem.ProjectListItem;
public class ProgressCircleContainer extends Container {
/* attributes */
private ProgressCircle progressCircle;
/************************/
/**
* Constructor for the Container.
* The given parameter is the clicked listitem
*
* #param clicked List item clicked by the user
*/
public ProgressCircleContainer (ProjectListItem clicked) {
this.clicked = clicked;
init();
}
/*
* initializes the layout of the container
*/
private void init () {
this.layout = new GridLayout (2);
/* left container */
progressCircle = new ProgressCircle(clicked.getStatus());
leftCont = new Container ();
leftContLayout = new BorderLayout();
leftCont.setLayout(leftContLayout);
leftCont.add(BorderLayout.CENTER, progressCircle);
/****************************/
this.add(leftCont); //using gridlayout for the form
}
/* Getter and Setter */
}
The class is much larger, but I left out the unnessecary parts of it.
Here is the ProgCircle class:
package com.companyname.mobile.container.projectDetailsContainer.top.center.progCircle;
import java.io.IOException;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Graphics;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.layouts.LayeredLayout;
import com.codename1.ui.util.Resources;
import com.codename1.ui.Graphics;
import com.codename1.ui.geom.Rectangle;
/**
* This class partly draws and partly displays the round progress circle
* one can see in the north of ProjectDetailsForm.
*
* It uses a LayeredLayout to paint the progress as a circle in the background
* while concealing the unnecessary part of it with a picture. On the GlassPane
* layer, there is a label showing the progress in percent
*
* {#http://stackoverflow.com/questions/35841377/how-to-make-a-round-progress-bar-in-codename-one}
*
*/
public class ProgressCircle extends Container {
/* attributes */
private Label percent;
private LayeredLayout layout;
/************************/
/* constants */
public static final String ROUND_PROG_BAR = "roundprogbar.png";
/************************/
/**
* Constructor for the round progress bar.
* The parameter given is the color it will be drawn in.
*
* #param statusColor color the progress will be drawn in
*/
public ProgressCircle (int statusColor) {
layout = new LayeredLayout();
this.setLayout(layout);
try {
Resources s = Resources.open("/theme.res");
Image progressOverlayImage = s.getImage(ROUND_PROG_BAR);
int currentProgress360 = 100;
percent = new Label (String.valueOf((int) (((double)currentProgress360 /360)*100))+ "%");
percent.getUnselectedStyle().setFgColor(0x000000);
percent.getUnselectedStyle().setAlignment(Component.CENTER);
this.add(new Label (progressOverlayImage.scaled((int)(progressOverlayImage.getWidth()*0.65), (int)(progressOverlayImage.getHeight()*0.65)), "Container")).
add(FlowLayout.encloseCenterMiddle(percent));
this.getUnselectedStyle().setBgPainter((Graphics g, Rectangle rect) -> {
g.setColor(statusColor);
g.fillArc(this.getX(), this.getY(),(int)(progressOverlayImage.getWidth()*0.65), (int)(progressOverlayImage.getHeight()*0.65), 0, currentProgress360);
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
Another notice:
I was wondering if it could be the too long package name. I replaced my companies name by 'companyname', but their length is equal.
If you need further information, let me know.
If it does not compile like this, I may have deleted a nessecary part, but then it is my fault right now. The app compiles successfully in the simulator and is fully functioning
EDIT 2:
here a link to the full error:
http://pastebin.com/ktCAbxk5
Have you modified your project class path in any way (eg added any jars or other source dirs)?
Do you have a class within the package com.private?
private is a reserved word in Java so I'm actually very surprised this works for you anywhere.

What does 'moveFailed' really do?

I want to create a file input that behaves as follows:
Process the exchange
Attempt to copy the input file to a shared drive
If step (2) fails (e.g. share is down) then move to local file instead
Following the doc the 'moveFailed' parameter allows to "set a different target directory when moving files after processing (configured via move defined above) failed". So this sounds like the moveFailed would cover step (3).
The following test, however fails...what am I doing wrong ? I am using camel 2.10.0.fuse.
package sandbox.camel;
import java.io.File;
import org.apache.camel.Endpoint;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
public class MoveFailedTest extends org.apache.camel.test.junit4.CamelTestSupport {
private String failedDir = "move-failed";
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:tmp/prepare").to("file:tmp/input");
from("file:tmp/input?move=/doesnotexist&moveFailed=" + failedDir).to("file:tmp/output");
}
};
}
#Test
public void test_move() throws Exception {
// arrange
File moveFailedDir = new File("tmp/input/" + failedDir);
moveFailedDir.mkdirs();
File[] failedCount1 = moveFailedDir.listFiles();
failedCount1 = failedCount1 == null ? new File[0] : failedCount1;
String messagePayload = "Hello";
Endpoint input = getMandatoryEndpoint("file:tmp/prepare");
MockEndpoint output = getMockEndpoint("mock:file:tmp/output");
output.setMinimumExpectedMessageCount(1);
output.expectedBodiesReceived(messagePayload);
// act
template.asyncSendBody(input, messagePayload);
Thread.sleep(3000);
// assert: only 1 output
assertMockEndpointsSatisfied();
// assert: renamed failed, hence input file was moved to 'movefailed' directory
File[] failedCount2 = moveFailedDir.listFiles();
assertEquals("No file appeared in 'movefailed' directory", failedCount1.length + 1, failedCount2.length);
}
}
Your test is most likely wrong. The autocreate option is default true, which means directories is created if needed.

Problems calling Android's getSharedPreferences(); from SQLiteOpenHelper class

First I want to describe my situation briefly.
I have two classes, one MainClass and one DataBaseHelper class, which extends SQLiteOpenHelper.
From my MainClass I call a method in the DataBaseHelper class to open a data base. Before opening the data base I want to check the users data base version (this is important as soon as I want to update the data base and push it to the Android market). So from the DataBaseHelper class I call the following method, which is in the MainClass.
public int checkCurrentDbVersion(){
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
int dbUpgradeVar = settings.getInt("dbUpgradeVar", 1);
return dbUpgradeVar;
}
I call the checkCurrentDbVersion() method from the DataBaseHelper class like so:
MainClass currentDbVersion = new MainClass();
int oldDbVersion = currentDbVersion.checkCurrentDbVersion();
As soon as the debugger runs the following line, it stops.
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
What am I doing wrong? I have no constructor defined. Could that be the failure?
Best Regards
Johe
I found a solution, which I wanna share. It can be found here:
Passing data through intents instead of constructors
I forgot the context (I am still not 100% sure what the context is all about, but anyways...).
So to get the code working I changed it like so:
public int checkCurrentDbVersion(Context context){
// Restore preferences
SharedPreferences settings = context.getSharedPreferences(PREFERENCES, 0);
int dbUpgradeVar = settings.getInt("dbUpgradeVar", 1);
return dbUpgradeVar;
}
Call the method
private final Context myContext;
/*
*do some other stuff here
*/
MainClass currentDbVersion = new MainClass();
int oldDbVersion = currentDbVersion.checkCurrentDbVersion(myContext);
Here is my solution
1.my app can not use.
import androidx.appcompat.app.AppCompatActivity;
SharedPreferences settings = new AppCompatActivity().getSharedPreferences(PREFERENCES, 0);
2.works fine in my app
public static boolean isLoggedIn(AppCompatActivity activity) {
final SharedPreferences loggedSP = activity.getSharedPreferences(SP_name.get_Logged_SPname(), MODE_PRIVATE);
return loggedSP.getBoolean(SP_name.get_Logged_SPkey(),false);
}
to execute it in my main activity
boolean a = LoginRepository.isLoggedIn(this);

Resources