Sonar Custom Widget - api

I created a widget using the source code available in github. Now I'm using that widget in SonarQube V5.3. This is where I got the source code from:
https://github.com/SonarSource/sonar-examples/tree/master/plugins/sonar-reference-plugin
When I use this widget it is showing up the same data across multiple projects. I would like to know if there is any way I can display different data for different projects. Please share your ideas. Below is the code that displays the ruby widget
import org.sonar.api.web.AbstractRubyTemplate;
import org.sonar.api.web.Description;
import org.sonar.api.web.RubyRailsWidget;
import org.sonar.api.web.UserRole;
import org.sonar.api.web.WidgetCategory;
import org.sonar.api.web.WidgetProperties;
import org.sonar.api.web.WidgetProperty;
import org.sonar.api.web.WidgetPropertyType;
import org.sonar.api.batch.CheckProject;
import org.sonar.api.resources.Project;
#UserRole(UserRole.USER)
#Description("Sample")
#WidgetCategory("Sample")
#WidgetProperties({
#WidgetProperty(key = "Index",type=WidgetPropertyType.TEXT
),
})
public class OneMoreRubyWidget extends AbstractRubyTemplate implements RubyRailsWidget {
#Override
public String getId() {
return "Sample";
}
#Override
public String getTitle() {
return "Sample";
}
#Override
protected String getTemplatePath() {
return "/example/Index.html.erb";
}
}
Thank you so much in advance

You haven't specified global scope for your widget (#WidgetScope("GLOBAL")) in the .java file, so this is a question of what's in your .erb file.
This Widget Lab property widget should give you some pointers. Specifically: you want to pick up #project in your widget, and query with #project.uuid. Here's another project-level widget for comparison.
You should be aware, though, that SonarSource is actively working to remove Ruby from the platform, so at some future date, you'll probably end up re-writing your widgets (likely in pure JavaScript).

Related

Selenium framework and test data in json

I am just completed a test automation using with selenium. And I want to know about how to keep the test data separately in json format.
Can you please tell me how to write test data in the page object pattern.
Here I am using multiple packages. One is for locators identification, another is for page factory for initializing elements, and the other is package utilities for common values like get URL. I also have a test package for testing a login module.
What I don't know is where should I put the test data class ?
I want to keep the test data separately. Not scattering all over the script. Keep the test data in Json. And read it from there where ever it is necessary.
Still I'm getting confusing about where Should I put the json format
And also I am selenium code doesn't follow a framework. I did n't follow any frameworks. Anybody please tell me about frameworks ?
Frameworks are : Data driven, keyword driven, hybrid and modular. which framework is most people using , because and why ?
As a tester should have knowledge about all frameworks ?
I am following page object design pattern:
Page object :
package pageobjects;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class HomePage
{
#FindBy(how= How.NAME, using = "username")
WebElement username;
#FindBy(how=How.NAME, using = "password")
WebElement password;
#FindBy(how=How.XPATH, using="//*[#id=\'login-container\']/form/div[3]/div/p/input[1]" )
WebElement button;
//enter username
public void userLogin(String user, String pass)
{
username.sendKeys(user);
password.sendKeys(pass);
button.click();
}
}
Steps:
package steps;
import org.openqa.selenium.support.PageFactory;
import pageobjects.ClientPage;
import pageobjects.HomePage;
import util.DriverManager;
public class LoginSteps
{
public HomePage Login(String nam, String pas) {
HomePage homePageObj = PageFactory.initElements(DriverManager.driver, HomePage.class);
homePageObj.userLogin(nam,pas);
return homePageObj;
}
}
Util:
package util;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DriverManager
{
public static WebDriver driver;
String baseUrl="//http:qms";
public DriverManager()
{
System.setProperty("webdriver.chrome.driver","/home/naveen/chromedriver");
driver=new ChromeDriver();
driver.get(baseUrl);
driver.manage().window().maximize();
}
}
Login Test :
package login;
import org.testng.Assert;
import org.testng.annotations.*;
import pageobjects.HomePage;
import steps.LoginSteps;
import util.DriverManager;
import static util.DriverManager.driver;
public class loginTest
{
#BeforeSuite(groups = {"regression"})
public void initDriver(){
DriverManager manager = new DriverManager();
}
#DataProvider(name= "login")
public static java.lang.Object[][] loginData(){
return new Object[][]{{"geoso","1"},{"ges","2"},{"geo","1"}};
}
#Test(dataProvider = "login")
public void verifyValidLoginWithDataProvider(String userName,String password)
{
LoginSteps loginSteps= new LoginSteps();
HomePage ex=loginSteps.Login(userName,password);
Assert.assertTrue(driver.getPageSource().contains("Hello Naveen"));
}
}
Here is the scenario of json format Please tell me how to write the code?
first open URL and go to login page then .
login
{
"username" :"ertte"
password: "34"
}
"Admin"
"users"
"add users"
"username" :"tsrt"
"password":"sdfgsdrfg"
name:"gfgf"
nickname:"fgsdgf"
role:"client"
email:"sdfsd#gmail.com"
submit
}}
There are so many different frameworks you can use now in combination with selenium.
I use Cucumber [BDD].
You can write your scenarios as regular sentences and Gherkin will transfer them in a methods. Sentences can have parameters or list of a parameters.
You have execution control for your test at two, let call it top levels. You can choose which feature file you want to ran.
Second execution filter can be build by using tags. For e.g. #smoketest #regression and so on.
You can use also TestNG. You have .xml file where you can make your setup. Execute particular clases, methods, prioretize test, make test dependencies, skip tests, and have full control over execution.
There are lot more I assume but these two are the most popular.

Can "driver.findElement" be used as method and be called in a program

I am using "driver.findElement" multiple times. So can it be saved in a method and called multiple times?
driver.findElement(By.xpath("//tbody[#id='detailsstockid']/tr/td[12]/a/input")).click();
driver.findElement(By.id("supplier_name")).click();
driver.findElement(By.xpath("//select[#id='supplier_name']/option[7]")).click();
driver.findElement(By.id("catagory_name")).click();
driver.findElement(By.id("productname")).sendKeys("AutoProductNew");
driver.findElement(By.id("productcode")).sendKeys("ap02");
You just need a wrapper like this
public static WebElement findElement(By locator){
WebElement anElement = driver.findElement(locator);
return anElement;
}
findElement(By.id("id")).click();
Basically you can call whatever method available to the object
I think what you are trying to do is to simplify your code... maybe make it more human readable. This is a noble goal but I would suggest that you take a different approach. Without more info, I don't know what your typical script is like. From the example code you provided, I would assume that you are going to a few pages, clicking on things, filling in textboxes, etc. I would suggest that you look into the page object model.
There are a LOT of references on the web on this topic, here's a good one to start with.
http://www.seleniumhq.org/docs/06_test_design_considerations.jsp#page-object-design-pattern
The basic concept is create one Class file per page. [Page doesn't always literally mean an entire page. For example, I would create a separate page object for each popup dialog.] What this allows you to do is to consolidate all the code specific to that page into a single location. If you know what an API is and understand it, you will basically create an API for each page/dialog you touch. If done properly, it will greatly simplify and organize your code and will make creating new scripts drastically easier and they will be much easier to read. The benefits are numerous... one big one is code maintenance is made SO much easier. Imagine you have 100 scripts that all start by logging into the site. Let's assume the design of the login page changes... without the page object model, you will have to update all 100 scripts individually. If you are using the page object model, you open the LoginPage.java class, make the change to the Login() method, and you just fixed all 100 scripts.
You may be asking... how does this answer my question? What it does is turns
driver.findElement(By.id("supplier_name")).click();
into
somePage.clickSupplierName();
in your actual script. I think this is more along the lines of what you are asking without answering your specific question. The .findElement code still exists, but is "hidden away" in the page object.
A simple example. I wrote a script, with supporting page objects, to navigate to Amazon.com, search for Star Wars, return the # of found items, and then navigate to the Today's Deals page. The entire code is below.
program.java (Main script)
public class program
{
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.com");
// HOME PAGE
HomePage homepage = new HomePage(driver);
homepage.search("star wars");
// SEARCH RESULTS PAGE
SearchResultsPage searchResultsPage = new SearchResultsPage(driver);
System.out.println(searchResultsPage.getNumberOfResults());
// navigate to the Today's Deals page
searchResultsPage.clickTodaysDealsLink();
// TODAY'S DEALS PAGE
// do more stuff
driver.close();
driver.quit();
System.out.println("Done");
}
}
HomePage.java (Home page page object)
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class HomePage
{
WebDriver driver;
private By searchTextboxLocator = By.id("twotabsearchtextbox");
public HomePage(WebDriver driver)
{
this.driver = driver;
}
public void search(String searchString)
{
driver.findElement(searchTextboxLocator).sendKeys(searchString + "\n");
}
}
SearchResultsPage.java (Search results page page object)
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class SearchResultsPage
{
WebDriver driver;
private By todaysDealsLinkLocator = By.linkText("Today's Deals");
private By numberOfResultsLocator = By.id("s-result-count");
public SearchResultsPage(WebDriver driver)
{
this.driver = driver;
}
public String getNumberOfResults()
{
// grabs only the total count of search results from the string in the form "1-16 of 7,488,146 results for "
return driver.findElement(numberOfResultsLocator).getText().split(" ")[2];
}
public void clickTodaysDealsLink()
{
driver.findElement(todaysDealsLinkLocator).click();
}
}

Need help about #Get #Post #Put #Delete in Restful webservice

I need your help and advice. This is my first project in jersey. I don't know much about this topic. I'm still learning. I created my school project. But I have some problems on the web service side. Firstly I should explain my project. I have got 3 tables in my database. Movie,User,Ratings
Here my Movie table columns. I will ask you some points about Description column of the Movie table. I will use these methods to these columns.
Movie= Description (get,put,post and delete) I have to use all methods in this page.
movieTitle (get)
pictureURL (get,put)
generalRating (get,post)
I built my Description page. But I'm not sure if its working or not .(My database is not ready to check them). Here is my page. I wrote this page, looking at the example pages. Can u help me to find the problems and errors. I just want to do simple methods get(just reading data), post(update existing data), put(create new data), delete(delete specific data) these things.What should I do now, is my code okay or do you have alternative advice? :( I need your help guys ty
package com.vogella.jersey.first;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
#Path("/Movie/Description")
public class Description {
private Moviedao moviedao = new Moviedao();
#GET
#Path("/Description/")
#Produces(MediaType.APPLICATION_XML)
public Description getDescriptionID(#PathParam("sample6") string sample6){
return moviedao.getDescriptionID(id);
}
#POST
#Path("/Description/")
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void updateDescription(#PathParam("sampleID")int sampleID,
#PathParam("sample2Description")string sample2Description)
throws IOException {
Description description = new Description (sampleID, sample2Description);
int result = moviedao.updateDescription(description);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
#PUT
#Path("/Description")
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createUser(#FormParam("sample8ID") int sample8ID,
#FormParam("sample8Description") String sample8Description,
#Context HttpServletResponse servletResponse) throws IOException{
Description description = new Description (sample8ID, sample8Description);
int result = movidao.addDescription(description);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
#DELETE
#Path("/Description/{descriptionID}")
#Produces(MediaType.APPLICATION_XML)
public String deleteUser(#PathParam("descriptionID") int descriptionID){
int result = moviedao.deleteDescription(descriptionID);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
#OPTIONS
#Path("/Description")
#Produces(MediaType.APPLICATION_XML)
public String getSupportedOperations(){
return "<operations>GET, PUT, POST, DELETE</operations>";
}
}
I just want to do simple methods get(just reading data), post(update
existing data), put(create new data), delete(delete specific data)
these things
POST should be used to create resources and PUT should be used to update resources.
Your class already has webservice path /Movie/Description, so there is no need to repeat word Description in the methods.
Also, I would recommend keep path names in lower case e.g. /movie/description

Eclipse: Within a plug-in, how to access another plug-ins preference store?

I have an Eclipse plug-in with a checkbox in the plug-in's preference page.
This checkbox is used for enabling and disabling an editor, which is being launched from this plug-in.
However, the problem is, I would also like to be able to enable and disable this 'editor-launch' from another plug-in, by having actions which change the value of the checkbox in the above mentioned preference page.
Here's the problem, how do I access that local preference store from another plug-in?
I've tried things like..
View myView = (View) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("ViewID");
But this 'myView' always seems to be null.. And also, what would I do with the view since it's the Plug-in I want.
Platform.getBundle('bundleName')...
Same here, want the Plugin, not the bundle corresponding to is.
No matter what I try nothing seems to work.
Does anyone have any ideas?
There are two ways of doing this:
Please refer to http://www.vogella.com/tutorials/EclipsePreferences/article.html#preferences_pluginaccess
Using .getPluginPreferences(). For example, there is a plugin class "com.xxx.TestPlugin" which extends org.eclipse.ui.plugin.AbstractUIPlugin.Plugin, in order to get access to the preferences of TestPlugin. The plugin code could be below:
public class TestPlugin extends AbstractUIPlugin {
private static TestPlugin plugin;
public static final String PREF_TEST = "test_preference";
/**
* The constructor.
*/
public TestPlugin() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static TestPlugin getDefault() {
return plugin;
}
}
To access the preference of TestPlugin, the code could be:
TestPlugin.getDefault().getPluginPreferences().getDefaultBoolean(TestPlugin.PREF_TEST);
Or have a look at this answer: Writing Eclipse plugin to modify Editor Preferences
This thread recommend the use of a Service tracker:
ServiceTracker tracker = new ServiceTracker(ToolkitPlugin.getDefault().getBundle().getBundleContext(),
IProxyService.class.getName(), null);
tracker.open();
proxyService = (IProxyService) tracker.getService();
proxyService.addProxyChangeListener(this);
This may work.
Prefs stores are found per plugin. This is one way to get a prefs store for the plugin whose activator class is ActivatorA.
IPreferenceStore store = ActivatorA.getDefault().getPreferenceStore();
If you want another plugin to refer to the same store, perhaps you could expose some api on ActivatorA for it to get there, e.g.
public IPreferenceStore getSharedPrefs() {
return ActivatorA.getDefault().getPreferenceStore();
}
The second plugin would find the shared store by doing this
IPreferenceStore sharedPrefs = ActivatorA.getSharedPrefs();
Good luck.

How do I create a custom directive for Apache Velocity

I am using Apache's Velocity templating engine, and I would like to create a custom Directive. That is, I want to be able to write "#doMyThing()" and have it invoke some java code I wrote in order to generate the text.
I know that I can register a custom directive by adding a line
userdirective=my.package.here.MyDirectiveName
to my velocity.properties file. And I know that I can write such a class by extending the Directive class. What I don't know is how to extend the Directive class -- some sort of documentation for the author of a new Directive. For instance I'd like to know if my getType() method return "BLOCK" or "LINE" and I'd like to know what should my setLocation() method should do?
Is there any documentation out there that is better than just "Use the source, Luke"?
On the Velocity wiki, there's a presentation and sample code from a talk I gave called "Hacking Velocity". It includes an example of a custom directive.
Also was trying to come up with a custom directive. Couldn't find any documentation at all, so I looked at some user created directives: IfNullDirective (nice and easy one), MergeDirective as well as velocity build-in directives.
Here is my simple block directive that returns compressed content (complete project with some directive installation instructions is located here):
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.log.Log;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
/**
* Velocity directive that compresses an HTML content within #compressHtml ... #end block.
*/
public class HtmlCompressorDirective extends Directive {
private static final HtmlCompressor htmlCompressor = new HtmlCompressor();
private Log log;
public String getName() {
return "compressHtml";
}
public int getType() {
return BLOCK;
}
#Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
super.init(rs, context, node);
log = rs.getLog();
//set compressor properties
htmlCompressor.setEnabled(rs.getBoolean("userdirective.compressHtml.enabled", true));
htmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressHtml.removeComments", true));
}
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
//render content to a variable
StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);
//compress
try {
writer.write(htmlCompressor.compress(content.toString()));
} catch (Exception e) {
writer.write(content.toString());
String msg = "Failed to compress content: "+content.toString();
log.error(msg, e);
throw new RuntimeException(msg, e);
}
return true;
}
}
Block directives always accept a body and must end with #end when used in a template. e.g. #foreach( $i in $foo ) this has a body! #end
Line directives do not have a body or an #end. e.g. #parse( 'foo.vtl' )
You don't need to both with setLocation() at all. The parser uses that.
Any other specifics i can help with?
Also, have you considered using a "tool" approach? Even if you don't use VelocityTools to automatically make your tool available and whatnot, you can just create a tool class that does what you want, put it in the context and either have a method you call to generate content or else just have its toString() method generate the content. e.g. $tool.doMyThing() or just $myThing
Directives are best for when you need to mess with Velocity internals (access to InternalContextAdapter or actual Nodes).
Prior to velocity v1.6 I had a #blockset($v)#end directive to be able to deal with a multiline #set($v) but this function is now handled by the #define directive.
Custom block directives are a pain with modern IDEs because they don't parse the structure correctly, assuming your #end associated with #userBlockDirective is an extra and paints the whole file RED. They should be avoided if possible.
I copied something similar from the velocity source code and created a "blockset" (multiline) directive.
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.TemplateInitException;
import java.io.Writer;
import java.io.IOException;
import java.io.StringWriter;
public class BlockSetDirective extends Directive {
private String blockKey;
/**
* Return name of this directive.
*/
public String getName() {
return "blockset";
}
/**
* Return type of this directive.
*/
public int getType() {
return BLOCK;
}
/**
* simple init - get the blockKey
*/
public void init( RuntimeServices rs, InternalContextAdapter context,
Node node )
throws TemplateInitException {
super.init( rs, context, node );
/*
* first token is the name of the block. I don't even check the format,
* just assume it looks like this: $block_name. Should check if it has
* a '$' or not like macros.
*/
blockKey = node.jjtGetChild( 0 ).getFirstToken().image.substring( 1 );
}
/**
* Renders node to internal string writer and stores in the context at the
* specified context variable
*/
public boolean render( InternalContextAdapter context, Writer writer,
Node node )
throws IOException, MethodInvocationException,
ResourceNotFoundException, ParseErrorException {
StringWriter sw = new StringWriter(256);
boolean b = node.jjtGetChild( 1 ).render( context, sw );
context.put( blockKey, sw.toString() );
return b;
}
}