Using Selenium RemoteWebDriver behind corporate proxy - java

How can I connect to a selenium grid such as BrowserStack via RemoteWebDriver from behind a corporate proxy?
The application under test is outside the proxy and freely accessible from BrowserStack.
This Using Selenium RemoteWebDriver behind corporate proxy (Java) stackoverflow question asked the same question but I couldn't follow the accepted answer.

I managed to get something working based on the accepted answer in the linked stackoverflow question, here's my implementation in case anyone else is stuck on the same problem:
Example
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.remote.CommandInfo;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.http.HttpClient.Factory;
public class Example {
public RemoteWebDriver connectViaProxy(DesiredCapabilities caps) {
String proxyHost = "?";
int proxyPort = 8080;
String proxyUserDomain = "?";
String proxyUser = "?";
String proxyPassword = "?";
URL url;
try {
url = new URL("http://bsuser:bspassword#hub.browserstack.com/wd/hub");
} catch (MalformedURLException e) {
throw new RuntimeException(e.getMessage(), e);
}
HttpClientBuilder builder = HttpClientBuilder.create();
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(url.getUserInfo()));
}
builder.setProxy(proxy);
builder.setDefaultCredentialsProvider(credsProvider);
Factory factory = new MyHttpClientFactory(builder);
HttpCommandExecutor executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);
return new RemoteWebDriver(executor, caps);
}
private String getWorkstation() {
Map<String, String> env = System.getenv();
if (env.containsKey("COMPUTERNAME")) {
// Windows
return env.get("COMPUTERNAME");
} else if (env.containsKey("HOSTNAME")) {
// Unix/Linux/MacOS
return env.get("HOSTNAME");
} else {
// From DNS
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException ex)
{
return "Unknown";
}
}
}
}
MyHttpClientFactory
import java.net.URL;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.remote.internal.ApacheHttpClient;
public class MyHttpClientFactory implements org.openqa.selenium.remote.http.HttpClient.Factory {
final HttpClientBuilder builder;
public MyHttpClientFactory(HttpClientBuilder builder) {
this.builder = builder;
}
#Override
public org.openqa.selenium.remote.http.HttpClient createClient(URL url) {
return new ApacheHttpClient(builder.build(), url);
}
}

Adding to the answer above by Andrew, to make this work with Appium change the
HttpCommandExecutor executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);
to
HttpCommandExecutor executor = new HttpCommandExecutor(MobileCommand.commandRepository, url, factory);

I've reworked Andrew Sumner's solution slightly and taken some out in case someone like me wants to just quickly funnel their WebDriver traffic through Fiddler to see the traffic.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.CommandInfo;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpClient.Factory;
import org.openqa.selenium.remote.internal.ApacheHttpClient;
public class ProxiedRemoteExample {
private static final String PROXY_HOST = "localhost";
private static final int PROXY_PORT = 8888;
public ProxiedRemoteExample() throws MalformedURLException {
InternetExplorerOptions ieOptions = new InternetExplorerOptions();
RemoteWebDriver driver = new RemoteWebDriver(new HttpCommandExecutor(new HashMap<String, CommandInfo>(),
new URL("http://localhost:5555/"), new Factory() {
private HttpClientBuilder builder;
{
builder = HttpClientBuilder.create();
builder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
}
#Override
public HttpClient createClient(URL url) {
return new ApacheHttpClient(builder.build(), url);
}
}), ieOptions);
}
}

With
org.seleniumhq.selenium:selenium-java:4.0.0-beta-3 I had to apply proxy settings in the following way:
configure async http client to use proxy settings
create ahc.properties file under org/asynchttpclient/config folder
file content: org.asynchttpclient.useProxyProperties = true
configure JVM proxy properties
System.getProperties().setProperty("http.proxyHost", "yourProxyHost")
System.getProperties().setProperty("http.proxyPort", "yourProxyPort")

Related

Using proxy for specific HTTPS request in java

I have requirement to pass HTTPs calls of some specific URL via proxy and rest direct. I have written my own custom proxy implementation using ProxySelector of java.net. It is working fine for HTTP calls ( I can see in proxy access logs in that case) but in case of HTTPS calls it seems it is not using proxy).Am I missing something here.? Proxy server is configured properly and its access log is updating when some HTTPS calls passed from browser with proxy.
package com.blabla.proxy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.vuclip.pubsub.logging.PubSubUtil;
import com.vuclip.pubsub.logging.client.GooglePubSubClient;
public class CustomProxySelector extends ProxySelector {
private static final Logger LOGGER = LogManager.getLogger(PubSubUtil.class);
private final ProxySelector def;
private final String PUB_SUB_URL = "pubsub.googleapis.com";
List<Proxy> proxyList = new ArrayList<Proxy>();
private Proxy proxy=null;
public CustomProxySelector(ProxySelector aDefault) {
this.def = aDefault;
}
#Override
public void connectFailed(URI arg0, SocketAddress soc, IOException ex) {
LOGGER.error("Error in connecting to proxcy "+soc +" for pubsub :"+ ex);
}
#Override
public List<Proxy> select(URI uri) {
if ("https".equalsIgnoreCase(uri.getScheme()) && uri.getHost().startsWith(PUB_SUB_URL)
&& GooglePubSubClient.isProxyEnabled()) {
synchronized (this) {
if (proxy == null) {
proxy = new Proxy(Proxy.Type.SOCKS,
new InetSocketAddress(GooglePubSubClient.getProxyHost(), GooglePubSubClient.getProxyPort()));
}
}
proxyList.add(proxy);
LOGGER.debug("ProxyList:" + proxyList);
return proxyList;
}
proxyList = def.select(uri);
LOGGER.debug("Default proxy list : " + proxyList);
return proxyList;
}
}
I changed Proxy.Type.SOCKS to Proxy.Type.HTTP and it worked for me.

Capturing LOGIN COOKIE via Rest Template

I have below code for making a POST call to RestAPI for Tableau system, which is working and seeing response output.
However, I would like to capture cookie from this output and need to be used for further consumption! Can somebody help me on this problem?
Code:
package com.abc.it.automation.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Properties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity.HeadersBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import com.abc.it.automation.utils.SSLUtil;
public class BIaaSTableauService {
private static Properties tableau_properties = new Properties();
static {
// Loads the values from configuration file into the Properties instance
try {
tableau_properties.load(new FileInputStream("res/config.properties"));
} catch (IOException e) {
System.out.println(e);
}
}
private static final String loginURL = tableau_properties.getProperty("server.host");
private static final String siteSearchURL = tableau_properties.getProperty("site.search.url");
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException {
RestTemplate restTableau = new RestTemplate();
String requestLogin = "<tsRequest>"+
"<credentials name=\"svc_tableau\" password=\"xxxxxxxxx\" >"+
"<site contentUrl=\"\"/>"+
"</credentials>"+
"</tsRequest>";
SSLUtil.turnOffSslChecking();
ResponseEntity<String> responseLogin = restTableau.postForEntity(loginURL, requestLogin, String.class);
System.out.println(responseLogin.getBody());
You need to build your RestTemplate as follows.
RestTemplate restTableau = new RestTemplate(new MyClientHttpRequestFactory());
Extend ClientHttpRequestFactory as follows.
public class MyClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private Cookie cookie;
//setters and getters.
#Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
this.setCookie(connection.getRequestProperty("Cookie"));
}
}

Android : Jetty's HttpClient not working with Https

I am working on an Android project in which I am trying to connect HttpClient to an Https endpoint. For this, I found out that I had to add an SSLContextFactory while instantiating. After doing that, when I run the code, I get the an error mentioned below.
How can I setup HttpClient to work with https?
Error log :
java.lang.NoSuchMethodError: No virtual method setEndpointIdentificationAlgorithm(Ljava/lang/String;)V in class Ljavax/net/ssl/SSLParameters; or its super classes (declaration of 'javax.net.ssl.SSLParameters' appears in /system/framework/core-libart.jar)
at org.eclipse.jetty.util.ssl.SslContextFactory.customize(SslContextFactory.java:1382)
at org.eclipse.jetty.util.ssl.SslContextFactory.newSSLEngine
at org.eclipse.jetty.util.ssl.SslContextFactory.doStart(SslContextFactory.java:309)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start
at org.eclipse.jetty.util.component.ContainerLifeCycle.start
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart
at org.eclipse.jetty.client.HttpClient.doStart(HttpClient.java:229)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start
Affected code :
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.LongPollingTransport;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import java.net.HttpCookie;
public class ConsoleChatClient extends Service {
private final IBinder mBinder = new LocalBinder();
BayeuxClient bayeuxClient = StaticRestTemplate.getClient();
HttpClient httpClient = new HttpClient(new SslContextFactory());
private void performConnection() {
try {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
HttpClient localClient = new HttpClient(sslContextFactory);
localClient.start();
ClientTransport clientTransport = new LongPollingTransport(null, localClient);
bayeuxClient = new BayeuxClient(defaultURL, clientTransport);
// Below for use with Spring-Security post-login.
bayeuxClient.putCookie(new HttpCookie("JSESSIONID", StaticRestTemplate.jsessionid));
bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener(new InitializerListener());
bayeuxClient.getChannel(Channel.META_CONNECT).addListener(new ConnectionListener());
bayeuxClient.handshake();
StaticRestTemplate.setClient(bayeuxClient);
StaticRestTemplate.setHttpClient(localClient);
httpClient = localClient;
boolean success = bayeuxClient.waitFor(4000, BayeuxClient.State.CONNECTED);
if (!success) {
System.err.printf("Could not handshake for ConsoleChatClient with server at %s%n", defaultURL);
} else {
System.err.printf("Handhskare ConsoleChatClient complete");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Creating service provider in WSO2 Identity Server with OAuth facility using Java

I am developing a Java client which creates the service provider dynamically with Inbound Authentication set to OAuth in WSO2 Identity Server. The code goes as follows
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.authenticator.proxy.AuthenticationAdminStub;
import org.wso2.carbon.um.ws.api.WSRealmBuilder;
import org.wso2.carbon.um.ws.api.stub.ClaimValue;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub;
import org.wso2.carbon.identity.oauth.stub.*;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
public class IdentityClient {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
String appName = "Sample_App_3";
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null,
SERVER_URL + "OAuthAdminService");
IdentityApplicationManagementServiceStub IAMStub = new IdentityApplicationManagementServiceStub(
null, SERVER_URL + "IdentityApplicationManagementService");
ServiceClient client = stub._getServiceClient();
ServiceClient IAMClient = IAMStub._getServiceClient();
authenticate(client);
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO();
consumerApp.setApplicationName(appName);
consumerApp.setOAuthVersion("OAuth-2.0");
consumerApp.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerApp.setGrantTypes(
"authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
/* OAuthAdminProxy.registerOAuthApplicationData(consumerApp); */
stub.registerOAuthApplicationData(consumerApp);
System.out.println("Application created successfully");
authenticate(IAMClient);
InboundAuthenticationRequestConfig iaReqConfig = new InboundAuthenticationRequestConfig();
iaReqConfig.setInboundAuthKey(stub.getOAuthApplicationDataByAppName(appName)
.getOauthConsumerKey());
iaReqConfig.setInboundAuthType(stub.getOAuthApplicationDataByAppName(appName)
.getOauthConsumerSecret());
InboundAuthenticationRequestConfig[] iaReqConfigList = { iaReqConfig };
InboundAuthenticationConfig ib = new InboundAuthenticationConfig();
ib.setInboundAuthenticationRequestConfigs(iaReqConfigList);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(
stub.getOAuthApplicationDataByAppName(appName).getApplicationName());
serviceProvider.setInboundAuthenticationConfig(ib);
IAMStub.createApplication(serviceProvider);
System.out.println("Service Provider created");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Once I run this code, the service provider is getting created in the WSO2 Identity Server which I could see in the management console. The OAuth configuration which has been done vis-a-vis the service provider is not showing up and it is empty with just a 'configure' link. Had I understood WSO2 IS properly then I should be getting the consumer key and consumer secret under Inbound Authentication Configuration --> OAuth/OpenID Connect Configuration drop down.
Please help me in what should be done right ?
Try changing your client as bellow,
import java.rmi.RemoteException;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.Property;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
public class IdentityClient {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
String appName = "Sample_App_5";
String appDescription = "Test description";
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null,
SERVER_URL + "OAuthAdminService");
IdentityApplicationManagementServiceStub IAMStub = new IdentityApplicationManagementServiceStub(
null, SERVER_URL + "IdentityApplicationManagementService");
ServiceClient client = stub._getServiceClient();
ServiceClient IAMClient = IAMStub._getServiceClient();
authenticate(client);
authenticate(IAMClient);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(appName);
serviceProvider.setDescription(appDescription);
IAMStub.createApplication(serviceProvider);
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO();
consumerApp.setApplicationName(appName);
consumerApp.setOAuthVersion("OAuth-2.0");
consumerApp.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerApp.setGrantTypes(
"authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
/* OAuthAdminProxy.registerOAuthApplicationData(consumerApp); */
stub.registerOAuthApplicationData(consumerApp);
System.out.println("Application created successfully");
System.out.println(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerKey());
authenticate(IAMClient);
InboundAuthenticationRequestConfig iaReqConfig = new InboundAuthenticationRequestConfig();
iaReqConfig.setInboundAuthKey(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerKey());
iaReqConfig.setInboundAuthType("oauth2");
Property property = new Property();
property.setName("oauthConsumerSecret");
property.setValue(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerSecret());
Property[] properties = { property };
iaReqConfig.setProperties(properties);
InboundAuthenticationRequestConfig[] iaReqConfigList = { iaReqConfig };
InboundAuthenticationConfig ib = new InboundAuthenticationConfig();
ib.setInboundAuthenticationRequestConfigs(iaReqConfigList);
serviceProvider = IAMStub.getApplication(appName);
serviceProvider.setApplicationName(
stub.getOAuthApplicationDataByAppName(appName).getApplicationName());
serviceProvider.setInboundAuthenticationConfig(ib);
IAMStub.updateApplication(serviceProvider);
System.out.println("Service Provider created");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Problem is createApplication does not save the configurations other than the name and the description. You have to call updateApplication to save other application configurations.

NPE using QBOVendorService

I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);
where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
vService.addVendor(context, vendor);
I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?
I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;
// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubVendorall {
final PlatformSessionContext context;
public CodegenStubVendorall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd() {
final List<QBVendor> entityList = new ArrayList<QBVendor>();
try {
QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);
//Your Code
//Use Vendor POJO for creating Vendor
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext();
CodegenStubVendorall testObj = new CodegenStubVendorall(context);
testObj.testAdd();
}
public static PlatformSessionContext getPlatformContext() {
String accesstoken = "rplce_your_application_token";
String accessstokensecret = "rplce_your_application_token";
String appToken = "rplce_your_application_token";
String oauth_consumer_key = "rplce_your_application_token";
String oauth_consumer_secret = "rplce_your_application_token";
String realmID = "123456";
String dataSource = "QBO";
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
}
You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks

Categories

Resources