Pyjnius Autoclass with multiple constructor options - android

I'm trying to use Stripe payments Android SDK in a Kivy app with pyjnius. When trying to initialize Card.java from https://github.com/stripe/stripe-android/blob/v2.1.0/stripe/src/main/java/com/stripe/android/model/Card.java
I get an error 'jnius.jnius.JavaException: No constructor matching your arguments' I think this has to do with the fact the Card.java has multiple constructor options. Here's my code below. (crashes on card = Card(cardNum,expMon,expYear,cvc))
from jnius import autoclass,PythonJavaClass,cast,java_method
Stripe = autoclass('com.stripe.android.Stripe')
Card = autoclass('com.stripe.android.model.Card')
Token = autoclass('com.stripe.android.model.Token')
TokenCallback = autoclass('com.stripe.android.TokenCallback')
class StripeTokenCallback(PythonJavaClass):
__javainterfaces__ = ('com.stripe.android.TokenCallback',)
#java_method('([Lcom.stripe.android.model.Token;)V')
def onSuccess(self,token):
print 'printing token debug'
print token
Cipher = AESCipher.AESCipher(_key)
msg = '{"client_nonce:"' + token + '"}'
print msg
encMsg = Cipher.encrypt(msg)
rsp = connectToServer(_host, _port, encMsg)
decRsp = Cipher.decrypt(rsp)
pass
#java_method('[Ljava.lang.Exception;)V')
def onError(self,error):
print 'Error - Debug'
print error
pass
class StripeToken():
def __init__(self):
pass
def genToken(self,token,cardNum,expMon,expYear,cvc):
card = Card(cardNum,expMon,expYear,cvc)
if not card.validateCard():
print 'Card Not Valid'
return False
stripe = Stripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh")
token_cb = StripeTokenCallback()
stripe.createToken(card,token_cb)

Fixed by casting the input variables to strings and integers
from jnius import autoclass,PythonJavaClass,cast,java_method
Integer = autoclass('java.lang.Integer')
String = autoclass('java.lang.String')
Stripe = autoclass('com.stripe.android.Stripe')
Card = autoclass('com.stripe.android.model.Card')
Token = autoclass('com.stripe.android.model.Token')
TokenCallback = autoclass('com.stripe.android.TokenCallback')
class StripeTokenCallback(PythonJavaClass):
__javainterfaces__ = ('com.stripe.android.TokenCallback',)
#java_method('([Lcom.stripe.android.model.Token;)V')
def onSuccess(self,token):
print 'printing token debug'
print token
Cipher = AESCipher.AESCipher(_key)
msg = '{"client_nonce:"' + token + '"}'
print msg
encMsg = Cipher.encrypt(msg)
rsp = connectToServer(_host, _port, encMsg)
decRsp = Cipher.decrypt(rsp)
pass
#java_method('[Ljava.lang.Exception;)V')
def onError(self,error):
print 'Error - Debug'
print error
pass
def genToken(token,cardNum,expMon,expYear,cvc):
jcardNum = cast('java.lang.String', String(cardNum))
jexpMon = cast('java.lang.Integer', Integer(expMon))
jexpYear = cast('java.lang.Integer', Integer(expYear))
jcvc = cast('java.lang.String', String(cvc))
card = Card(jcardNum,jexpMon,jexpYear,jcvc)
if not card.validateCard():
print 'Card Not Valid'
return False
stripe = Stripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh")
token_cb = StripeTokenCallback()
stripe.createToken(card,token_cb)

Related

How to Use Edit images in OpenAi Kotlin Client

I am using openAi client with android kotlin (implementation com.aallam.openai:openai-client:2.1.3).
Is the path wrong or is the library missing?
val imgURL = Uri.parse("android.resource://" + packageName + "/" + R.drawable.face3)
try {
val images = openAI.image(
edit = ImageEditURL( // or 'ImageEditJSON'
image = FilePath(imgURL.toString()), // <-
mask = FilePath(imgURL.toString()), // <-
prompt = "a sunlit indoor lounge area with a pool containing a flamingo",
n = 1,
size = ImageSize.is1024x1024
)
);
} catch (e: Exception) {
println("error is here:"+e)
}
As can be seen, it wants a path from me, but it does not succeed even though I give the path.
I would suggest updating to version 3 of openai-kotlin, and use Okio's Source to provide files.
Assuming the images are in the res/raw folder, your example would be something like this:
val request = ImageEdit(
image = FileSource(
name = "image.png",
source = resources.openRawResource(R.raw.image).source()
),
mask = FileSource(
name = "mask.png",
source = resources.openRawResource(R.raw.mask).source()
),
prompt = "a sunlit indoor lounge area with a pool containing a flamingo",
n = 1,
size = ImageSize.is1024x1024,
)
val response = client.imageURL(request)

Can't debug variable received from Channel in Kotlin

A have a Kotlin Channel like below. When I put a breakpoint at the Log line I want to be able to see the test variable in Android Studio, but I can not.
val channel = Channel<Int>()
launch {
val test = channel.receive()
Log.d(test.toString()) <--- Breakpoint set here
}
launch {
channel.send(1)
}
This is shown in the Android Studio debugger when I stop at the breakpoint.
this = {Test$test$8#7232}
$channel = {RendezvousChannel#7435}
p$ = {StandaloneCoroutine#7478}
_context = {CombinedContext#7483}
_facade = {DispatchedContinuation#7484}
completion = {StandaloneCoroutine#7478}
label = 1
arity = 2
shadow$_klass_ = {Class#7194} ""
shadow$_monitor_ = -1282289382

Trouble while providing webservices in django python to android

I am new for Django1.10 Python.
I've to provide web services for an app. So I created a web service in python's Django framework. The web service is properly working for iOS but getting issue while handling with android. For dealing with web services in android, using Volley library.
Following error occurring:-
Error Code 500 Internal Server Error
So unable to POST data through android end...
For Web service I am using following code :-
views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.views.decorators import csrf
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.db import IntegrityError, connection
from django.views.decorators.cache import cache_control
from django.core.files.images import get_image_dimensions
import json
from json import loads, dump
from models import Gym
#csrf_exempt
def gym_register_web(request):
data = json.loads(request.body)
gN = str(data['gym_name'])
gPh = str(data['gym_phone'])
gE = str(data['gym_email'])
gL = str(data['gym_landmark'])
gAdd = str(data['gym_address'])
exE = Gym.objects.filter(gym_email = gE)
if exE:
status = 'failed'
msg = 'EmailId already exist'
responseMsg = '{\n "status" : "'+status+'",\n "msg" : "'+msg+'"\n}'
return HttpResponse(responseMsg)
else:
gymI = Gym(gym_name = gN, gym_phone = gPh, gym_email = gE, gym_area = gL, gym_address = gAdd)
gymI.save()
data = Gym.objects.get(gym_email = gE)
status = 'success'
dataType = 'gym_id'
val = str(data.gym_id)
responseMsg = '{\n "status" : "'+status+'",\n "'+dataType+'" : "'+val+'"\n}'
return HttpResponse(responseMsg)
urls.py
from django.conf.urls import url, include
from . import views
from django.views.decorators.csrf import csrf_protect, csrf_exempt
admin.autodiscover()
urlpatterns=[
url(r'^gymRegister/$', views.gym_register_web),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
EDIT:
models.py
from django.db import models
from django.contrib import admin
class Gym(models.Model):
gym_id = models.AutoField(primary_key = True)
gym_name = models.CharField(max_length = 100, null=True,default = None )
gym_email = models.CharField(max_length = 100, null=True,default = None )
gym_phone = models.BigIntegerField(null=True,default = None )
gym_area = models.TextField(max_length = 255, null=True,default = None )
gym_address = models.TextField(max_length = 255, null=True,default = None )
gym_latitude = models.CharField(max_length = 100, null=True,default = None )
gym_longitude = models.CharField(max_length = 100, null=True,default = None )
gym_status = models.IntegerField(null=True,default = None )
gym_website = models.CharField(max_length = 255,null=True,default = None )
gym_ladies_special = models.IntegerField(null=True,default = None )
I tested web service on Advance REST Client providing desired output,
and I would like to remind once again the web service is properly working for iOS
So, Where Should I improve my code...?
Thanks in Advance :)
EDIT:
my android developer trying to send data in json object manner
{ "key1"="val1", "key2"="val2"}
instead sending it in json array(key:value) manner
{
"key1" : "val1",
"key2" : "val2"
}
How can I fetch data sent in object format...
ThankYou
Make sure that in your 'request.body', you are getting a proper dictionary which have all the keys u accessed below.Because,if your 'data' variable dont have any key that you accessed below, it will raise keyerror and u didnt handle keyerror in your code.
If above does not worked, then show me your models.py

Adjust user agent in Android with Volley

I am wondering how to adjust the standard user agent in my http requests. I am using the Volley library and I KNOW how to
set a new user agent
retrieve the default user agent as a string (e.g. "Dalvik/1.6.0 (Linux; U; Android 4.0.2; sdk Build/ICS_MR0") => System.getProperty("http.agent")
What I DON'T know is:
how to get the single elements this user agent is build of, so I can replace only the string "Dalvik/1.6.0" with a custom string.
Is that possible, or do I have to make a string replacement?
Thx
In order to set the user agent globally for all requests sent via volley, here is my solution:
When you are initializing the volley request queue, instead of using the convenient method Volley.newRequestQueue(Context);, use the following snippet:
private RequestQueue makeRequestQueue(Context context) {
DiskBasedCache cache = new DiskBasedCache(new File(context.getCacheDir(), DEFAULT_CACHE_DIR), DISK_CACHE_SIZE);
BasicNetwork network = new BasicNetwork(new MyHurlStack());
RequestQueue queue = new RequestQueue(cache, network);
queue.start();
return queue;
}
public static class MyHurlStack extends HurlStack {
#Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
if (additionalHeaders == null || Collections.emptyMap().equals(additionalHeaders) {
additionalHeaders = new HashMap<>();
}
additionalHeaders.put("User-Agent", "test_user_agent_in_volley");
return super.executeRequest(request, additionalHeaders);
}
}
This solution assumes you are targeting api level >= 9, so we use the HurlStack
The reason why this works is because in HurlStack.executeRequest(Request<?> request, Map<String, String> additionalHeaders) method, the stuff you add to the additionalHeaders would later be added to an HttpUrlConnection request property as in connection.addRequestProperty(headerName, map.get(headerName));
Yes,
Build.FINGERPRINT contains all the information you need,
https://developer.android.com/reference/android/os/Build.html
To get the individual parts, use the individual constant strings,
For detailed OS Version information use Build.VERSION
import android.util.Log;
import android.os.Bundle;
import android.os.Build;
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Build","BOARD = "+Build.BOARD);
Log.i("Build","BOOTLOADER = "+Build.BOOTLOADER);
Log.i("Build","BRAND = "+Build.BRAND);
Log.i("Build","CPU_ABI = "+Build.CPU_ABI);
Log.i("Build","CPU_ABI2 = "+Build.CPU_ABI2);
Log.i("Build","DEVICE = "+Build.DEVICE);
Log.i("Build","DISPLAY = "+Build.DISPLAY);
Log.i("Build","FINGERPRINT = "+Build.FINGERPRINT);
Log.i("Build","HARDWARE = "+Build.HARDWARE);
Log.i("Build","HOST = "+Build.HOST);
Log.i("Build","ID = "+Build.ID);
Log.i("Build","MANUFACTURER = "+Build.MANUFACTURER);
Log.i("Build","MODEL = "+Build.MODEL);
Log.i("Build","PRODUCT = "+Build.PRODUCT);
Log.i("Build","RADIO = "+Build.RADIO);
Log.i("Build","SERIAL = "+Build.SERIAL);
Log.i("Build","TAGS = "+Build.TAGS);
Log.i("Build","TYPE = "+Build.TYPE);
Log.i("Build","USER = "+Build.USER);
Log.i("Build","BASE_OS = "+Build.VERSION.BASE_OS);
Log.i("Build","CODENAME = "+ Build.VERSION.CODENAME);
Log.i("Build","INCREMENTAL = "+ Build.VERSION.INCREMENTAL);
Log.i("Build","RELEASE = "+ Build.VERSION.RELEASE);
Log.i("Build","SDK = "+ Build.VERSION.SDK);
Log.i("Build","SECURITY_PATCH = "+ Build.VERSION.SECURITY_PATCH);
Log.i("$TAG#",Build.FINGERPRINT);
}
}
System.getProperty("http.agent") returns something like:
Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)
It's possible to build all the parts of this using a combination of android.os.Build and java.lang.System.getProperty().
This is an example of what's in android.os.Build running on an emulator:
Build.BOARD = "goldfish_x86"
Build.BOOTLOADER = "unknown"
Build.BRAND = "google"
Build.DEVICE = "generic_x86"
Build.DISPLAY = "sdk_gphone_x86-userdebug 9 PSR1.180720.075 5124027 dev-keys"
Build.FINGERPRINT = "google/sdk_gphone_x86/generic_x86:9/PSR1.180720.075/5124027:userdebug/dev-keys"
Build.HARDWARE = "ranchu"
Build.HOST = "abfarm904"
Build.ID = "PSR1.180720.075"
Build.MANUFACTURER = "Google"
Build.MODEL = "Android SDK built for x86"
Build.PRODUCT = "sdk_gphone_x86"
Build.SUPPORTED_32_BIT_ABIS = {"x86"}
Build.SUPPORTED_64_BIT_ABIS = {}
Build.SUPPORTED_ABIS = {"x86"}
Build.TAGS = "dev-keys"
Build.TIME = 1541887073000
Build.TYPE = "userdebug"
Build.USER = "android-build"
Build.UNKNOWN = "unknown"
Build.VERSION.BASE_OS = ""
Build.VERSION.CODENAME = "REL"
Build.VERSION.INCREMENTAL = "5124027"
Build.VERSION.PREVIEW_SDK_INT = 0
Build.VERSION.RELEASE = "9"
Build.VERSION.SDK_INT = 28
Build.VERSION.SECURITY_PATCH = "2018-09-05"
These properties are always provided by the Dalvik VM, according to Google's documentation:
file.separator = /
java.class.path = .
java.class.version = 50.0
java.compiler = Empty
java.ext.dirs = Empty
java.home = /system
java.io.tmpdir = /sdcard
java.library.path = /vendor/lib:/system/lib
java.vendor = The Android Project
java.vendor.url = http://www.android.com/
java.version = 0
java.specification.version = 0.9
java.specification.vendor = The Android Project
java.specification.name = Dalvik Core Library
java.vm.version = 1.2.0
java.vm.vendor = The Android Project
java.vm.name = Dalvik
java.vm.specification.version = 0.9
java.vm.specification.vendor = The Android Project
java.vm.specification.name = Dalvik Virtual Machine Specification
line.separator = \n
os.arch = armv7l
os.name = Linux
os.version = 2.6.32.9-g103d848
path.separator = :
user.dir = /
user.home = Empty
user.name = Empty
So, the default user agent appears to be composed of:
System.getProperty("java.vm.name") // Dalvik
System.getProperty("java.vm.version") // 2.1.0
System.getProperty("os.name") // Linux
"U" // not sure where to get this
"Android" // or this, probably safe to hard code though
Build.VERSION.RELEASE // 9
Build.MODEL // Android SDK built for x86
Build.ID // PSR1.180720.075

Using App inventor app to mail from google app engine

Using Shival wolfs WolfWebEmail2 in app inventor to send mail via Google app engine and nothing arriving in recipient email.
need to confirm if my code is correct.
not showing any errors on app engine.
Does this look correct for command to run webapp?
application = webapp.WSGIApplication([('/', MainPage), ('/sendemail', sendemail), ('/attach', attachfile)], debug=True)
def main():
run_wsgi_app(application)
Think i have got a bit of small keyboard large finger syndrome.
Many thanks in advance.
OK Zig. Many thanks. Here it is
class sendemail(webapp.RequestHandler):
def process_email(self, data):
outvalue=""
ValidData = False
logging.info("data: %s" %data)
details=data.split("|||")
data = "\"%s\"" %data
if len(details) == 5 or len(details) == 7:
message = mail.EmailMessage()
message.sender = EmailFrom
NewAuthKey = details[0]
EmailTo = details[1]
EmailSubject = details[2]
EmailBody = details[3]
EmailBody = EmailBody.replace("\\t","\t")
if details[4].lower()=="yes" and len(details) == 7:
filename=details[5];
file_id=details[6];
ValidData = True
if ValidData:
if NewAuthKey == AuthKey:
logging.info("Auth Key Valid")
else:
logging.info("Auth Key does not Match")
outvalue = "Auth Key is Invalid"
ValidData = False
if ValidData:
if mail.is_email_valid(EmailTo):
message.to = EmailTo
else:
logging.info("Email Address for TO Address is Invalid")
outvalue = "Email Address for TO Address is Invalid"
ValidData = False
if ValidData:
if len(EmailBody) > 0 and len(EmailSubject) > 0:
message.subject = EmailSubject
message.body = EmailBody
else:
logging.info("Subject or Body was Empty")
outvalue = "Subject or Body was left Empty"
ValidData = False
if ValidData:
if details[4].lower()=="yes":
try:
filedata = db.GqlQuery("SELECT * FROM emailattach WHERE id = :1 LIMIT 1",file_id).get()
if filedata:
message.attachments = [(filename, filedata.blob)]
except Exception, message:
ValidData = False
logging.info("Could not attach file:\n\n "+str(message))
outvalue = "Could not attach file:\n\n "+str(message)
if ValidData:
try:
message.send()
logging.info("Email Sent")
outvalue = "Email Sent"
if details[4].lower()=="yes": ##delete the file once emailed
key = db.GqlQuery("SELECT __key__ FROM emailattach where id = :1", file_id).get()
if key:
db.run_in_transaction(dbSafeDelete,key)
except Exception, message:
logging.info(message)
outvalue = str(message)
self.response.out.write(outvalue)
I hope thats it! new to this.
You've left out the last part of the boiplerplate:
if __name__ == '__main__':
main()
Without it, the first request to each instance won't be processed.
Can you show us the sendemail function?
EDIT
message.sender = EmailFrom
Where is EmailFrom?
Try removing all the validations and check if the email gets sent.
First try running this-
message = mail.EmailMessage(sender="you#domain.com",
subject="Testing")
message.to = "you#domain.com"
message.body = "This is the body!"
message.send()
Change both email addresses to your email.
If it works then check the validation and other parts one at a time.

Categories

Resources