Tuesday, 3 July 2018

Jenkins how to clear cache

In this article we will see how to clear cache for Jenkins. 

Introduction:

While deploying new installation or driver, there is a need to clear cache for Jenkins. Even though Jenkins is removed, the previous installation details (as cache) can cause issue to the new installation. The solution lies in clearing the cache.



Background & Solution:

To understand this, first find out which all paths / locations where jenkins will be installed.

[root@server1 install]# rpm -ql jenkins
/etc/init.d/jenkins
/etc/logrotate.d/jenkins
/etc/sysconfig/jenkins
/usr/lib/jenkins
/usr/lib/jenkins/jenkins.war
/usr/sbin/rcjenkins /var/cache/jenkins
/var/lib/jenkins
/var/log/jenkins

So, as you can see these are the above paths / locations where jenkins will be installed. Any jenkins cache files, which remains in these paths might cause trouble to the new installation. So as a solution to this problem, we need to remove all files from these paths:
/var/cache/jenkins
/var/lib/jenkins
/var/log/jenkins

Here are the steps / commands to clear cache:

[root@server1 install]# rm -rf /var/cache/jenkins/*
[root@server1 install]# rm -rf  /var/lib/jenkins/*
[root@server1 install]# rm -rf /var/log/jenkins/*

After these paths / locations are cleared, we can go ahead with a new installation with no previous cache.

That's all about steps to clear cache for Jenkins. If you have queries, please write in comment section. Thanks.

Monday, 2 July 2018

Design Chess game

Chess Game Design


Here give an example about an object oriented design of a chess game.

The design can be modularized into four parts: board, piece sets, game and player.





Board

A Board class has an attribute of Squares Array (8x8) and PieceSets (black and white).

A Board class also has an attribute of "pieceSetOnTop". The attribute helps to figure the piece moves that are direction-restricted.


PieceSets

A PieceSet class has an attribute of a List<Piece>. The size of the List<Piece> is initially set to 16.

A Piece class has two attributes: color and placeAt (i.e. located at which square).

A Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations:

  • validMoves() - The valid movement for a Piece
  • attackSquares() - The squares that a Piece can attack
  • captureFreeMove - The squares that a Piece can move to without being captured. 
  • toBeCaptured() - The boolean indicates whether a Piece is going to be captured.

The validMoves() operation implements the movement rules. For example, the validMoves of a Pawn class ensures that the Pawn can only move in the direction towards the opponent side. A Pawn class has additional attributes of promoted and promotedTo, which describes the movement/conversion rule of a Pawn at reaching the end of an opponent side and at the conversion about the piece that a Pawn converted to.

Game

A Game class controls the flow of a game. The class has attributes:

  • playedMoves - Keep a record of moves
  • turn - Indicate either it is a Black's turn or a White's turn
  • players - Represent the two players, this can be Human/Human, Computer/Computer or Human/Computer
  • result - Indicate the result of a game
  • checkStatus - Indicate which side is being checked or checkmated

Player

A Player class represents a Player. A Player has two attributes:

  • pieceColor - The color that used by a Player
  • engine - The engine that makes the moves. This can be a human or a computer

Saturday, 23 June 2018

Ansible Loops with_items, with_nested and with_subelements example

In this article we will see the usage of Ansible Loops

Ansible Loops are used to execute the task multiple times. Consider a scenario where we want to create multiple users or want to install multiple packages. In any normal programming language, we achieve these using loops. Anisble also provide a similar feature.


Example of Ansible Loops with_items, with_nested and with_subelements example

Using Loops for multiple tasks

By passing a list, Ansible will run the task for all packages listed. This is called Standard Loops. For example

[root@server1 loops]# cat loop3.yml
---
- hosts: ubuntu
  tasks:

  - name: Create Multiple users
    shell: useradd {{ item }}
    with_items:
       - testuser1
       - testuser2

This example playbook will run the useradd command taking each from the list defined under the with_items construct. Each of the names is exposed as item, which is a default variable that Ansible creates. Ansible then assigns a package name to item, based on the iteration it is currently part of.


Once we run the above playbook,

[root@server1 loops]# ansible-playbook loop3.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Create Multiple users] *************************************************
changed: [172.18.188.24] => (item=testuser1)
changed: [172.18.188.24] => (item=testuser2)

PLAY RECAP ********************************************************************

172.18.188.24              : ok=2    changed=1    unreachable=0    failed


From the above example, we can now see that both users are created by using loops


How to use with_items construct using Ansible:


Lets see one more example of using with_items construct with variable substitution.

[root@server1 loops]# cat loop6.yml
---
- hosts: ubuntu
  tasks:

  - name: Installing Packages
    yum: name={{item.name}} state={{item.value}}
    with_items:
       - {name: 'httpd', value: 'present'}

Here in the above example playbook, we have defined a task which installs packages that are defined in the with_items construct. We have defined the package name with name and value variable which are then accessed by the item element. The item does then have the name and value data which will substitute when needed. 

Lets execute the playbook:

[root@server1 loops]# ansible-playbook loop6.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Installing Packages] ***************************************************
changed: [172.18.188.24] => (item={'name': 'httpd', 'value': 'present'})

PLAY RECAP ********************************************************************

172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  



Nested Loops using with_nested construct

Nested loops comes into picture where we want to perform multiple operations on the same resource. Take a simple example of usecase where we want to set different permission on a file or directory thus defining them using sub elements. As the title explains, Nested loop is a loop within a loop.

[root@server1 loops]# cat nested_loop1.yml
---
- hosts: ubuntu
  tasks:

  - name: Nested Loop / Change File Permissions
    shell: chmod -R {{ item[0] }} {{ item[1] }}
    with_nested:
       - [ '700' ]
       - [ '/tmp/test' ]

Okay, here is the simple example of nested loops. In the above usecase we have defined a task which will change the permission on a file /tmp/test with 700. The values are defined with with_nested construct and can be accessed as an array access (a[0]), while executing the above playbook.

 [root@server1 loops]# ansible-playbook nested_loop1.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Nested Loop / Change File Permissions] *********************************
changed: [172.18.188.24] => (item=['700', '/tmp/test'])

PLAY RECAP ********************************************************************
172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  


Sub Nested Loops using Ansible with_subelements

Sub Nested Loops come into picture when we want to give data dynamically. uptill now, we have seen loops with static data but what if we want give data dynamically. Consider an example of creating multiple users along with different comments. To deal with such cases, we can use a dictionary to loop over sub-elements. Using such loops, we can specify a set of comments per user. Consider a sample example as,

[root@server1 loops]# cat subnested1.yml
---
- hosts: ubuntu
  vars:
    users:
     - name: testuser
       comments:
         - 'For testing purpose'

     - name: devuser
       comments:
         - 'For Dev purpose' 

  tasks:
   - name: User Creation
     shell: useradd -c "{{ item.1 }}" "{{ item.0.name }}"
     with_subelements:
         - users
         - comments

In the above playbook we defined a task which will create users along with user comments taken from 2 dictionaries users and comments. As we can see both users and comments are defined in the vars element above. Both dictionaries are defined under the with_subelements construct making Ansible to get sub elements from users and comments for running the task. Now lets execute this playbook:

[root@server1 loops]# ansible-playbook subnested1.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [User Creation] *********************************************************
changed: [172.18.188.24] => (item=({'name': 'testuser'}, 'For testing purpose'))
changed: [172.18.188.24] => (item=({'name': 'devuser'}, 'For Dev purpose'))

PLAY RECAP ********************************************************************
172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  


That’s all about Ansible Loops with multiple tasks, with_items, with_nested and with_subelements.

Saturday, 26 May 2018

Ansible delegate_to

In this post, we will see the use of Ansible delegation using delegate_to


Purpose:

By default, on remote configure machine, Ansible run the task all at once. Consider the situation where task is based on status / output of a certain command on another machine. For example, if we are doing patching a package on a machine and you need to continue until a certain file is available on another machine. This can be achieved in Ansible using the delegation option.

As the terminology indicates, through Ansible delegate option we can configure to run a task on a different host (and not the default one) than the one that is being configured using the delegate_to key. The module will still run once for every machine, but instead of running on the target machine, it will run on the delegated host. The facts available will be the ones applicable to the current host. 


Code Example / Playbook using Ansible delegate:

[root@server1 delegate]# cat delegation-playbook.yml
---
- hosts: cent
 
  tasks:
    - name: Install zenity
      action: yum name=zenity state=installed
    - name: configure zenity
      action: template src=hosts dest=/tmp/zenity.conf
    - name: Tell Master
      action: shell echo "{{ansible_fqdn}} done" >> /tmp/list
      delegate_to: 172.16.202.99

We have defined multiple tasks to install zenity, configure zenity and the last task is to echo command on the delegate machineof different IP address.  Ansible-playbook will delegate the last task to the IP address 172.16.202.99. 

Once we run the playbook we can see the following:

[root@server1 delegate]# ansible-playbook delegation-playbook.yml

PLAY [cent] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.16.202.96]

TASK: [Install zenity] ********************************************************
changed: [172.16.202.96]

TASK: [configure zenity] ******************************************************
changed: [172.16.202.96]

TASK: [Tell Master] ***********************************************************
changed: [172.16.202.96 -> 172.16.202.99]

PLAY RECAP ********************************************************************
172.16.202.96              : ok=4    changed=3    unreachable=0    failed=0  

Now we can check the remote machine 172.16.202.99 for the file created.

root@ubuntu:/home/vagrant# cat /tmp/list
dev.foohost.vm done

Thats all for usage of Ansible delegation using delegate_to.

Thursday, 4 January 2018

Java Program to find Prime Number with explanation

In this post, we will see how to find if the given number is Prime or not. Prime number are those numbers which cannot be divided by any number. 

For Example: 7 is a Prime Number because it is not divisible by 2 to 6. Similarly, 9 is a non-prime number as it is divisible by 3 

In this article, we will see three ways to find a number as Prime. From first to third program, you will find improvement in finding the prime number. The last program will be much better way (performance wise) to find Prime Number.


Program-I:


import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < num; i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a Prime number");
   else
    System.out.println("Number "+ input + " is a not Prime number");
 }
}


Output:


Run-1:
Enter number:
99
Number 99 is a not prime number
Run-2:
Enter number:
97
Number 97 is a prime number

Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to that number and checking if any of the number is divisible by the given number or not. To check that we are checking if the remainder of the division is zero or not (num % i == 0).
% is the Java operator which returns the remainder of the divided number. If the number is divided and remainder is zero then the number is divisible by other number.



Program-II:

The second program is an improvement over the previous program. In this code example, we will check (if the input number is divisible) till half of that number. More information is provided in explanation section.

import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < num/2; i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a prime number");
   else
    System.out.println("Number "+ input + " is a not prime number");
 }
}


Output:


Run-1:
Enter number:
108
Number 108 is a not prime number
Run-2:
Enter number:
109
Number 109 is a prime number

Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to the half of that  number. We don't need to check more as if the number is not divisible till half of that number, it will not be divisible by other half. For example to check prime number upto 100, we need to check till 50 because if the number is divisible by any number, its other divisible part will already been considered. 


Program-III:

import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < Math.sqrt(num); i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a prime number");
   else
    System.out.println("Number "+ input + " is a not prime number");
 }
}


Output:


Run-1:
Enter number:
105
Number 105 is a not prime number
Run-2:
Enter number:
101
Number 101 is a prime number


Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to square root of that number and checking if any of the number is divisible by the given number or not. We don't need to check the complete squence, checking till its square root value is enough to say whether the number is prime or not. The reason is that if the number is non-prime, one of the divisible will fall within the square root of that number.

Among all this three examplex, Program-III is the best optimized one and is prefer to use it to find prime number.

That's all for this topic Java Program to find Prime Number. Please drop a comment if you have any doubt or suggestion. Thanks!

Saturday, 9 December 2017

How to integrate Salesforce webservices with Ruby on Rails

In this article we will see how to integrate Salesforce REST API to push data from Ruby on Rails application. Please note it requires Ruby greater than 2.0 because of TLS security issues. 

Here are the detailed steps for integrating Salesforce API with Rails application:-


(a) GET WSDL Files and Security Token


Enterprise/ParterWSDL Files: If you have salesforce account you can get your WSDL files from there. You can get this file from your salesforce account “App Setup > Develop > Download your organization-specific WSDL” link.


<?xml version=”1.0″ encoding=”UTF-8″?>
<!–
Web Services API : WebToLeadServices
–>
<definitions targetNamespace=”http://soap.sforce.com/schemas/class/WebToLeadServices” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns=”http://schemas.xmlsoap.org/wsdl/” xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/” xmlns:tns=”http://soap.sforce.com/schemas/class/WebToLeadServices”>
<types>
<xsd:schema elementFormDefault=”qualified” targetNamespace=”http://soap.sforce.com/schemas/class/WebToLeadServices”>
.
.
.
<xsd:complexType name=”WebLead”>
<xsd:sequence>
<xsd:element name=”name” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”email” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”phone” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”comments” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
</xsd:sequence>
</xsd:complexType><xsd:element name=”createLeadFromWeb”>
<xsd:complexType>
<xsd:sequence>
<xsd:element name=”wl” type=”tns:WebLead” nillable=”true”/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
.
.
.
<service name=”WebToLeadServicesService”>
<documentation></documentation>
<port binding=”tns:WebToLeadServicesBinding” name=”WebToLeadServices”>
<soap:address location=”https://ap7.salesforce.com/services/Soap/class/WebToLeadServices”/>
</port>
</service>
</definitions>

Webtolead.wsdl : If you want to send data from your website to salesforce then it will require wsdl files for e.g webtosalesforcelead.xml with content something like this.


Security token : Navigate to My Settings > Personal > Reset My Security Token and click on “Reset Security Token”. This will send you security token on your registered mail id.


(b) Install the SOAP4R gem using Terminal.


gem install soap4r


(c) Run wsdl2ruby


Go to folder where have install soam gem. run the following commands in terminal.

cd /path/to/gem/soap/
wsdl2ruby.rb –wsdl ~/path/to/enterprise.wsdl.xml –type client

Change your paths accordingly. This will produce 4 files in your current working directory: default.rb, defaultDriver.rb, defaultMappingRegistry.rb, and SforceServiceClient.rb.

One more file is required as SOAP4R uses “header handlers” to modify outgoing and read incoming headers (and note that these are SOAP headers, not HTTP headers), so you’ll have to write one of your own (syntax highlighted version):

client_auth_header_handler.rb

require ‘soap/header/simplehandler’
class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
SessionHeader = XSD::QName.new(“rn:enterprise.soap.sforce.com”, “SessionHeader”)

attr_accessor :sessionid
def initialize
super(SessionHeader)
@sessionid = nil
end


def on_simple_outbound

if @sessionid
{“sessionId” => @sessionid}
end
end


def on_simple_inbound(my_header, mustunderstand)

@sessionid = my_header[“sessionid”]
end
end



(d) Create Rails application


install these two gems

gem ‘soap4r’
gem ‘soap4r-spox’


(e) Put all generated files and client_auth_header_handler.rb in you salesforce folder in lib folder of your project.

lib/salesforce
lib/salesforce/default.rb
lib/salesforce/defaultDriver.rb
lib/salesforce/defaultMappingRegistry.rb
lib/salesforce/SforceServiceClient.rb
lib/salesforce/client_auth_header_handler.rb

and change require path accordingly on each files e.g.

require ‘salesforce/default.rb’
require ‘salesforce/defaultMappingRegistry.rb’
require ‘soap/rpc/driver’


(f) Create helper salesfore_helper.rb


module SiteHelper
require ‘rubygems’
gem ‘soap4r’
require ‘soap/soap’
require ‘salesforce/defaultDriver’
require ‘salesforce/client_auth_header_handler’
require ‘soap/wsdlDriver’

def sendtosf

sf = User.first
d = Soap.new
d.wiredump_dev = STDOUT
h = ClientAuthHeaderHandler.new
username = “yourusername”
password = “yourpassword”
token = “yoursectoken”
l=d.login(:username => username, :password => password+token)
h.sessionid = l.result.sessionId
d.headerhandler << h
client = SOAP::WSDLDriverFactory.new( ‘lib/salesforce/webtosalesforcelead.xml’ ).create_rpc_driver
client.wiredump_dev = STDOUT
client.headerhandler << h
leadData = {}
leadData[“wl”] = sf #=> “wl” createLeadFromWeb element
Rails.logger.info “========#{leadData.inspect}============”
response = client.createLeadFromWeb(leadData) #=> createLeadFromWeb method which is present in webtosalesforcelead.xml

#Rails.logger.info “========#{leadData.inspect}============”

Rails.logger.info “========#{response.inspect}============”
#response = client.WebLead(sf)
end
end

That's all for steps to integrate Salesforce REST API with Ruby on Rails. If you have any query, please write in comment section.

Tuesday, 6 June 2017

Can Ansible make a REST call

In this article, we will learn how Ansible can make a REST call

Introduction:

RESTful API’s is a platform independent architecture based on representational state transfer (REST) technology and are now a days used to  integrate  different applications. So, if we want to interact with an existing infrastructure we can expose the infrastructure as REST webservice and other applications can use its API to make calls.

Ansible, using URI module, provides way to make the REST calls. The URI module allows us to send XML or JSON payload and get the necessary details. In this article we will see how we can use the URI module and make the REST calls. 



REST call - 

In the below example, we are using the Nexus artifactory to connect to REST Webservice running on 8081 Port. The URL are specified in the vars/main.yml file.

The idea here is to make a Get REST Call using the Ansible URI module to fetch the necessary details. Get call doesn't change anything on REST Server.



- name: Make a Call


  uri:

   url: "{{nexus_url}}/repositories"

   method: GET

   user: user1

   password: user123

   force_basic_auth: yes

   return_content: yes


In the above code, we are making the Get REST call to the “nexus_url/respositories” URL by passing them the user name and password along with the method as “Get” and the return_content.  We can use the Ansible debug to check the obtained response.



POST call – 

Making a Post call needs a little extra details. Now for making a post call we need the JSON data. We have option to create a file with JSON data and pass that to the file or we can include the JSON data at the same POST call. Lets create a JSON file first as below:


{


    "data": {

        "repoType": "proxy",

        "id": "somerepo1",

        "name": "Some Repo Name1",

        "browseable": true,

        "indexable": true,

        "notFoundCacheTTL": 1440,

        "artifactMaxAge": -1,

        "metadataMaxAge": 1440,

        "itemMaxAge": 1440,

        "repoPolicy": "RELEASE",

        "provider": "maven2",

        "providerRole": "org.sonatype.nexus.proxy.repository.Repository",

        "downloadRemoteIndexes": true,

        "autoBlockActive": true,

        "fileTypeValidation": true,

        "exposed": true,

        "checksumPolicy": "WARN",

        "remoteStorage": {

            "remoteStorageUrl": "http://testserver.com:8081/local",

            "authentication": null,

            "connectionSettings": null

        }

    }

}

Next, we will save this file as proxy.json and move the file to the files location. Now we can use the proxy.json using the lookup in ansible as follows:



- name: Make a Proxy Repository


  uri:

    url: "{{ nexus_url }}/repositories"

    method: POST

    body: "{{ lookup('file','proxy.json') }}"

    user: user1

    password: user123

    force_basic_auth: yes

    body_format: json

    HEADER_Content-Type: application/json

    HEADER_Accept: application/json,version=2

    return_content: yes

    status_code: 201



Explanation:

In the above code,we passed the JSON file an argument to the  Ansible lookup. Besides this we passed the user name , password and most importantly the body_format , Header fields etc. We also need to pass the return code of the REST call so that Ansible will compare the return status code with the status code that we defined. In the above example we passed the status code as 201. In this example Ansible will check the rest call status code and passed status code to check if that is success or not. Even though the rest call is success if the status codes are not same Ansible will throw an error.

If we want to pass the JSON format in the body itself without using the file, we can use it this way:



- name: Make a Hosted Repository


  uri:

    url: "{{nexus_url}}/{{ nexus_endpoint }}/{{ nexus_repositories_service }}"

    method: POST

    body: >

     {

      data: {

        "repoType": "{{ hosted_repo_data.repoType }}",

        "id": "{{ repoId }}",

        "name": "{{ repoName }}",

        "provider": "{{ repoProvider}}",

        "browseable": {{ hosted_repo_data.browseable }},

        "repoPolicy": {{ hosted_repo_data.repoPolicy }},

        "providerRole": {{ hosted_repo_data.providerRole }}

           }

     }

    user: "{{ nexus_admin }}"

    password: "{{ nexus_admin_password }}"

    force_basic_auth: yes

    body_format: json

    HEADER_Content-Type: application/json

    HEADER_Accept: application/json,version=2

    return_content: yes

    status_code: 201

The body can be added directory to the Body method in the Ansible JSON call.


Thats all for different ways to make REST call via Ansible. If you have a query please mention in comments section and don't forget to subscribe to latest articles -> Subscribe to Tech693