Connecting to Microsoft Dynamics CRM on-premise web service with Java? - java

Are there any online resources which show the basic steps to access the Microsoft CRM on-premise web service with a client written in Java?
Which web service toolkit should I use?
I tried it with JAXB but there is a conflict in the WSDL element naming which requires a class customization. If I find the correct binding fix, I will post it here.

The Microsoft Dynamics CRM application on premise version uses Active Directory authentication.
Although I never tried referencing the Microsoft Dynamics CRM web services from Java, I am sure it is feasible, as these are standard web services and therefor can be referenced from Java via SOAP, just like any other web service.
public class TestCRM {
private static String endpointURL = "http://server:port/MSCrmServices/2007/CrmService.asmx";
private static String userName = "username";
private static String password = "password";
private static String host = "server";
private static int portport = port;
//To make sure you are using the correct domain open ie and try to reach the service. The same domain you entered there is needed here
private static String domain = "DOMAIN";
private static String orgName = "THIS_IS_REQUIRED"; //this does the work....
public static void main(String[] args) {
CrmServiceStub stub;
try {
stub = new CrmServiceStub(endpointURL);
setOptions(stub._getServiceClient().getOptions());
RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance();
RetrieveMultiple rm = RetrieveMultiple.Factory.newInstance();
QueryExpression query = QueryExpression.Factory.newInstance();
query.setColumnSet(AllColumns.Factory.newInstance());
query.setEntityName(EntityName.######.toString());
//query.setFilter...
rm.setQuery(query);
rmd.setRetrieveMultiple(rm);
//Now this is required. Without it all i got was 401s errors
CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();
CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();
token.setAuthenticationType(0);
token.setOrganizationName(orgName);
catd.setCrmAuthenticationToken(token);
boolean fetchNext = true;
while(fetchNext){
RetrieveMultipleResponseDocument rmrd = stub.RetrieveMultiple(rmd, catd, null, null);
RetrieveMultipleResponse rmr = rmrd.getRetrieveMultipleResponse();
BusinessEntityCollection bec = rmr.getRetrieveMultipleResult();
String pagingCookie = bec.getPagingCookie();
fetchNext = bec.getMoreRecords();
ArrayOfBusinessEntity aobe = bec.getBusinessEntities();
BusinessEntity[] myEntitiesAtLast = aobe.getBusinessEntityArray();
for(int i=0; i<myEntitiesAtLast.length; i++){
//cast to whatever you asked for...
### myEntity = (###) myEntitiesAtLast[i];
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static void setOptions(Options options){
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
List authSchemes = new ArrayList();
authSchemes.add(HttpTransportProperties.Authenticator.NTLM);
auth.setAuthSchemes(authSchemes);
auth.setUsername(userName);
auth.setPassword(password);
auth.setHost(host);
auth.setPort(port);
auth.setDomain(domain);
auth.setPreemptiveAuthentication(false); //it doesnt matter...
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); //i think this is good.. not required though
}

Java -> SOAP -> MS CRM 2011 Online : http://zsvoboda.blogspot.com/2011/03/connecting-to-microsoft-crm-2011-online.html

The stub has been created with the Apache Axis2 framework.

You can find resources here. You can even work with an example is available in Dynamics CRM SDK. As Manuel Freiholz said, you have to use Axis2.
https://msdn.microsoft.com/en-us/library/jj602979(v=crm.5).aspx
http://blogs.msdn.com/b/dynamics-coe/archive/2013/09/21/integrating-microsoft-dynamics-crm-2011-online-with-java-and-other-non-net-clients.aspx
Alternatively, you can use RESTFul web services through the OData interface offered by Dynamics (https://msdn.microsoft.com/en-us/library/gg334279.aspx)

Related

Java Playwright using connect with Proxy for browserless

I want to use Playwright.connect() method using Proxy to consume Browserless. According to Browserless doc.
https://docs.browserless.io/docs/playwright.html
The standard connect method uses playwright's built-in browser-server
to handle the connection. This, generally, is a faster and more
fully-featured method since it supports most of the playwright
parameters (such as using a proxy and more). However, since this
requires the usage of playwright in our implementation, things like
ad-blocking and stealth aren't supported. In order to utilize those,
you'll need to see our integration with connectOverCDP.
I thought well connect will have a .setProxy(), Like launch()
browserType.launch(new BrowserType.LaunchOptions().setProxy(proxy));
But connect methods it has 2 variations
default Browser connect(String wsEndpoint) {
return connect(wsEndpoint, null);
}
Browser connect(String wsEndpoint, ConnectOptions options);
I thought well i will pick connect + ConnectOptions it sures has a .setProxy as well but it doesn't.
class ConnectOptions {
public Map<String, String> headers;
public Double slowMo;
public Double timeout;
public ConnectOptions setHeaders(Map<String, String> headers) {
this.headers = headers;
return this;
}
public ConnectOptions setSlowMo(double slowMo) {
this.slowMo = slowMo;
return this;
}
public ConnectOptions setTimeout(double timeout) {
this.timeout = timeout;
return this;
}
}
I have try this
final Browser.NewContextOptions browserContextOptions = new Browser.NewContextOptions().setProxy(proxy);
Browser browser = playwright.chromium()
.connect("wss://&--proxy-server=http://myproxyserver:1111")
.newContext(browserContextOptions)
.browser();
browser.newPage("resource");
But the proxy returns authentication is required.
I'm confused now Browserless says that .connect could provide a Proxy but how? Is browserless wrong? Or am I missing something? I'm new on this technology.
I have tried as well using page.setExtraHTTPHeaders.
private void applyProxyToPage(final Page page,final String
userPassCombination){
final String value = "Basic "+Base64.getEncoder().encodeToString(userPassCombination.getBytes(Charset.forName("UTF-8")));
page.setExtraHTTPHeaders(Collections.singletonMap("Authorization",value));
//page.setExtraHTTPHeaders(Collections.singletonMap("Proxy-Authorization",value));// Not working either
}
With the help of my friend Alejandro Loyola at Browserless, I am now able to connect. I will post the snippet:
private String navigateWithPlaywrightInBrowserlessWithProxy(final String token,final String proxyHost,final String userName,final String userPass,final String url){
final Browser.NewContextOptions browserContextOptions = new Browser.NewContextOptions()
.setProxy(new Proxy(proxyHost)
.setUsername(userName)
.setPassword(userPass));//Raw password not encoded in any way;
try (final Playwright playwright = Playwright.create(); Browser browser = playwright.chromium().connectOverCDP("wss://chrome.browserless.io?token=" + token);final BrowserContext context = browser.newContext(browserContextOptions);){
Page page = context.newPage();
page.route("**/*.svg", Route::abort);
page.route("**/*.png", Route::abort);
page.route("**/*.jpg", Route::abort);
page.route("**/*.jpeg", Route::abort);
page.route("**/*.css", Route::abort);
page.route("**/*.scss", Route::abort);
page.navigate(url, new Page.NavigateOptions()
.setWaitUntil(WaitUntilState.DOMCONTENTLOADED));
return page.innerHTML("body");
}
}
My gotchas were as follows.
I was using:
"wss://chrome.browserless.io/playwright?token=
Instead of:
"wss://chrome.browserless.io?token="
And use:
connectOverCDP

Oauth 2.0 with grant_type=client_credentials?

I am looking for a OAuth 2.0 client in Java which supports machine to machine communication via grant_type=client_credentials.
Any recommendations?
Edit: I am asking here, since 2 days of research indicate so far, that there are many libs for OAuth 2.0, but none seems to support the required mode of operation.
After many headaches, I finally found that ScribeJava supports the needed mode of operations – although it’s somewhat hidden.
Here is my adopted version:
public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
// Replace these with your client id and secret
final String clientId = "your client id";
final String clientSecret = "your client secret";
final OAuth20Service service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.defaultScope("any") // replace with desired scope
.build(new DefaultApi20() {
#Override
public String getAccessTokenEndpoint() {
return "http://127.0.0.1:8082/token";
}
#Override
protected String getAuthorizationBaseUrl() {
throw new UnsupportedOperationException(
"This API doesn't support a Base URL.");
}
});
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
final OAuth2AccessToken accessToken = service.getAccessTokenClientCredentialsGrant();
System.out.println("Got the Access Token!");
System.out.println(accessToken.getRawResponse());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)");
}
The original example can be found at https://github.com/scribejava/scribejava/blob/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/VkontakteClientCredentialsGrantExample.java

How to set up default browser that jdk/jre uses

I used code of programm that you can see below.The logic of class is to get some properties from html code from YouTube page.For long time it worked fine, but now not. The reason of problem is the next: jdk/jre uses Internet explorer as default browser and now YouTube not support ie (It returns the page with suggestion of updating browser).
The question is : how to change default browser taht java uses?
I switched the default browser of the system to Chrome and default browser of Intellij IDE to Chrome too, but it didn't give any result to me.
#Component(immediate = true, service = LastActualVideoService.class)
public class LastActualVideoServiceServiceImpl implements LastActualVideoService {
private final Logger logger = LoggerFactory.getLogger(getClass());
private static final String LINK_TO_YOU_TUBE = "https://www.youtube.com/embed/";
private static final String TRIGGER_FOR_VIDEO = "/watch?v=";
private static final String VIDEO_SELECTOR = "/videos";
private static final String HTML_SEPARATOR = "\\A";
private static final String ERROR_MASSAGE = "Incorrect input URL";
private static final String OPEN_TITLE_TAG = "<title>";
private static final String CLOSE_TITLE_TAG = "</title>";
#Override
public YouTubeChannelInfo getVideoBlob(String channelURL) {
channelURL = channelURL.concat(VIDEO_SELECTOR);
try (InputStream response = new URL(channelURL).openStream()) {
Scanner scanner = new Scanner(response);
String responseBody = scanner.useDelimiter(HTML_SEPARATOR).next();
String uniqueVideo = responseBody.substring(responseBody.indexOf(TRIGGER_FOR_VIDEO), responseBody.indexOf(TRIGGER_FOR_VIDEO) + 20);
String title = responseBody.substring(responseBody.indexOf(OPEN_TITLE_TAG) + 7, responseBody.indexOf(CLOSE_TITLE_TAG));
String linkToVideo = LINK_TO_YOU_TUBE.concat(uniqueVideo.substring(uniqueVideo.lastIndexOf('=') + 1));
return new YouTubeChannelInfo(linkToVideo, title, channelURL);
} catch (IOException e) {
logger.error(ERROR_MASSAGE, e);
return null;
}
}
}
URL.openStream does not "use the browser", your Java program acts as HTTP client itself. The way the remote server can know what type of browser is connecting is the user agent that the client sends with the request. It's possible that Youtube does not recognize or like whatever the default is.
Like Joachim Rohde commented, the solution is to manually set the user agent to something Youtube will recognize as supported.

Jira issue type values for Rest api

Where can I find Jira issue type values that we pass to IssueBuilder class constructor?
For ex: If i want to create a issue type of bug using jira rest api , We pass value '1L' to Issue Builder class constructor.
IssueInputBuilder issueBuilder = new IssueInputBuilder("Key", 1l);
Similarly what are the values of other jira issue types ?.. Anybody know the values we need to pass ?
If you are using later Jira REST Java Client API (e.g. 4.0), the interface has been changed. You must use following code to browsing all issue types:
private static final String JIRA_SERVER = "http://jiralab";
public static void main(String[] args) {
try {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_SERVER);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, "admin", "admin");
listAllIssueTypes(client);
}
catch (Exception ex) {
}
}
private static void listAllIssueTypes(JiraRestClient client) throws Exception {
Promise<Iterable<IssueType>> promise = client.getMetadataClient().getIssueTypes();
Iterable<IssueType> issueTypes = promise.claim();
for (IssueType it : issueTypes) {
System.out.println("Type ID = " + it.getId() + ", Name = " + it.getName());
}
}
If you want to get a list of all available issuetypes, you can use the REST API (/rest/api/2/issuetype). To try that on your JIRA instance, I like to recommend the Atlassian REST API Browser.
Or just look here: Finding the Id for Issue Types
In Java you can get a list of all issuetype object using getAllIssueTypeObjects().

string escaping with non-nullable named parameters

I am trying to use the google cloud endpoints Java from android as such:
client:
Core.Builder coreBuilder = new Core.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(), null);
coreBuilder.setApplicationName("myapp");
if (MainActivity.ENDPOINTS_URL != null) {
coreBuilder.setRootUrl(MainActivity.ENDPOINTS_URL);
coreBuilder.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
public void initialize(AbstractGoogleClientRequest<?> request)
throws IOException {
request.setDisableGZipContent(true);
}
});
}
Core core = coreBuilder.build();
myList = core.asdf("x=&+x", myObject);
server:
#ApiMethod(name = "asdf")
public List<String> asdf(#Named("param1") String param1, MyObject myObject) {
if (param1.equals("x=&+x")) {
//should go here, but never does
}
...
While it mostly works, somehow the param1 string does not get correctly transmitted, meaning that "x=&+x" arrives at the server as "x=&%2Bx". Is this a known bug? Or do arguments have to be manually encoded somehow? Or is this somehow particular to my environment?
Appengine SDK V1.8.8 for java, google api 1.17.0-rc, using the dev environment.
Cheers,
Andres

Categories

Resources