How to use nested NamedDomainObjectContainer in Java - java

I have been trying to create a custom plugin with an extension that has has nested NamedDomainObjectContainer's. I keep getting a strange error if I implement it in Java using Action compared to the same thing in Groovy using Closure.
Here is the Groovy one:
package com.example.gradle
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.Plugin
class DeploymentPlugin implements Plugin<Project> {
void apply(final Project project) {
def servers = project.container(Server)
servers.all {
nodes = project.container(Node)
}
project.extensions.add('deployments', servers)
}
static class Server {
NamedDomainObjectContainer<Node> nodes
String url
String name
Server(String name) {
this.name = name
}
def nodes(final Closure configureClosure) {
nodes.configure(configureClosure)
}
}
static class Node {
String name
Integer port
Node(String name) {
this.name = name
}
}
}
And the Java one:
package com.example.gradle;
import org.gradle.api.Action;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public class DeploymentPlugin2 implements Plugin<Project> {
public void apply(final Project project) {
final NamedDomainObjectContainer<Server2> servers = project.container(Server2.class);
servers.all(it ->
it.nodes = project.container(Node2.class)
);
project.getExtensions().add("deployments2", servers);
}
public static class Server2 {
public NamedDomainObjectContainer<Node2> nodes;
public String url;
public String name;
public Server2(String name) {
this.name = name;
}
public void nodes(final Action<? super NamedDomainObjectContainer<Node2>> action) {
action.execute(nodes);
}
}
public static class Node2 {
public String name;
public Integer port;
public Node2(String name) {
this.name = name;
}
}
}
And the build.gradle file:
apply plugin: com.example.gradle.DeploymentPlugin
apply plugin: com.example.gradle.DeploymentPlugin2
wrapper {
gradleVersion = '5.4.1'
distributionType = Wrapper.DistributionType.ALL
}
deployments {
aws {
url = 'http://aws.address'
nodes {
node1 {
port = 9000
}
node2 {
port = 80
}
}
}
cf {
url = 'http://cf.address'
nodes {
test {
port = 10001
}
acceptanceTest {
port = 10002
}
}
}
}
deployments2 {
aws {
url = 'http://aws.address'
nodes {
node1 {
port = 9000
}
node2 {
port = 80
}
}
}
cf2 {
url = 'http://cf.address'
nodes {
test {
port = 10001
}
acceptanceTest {
port = 10002
}
}
}
}
Which fails with:
PS C:\source\gradle-nested-doc-bug> ./gradlew tasks
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\source\gradle-nested-doc-bug\build.gradle' line: 42
* What went wrong:
A problem occurred evaluating root project 'gradle-nested-doc-bug'.
> Could not find method node1() for arguments [build_afudfj5pxfy9w4tkoowa6djon$_run_closure3$_closure12$_closure14$_closure15#4724dfaa] on object of type com.example.gradle.DeploymentPlugin2$Server2.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
There is something funky going on with nested NamedDomainObjectContainer's when using Action.
Any idea what is wrong with this?

Something Like:
import org.gradle.api.Project;
public static class Server2 {
Project project;
public NamedDomainObjectContainer<Node2> nodes = getProject().container(Node2.class);
public String url;
public String name;
public Server2(String name) {
this.name = name;
}
public void nodes(final Action<? super NamedDomainObjectContainer<Node2>> action) {
action.execute(nodes);
}
}

Related

Java - Override a WebRequest on Web Service Call

Quick background, our company connects to an ERP system (Sage) via web services for some functions. We have both c# (.net) and java code that performs calls to the Web Service (WS). Recently Sage introduced Basic Authentication into their WS.
Please note: This is a JAVA question, but I'll show an example in C# first to explain.
In the c# program, I first would create an object that is for accessing the WS:
var sageService = new CAdxWebServiceXmlCCServiceBasicAuth();
I then set up credential information:
var sageServiceCallContext = SageFactory.Instance.GetCallContext();
sageService.Credentials = new NetworkCredential(SageUser, SagePwd);
sageService.PreAuthenticate = true;
then finally the call to the specific web service method:
sageCustomerSvcResponse = sageService.run(sageServiceCallContext, "YTDPROF", sageCustomerRequestInXml);
When I set up the service object I use a custom class that looks like this:
public class CAdxWebServiceXmlCCServiceBasicAuth : CAdxWebServiceXmlCCService
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
NetworkCredential credentials = Credentials as NetworkCredential;
if (credentials != null)
{
string authInfo = "";
if (credentials.Domain != null && credentials.Domain.Length > 0)
{
authInfo = string.Format(#"{0}\{1}:{2}", credentials.Domain, credentials.UserName, credentials.Password);
}
else
{
authInfo = string.Format(#"{0}:{1}", credentials.UserName, credentials.Password);
};
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
webRequest.Headers["Authorization"] = "Basic " + authInfo;
}
return webRequest;
}
}
What happens is that now, when I perform any call to the web service methods, the GetWebRequest from the class is invoked every time. This is how we implemented basis authentication in c#.
How do I do this in Java?
In the java code currently, I create the service object (that which accesses the web services) this way:
WebServiceInvoker service = new WebServiceInvoker(SageWSURL,"");
and the WebServiceInvoker looks like this (truncated for brevity):
public WebServiceInvoker(String url, String dummy) throws ServiceException, IOException {
serviceLocator = new CAdxWebServiceXmlCCServiceLocator();
service = serviceLocator.getCAdxWebServiceXmlCC(url);
cc = new CAdxCallContext();
cc.setCodeLang("ENG");
cc.setCodeUser("USER");
cc.setPassword("PAWWORD");
cc.setPoolAlias("POOL");
cc.setRequestConfig("adxwss.trace.on=on&adxwss.trace.size=16384&adonix.trace.on=on&adonix.trace.level=3&adonix.trace.size=8");
log = new PrintWriter(new BufferedWriter(new FileWriter("C:/Kalio/service/orders/log.txt")));
}
the webservice locator looks like this:
public class CAdxWebServiceXmlCCServiceLocator extends org.apache.axis.client.Service implements com.adonix.www.WSS.CAdxWebServiceXmlCCService {
public CAdxWebServiceXmlCCServiceLocator() {
}
public com.adonix.www.WSS.CAdxWebServiceXmlCC getCAdxWebServiceXmlCC() throws javax.xml.rpc.ServiceException {
java.net.URL endpoint;
System.out.println("using local Sage Web Servivce URL:" + CAdxWebServiceXmlCC_address);
try {
endpoint = new java.net.URL(CAdxWebServiceXmlCC_address);
}
catch (java.net.MalformedURLException e) {
throw new javax.xml.rpc.ServiceException(e);
}
return getCAdxWebServiceXmlCC(endpoint);
}
public com.adonix.www.WSS.CAdxWebServiceXmlCC getCAdxWebServiceXmlCC(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
try {
com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub _stub = new com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub(portAddress, this);
_stub.setPortName(getCAdxWebServiceXmlCCWSDDServiceName());
return _stub;
}
catch (org.apache.axis.AxisFault e) {
return null;
}
}
and the specific method within that class is this:
public String getCustomer(String constructedXML) throws RemoteException {
**CAdxResultXml result = service.run(cc, "XTDPROF", constructedXML);**
CAdxMessage[] messages = result.getMessages();
for (int i = 0; i<messages.length; i++) {
CAdxMessage message = messages[i];
log.println("X3 get customer message: " + message.getMessage());
log.println("X3 get customer message type: " + message.getType());
}
return result.getResultXml();
}
So my questions is, how to I emulate that override that I see in the .net program in Java? It seems like it would be somewhere in either the service locator or invoker, but the program does not use standard http classes, but this adxwss stuff. I tried a straight c# to java conversion and that way didn't help. I have seen examples where basicAuth is implemented, but not against web service calls.
The c# is pretty clear cut, because once I create the service object using the basicAuth override, every web service calls goes through the orderride. How does that happen in Java?
I'll be happy to provide more info if needed and I'll continue to look/experiment, but at the moment I'm treading water.
Adding:
In tracing through the java code I found the specific web service call (run) where an apache "call" object is created. Is this where basicauth can be added?
public com.adonix.www.WSS.CAdxResultXml run(com.adonix.www.WSS.CAdxCallContext callContext, java.lang.String publicName, java.lang.String inputXml) throws java.rmi.RemoteException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("http://www.adonix.com/WSS", "run"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {callContext, publicName, inputXml});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.adonix.www.WSS.CAdxResultXml) _resp;
} catch (java.lang.Exception _exception) {
return (com.adonix.www.WSS.CAdxResultXml) org.apache.axis.utils.JavaUtils.convert(_resp, com.adonix.www.WSS.CAdxResultXml.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
throw axisFaultException;
}
}
The solution I came up with is not elegant, but then I'm not a guru in Java, just know enough to be given these tasks.
Our company uses Sage as our ERP system and Sage has a WSDL to define the basic web services it provides.
Sage Web Servicew WSDL
In their latest version of Sage they went with basic authentication, but did not build it into the new WSDL. Since I could not seem to extend the class (CAdxWebServiceXmlCCService), I just copied/pasted a new class called CAdxWebServiceXmlCCServiceBasicAuth. The full code is shown below if anyone ever has need to deal with something like this in a web service.
The key point where BaiscAuth set set up is in the getCAdxWebServiceXmlCC method. I added setPassword and setUserName to the stub that is returned. What this accomplishes is that every time I perform a webservice method call, that stub is now part of the header.
package com.adonix.www.WSS;
import java.net.URL;
import java.util.Base64;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import javax.xml.rpc.ServiceException;
public class CAdxWebServiceXmlCCServiceBasicAuth extends org.apache.axis.client.Service implements com.adonix.www.WSS.CAdxWebServiceXmlCCService {
public CAdxWebServiceXmlCCServiceBasicAuth() {
}
public CAdxWebServiceXmlCCServiceBasicAuth(org.apache.axis.EngineConfiguration config) {
super(config);
}
public CAdxWebServiceXmlCCServiceBasicAuth(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
super(wsdlLoc, sName);
}
// Use to get a proxy class for CAdxWebServiceXmlCC
private java.lang.String CAdxWebServiceXmlCC_address = "http://10.28.0.7:8124/soap-generic/syracuse/collaboration/syracuse/CAdxWebServiceXmlCC";
public java.lang.String getCAdxWebServiceXmlCCAddress() {
return CAdxWebServiceXmlCC_address;
}
// The WSDD service name defaults to the port name.
private java.lang.String CAdxWebServiceXmlCCWSDDServiceName = "CAdxWebServiceXmlCC";
public java.lang.String getCAdxWebServiceXmlCCWSDDServiceName() {
return CAdxWebServiceXmlCCWSDDServiceName;
}
public void setCAdxWebServiceXmlCCWSDDServiceName(java.lang.String name) {
CAdxWebServiceXmlCCWSDDServiceName = name;
}
public com.adonix.www.WSS.CAdxWebServiceXmlCC getCAdxWebServiceXmlCC(String userName,String password) throws javax.xml.rpc.ServiceException {
java.net.URL endpoint;
try {
endpoint = new java.net.URL(CAdxWebServiceXmlCC_address);
}
catch (java.net.MalformedURLException e) {
throw new javax.xml.rpc.ServiceException(e);
}
return getCAdxWebServiceXmlCC(endpoint,userName,password);
}
public com.adonix.www.WSS.CAdxWebServiceXmlCC getCAdxWebServiceXmlCC(java.net.URL portAddress,String userName,String password) throws javax.xml.rpc.ServiceException {
try {
com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub _stub = new com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub(portAddress, this);
_stub.setPortName(getCAdxWebServiceXmlCCWSDDServiceName());
_stub.setPassword(password);
_stub.setUsername(userName);
return _stub;
}
catch (org.apache.axis.AxisFault e) {
return null;
}
}
public void setCAdxWebServiceXmlCCEndpointAddress(java.lang.String address) {
CAdxWebServiceXmlCC_address = address;
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
try {
if (com.adonix.www.WSS.CAdxWebServiceXmlCC.class.isAssignableFrom(serviceEndpointInterface)) {
com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub _stub = new com.adonix.www.WSS.CAdxWebServiceXmlCCSoapBindingStub(new java.net.URL(CAdxWebServiceXmlCC_address), this);
_stub.setPortName(getCAdxWebServiceXmlCCWSDDServiceName());
return _stub;
}
}
catch (java.lang.Throwable t) {
throw new javax.xml.rpc.ServiceException(t);
}
throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
if (portName == null) {
return getPort(serviceEndpointInterface);
}
java.lang.String inputPortName = portName.getLocalPart();
if ("CAdxWebServiceXmlCC".equals(inputPortName)) {
return getCAdxWebServiceXmlCC();
}
else {
java.rmi.Remote _stub = getPort(serviceEndpointInterface);
((org.apache.axis.client.Stub) _stub).setPortName(portName);
return _stub;
}
}
public javax.xml.namespace.QName getServiceName() {
return new javax.xml.namespace.QName("http://www.adonix.com/WSS", "CAdxWebServiceXmlCCService");
}
private java.util.HashSet ports = null;
public java.util.Iterator getPorts() {
if (ports == null) {
ports = new java.util.HashSet();
ports.add(new javax.xml.namespace.QName("http://www.adonix.com/WSS", "CAdxWebServiceXmlCC"));
}
return ports.iterator();
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
if ("CAdxWebServiceXmlCC".equals(portName)) {
setCAdxWebServiceXmlCCEndpointAddress(address);
}
else
{ // Unknown Port Name
throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
}
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
setEndpointAddress(portName.getLocalPart(), address);
}
#Override
public CAdxWebServiceXmlCC getCAdxWebServiceXmlCC() throws ServiceException {
// TODO Auto-generated method stub
return null;
}
#Override
public CAdxWebServiceXmlCC getCAdxWebServiceXmlCC(URL portAddress) throws ServiceException {
// TODO Auto-generated method stub
return null;
}
}

Override Ribbon Server List to get a list of host names from consul

I am trying to override Ribbon Server List to get a list of host names from consul. I have the consul piece working properly(when testing with hardcode values) to get the hostname and port for a service. The issue I am having is when I try to autowire in IClientConfig. I get an exception that IClientConfig bean could not be found. How do I override the ribbon configurations and autowire IClientConfig in the ribbonServerList method.
I have tried following the instructions here at http://projects.spring.io/spring-cloud/spring-cloud.html#_customizing_the_ribbon_client on how to customize ribbon client configuration. I keep getting the following error:
Description:
Parameter 0 of method ribbonServerList in com.intradiem.enterprise.keycloak.config.ConsulRibbonSSLConfig required a bean of type 'com.netflix.client.config.IClientConfig' that could not be found.
Which is causing spring-boot to fail.
Bellow are the classes that I am trying to use to create
AutoConfiguration Class:
#Configuration
#EnableConfigurationProperties
#ConditionalOnBean(SpringClientFactory.class)
#ConditionalOnProperty(value = "spring.cloud.com.intradiem.service.apirouter.consul.ribbon.enabled", matchIfMissing = true)
#AutoConfigureAfter(RibbonAutoConfiguration.class)
#RibbonClients(defaultConfiguration = ConsulRibbonSSLConfig.class)
//#RibbonClient(name = "question-answer-provider", configuration = ConsulRibbonSSLConfig.class)
public class ConsulRibbonSSLAutoConfig
{
}
Configuration Class:
#Component
public class ConsulRibbonSSLConfig
{
#Autowired
private ConsulClient client;
private String serviceId = "client";
public ConsulRibbonSSLConfig() {
}
public ConsulRibbonSSLConfig(String serviceId) {
this.serviceId = serviceId;
}
#Bean
#ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig clientConfig) {
ConsulSSLServerList serverList = new ConsulSSLServerList(client);
serverList.initWithNiwsConfig(clientConfig);
return serverList;
}
}
ServerList Code:
public class ConsulSSLServerList extends AbstractServerList<Server>
{
private final ConsulClient client;
private String serviceId = "client";
public ConsulSSLServerList(ConsulClient client) {
this.client = client;
}
#Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
this.serviceId = clientConfig.getClientName();
}
#Override
public List<Server> getInitialListOfServers() {
return getServers();
}
#Override
public List<Server> getUpdatedListOfServers() {
return getServers();
}
private List<Server> getServers() {
List<Server> servers = new ArrayList<>();
Response<QueryExecution> results = client.executePreparedQuery(serviceId, QueryParams.DEFAULT);
List<QueryNode> nodes = results.getValue().getNodes();
for (QueryNode queryNode : nodes) {
QueryNode.Node node = queryNode.getNode();
servers.add(new Server(node.getMeta().containsKey("secure") ? "https" : "http", node.getNode(), queryNode.getService().getPort()));
}
return servers;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("ConsulSSLServerList{");
sb.append("serviceId='").append(serviceId).append('\'');
sb.append('}');
return sb.toString();
}
}

Not able to load application.conf from cron job in play framework 2.4

I have created a cron job that start during application restart but when i tried to create db connection i am geeting null pointer exception. I am able to create and use db from other module using same configuration.
Below is my Application.conf
db.abc.driver=com.mysql.jdbc.Driver
db.abc.url="jdbc:mysql://localhost:3306/db_name?useSSL=false"
db.abc.username=root
db.abc.password=""
db.abc.autocommit=false
db.abc.isolation=READ_COMMITTED
And code that tried to access db is
public class SchduleJob extends AbstractModule{
#Override
protected void configure() {
bind(JobOne.class)
.to(JobOneImpl.class)
.asEagerSingleton();
} }
#ImplementedBy(JobOneImpl.class)
public interface JobOne {}
#Singleton
public class JobOneImpl implements JobOne {
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef alertActor = actorSystem.actorOf(AlertActor.props);
public JobOneImpl() {
scheduleJobs();
}
private Cancellable scheduleJobs() {
return actorSystem.scheduler().schedule(
Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds
Duration.create(6, TimeUnit.MINUTES), //Frequency 30 minutes
alertActor,
"alert",
actorSystem.dispatcher(),
null
);
}
}
public class AlertActor extends UntypedActor{
public static Props props = Props.create(AlertActor.class);
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef messageActor = actorSystem.actorOf(MessageActor.props());
#Override
public void onReceive(Object message) throws Exception {
if(message != null && message instanceof String) {
RequestDAO requestDAO = new RequestDAO();
try {
List<DBRow> rows = requestDAO.getAllRow();
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
}
public class RequestDAO {
public List<DBRow> getAllRow() throws Exception {
List<DBRow> rows = new ArrayList<DBRow>();
Connection connection = null;
try {
connection = DB.getDataSource("abc").getConnection();
connection.setAutoCommit(false);
} catch(Exception exception) {
exception.printStackTrace();
if(connection != null) {
connection.rollback();
} else {
System.out.println("in else***********");
}
return null;
} finally {
if(connection != null)
connection.close();
}
return schools;
}
When i am calling method getAllRow() of RequestDAO class it's throwing
java.lang.NullPointerException
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.utils.InlineCache.fresh(InlineCache.scala:69)
at play.utils.InlineCache.apply(InlineCache.scala:55)
at play.api.db.DB$.db(DB.scala:22)
at play.api.db.DB$.getDataSource(DB.scala:41)
at play.api.db.DB.getDataSource(DB.scala)
at play.db.DB.getDataSource(DB.java:33)
But same code is working without cron job. What should i do to remove this error
Play uses the Typesafe config library for configuration.
I suspect your current working directory from the cron script isn't set, so it's probably not finding your application.conf (application.properties) file.
However, Config is nice in that it allows you to specify where to look for the file, either by its base name (to choose among .conf | .properties | .json extensions) or the filename including the extension on the java command line:
To specify the base name, use -Dconfig.resource=/path/to/application
To specify the full name, use -Dconfig.file=/path/to/application.properties

Stripe Integration in Android Studio

I am working to integrate the Stripe payment gateway in an Android app that I am developing. I have followed the steps listed on https://stripe.com/docs/mobile/android.
When I try to create a new card I get errors.
I run this in my activity
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Card card = new Card(
// Get values from the form
cardNumber.getText().toString(),
getInteger(monthSpinner),
getInteger(yearSpinner),
cvc.getText().toString()
);
}
});
Which uses the Card model.
Card model
package com.stripe.android.model;
import com.stripe.android.util.DateUtils;
import com.stripe.android.util.TextUtils;
public class Card extends com.stripe.model.StripeObject {
String number;
String cvc;
Integer expMonth;
Integer expYear;
String name;
String addressLine1;
String addressLine2;
String addressCity;
String addressState;
String addressZip;
String addressCountry;
String last4;
String type;
String fingerprint;
String country;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCVC() {
return cvc;
}
public void setCVC(String cvc) {
this.cvc = cvc;
}
public Integer getExpMonth() {
return expMonth;
}
public void setExpMonth(Integer expMonth) {
this.expMonth = expMonth;
}
public Integer getExpYear() {
return expYear;
}
public void setExpYear(Integer expYear) {
this.expYear = expYear;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getAddressCity() {
return addressCity;
}
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
public String getAddressZip() {
return addressZip;
}
public void setAddressZip(String addressZip) {
this.addressZip = addressZip;
}
public String getAddressState() {
return addressState;
}
public void setAddressState(String addressState) {
this.addressState = addressState;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public String getLast4() {
if (!TextUtils.isBlank(last4)) {
return last4;
}
if (number != null && number.length() > 4) {
return number.substring(number.length() - 4, number.length());
}
return null;
}
public String getType() {
if (TextUtils.isBlank(type) && !TextUtils.isBlank(number)) {
if (TextUtils.hasAnyPrefix(number, "34", "37")) {
return "American Express";
} else if (TextUtils.hasAnyPrefix(number, "60", "62", "64", "65")) {
return "Discover";
} else if (TextUtils.hasAnyPrefix(number, "35")) {
return "JCB";
} else if (TextUtils.hasAnyPrefix(number, "30", "36", "38", "39")) {
return "Diners Club";
} else if (TextUtils.hasAnyPrefix(number, "4")) {
return "Visa";
} else if (TextUtils.hasAnyPrefix(number, "5")) {
return "MasterCard";
} else {
return "Unknown";
}
}
return type;
}
public String getFingerprint() {
return fingerprint;
}
public String getCountry() {
return country;
}
public Card(String number, Integer expMonth, Integer expYear, String cvc, String name, String addressLine1, String addressLine2, String addressCity, String addressState, String addressZip, String addressCountry, String last4, String type, String fingerprint, String country) {
this.number = TextUtils.nullIfBlank(normalizeCardNumber(number));
this.expMonth = expMonth;
this.expYear = expYear;
this.cvc = TextUtils.nullIfBlank(cvc);
this.name = TextUtils.nullIfBlank(name);
this.addressLine1 = TextUtils.nullIfBlank(addressLine1);
this.addressLine2 = TextUtils.nullIfBlank(addressLine2);
this.addressCity = TextUtils.nullIfBlank(addressCity);
this.addressState = TextUtils.nullIfBlank(addressState);
this.addressZip = TextUtils.nullIfBlank(addressZip);
this.addressCountry = TextUtils.nullIfBlank(addressCountry);
this.last4 = TextUtils.nullIfBlank(last4);
this.type = TextUtils.nullIfBlank(type);
this.fingerprint = TextUtils.nullIfBlank(fingerprint);
this.country = TextUtils.nullIfBlank(country);
}
public Card(String number, Integer expMonth, Integer expYear, String cvc, String name, String addressLine1, String addressLine2, String addressCity, String addressState, String addressZip, String addressCountry) {
this(number, expMonth, expYear, cvc, name, addressLine1, addressLine2, addressCity, addressState, addressZip, addressCountry, null, null, null, null);
}
public Card(String number, Integer expMonth, Integer expYear, String cvc) {
this(number, expMonth, expYear, cvc, null, null, null, null, null, null, null, null, null, null, null);
this.type = getType();
}
public boolean validateCard() {
if (cvc == null) {
return validateNumber() && validateExpiryDate();
} else {
return validateNumber() && validateExpiryDate() && validateCVC();
}
}
public boolean validateNumber() {
if (TextUtils.isBlank(number)) {
return false;
}
String rawNumber = number.trim().replaceAll("\\s+|-", "");
if (TextUtils.isBlank(rawNumber)
|| !TextUtils.isWholePositiveNumber(rawNumber)
|| !isValidLuhnNumber(rawNumber)) {
return false;
}
if (!"American Express".equals(type) && rawNumber.length() != 16) {
return false;
}
if ("American Express".equals(type) && rawNumber.length() != 15) {
return false;
}
return true;
}
public boolean validateExpiryDate() {
if (!validateExpMonth()) {
return false;
}
if (!validateExpYear()) {
return false;
}
return !DateUtils.hasMonthPassed(expYear, expMonth);
}
public boolean validateExpMonth() {
if (expMonth == null) {
return false;
}
return (expMonth >= 1 && expMonth <= 12);
}
public boolean validateExpYear() {
if (expYear == null) {
return false;
}
return !DateUtils.hasYearPassed(expYear);
}
public boolean validateCVC() {
if (TextUtils.isBlank(cvc)) {
return false;
}
String cvcValue = cvc.trim();
boolean validLength = ((type == null && cvcValue.length() >= 3 && cvcValue.length() <= 4) ||
("American Express".equals(type) && cvcValue.length() == 4) ||
(!"American Express".equals(type) && cvcValue.length() == 3));
if (!TextUtils.isWholePositiveNumber(cvcValue) || !validLength) {
return false;
}
return true;
}
private boolean isValidLuhnNumber(String number) {
boolean isOdd = true;
int sum = 0;
for (int index = number.length() - 1; index >= 0; index--) {
char c = number.charAt(index);
if (!Character.isDigit(c)) {
return false;
}
int digitInteger = Integer.parseInt("" + c);
isOdd = !isOdd;
if (isOdd) {
digitInteger *= 2;
}
if (digitInteger > 9) {
digitInteger -= 9;
}
sum += digitInteger;
}
return sum % 10 == 0;
}
private String normalizeCardNumber(String number) {
if (number == null) {
return null;
}
return number.trim().replaceAll("\\s+|-", "");
}
}
This is the error I am getting.
This is new to me. What can I do to resolve this?
Since this is a top hit on Google search for 'How to integrate Stripe to Android Studio' and since Android studio removed the import module this is how I solved the import.
Right click on the project and select > New > Module
In your directories copy contents under Stripe > Stripe folder to the module folder (You should see a newly created folder. Delete the contents of this new folder and paste the contents of Stripe > Stripe)
Back to Android Studio navigate to build.gradle under src add compile project(":stripe") under dependencies.
Refresh your gradle.
EDIT 1
Since posting this answer some changes have happened. If you would wish to add stripe into your project do so via Maven. Just add this line to your app's build.gradle inside the dependencies section:
compile 'com.stripe:stripe-android:2.0.2'
EDIT 2 It's now implementation and not compile.
implementation 'com.stripe:stripe-android:6.1.2'
You can get more details here : https://stripe.com/docs/mobile/android
Okay, so I believe what's happening is that you don't have access to the proper Card() constructor because you haven't set things up properly.
Go to the github page and download the link [for the library]https://github.com/stripe/stripe-android. Unpack that folder and keep it handy.
Now, go into android studio and hit 'import module'. Navigate into that stripe-android directory that you just unzipped, and hit okay. Make sure you only have 'stripe' checked when importing, and not 'example' (only 'example' will be checked by default: fix this.)
Copy the jarfile stripe-java-1.12.0.jar to the directory :libs in your project (where you'd have other libraries). That jarfile should show up under the new 'stripe' directory in android studio.
Go into your src directory and find your app's build.gradle. You're going to want to add, under dependencies:
compile project(":stripe")
You may run into an error at some point saying that you need a newer version of build tools to build the project. If that's so, just start rummaging through the gradle files and changing numbers until it builds. That's what I do, at least.
Hope this helps!
(p.s: remember to include com.stripe.android.* and not com.stripe.*!)
Edit: Just ran into a new problem, and it turns out you should skip step 3. It'll cause dex to freak out that the same class is being defined in the same jarfile twice. So don't do it.
If you're not using Gradle then below is how I got it to work:
Download the zip from the stripe GitHub (stripe-android-master)
Import JUST the stripe folder as a module into your project. You shouldn't have to do anything fancy here.
It added to my project as "main". Go into Project Structure -> modules and add "main" as a module dependency to your working module
Click on the "main" (stripe) module and click the "Export" checkbox on the lib so that your working module has access to it
????
Profit
I just had exactly the same problem as the OP. I was importing some variant of Stripe code but did not have the multi-argument constructor or any of the specific methods I was looking for, so I clearly was not importing what I wanted/needed.
I tried many of the Import Module or Add Library incantations found here or elsewhere. Finally, about to give up, I tried that most desperate of all measures: RTFM. Or, in this case the README.md that came with the project I downloaded.
There, for Android Studio users, was the trivial solution that actually worked for me:
No need to clone the repository or download any files -- just add this line to your app's `build.gradle` inside the `dependencies` section:
compile 'com.stripe:stripe-android:+'
It worked like a charm.
Ironically, you don't have to download or clone to USE the library but so far the only way I know to get the README.md is to download the library files from here:
https://stripe.com/docs/mobile/android
Caveat: I wrote the above as soon as Android Studio started importing the right library and my IDE compilation errors went away. But as soon as I tried to actually build and run my code, I ran head on into the multiple dex horror for, I believe, pulling in multiple copies of the gson library that Stripe depends on and my code already uses. Sigh. I DID fix the problem by removing my local copy of the gson jar and, I presume, depending on the one located with the stripe package. Just deleting all the bin/intermediate/generated folders wasn't good enough. I'm not real happy with this solution but may live with it for now.
well, to use Stripe, you don't need to download anything from github or Stripe.com.
Here is how I do it.
Since I can't post image (with only 1 reputation), its destribed as below:
1. Right-click on your project
2. click Open Module Settings
3. Click dependencies
4. click add
5. click choose library dependencies
6. input "stripe"
7. click search
8. click com.stripe:stripe.android 1.0.0
9. click OK.
Card card = new Card(cardNumber.getText().toString(),getInteger(this.monthSpinner),getInteger(this.yearSpinner),cvc.getText().toString());
use this, the actual and formal parameter are not matching.
Thanks
For all those who could not find a fix with above answers.Here's what I did when I faced the same situation.
Make sure you have gradle dependency as: compile 'com.stripe:stripe-android:+'
In the class where you are using Card model-delete all the stripe import statements and then click on the Card and make sure to import from -
"com.stripe.android.model"
Hope that fixes the issue.Thanks
monthSpinner.getselecteditem() use this and pass it to the getinteger.
Same for the yearSpinner..

JSON Conversion to Java Object

I was trying to parse the following string from Python into Java Object, but the Java Object that I have created for it shows the properties as null I could see the id part of it not the other properties.
Please find the Java Class below:
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
#JsonProperty("remote-system-desc")
public String getRemote_system_desc()
{
return remote_system_desc;
}
#JsonProperty("remote-system-desc")
public void setRemote_system_desc(String remote_system_desc)
{
this.remote_system_desc = remote_system_desc;
}
#JsonProperty("remote-system-capabilities")
public String getRemote_system_capabilities()
{
return remote_system_capabilities;
}
#JsonProperty("remote-system-capabilities")
public void setRemote_system_capabilities(String remote_system_capabilities)
{
this.remote_system_capabilities = remote_system_capabilities;
}
#JsonProperty("remote-chassis-id")
public String getRemote_chassis_id()
{
return remote_chassis_id;
}
#JsonProperty("remote-chassis-id")
public void setRemote_chassis_id(String remote_chassis_id)
{
this.remote_chassis_id = remote_chassis_id;
}
public List<ExternalSwitchPort> getPorts()
{
return ports;
}
public void setPorts(List<ExternalSwitchPort> ports)
{
this.ports = ports;
}
#JsonProperty("remote-system-name")
public String getRemote_system_name()
{
return remote_system_name;
}
#JsonProperty("remote-system-name")
public void setRemote_system_name(String remote_system_name)
{
this.remote_system_name = remote_system_name;
}
"externalSwitches": [{"id": "00:15:60:00:eb:80", "remote-system-desc": "ProCurve J4904A Switch 2848, revision I.10.77, ROM I.08.07 (/sw/code/build/mako(mkfs))", "remote-system-capabilities": "bridge,router", "remote-chassis-id": "00:15:60:00:eb:80", "ports": [{"remote-port-desc": "33", "id": "enc0:iobay2:X5", "remote-port-id": "33"}], "remote-system-name": "VirtSW Rack9"}, {"id": "00:13:21:dd:35:00", "remote-system-desc": "ProCurve J4904A Switch 2848, revision I.10.77, ROM I.08.07 (/sw/code/build/mako(mkfs))", "remote-system-capabilities": "bridge,router", "remote-chassis-id": "00:13:21:dd:35:00", "ports": [{"remote-port-desc": "19", "id": "enc0:iobay1:X5", "remote-port-id": "19"}], "remote-system-name": "swr5-hpqcorp"}]}
I am not able to find out whether it's due to the data content or because it's not able to properly parse the properties remote-system-desc but I have mentioned that in the JSON property.

Categories