Tuesday, 21 March 2017

Find longest sequence of zeros in binary representation of an integer


 A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

Write a function:

int solution(int N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.

Solution:


 public class Test {  
      private static long maxConsecutiveZeroes(int x) {  
           boolean flagOne = false;  
           long count = 0, max = 0;  
           //Loop until x becomes 0.  
           while (x != 0) {  
                if ((x & 1) == 1) {  
                     flagOne = true;  
                     if (count > max) {  
                          max = count;  
                     }  
                     count = 0;  
                } else if (flagOne) {  
                     count += 1;  
                } else {  
                     count += 1;  
                }  
                x = x >> 1;//Move ht binary digits to right side bit by bit.  
           }  
           return max;  
      }  
      public static void main(String strings[]) {  
           System.out.println(maxConsecutiveZeroes(16));  
           System.out.println(maxConsecutiveZeroes(9));  
           System.out.println(maxConsecutiveZeroes(14));  
           System.out.println(maxConsecutiveZeroes(222));  
           System.out.println(maxConsecutiveZeroes(3));  
           System.out.println(maxConsecutiveZeroes(4));  
           System.out.println(maxConsecutiveZeroes(1041));  
      }  
 }  

Output:


 4  
 2  
 1  
 1  
 0  
 2  
 5  

Enjoy Coding.

CheckMarx Secure Code Analyzer


  1. Login into CheckMarx using your Credentials.
  2. Go to Projects & Scans and select " Create New Project ".



  3. After select, you need to give project name, Select Preset in the field (General Tab). As shown below.
    Example :- Project Name : Universal Payment
                      Preset : APPSEC-Java-JS



  4. Click on Next. you can see Location tab, Click Source Control then click on Select button. new window will popup in there you need to select folder for Source Control i.e. SVN, GIT etc. 
  5. In Port number by default 8080 will show, we need to change 8080 to 443.
  6. Select " Required Authentication " , Enter your User Name and Password (Enterprise ID and Password). and Click on OK.



  7. After Clicking OK you can see another window where you need to select " Root " folder of Project and Click on OK.


  8. After Clicking OK, you can see Source Control got selected, Then click on Next.


  9. In next Scheduling tab select " None " and click on Next.


  10. Next in Advanced Actions tab Enter email to Example : your_email Id and select run post scan action (New_Eport_Script: PrepareAgregatedResult4Splunk.bat [XML_output]). and click on Next.


  11. In next Custom Fields Tab, select Next, and in Data Retention tab select Finish button. you can see Project got Added.


  12. Click on Full scan. it will take time to scan Project.


  13. After completed scan, click on View Project Scan.


  14. After Clicking view project scan, you can see below window. click on Create Report.


  15. After Clicking create report you can see popup window. in there form Report Format select format which is you wants to be created Example : PDF, CSV etc. and click on Generate Report Button.


  16. After Clicking Generate report it will take some time to get generate the report and will download in your local machine (Download folder).

Enjoy Learning.

Cron job to run a jar file


If the requirement is to run the jar file on daily basis, we need to create a cron job.
To create a cron job, follow below steps:


  • Open terminal.
  • Type crontab -e ,It will open an editor to edit cron job.
  • If you want to run your jar on daily basis , put 0 0 * * * java -jar Sample.jar
  • For ex: 0 0 * * * java -Dlog4j.debug -DlogDir=./ -jar /opt/appl/giftcard/valuelinkSimulator/valuelink-simulator.jar.
  • Save the cron job.
We can also view the job using crontab -l command.

Enjoy Learning.

How to indent XML files automatically when opened in Sublime Text 2


To indent and beautify XML, Use SublimeText Indent plugin:sublimetext_indentxml.

  • Download the Package and Extract to Sublime Installation directory,inside package folder.For ex:C:\softwares\Sublime Text 2.0.2 x64\Data\Packages.
  • Open any XML file or create a new file and paste any XML into it.
  • Press Ctrl-K, F to indent it.

Enjoy Learning.

Monday, 20 March 2017

MySQL Workbench Connection over SSH

Setting up MySQL Client

  • Install MySQL Workbench
  • To start MySQL in Local machine, Go To Start-> All Programs->MySQL->MySQL Workbench
  • OR
  • You can search in “Start” as MySQL Workbench in your Machine e.g Click OS Start button-> write MySQL Workbench
  • After MySQL started in your local machine you can see below page.
                     

  • Click on “+” button side to MySQL Connections as shown in below image
                   

  • It will open a new pop up page name “ Setup New Connection ” as shown in below image.
                   
  • Click on Connection Method dropdown, Choose “Standard TCP/IP over SSH” as shown below
                   


  • After selecting “Standard TCP/IP over SSH” you will see the below page.

                     


  • Note : If all options are not visible you can expand the small pop up page
  • Put these details in the new Pop up page ( Setup New Connection )
  • Connection Name : SampleConnection
  • SSH Hostname : servername.com
  • SSH Username : Your user name
  • Password : Your password
  • Password always needs to store in vault ( MySQL Secure place )
  • Follow same “Store in Vault …” Procedure as described above
  • Put password in the Password field
  • Press OK
  • MySQL Hostname : db servername.com
  • Username :db user name
  • Password :db password
  • Password always needs to store in vault ( MySQL Secure place )
  • Follow same “Store in Vault …” Procedure as described above
  • Default Schema : schema name(optional)
  • Press “Test Connection” You will see a connection success message.
  • Press "OK" Button
  • After Pressing "Ok" ButtonSampleConnection will be visible in below MySQL Connection Area

Enjoy Reading.


Adding Wildfly Server Plugin in Eclipse Luna


When we try to add a Wildfly 8 server in Eclipse Luna,By default it does not show Wildfly Servers.
In order to add Wildlfy Server, Please follow below Steps:

  • Go to Help–>Eclipse Market Place 

  • Search for Jboss Tools.

  • Find JBoss Tools(Luna) 4.2.3.Final and select only JbossAs tools and Jboss Webservice tools.

  • Click Next, agree to the license terms, install, restart Eclipse.

  • After Eclipse restarts:

  • Go to your Servers view and right-click.

  • Select "WildFly 8.x", click Next.

  • Set the Home Directory appropriately.

  • Click Finish.

  • Enjoy Reading. 

    Creating a self-signed certificate on Windows 7


    Using the Internet Information Services(IIS)

    By default, IIS 7.5 is not installed on Windows® 7 Professional, Enterprise, or Windows® 7 Ultimate. You can install IIS by clicking Windows Features in Advanced Options under Programs in Control Panel.

    Installing IIS using UI

    1. Click Start and then click Control Panel.
    2. In Control Panel, click Programs and then click Turn Windows features on or off.
    3. In the Windows Features dialog box, click Internet Information Services and then click OK.


    Creating Self signed Certificate

    4. Click Start, and in the Start Search box, type inetmgr and press ENTER.
    5. Click the computer name (top of the tree on top-left).
    6. Double click 'server certificates' from center pane.
    7. Click on the option of 'create self-signed certificate' from the right pane.
    8. Give some name for the certificate and click Ok.

    Exporting the certificate to save locally

    9. In the IIS console under Server Certificates, you would be able to see the certificate you created just now.
    10. Double-click on the certificate that you created which will open up the certificate in separate window.
    11. Go to the details tab and click Copy to File.. which will open a Certificate export Wizard in separate window.
    12. Click Next.
    13. Select "No,do not export the private key" and click Next again.
    14. Select DER encoded binary x.509(.CER) and click Next.
    15. Give the name(eg: LocalSSLCertificate) and path where you want to save this certificate locally and click Next.
    16. Click Finish.
    17. Repeat steps 9-16 with step 13 as Select "Yes, export the private key" and step 14 as Select Personal Information Exchange -PKCS #12(.pfx)
    18. For exporting the the certificate as pfx, you will be prompted to enter and re-enter password. Remember the password which will be used later (eg:changeit)

    Creating the keystore file

    Very important do not miss this step --> Navigate to the bin folder of your respective JRE/JDK (i.e. C:\Program Files\Java\jdk1.6.0_37\bin for Windows 7).  Failure to follow this step will yield the following error: keytool' is not recognized as an internal or external command, operable program or batch file' when attempting to run the below command requiring the keytool.exe file to be present.

    Next Go to Start->All Programs->Accessories
    Right click on Command Prompt and select Run as administrator

    Run the following commands.

    keytool -import -keystore jboss.jks -file D:localSSLcertificate.cer
    Enter keystore  password: changeit
    Re-enter  new password: changeit
    Trust this certificate? [no]:  y
    Certificate was added to keystore

    keytool -importkeystore -keystore jboss.jks -srckeystore D:localSSLcertificate.pfx -srcstoretype PKCS12
    Enter destination keystore password: changeit
    Enter source keystore password: changeit

    You will need to put the jboss.jks file in a place where all your current and future JBoss 7 installations can use it, as follows:

    1. In your Projects directory, create the directory Jboss
    2. Create the directory certs in the jboss directory you created above
    3. copy the file jboss.jks  to the jboss/certs directory you created above.
    Enjoy Reading.

    GitLab Code Chekout,Checkin and Merge Request


     You need to install Git Bash software in you local machine. 

       1. Code Checkout Form Gitlab.

    1. Get open any browser and enter above url.
    2. Get login in gitlab using your LDAP Username and Password or Standard Login.

    3. After login you can see below window.


    4. Before get code in local need to fork your repository, where you want to get code (copy of code for your changes for with out affecting original code ) form master branch. you need to fork project it will create copy of project on your repository.
    5. Click on Fork as shown below.


    6. After fork, you will be enter int your fork project as shown below.




    7. Create location to checkout GC code Ex: C:\WorkSpace\USP_GC\giftcard.
    8. Goto giftcard folder and click right side button of mouse and click select Git Bash.


    9. After select you will get following window.


    10. In git Bash run git init command for initializing git repository (image 1) OR Use git clone <repo url> command Ex: $ git clonegit@gitlab.xxxxxxx.com:USP/giftcard.git ( to download the code from specified repo to local ) image 2.



    11. IF you use clone command then no need to follow step 12 to step 14,if you use init command we need to add remote repository from where we want to get code using : git remote add org (org is alias name) git@gitlab.xxxxxxx.com:USP/giftcard.git  and enter.


    12. Run the command for add repo : git remote add org git@gitlab.xxxxxxx.com:USP/giftcard.git



    13. Do copy your repository link where you want to copy as shown below and again go to the step 9 and add your fork repository link into the git bash (in 2nd image).





    14. After adding remote repo, you can use pull the code form master repo to your fork repo using git pull command  Ex:git pull org master.


    15. You will see code got download in your location folder.


      2. Code Checkin into Gitlab (Pushing changes).

      1. Open Git GUI and click on Open Existing Repository.

      2. Browse your local repository where you have done the changes and click on Open button.


      3. You will get following windows, In this you can see Unstaged changes files, Staged changes (which will be going to commit), commit Message and 4th one for what changes you have done in the file.



      4. Rescan button use for find the changes files form your repo, stage Changed button use for which file you wants to commit into the repo. commit for commit the file into the repo, after commit you can push it to the your gitlab repo.
      5. Once you staged changes file you need to write commit message (Note : Do staged only those file which you have wants to be commit or you have done changes) after that click on commit button.it will ask your username and password, and file changes will committed into the your fork repo.
      6. Once your changes has been committed into the repo you can push that file into the master repo. (Note : you should have the authorization for pushing changes into the master branch otherwise you need create a merge request)

    3. How to create a merge request.

    1. Once changes has been committed into your fork branch. you need to create a merge request to a person who is having higher authority to merge the changes with master branch code. 
    2. Merge request can be create form your gitlab, go to your gitlab URL and get log in using your LDAP id and password.as follows.


    3. Click on fork button, It will go to your fork project window.


    4. Click on Marge Requests, you will get below window.


    5. After that click on New Merge Request. and in the Source Branch select source project and source branch(form merge) ,same for Target Branch select target project(To merge).

    6. After that click on Compare branches and continue. and Enter Title and Description and assign to Authorize person who have the right to merge.and submit merge request.


    7. After submit, your request will go to Authorize per and he will merge the changes with Master Branch.

    Enjoy Reading.

    How to Check if MySQL Instance is read only


    In order to find out if your DB server in read mode or read/write mode.

    Follow the below Steps:

    • Login into your DB Server using MySQL Tools,Mysqlem etc.
    • Run below queries:
      • SELECT @@global.read_only;
      • If the Output is 1, it means DB server is read only.
      • else if Output is 0, it means DB server is both read/write.




    Enjoy Reading.


    Wednesday, 15 March 2017

    Enable Access logs in Wildfly 8.1


    In order to enable access logs in Wildfly 8.1,Please refer below steps:

    1. Go to WILDFLY_HOME/standalone/configuration folder.
    2. Open Standalone.xml and put following snippet under <subsystem xmlns="urn:jboss:domain:undertow:1.2">

     <subsystem xmlns="urn:jboss:domain:undertow:1.2">  
           <buffer-cache name="default"/>  
           <server name="default-server">  
             <http-listener name="default" socket-binding="http" record-request-start-time="true"/>  
             <host name="default-host" alias="localhost">  
               <location name="/" handler="welcome-content"/>  
               <access-log pattern="%h&#x9;%p&#x9;%l&#x9;%u&#x9;%t&#x9;&quot;%r&quot;&#x9;%s&#x9;%b&#x9;&quot;%{i,Referer}&quot;&#x9;&quot;%{i,User-Agent}&quot;&#x  
     9;%D&#x9;&quot;%{i,X-Forwarded-For}&quot;&#x9;&quot;%{i,True-Client-IP}&quot;&#x9;&quot;%{i,JSESSIONID}c&quot;" directory="${jboss.server.log.dir}" prefix="access-log"  
     worker="default" rotate="true"/>  
               <filter-ref name="server-header"/>  
               <filter-ref name="x-powered-by-header"/>  
             </host>  
           </server>  
           <servlet-container name="default">  
             <jsp-config/>  
             <websockets/>  
           </servlet-container>  
           <handlers>  
             <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>  
           </handlers>  
           <filters>  
             <response-header name="server-header" header-name="Server" header-value="WildFly/8"/>  
             <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>  
           </filters>  
         </subsystem>  



    For access log pattern configuration, refer Access log Patterns

    Enjoy Learning.

    Enable Access logs in JBOSS 7.2.1


    In order to enable access logs in JBOSS 7.2.1,Please refer below steps:

    1. Go to JBOSS_HOME/standalone/configuration folder.
    2. Open Standalone.xml and put following snippet under <subsystem xmlns="urn:jboss:domain:web:1.4">

     <subsystem xmlns="urn:jboss:domain:web:1.4" default-virtual-server="default-host" instance-id="${jboss.instance-id.jvmRoute}" native="false">  
           <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" max-connections="250"/>  
           <connector name="ajp" protocol="AJP/1.3" scheme="http" socket-binding="ajp" max-connections="250"/>  
           <connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">  
             <ssl name="https" password="g04theau" certificate-key-file="/opt/jboss/certs/wildcard.prod.ch3.s.com.jks"/>  
           </connector>  
           <virtual-server name="default-host" enable-welcome-root="false">  
             <alias name="localhost"/>  
             <alias name="example.com"/>  
             <access-log pattern='%h&#9;%p&#9;%l&#9;%u&#9;%t&#9;"%r"&#9;%s&#9;%b&#9;"%{Referer}i"&#9;"%{User-Agent}i"&#9;%D&#9;"%{X-Forwarded-For}i"&#9;"%{True-Clien  
     t-IP}i"&#9;"%{JSESSIONID}c"' prefix="access-log-" rotate="true">  
               <directory path="." relative-to="jboss.server.log.dir"/>  
             </access-log>  
           </virtual-server>  
         </subsystem>  

    For access log pattern configuration, refer Access log Patterns

    Enjoy Learning.

    Tuesday, 14 March 2017

    Tunneling with Local Port Forwarding



    This diagram illustrates that our localhost is being blocked from connection to the Target Server(say Sharp Server) using a proxy filter in our corporate network.



    We need a gateway server which would accept the requests from the localhost and fetch data and tunneling it back. Actually the gateway server should have a access to the Target server to perform the tunneling.
    For example, the some.server.com(say pvvault301p.dev.ch3.com) server has already got the access, to connect to the Target server, so it can act as a gateway to connect to the Target sever from the localhost .

    To Create the SSH tunnel execute the following from Localhost.

    1. First load the gateway server , which have the access to the Target server, in the putty




    2. Select the Tunnels option from the category to add the binding port (this can be some arbitrary value) of localhost and remote host ip and port (sharp server ip and active ports).



    The ‘L’ switch indicates that a local port forward is need to be created. The switch syntax is as follows.
    -L <local-port-to-listen>:<remote-host>:<remote-port>

    Refer the below diagram for understanding


    Now the SSH client at localhost will connect to SSH server running at some.server.com (usually running at port 22) binding port 4444 of localhost to listen for local requests thus creating a SSH tunnel between some.server.com and localhost. At the some.server.com end it will create a connection to Target Server at port 17030. So localhost doesn’t need to know how to connect to Target Server. Only some.server.com needs to worry about that. The channel between localhost and some.server.com will be encrypted while the connection between some.server.com and localhost will be unencrypted.
    Now it is possible to connect to target server by localhost:4444  at localhost computer. The some.server.com computer will act as a gateway which would accept requests from localhost machine and fetch data and tunneling it back.
    3. Then click Open and enter the login credentials and keep it open.


    Now the server is open to connect to Target server for the localhost

    To test this replace the hardcoded target server details from the code with the binding port (4444)



    The same can be modified in the xml or properties file( for ex:sharpserverconfig.xml) if the server details are taking from it.






    After this the connection can be make from localhost to Target Server through tunneling.

    Enjoy Learning.

    Rotate an array to the right by a given number of steps


    Given an list of integers of Strings.We need to rotate the list in right direction.
    There are few approaches to accomplish the Solution:

    • We can use two for loops and rotate the elements one by one.
    • We can use Collections utility class rotate method.


    Sample Program:

    import java.util.ArrayList;  
     import java.util.Collections;  
     import java.util.List;  
     /**  
      *   
      */  
     /**  
      * @author Dixit  
      *  
      */  
     public class RotateElement {  
          /**  
           * @param args  
           */  
          public static void main(String[] args) {  
               List<String> list = new ArrayList<String>();  
               list.add("1");  
               list.add("2");  
               list.add("3");  
               list.add("4");  
               list.add("5");  
               list.add("6");  
               System.out.println("Before Rotating :" + list);  
               Collections.rotate(list, 2);  
               System.out.println("After Rotating :" + list);  
          }  
     }  


    Output:

     Before Rotating :[1, 2, 3, 4, 5, 6]  
     After Rotating :[5, 6, 1, 2, 3, 4]  

    Enjoy Learning.

    Find value that occurs in odd number of times in array of elements.



    Given an array of Integers.Some Integers occurs even number of times and some odd.We need to find the number which occurs odd number of times.

    Sample:-

    Input:{1,2,3,2,3,1,2}

    Output:2


    Sample Program:

    import java.util.HashSet;  
     import java.util.Set;  
     public class OddElements {  
          public static void main(String[] args) {  
               int[] integerArray={1,2,3,2,3,2,3};  
               printOddElementOccurence(integerArray);  
          }  
          private static void printOddElementOccurence(int[] integerArray) {  
            Set<Integer> unpaired = new HashSet<Integer>();  
            for (int i = 0; i<integerArray.length; i++){  
              if (unpaired.contains(integerArray[i])){  
                unpaired.remove(new Integer(integerArray[i]));  
              }else{  
                unpaired.add(integerArray[i]);  
              }  
            }  
            // all printed out values are odd  
            for (Integer result : unpaired){  
              System.out.println(result);  
            }   
          }  
     }  

    Output:

     1  
     2  
     3  


    Enjoy Learning.