Friday, June 3, 2016

Sample UI test for gerg LifeCycle scenarios

Refer :

[1]

https://github.com/wso2/product-greg/blob/master/modules/integration/tests-ui-integration/tests-es-ui/src/test/java/org/wso2/carbon/greg/ui/test/lifecycle/LifeCycleSmokeUITestCase.java


/*
*Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied.  See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.greg.ui.test.lifecycle;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.context.beans.User;
import org.wso2.carbon.automation.extensions.selenium.BrowserManager;

import org.wso2.greg.integration.common.ui.page.LoginPage;
import org.wso2.greg.integration.common.ui.page.lifecycle.LifeCycleHomePage;
import org.wso2.greg.integration.common.ui.page.lifecycle.LifeCyclesPage;
import org.wso2.greg.integration.common.ui.page.publisher.PublisherHomePage;
import org.wso2.greg.integration.common.ui.page.publisher.PublisherLoginPage;
import org.wso2.greg.integration.common.ui.page.store.StoreLoginPage;
import org.wso2.greg.integration.common.ui.page.util.UIElementMapper;
import org.wso2.greg.integration.common.utils.GREGIntegrationUIBaseTest;

import static org.testng.Assert.assertTrue;

/**
 * This UI test class covers a full testing scenario of,
 *
 *  1. Uploading a LC to greg,
 *  2. Implementation of rest service,
 *  3. Adding the LC to rest service,
 *  4. Attaching of LC for rest service
 *  5. Promoting of rest service
 *  6. Store related operations - JIRA STORE-1156
 *
 */
public class LifeCycleSmokeUITestCase extends GREGIntegrationUIBaseTest {

    private WebDriver driver;
    private User userInfo;

    private String restServiceName = "DimuthuD";
    private UIElementMapper uiElementMapper;

    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {

        super.init(TestUserMode.SUPER_TENANT_ADMIN);
        userInfo = automationContext.getContextTenant().getContextUser();
        driver = BrowserManager.getWebDriver();
        this.uiElementMapper = UIElementMapper.getInstance();
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
    }

    @Test(groups = "wso2.greg", description = "verify login to governance registry")
    public void performingLoginToManagementConsole() throws Exception {

        driver.get(getLoginURL());
        LoginPage test = new LoginPage(driver);
        test.loginAs(automationContext.getContextTenant().getContextUser().getUserName(),
                automationContext.getContextTenant().getContextUser().getPassword());

        driver.get(getLoginURL() + "admin/index.jsp?loginStatus=true");
        LifeCycleHomePage lifeCycleHomePage = new LifeCycleHomePage(driver);


        String lifeCycle = "<aspect name=\"SampleLifeCycle\" class=\"org.wso2.carbon.governance.registry.extensions.aspects.DefaultLifeCycle\">\n" +
                "    <configuration type=\"literal\">\n" +
                "        <lifecycle>\n" +
                "            <scxml xmlns=\"http://www.w3.org/2005/07/scxml\"\n" +
                "                   version=\"1.0\"\n" +
                "                   initialstate=\"Development\">\n" +
                "                <state id=\"Development\">\n" +
                "                    <datamodel>\n" +
                "                        <data name=\"checkItems\">\n" +
                "                            <item name=\"Code Completed\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                            <item name=\"WSDL, Schema Created\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                            <item name=\"QoS Created\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                        </data>\n" +
                "                    </datamodel>\n" +
                "                    <transition event=\"Promote\" target=\"Tested\"/>\n" +
                "                    <checkpoints>\n" +
                "                        <checkpoint id=\"DevelopmentOne\" durationColour=\"green\">\n" +
                "                            <boundary min=\"0d:0h:0m:0s\" max=\"1d:0h:00m:20s\"/>\n" +
                "                        </checkpoint>\n" +
                "                        <checkpoint id=\"DevelopmentTwo\" durationColour=\"red\">\n" +
                "                            <boundary min=\"1d:0h:00m:20s\" max=\"23d:2h:5m:52s\"/>\n" +
                "                        </checkpoint>\n" +
                "                    </checkpoints>\n" +
                "                </state>\n" +
                "                <state id=\"Tested\">\n" +
                "                    <datamodel>\n" +
                "                        <data name=\"checkItems\">\n" +
                "                            <item name=\"Effective Inspection Completed\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                            <item name=\"Test Cases Passed\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                            <item name=\"Smoke Test Passed\" forEvent=\"\">\n" +
                "                            </item>\n" +
                "                        </data>\n" +
                "                    </datamodel>\n" +
                "                    <transition event=\"Promote\" target=\"Production\"/>\n" +
                "                    <transition event=\"Demote\" target=\"Development\"/>\n" +
                "                </state>\n" +
                "                <state id=\"Production\">\n" +
                "                    <transition event=\"Demote\" target=\"Tested\"/>\n" +
                "                </state>\n" +
                "            </scxml>\n" +
                "        </lifecycle>\n" +
                "    </configuration>\n" +
                "</aspect>\n";


        lifeCycleHomePage.addNewLifeCycle(lifeCycle);

        driver.get(getLoginURL() + "lcm/lcm.jsp?region=region3&item=governance_lcm_menu");
        LifeCyclesPage lifeCyclesPage = new LifeCyclesPage(driver);

        assertTrue(lifeCyclesPage.checkOnUploadedLifeCycle("SampleLifeCycle"), "Sample Life Cycle Could Not Be Found");

        Thread.sleep(6000);

        driver.findElement(By.linkText("Sign-out")).click();

        log.info("Login test case is completed ");
    }

    @Test(groups = "wso2.greg", description = "logging to publisher",
            dependsOnMethods = "performingLoginToManagementConsole")
    public void performingLoginToPublisher() throws Exception {

        // Setting publisher home page
        driver.get(getPublisherUrl().split("\\/apis")[0]);

        PublisherLoginPage test = new PublisherLoginPage(driver);

        // performing login to publisher
        test.loginAs(userInfo.getUserName(), userInfo.getPassword());

        driver.get(getPublisherUrl().split("/apis")[0] + "/pages/gc-landing");

        PublisherHomePage publisherHomePage = new PublisherHomePage(driver);

        //adding rest service
        publisherHomePage.createRestService(restServiceName, "/lana", "1.2.5");

        driver.findElement(By.cssSelector("div.auth-img")).click();
        driver.findElement(By.linkText("Sign out")).click();

        Thread.sleep(3000);
    }


    @Test(groups = "wso2.greg", description = "Adding of LC to the rest service",
            dependsOnMethods = "performingLoginToPublisher")
    public void addingLCToRestService() throws Exception {

        driver.get(getLoginURL());

        LoginPage loginPage = new LoginPage(driver);
        loginPage.loginAs(automationContext.getContextTenant().getContextUser().getUserName(),
                automationContext.getContextTenant().getContextUser().getPassword());

        loginPage.assignLCToRestService(restServiceName);

        driver.findElement(By.linkText("Sign-out")).click();

        Thread.sleep(3000);
    }

    @Test(groups = "wso2.greg", description = "Promoting of rest service with the LC",
            dependsOnMethods = "addingLCToRestService")
    public void lifeCycleEventsOfRestService() throws Exception {

        // Setting publisher home page
        driver.get(getPublisherUrl().split("/apis")[0]);

        PublisherLoginPage publisherLoginPage = new PublisherLoginPage(driver);

        // performing login to publisher
        publisherLoginPage.loginAs(userInfo.getUserName(), userInfo.getPassword());

        driver.get(getPublisherUrl().split("/apis")[0] + "/pages/gc-landing");

        driver.findElement(By.cssSelector("span.btn-asset")).click();
        driver.findElement(By.linkText("REST Services")).click();
        driver.findElement(By.linkText(restServiceName)).click();

        driver.findElement(By.id("Lifecycle")).click();

        driver.findElement(By.linkText("Other lifecycles")).click();
        driver.findElement(By.linkText("SampleLifeCycle")).click();

        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox1.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox2.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox3.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.id("lcActionPromote")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox1.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox2.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath(uiElementMapper.getElement("publisher.promote.checkbox3.xpath"))).click();
        Thread.sleep(2000);
        driver.findElement(By.id("lcActionPromote")).click();

        // removal of added rest service
        driver.findElement(By.id("Edit")).click();
        driver.findElement(By.id("Delete")).click();
        driver.findElement(By.id("btn-delete-con")).click();
    }

}

Thursday, June 2, 2016






[1] Docker + Java 

Below code segment can be used for pushing your Docker images to public docker registry / hub.


  private StringBuffer output = new StringBuffer();

  private String gitPush(String command) {

      Process process;
      try {
          process = Runtime.getRuntime().exec(command);
          process.waitFor();
          BufferedReader reader =
                  new BufferedReader(new InputStreamReader(process.getInputStream()));


          String line = "";
          while ((line = reader.readLine()) != null) {
              output.append(line + "\n");
          }

      } catch (Exception e) {
          e.printStackTrace();
      }

      return output.toString();

  }


Build Doker image using fabric8
---------------------------------------

public static boolean buildDockerImage(String dockerUrl, String image, String imageFolder)
            throws InterruptedException, IOException {

        Config config = new ConfigBuilder()
                .withDockerUrl(dockerUrl)
                .build();

        DockerClient client = new DefaultDockerClient(config);
        final CountDownLatch buildDone = new CountDownLatch(1);


        OutputHandle handle = client.image().build()
                .withRepositoryName(image)
                .usingListener(new EventListener() {
                    @Override
                    public void onSuccess(String message) {
                        log.info("Success:" + message);
                        buildDone.countDown();
                    }

                    @Override
                    public void onError(String messsage) {
                        log.error("Failure:" + messsage);
                        buildDone.countDown();
                    }

                    @Override
                    public void onEvent(String event) {
                        log.info("Success:" + event);
                    }
                })
                .fromFolder(imageFolder);

        buildDone.await();
        handle.close();
        client.close();
        return true;
    }

Thursday, May 12, 2016

Troubleshooting Wso2 TAF
=====================


This is series of super important clues to overcome such bugs we would encounter while working with Wso2 TAF - Automation Framework ....


1. Errror 

when building wso2 TAF if you get something like this on the console .......

diamond operator is not supported in -source 1.6
  (use -source 7 or higher to enable diamond operator)
  
  Solution 
Add the maven source plugin to the pom.xml file. 


            <plugin>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>2.3.1</version>
                   <inherited>true</inherited>
                       <configuration>
                               <source>1.8</source>
                               <target>1.8</target>
                       </configuration>
            </plugin>

Monday, December 8, 2014

Sample Jaxrs service .....

Here is a sample Jaxrs service which you can use as a backend hosted in Tomcat server.

Package structure ...

  * musicsample
        |- bean
              |- Music
        |- JaxRsApiApplication  
        |- MusicConfig
        |- MusicRestService
        |- MusicService
        |- Server


Server.java

package org.wso2.automation.musicsample;

import org.apache.catalina.Context;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.io.File;
import java.io.IOException;

public class Server {

    private final static Log log = LogFactory.getLog(Server.class);

    public static void main(final String[] args) throws Exception {
        final File base = createBaseDirectory();
        log.info("Using base folder: " + base.getAbsolutePath());

        final Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);
        tomcat.setBaseDir( base.getAbsolutePath() );

        Context context = tomcat.addContext( "/", base.getAbsolutePath() );
        Tomcat.addServlet( context, "CXFServlet", new CXFServlet() );

        context.addServletMapping( "/rest/*", "CXFServlet" );
        context.addApplicationListener( ContextLoaderListener.class.getName() );
        context.setLoader( new WebappLoader( Thread.currentThread().getContextClassLoader() ) );

        context.addParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
        context.addParameter( "contextConfigLocation", MusicConfig.class.getName() );

        tomcat.start();
        tomcat.getServer().await();
    }

    private static File createBaseDirectory() throws IOException {
        final File base = File.createTempFile( "tmp-", "", new File("/home/dimuthu/Desktop/JMS"));

        if( !base.delete() ) {
            throw new IOException( "Cannot (re)create base folder: " + base.getAbsolutePath()  );
        }

        if( !base.mkdir() ) {
            throw new IOException( "Cannot create base folder: " + base.getAbsolutePath()  );
        }
        return base;
    }
}


MusicService.java

package org.wso2.automation.musicsample;

import org.springframework.stereotype.Service;
import org.wso2.automation.musicsample.bean.Music;

import java.util.concurrent.ConcurrentHashMap;


@Service
public class MusicService {

    private final ConcurrentHashMap< String, Music> musicCollection = new ConcurrentHashMap< String, Music >();


    public MusicService() {
        init();
    }

    final void init() {
        System.out.println("Welcome To World Of Music .... ");
        Music music = new Music();
        music.setAlbum("Gold");
        music.setSinger("Elton John");
        musicCollection.put(music.getAlbum(), music);
    }

    public Music getByAlbum( final String albumName ) {
      
        return musicCollection.get(albumName);
    }

    public void setMusic( Music music ) {

        musicCollection.put(music.getAlbum(),music);
    }
}








MusicRestService.java

package org.wso2.automation.musicsample;

import org.wso2.automation.musicsample.bean.Music;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/music")
public class MusicRestService {

    @Inject
    private MusicService musicService;

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Music getMusicInJSON(@QueryParam("album") final String albumName) {
        /*            Music music = new Music();
       music.setAlbum("Beat It !!!");
       music.setSinger("Micheal Jackson");*/

        return musicService.getByAlbum(albumName);
        //return musicService.musicCollection.get("Dimuthu");

    }

    @POST
    @Path("/post")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createMusicInJSONPOST(Music music) {

        musicService.setMusic(music);

        String result = "Album Added : " + music;
        return Response.status(201).entity(result).build();
        //return music.getAlbum();

    }

    @PUT
    @Path("/put")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createMusicInJSONPUT(Music music) {

        musicService.setMusic(music);

        String result = "Album Added : " + music;
        return Response.status(200).entity(result).build();
        //return music;

    }
}

MusicConfig.java

package org.wso2.automation.musicsample;

import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.ws.rs.ext.RuntimeDelegate;
import java.util.Arrays;

@Configuration
public class MusicConfig {
    @Bean( destroyMethod = "shutdown" )
    public SpringBus cxf() {
        return new SpringBus();
    }

    @Bean
    public Server jaxRsServer() {
        JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
        factory.setServiceBeans( Arrays.< Object >asList(musicRestService()) );
        factory.setAddress( "/" + factory.getAddress() );
        factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
        return factory.create();
    }

    @Bean
    public org.wso2.automation.musicsample.JaxRsApiApplication jaxRsApiApplication() {
        return new JaxRsApiApplication();
    }

    @Bean
    public MusicRestService musicRestService() {
        return new MusicRestService();
    }

    @Bean
    public MusicService musicService() {
        return new MusicService();
    }

    @Bean
    public JacksonJsonProvider jsonProvider() {
        return new JacksonJsonProvider();
    }
}


Music.java

package org.wso2.automation.musicsample.bean;

public class Music {

        String album;
        String singer;

        public String getAlbum() {
            return album;
        }

        public void setAlbum(String album) {
            this.album = album;
        }

        public String getSinger() {
            return singer;
        }

        public void setSinger(String singer) {
            this.singer = singer;
        }

        @Override
        public String toString() {
            return "Your Album " + album + " Of " + singer + " Was Added Successfully";
        }

    }


JaxRsApiApplication.java 

package org.wso2.automation.musicsample;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath( "api" )
public class JaxRsApiApplication extends Application {
}




Friday, November 14, 2014

Useful Git commands

Q: How can I merge a distinct pull request to my local git repo ?

A:
   You can easily merge a desired pull request using the following command. If you are doing this merge at first time you need to clone a fresh check-out of the master branch to your local machine and apply this command from the console.
 
git pull https://github.com/wso2-dev/product-esb +refs/pull/78/head

Q: How do we get the current repo location of my local git repo?

A: The below command will give the git repo location your local repo is pointing to.

git remote -v

Q: Can we change my current repo url to a remote repo url

A: Yes. You can point to another repo url as below.

git remote set-url origin https://github.com/dimuthud/carbon-platform-integration-utils.git

Q: What is the git command to clone directly from a non-master branch (eg: two branches master & release-1.9.0 how to clone from release-1.9.0 branch directly without switching to release-1.9.0 after cloning from the master) 

A: Use the following git command.

git clone -b release-1.9.0 https://github.com/wso2/product-apim.git

Maven

Q : I need to go ahead and build no matter i get build failures. Can I do that with maven build?

A: Yes. Try building like this.

mvn clean install -fn 

Q : Can I directly clone a tag of a particular git branch ?

A : Yes. Lets Imagine your tag is 4.3.0 , Following command will let you directly clone the tag instead the branch.

Syntax : git clone --branch <tag_name> <repo_url>

eg:
git clone --branch carbon-platform-integration-utils-4.3.0 https://github.com/wso2/carbon-platform-integration-utils.git



Q : To See git remote urls in more detail

A : git remote show origin



Q: Creating  a new branch

git checkout -b NewBranchName
git push origin master
git checkout master
git branch      (The pointer * represents that, In which branch you are right now.)
git push origin NewBranchName



For More Info : http://stackoverflow.com/questions/9257533/what-is-the-difference-between-origin-and-upstream-on-github

Q : 1. Getting the below error -

To https://github.com/dimuthud/identity-metadata-saml2-1.git
 ! [rejected]        HEAD -> v0.5.0 (already exists)
error: failed to push some refs to 'https://github.com/dimuthud/identity-metadata-saml2-1.git'
hint: Updates were rejected because the tag already exists in the remote.

git tag -f v0.5.0
delete remote tag on github: git push origin --delete v0.5.0
git push origin v0.5.0

2. You can not use HTTPS on centos / linux based system it gets "Received HTTP code 403 from proxy after CONNECT" error:

Try using ssh :

For Windows Open a Git Bash terminal.
Generate an SSH key ssh-keygen -t rsa from the host CentOS machine. (Give Any Password)
Run cat ~/.ssh/id_rsa.pub. 

Now Add the output to your GitHub account. To do so go to: Settings -> SSH and GPG Keys -> New SSH key
Now try git clone git clone git@xxxxx:yyyy/RepoName.git

Amend your git messages:
https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4

Clone a specific commit from the git

git reset --hard ${SHA_value}