Lymun - Technology Blog

Lymun - Technology Blog
echnology with science is the systematic study of the architecture and behavior of the technology and digital world through observation, experimentation, and the testing of theories against the evidence obtained.

Tuesday, 21 March 2017

Microsoft Dynamics CRM - Java Web Client Implementation

CRM - Microsoft Dynamics

A Cloud based Customer Relationship Management(CRM) software package developed by Microsoft. Microsoft Dynamics CRM is cloud based server-client application, which provides RESTful endpoint to access different CRM entities, which is primarily an IIS based web application.

Here we are going to provide an overview on how to consume the RESTful endpoint for various Microsoft Dynamics CRM to access the CRM resources. The implementation is based on Java technology. This demonstration is based on the following dependencies which is managed through the Gradle:
So let's begin toward building a web client consuming the Microsoft Dynamics CRM RESTful endpoints and displaying the CRM data.

Problem: Develop a Java based implementation for web client to connect with Microsoft Dynamics CRM and display CRM data.

Solution: Here you need to create a Gradle project using Eclipse IDE. Gradle will manage all the required dependencies in the project for various libraries needed including Microsoft Azure. Focus on the steps below to create a fresh web client and connect with the Microsoft Dynamics CRM. We are considering you already have an account registered with Microsoft Dynamics CRM if not try registering for a trial version and pass the required configurations in Java constants class.

Step 1: Create a Gradle project with and add the classes as per the project structure.

 Step 2: Let's add required dependencies with build.gradle
dependencies {
compile group: 'org.slf4j', name : 'slf4j-api' version : '1.7.21'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.8.5'
compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.5.0'
compile group: 'com.sun.jersey', name: 'jersey-client', version: '1.19.1'
compile group: 'com.sun.jersey', name: 'jersey-json', version: '1.19.1'
compile group: 'javax.ws.rs', name: 'javax.ws.rs-api', version: '2.0'
compile group: 'com.sun.jersey', name: 'jersey-servlet', version: '1.19.1'
compile group: 'com.microsoft.azure', name: 'adal4j', version: '0.0.3'
testCompile 'junit:junit:4.12'
}
Step 3: Set the valid Microsoft Dynamics CRM configurations to the Java class to read and connect in AppConstants.java
package com.demo.dynamics.crm;

public class AppConstants {
  public final static String CLIENT_ID = "xxxxx-xxxx-xxxx-xxxx-xxxxx";
  public final static String RESOURCE = "https://xxxx.xxxx.dynamics.com/";
  public final static String USERNAME = "admin@xxxx.onmicrosoft.com";
  public final static String PASSWORD = "xx$xx";
  public final static String DISCOVERY_URL = "https://xxxx.crm4.dynamics.com/api/data/v8.1/";
  public final static String CLIENT_SECRET = "xx+xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx=";
  public static final String TOKEN_URL = "https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/oauth2/token";
  public static final String GRANT_TYPE = "password";
}

Step 4: Now we have the valid CRM configurations so now try obtaining a valid token using Java class with the implementation in TokenManager.java
package com.demo.dynamics.crm.rest.client;

/**
 * Token Manager will return the access token and refresh token
 */
public class TokenManager {
  private static Logger LOG = LoggerFactory.getLogger(TokenManager.class);
  private Client client;
  private ClientConfig clientConfig;

  public TokenManager() {
    this.clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    this.client = Client.create(clientConfig);
  }

  /**
   * Builds the access token
   *
   * @return access token
   * @throws Exception
   */
  public JwtToken getAccessToken() throws Exception {
    Form form = new Form();
    ClientResponse response = null;
    WebResource webResource = null;

    try {
      form.add("grant_type", AppConstants.GRANT_TYPE);
      form.add("username", AppConstants.USERNAME);
      form.add("password", AppConstants.PASSWORD);
      form.add("resource", AppConstants.RESOURCE);
      form.add("client_id", AppConstants.CLIENT_ID);
      form.add("client_secret", AppConstants.CLIENT_SECRET);
      webResource = client.resource(TOKEN_URL);
      response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
          .post(ClientResponse.class, form);

      if (response.getStatus() == 200) {
        JwtToken token = response.getEntity(JwtToken.class);
        return token;
      } else {
        String responseBody = response.getEntity(String.class);
        throw new CrmClientException(
            "Error fetching jwt: " + response.getStatus() + " " + response.getStatusInfo() + " : " + responseBody);
      }

    } catch (Exception e) {
      throw new CrmClientException("Unable to obtain token", e);
    }
  }
}
Step 5: After obtaining a valid JWT token to make a request create a client AbstractCrmClient.java which will help you creating multiple client for various entities
package com.demo.dynamics.crm.rest.client;

public abstract class AbstractCrmClient {
  protected final JwtToken jwtToken;
  protected final Client client;

  public AbstractCrmClient(JwtToken jwtToken) {
    this.jwtToken = jwtToken;

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    this.client = Client.create(clientConfig);
  }
}
Step 6: Now create a sample Dynamics CRM client with DynamicsCrmClient.java which will extends AbstractCrmClient.java
package com.demo.dynamics.crm.rest.client;

public class DynamicsCrmClient extends AbstractCrmClient {
  private static final String WHOAMI = "WhoAmI";

  public DynamicsCrmClient(JwtToken jwtToken) {
    super(jwtToken);
  }

  public DynamicsCrm CrmConnect() {
    String uri = AppConstants.DISCOVERY_URL + WHOAMI;
    WebResource webResource = client.resource(uri);

    try {
      ClientResponse clientResponse = webResource.header("Authorization", "Bearer " + jwtToken.getAccessToken())
          .type(MediaType.APPLICATION_JSON).get(ClientResponse.class);

      if (clientResponse.getStatus() == 200) {
        CrmEntity entity = clientResponse.getEntity(new GenericType>() {});
        return entity.getValue();
      } else {
        String jsonResponse = clientResponse.getEntity(String.class);
        throw new CrmClientException("Unexpected response: " + clientResponse.getStatus() + " "
            + clientResponse.getStatusInfo() + " " + jsonResponse);
      }
    } catch (Exception e) {
      throw new Exception("Unable to connect with Dynamics CRM.");
    }
  }
}
Step 7: We have used a POJO/model called DynamicsCRM.java
package com.demo.dynamics.crm.rest.model;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * CRM model to capture WhoAmI
 */
public class DynamicsCrm {
  @JsonProperty(value = "BusinessUnitId")
  private String businessUnitId;

  // the system user ID for the currently logged on user
  @JsonProperty(value = "UserId")
  private String systemUserId;

  public String getBusinessUnitId() {
    return businessUnitId;
  }

  public void setBusinessUnitId(String businessUnitId) {
    this.businessUnitId = businessUnitId;
  }

  public String getSystemUserId() {
    return systemUserId;
  }

  public void setSystemUserId(String systemUserId) {
    this.systemUserId = systemUserId;
  }

  public String getOrganizationId() {
    return organizationId;
  }

  public void setOrganizationId(String organizationId) {
    this.organizationId = organizationId;
  }

  @JsonProperty(value = "OrganizationId")
  private String organizationId;
}
Step 8: Also we have used a POJO/model for JWT token JwtToken.java
package com.demo.dynamics.crm.rest.model;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class JwtToken {

  @JsonProperty(value = "token_type")
  private String tokenType;

  @JsonProperty(value = "expires_in")
  private int expiresIn;

  @JsonProperty(value = "ext_expires_in")
  private int extExpiresIn;

  @JsonProperty(value = "expires_on")
  private int expiresOn;

  @JsonProperty(value = "not_before")
  private long notBefore;

  @JsonProperty(value = "refresh_token")
  private String refreshToken;

  @JsonProperty(value = "scope")
  private String scope;

  @JsonProperty(value = "resource")
  private String resource;

  @JsonProperty(value = "access_token")
  private String accessToken;

  public String getTokenType() {
    return tokenType;
  }

  public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
  }

  public int getExpiresIn() {
    return expiresIn;
  }

  public void setExpiresIn(int expiresIn) {
    this.expiresIn = expiresIn;
  }

  public int getExtExpiresIn() {
    return extExpiresIn;
  }

  public void setExtExpiresIn(int extExpiresIn) {
    this.extExpiresIn = extExpiresIn;
  }

  public int getExpiresOn() {
    return expiresOn;
  }

  public void setExpiresOn(int expiresOn) {
    this.expiresOn = expiresOn;
  }

  public long getNotBefore() {
    return notBefore;
  }

  public void setNotBefore(long notBefore) {
    this.notBefore = notBefore;
  }

  public String getRefreshToken() {
    return refreshToken;
  }

  public void setRefreshToken(String refreshToken) {
    this.refreshToken = refreshToken;
  }

  public String getScope() {
    return scope;
  }

  public void setScope(String scope) {
    this.scope = scope;
  }

  public String getResource() {
    return resource;
  }

  public void setResource(String resource) {
    this.resource = resource;
  }

  public String getAccessToken() {
    return accessToken;
  }

  public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
  }
}
Step 9: Finally I have created a Main class to test the Dyanmics CRM web client and print the result on console.
/**
 * Main class to test the GET Dynamics CRM requests
 */
public class Main {
  private static Logger LOG = LoggerFactory.getLogger(Main.class);

  public static void main(String[] args) throws Exception {
    // getting access token using user credentials
    JwtToken jwtToken = new TokenManager().getAccessToken();
    DynamicsCrm crm = new DynamicsCrmClient(jwtToken).CrmConnect();

    LOG.info("CRM connection Test: CRM with BusinessUnitId" + crm.getBusinessUnitId().toString() + "and OrganizationId "
        + crm.getOrganizationId().toString() + "working fine.");
  }
}
Hope the above sample implementation helping you in development your Dynamics Web Client solutions. If you have any queries or suggestions for me feel free to reach me out hello@vaacom.com.
VaaCom: A Blog on Technology

Saturday, 14 July 2012

Apache Click: RightCheckBox Control a Custom Checkbox Class

Click API Checkbox Customization

This customization is required to provide the labels to the right. Current available API is designed in this package org.apache.click.control.Checkbox which is providing label to the left only and if we want to use the checkbox with label on right then we have to override the current org.apache.click.control.Checkbox class and make the changes into this. Current available checkbox is available in the following options only:
Checkbox
Let's have a look on how we can customize the existing feature of the apache click org.apache.click.control.Checkbox control class.
RightCheckBox.java
package com.components.ui.click.control;

import java.text.MessageFormat;
import org.apache.click.Context;
import org.apache.click.control.Checkbox;
import org.apache.click.control.Label;
import org.apache.click.util.HtmlStringBuffer;

public class RightCheckBox extends Checkbox {

    private static final long serialVersionUID = 1L;

    // -------------------------------------------------------------- Constants
    
    private String rightLabel;
    protected final static String VALIDATE_CHECKBOX_FUNCTION =
        "function validate_{0}() '{'\n"
        + "   var msg = validateCheckbox(''{0}'',{1}, [''{2}'']);\n"
        + "   if (msg) '{'\n"
        + "      return msg + ''|{0}'';\n"
        + "   '}' else '{'\n"
        + "      return null;\n"
        + "   '}'\n"
        + "'}'\n";

    /** The field checked value. */
    protected boolean checked;

    // ----------------------------------------------------------- Constructors

    public RightCheckBox(String name) {
        super(name);
    }

    public RightCheckBox(String name, String label) {
        super(name, label);
    }

    public RightCheckBox(String name, boolean required) {
        super(name);
        setRequired(required);
    }

    public RightCheckBox() {
    }

    // ------------------------------------------------------ Public Attributes
    @Override
    public String getTag() {
        return "input";
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean value) {
        checked = value;
    }

    public String getType() {
        return "checkbox";
    }

    @Override
    public String getValue() {
        return String.valueOf(checked);
    }

    @Override
    public void setValue(String value) {
        checked = Boolean.valueOf(value);
     }

   public void setRightLabel(String label){
    rightLabel=label;
    setLabel("");
    }
    public String getRightLabel(){
      return rightLabel;
    }
    
    @Override
    public Object getValueObject() {
        if (checked) {
            return Boolean.TRUE;

        } else {
            return Boolean.FALSE;
        }
    }

    @Override
    public void setValueObject(Object object) {
        if (object != null && object instanceof Boolean) {
            checked = (Boolean) object;
        }
    }

    @Override
    public String getValidationJavaScript() {
        if (isRequired()) {
            Object[] args = new Object[3];
            args[0] = getId();
            args[1] = String.valueOf(isRequired());
            args[2] = getMessage("not-checked-error", getErrorLabel());

            return MessageFormat.format(VALIDATE_CHECKBOX_FUNCTION, args);

        } else {
            return null;
        }
    }

    // --------------------------------------------------------- Public Methods
    @Override
    public void bindRequestValue() {
        setChecked(getContext().getRequestParameter(getName()) != null);
    }

    @Override
    public boolean onProcess() {
        if (isDisabled()) {
            Context context = getContext();

            // Switch off disabled property if control has incoming request
            // parameter. Normally this means the field was enabled via JS
            if (context.hasRequestParameter(getName())) {
                setDisabled(false);
            } else {
                // If field is disabled skip process event
                return true;
            }
        }

        // In Html an unchecked Checkbox does not submit it's name/value so we
        // always validate and dispatch registered events
        bindRequestValue();

        if (getValidate()) {
            validate();
        }

        dispatchActionEvent();

        return true;
    }
    
    @Override
    public void render(HtmlStringBuffer buffer) {
     super.render(buffer);
     if(getRightLabel()!=null)
     buffer.append("

"); } @Override public void validate() { setError(null); if (isRequired() && !isChecked()) { setErrorMessage("not-checked-error"); } } }
After customization and overriding the methods the new class com.components.ui.click.control.RightCheckBox will have the backward compatibility and we have the option to use both either right or left label using RightCheckBox class. After overrriding the current class and overriding the methods we will be able to make Checkbox in the following options:
Checkbox
How to use RightCheckBox Class To use RightCheckBox class we need to create a demo java class let's assume RightCheckboxDemo is the name of the demo class which will use the above class to show the desired user interface: RightCheckboxDemo.java
package com.demo.page;

import org.apache.click.control.Form;

public class RightCheckboxDemo extends BorderPage{
 private Form form = new Form("form");
 private RightCheckBox checkbox1=new RightCheckBox("checkbox1");
 private RightCheckBox checkbox2=new RightCheckBox("checkbox2");
 private RightCheckBox checkbox3=new RightCheckBox("checkbox3");
 private RightCheckBox checkbox4=new RightCheckBox("checkbox4");
 private RightCheckBox checkbox5=new RightCheckBox("checkbox5");
 
 public RightCheckboxDemo(){
  form.add(checkbox1);
  form.add(checkbox2);
  form.add(checkbox3);
  form.add(checkbox4);
  form.add(checkbox5);
  
   //Using setLabel we can set the default label and lable will be on left side
  checkbox1.setLabel("Item 1");

 //Using setRightLabel we can set the custom label and lable will be on right side
  checkbox2.setRightLabel("Item 2");
  checkbox3.setRightLabel("Item 3");
  checkbox4.setRightLabel("Item 4");
  checkbox5.setRightLabel("Item 5");
  
  addControl(form);
 }
}

By using the addControl(form) we have provided the form to the htm page. Now we have to right one htm page to render the user interface: RightCheckboxDemo.htm
<html>
<head><title>Demo Page</title>
</head>
<body>
   $form
</body>
</html> 
Finally the user interface is ready to render and we can see how is this looks like:

Please share your comments or suggestion. You can visit our website and leave you comment over there. To visit our website visit on:
VaaCom : A Blog on Technology

Friday, 6 April 2012

Apache Click

Lymun - Technology with Science Blog


Apache Click is a modern and open source Java/J2EE and html page based component oriented web application framework. The framework is built on top of the Java Servlet API. For details on apache click framework and APIs visit on Apache Click .
RIA with Apache Click
We are here to develop Rich Internet Applications by extending the Apache Click capabilities and integration of Java/J2EE, JavaScript, jQuery, CSS, AJAX and other UI to for developing User Interfaces.
ImageRadio Control - Radio Group with Image
Apache Click ImageRadio is an extended form of Radio class. The new class ImageRadio provides a new control for Apache Click by extending the org.apache.click.control.Radio. The control will be similar implementation as Radio with the org.apache.click.control.RadioGroup instead of label you have to provide the image source and the source will be rendered as an image on user interface. The implementation logic has been shared in the below discussions:
ImageRadio.java
ImageRadio.java
package com.components; import org.apache.click.Context; import org.apache.commons.lang.StringUtils; import org.apache.click.control.Radio; import org.apache.click.util.HtmlStringBuffer; public class ImageRadio extends Radio{ private static final long serialVersionUID = 1L; // ----------------------------------------------------- Instance Variables protected String src; protected int x = -1; protected int y = -1; // ----------------------------------------------------- Constructors public ImageRadio(String name) { super(name); } public ImageRadio(String name, String src) { super(name); setSrc(src); } public ImageRadio() { super(); } // ----------------------------------------------------- Methods public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public int getX() { return x; } public int getY() { return y; } @Override public void bindRequestValue() { Context context = getContext(); String xValue = context.getRequestParameter(getName() + ".x"); if (xValue != null) { this.checked = true; try { this.x = Integer.parseInt(xValue); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } String yValue = context.getRequestParameter(getName() + ".y"); try { this.y = Integer.parseInt(yValue); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } } @Override public boolean onProcess() { if (isDisabled()) { Context context = getContext(); if (context.hasRequestParameter(getName() + ".x")) { setDisabled(false); } else { return true; } } bindRequestValue(); if (isChecked()) { dispatchActionEvent(); } return true; } @Override public void render(HtmlStringBuffer buffer) { // ----------------------------------------------------- Radio Button buffer.elementStart(getTag()); buffer.appendAttribute("type", "radio"); buffer.appendAttribute("name", getName()); buffer.appendAttribute("id", getId()); buffer.appendAttribute("title", getTitle()); if (getTabIndex() > 0) { buffer.appendAttribute("tabindex", getTabIndex()); } appendAttributes(buffer); if (isDisabled()) { buffer.appendAttributeDisabled(); } buffer.elementEnd(); // ----------------------------------------------------- Image Button buffer.elementStart(getTag()); buffer.appendAttribute("type", "image"); buffer.appendAttribute("id","i"+ getId()); buffer.appendAttributeDisabled(); if (getTabIndex() > 0) { buffer.appendAttribute("tabindex", getTabIndex()); } String src = getSrc(); if (StringUtils.isNotBlank(src)) { if (src.charAt(0) == '/') { src = getContext().getRequest().getContextPath() + src; } buffer.appendAttribute("src", src); } appendAttributes(buffer); if (isDisabled()) { buffer.appendAttributeDisabled(); } buffer.elementEnd(); } }
The above class is extending the org.apache.click.control.Radio class and during the render(HtmlStringBuffer buffer) method there are two radio controls has been added without label and the second radio attribute has been changes to image. Below we are using this custom class into the new component.
ImageRadioForm.java
package com.component.page; import org.apache.click.control.Form; import org.apache.click.control.RadioGroup; import com.components.ImageRadio; public class HomePage extends BorderPage { private Form form = new Form("form"); private RadioGroup radioGroup = new RadioGroup("Select Card Type:"); public HomePage() { addControl(form); radioGroup.add(new ImageRadio("VISA", "/images/VisaCardLogo.gif")); radioGroup.add(new ImageRadio("MC", "/images/MCLogo.gif")); radioGroup.add(new ImageRadio("DIS", "/images/DiscoverLogo.gif")); radioGroup.setValue("VISA"); radioGroup.setVerticalLayout(true); form.add(radioGroup); } }
After the Java component code now we need to use it on the home.htm page. Below is the code on htm to render the form on user interface:
ImageRadioForm.java
<html> <head><title>Home Page</title> </head> <body> $form </body> </html>
HTML User Interface
Finally you can see the output of the above code. Here are the attached image below:


References:-
  • Apache Click: http://click.apache.org
  • Apache Click with ClickClick: http://clickclick-examples.appspot.com
  • Apache Click jQuery Integration: http://click-jquery.appspot.com

Please share your comments or suggestion. You can visit our website and leave you comment over there. To visit our website visit on:
VaaCom: A Blog on Technology














Microsoft Dynamics CRM - Java Web Client Implementation

CRM - Microsoft Dynamics A Cloud based Customer Relationship Management(CRM) software package developed by Microsoft. Microsoft Dynamics ...