SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
Sonar	
  rules	
  in	
  ac-on	
  
with	
  Walkmod
Raquel	
  Pau	
  	
  
rpau@walkmod.com	
  
INTRODUCTION	
  
FROM THE BOTTOM TO THE TOP
The abstract syntax tree
rpau/javalang
rpau/javalang-compiler
Visitor pattern
node.accept (visitor, ctx);
Exercise 1
•  Fork	
  &	
  Clone	
  walkmod/walkmod-sonar-plugin
•  Run:	
  git checkout tutorial
•  	
  Open	
  from	
  src/test/java:	
  
– org.walkmod.sonar.tutorial.Exercise1	
  
•  Run	
  the	
  JUNIT	
  test	
  from	
  Eclipse	
  
•  Create	
  the	
  HelloVisitor	
  in	
  the	
  same	
  package	
  
that	
  modifies	
  the	
  class	
  name	
  “Foo”	
  per	
  
“Hello”	
  	
  
Execution Workflow
How to create Plugins
•  Create	
  a	
  Maven	
  project	
  
– Ar-factId:	
  walkmod-­‐xxxx-­‐plugin	
  
– Dependencies:	
  javalang-compiler	
  &	
  walkmod-core
•  Plugin descriptor:	
  
– META-­‐INF/walkmod/walkmod-­‐xxxx-­‐plugin.xml	
  
– Spring	
  configura-on	
  file	
  
•  Deployment	
  to	
  Maven	
  central	
  
SONAR	
  RULES	
  
GITHUB.COM/WALKMOD/WALKMOD-SONAR-PLUGIN
Syntactic rules
Only	
  require	
  a	
  valid	
  AST	
  
Collapsible "if" statements should be merged
[sonar:CollapsibleIfStatements] 	
  
	
   if (file != null) {
if (file.isFile() || file.isDirectory()){
/* ... */
}
}
if (file != null &&
(file.isFile() || file.isDirectory())) {
/* ... */
}
Other syntactic rules
•  String literals should not be duplicated
•  Useless parentheses around expressions should be removed
to prevent any misunderstanding
[sonar:RemoveUselessParentheses].
•  Strings literals should be placed on the left side when
checking for equality [sonar:StringCheckOnLeV]
Semantic rules
Require	
  type	
  or	
  symbol	
  resolu-on.	
  
•  Collection#isEmpty() should be used to test for emptiness 	
  
if (myCollection.size() == 0) {
/* ... */
}
if (myCollection.isEmpty()) {
/* ... */
}
How	
  to	
  resolve	
  if	
  size() is	
  a	
  java.util.Collection#size()	
  ?	
  
Example: UseCollectionIsEmpty
…
MethodCallExpr mce = (MethodCallExpr) methodExpr;
MethodSymbolData msd = mce.getSymbolData();
if (msd != null) {
if (mce.getName().equals("size")
&& ("0".equals(((IntegerLiteralExpr) numberExpr).getValue()))) {
if(Collection.class.isAssignableFrom(
msd.getMethod().getDeclaringClass())) {
Expression newExpr = new MethodCallExpr(mce.getScope(), "isEmpty");
if (n.getOperator().equals(BinaryExpr.Operator.notEquals)) {
newExpr = new UnaryExpr(newExpr, UnaryExpr.Operator.not);
}
n.getParentNode().replaceChildNode(n, newExpr);
}
}
[sonar:UseCollec-onIsEmpty]	
  
Symbol definitions and references
Field names should comply with a naming
convention	
  
class MyClass {
private int my_field;
}
class MyClass {
private int myField;
}
All	
  my_field	
  references	
  need	
  to	
  be	
  updated!	
  
this.my_field = my_field; this.myField = my_field;
 
@RequiresSemanticAnalysis
@RequiresSemanticAnalysis
public class UseCollectionIsEmpty
extends VoidVisitorAdapter<VisitorContext> {
….
}
Semantic API
•  SymbolDataAware#getSymbolData()
•  SymbolDefinition#getUsages()
•  SymbolReference#getSymbolDefinition()
•  ScopeAware
Interface	
  for	
  SymbolDefini-on,	
  SymbolReference	
  &	
  BlockStmt	
  
–  #getVariableDefinitions()
–  #getTypeDefinitions()
–  #getMethodDefinitions()
•  Refactorizable#rename()
Interface	
  for	
  VariableDeclara-on	
  &	
  Parameter.	
  
Applies	
  safe	
  updates	
  to	
  all	
  the	
  references	
  to	
  that	
  variable/parameter.	
  
[sonar:LocalVarsShouldComplyWithNamingConvention]
•  SemanticTest
	
  
Semantic rules testing
	
  
public class UseCollectionIsEmptyTest extends SemanticTest {
@Test
public void testEqualsToZero() throws Exception {
CompilationUnit cu = compile(
"import java.util.List; “+
” public class Foo { “+
”public boolean testIsEmpty(List list){“+
” return list.size() == 0; }}");
UseCollectionIsEmpty visitor = new UseCollectionIsEmpty();
cu.accept(visitor, null);
MethodDeclaration md = (MethodDeclaration) cu.getTypes()
.get(0).getMembers().get(0);
BlockStmt block = md.getBody();
ReturnStmt returnStmt = (ReturnStmt) block.getStmts().get(0);
Assert.assertTrue(returnStmt.getExpr() instanceof MethodCallExpr);
}
}
	
  
exercise 2
•  Open	
  org.walkmod.sonar.tutorial.Exercise2	
  
	
  
Try	
  to	
  implement	
  the	
  rule	
  #9	
  
Useless imports should be removed
	
  
Other semantic rules
•  Local variable and method parameter names should comply with a
naming convention
[sonar:LocalVarsShouldComplyWithNamingConvention]
•  Useless imports should be removed
[sonar:RemoveUselessImports]
•  Redundant casts should not be used
[sonar:RedundantCastsShouldNotBeUsed]
•  String literals should not be duplicated
•  Local variables should not shadow class fields
	
  
External symbol references
•  PROBLEM:	
  Other	
  files	
  could	
  contain	
  
references	
  to	
  the	
  desired	
  node	
  to	
  modify	
  
•  It	
  is	
  necessary	
  to	
  design	
  a	
  two	
  step	
  process.	
  
– First	
  step:	
  To	
  compute	
  the	
  required	
  refactorings.	
  
Produces	
  refactoring	
  configuraCon	
  
– Second	
  step:	
  To	
  apply	
  the	
  computed	
  refactorings.	
  
Executes	
  walkmod-­‐refactoring-­‐plugin	
  
External refactoring API
It	
  is	
  necessary	
  to	
  create	
  a	
  new	
  refactoring	
  chain	
  
dynamically	
  
RefactorConfigurationController
#getMethodRefactorRules
	
  
Returns	
  the	
  map	
  of	
  current	
  refactoring	
  rules	
  and	
  
creates	
  a	
  refactoring	
  chain	
  if	
  it	
  is	
  missing.	
  
	
  
{Foo:bar(java.lang.String s, int c) => Foo:bar(c)}	
  
Sonar Rules examples
•  Unused method parameters should be removed
[sonar:RemoveUnusedMethodParameters]
	
  
•  Method names should comply with a naming convention
•  Class variable fields should not have public accessibility 	
  
General working procedure
1.  Fork	
  walkmod/walkmod-sonar-plugin
2.  Git	
  checkout	
  master	
  
3.  Create	
  a	
  new	
  visitor	
  per	
  rule	
  
4.  Create	
  a	
  test	
  
5.  Define	
  it	
  in	
  the	
  walkmod-sonar-plugin.xml
6.  Create	
  pull	
  request	
  
7.  We	
  deploy	
  the	
  changes	
  under	
  a	
  new	
  version	
  
to	
  the	
  maven	
  repository	
  
Local integration tests
1.  Go	
  to	
  the	
  walkmod-­‐sonar-­‐plugin	
  directory	
  
2.  Execute	
  mvn	
  install	
  
3.  Replace	
  jars:	
  
1.  Open	
  the	
  following	
  directory:	
  
	
  ${HOME}/.ivy2/cache/org.walkmod/walkmod-­‐sonar-­‐plugin/jars	
  
2.  Replace	
  the	
  jar	
  that	
  has	
  the	
  same	
  name	
  than	
  
walkmod-­‐sonar-­‐plugin/target/walkmod-­‐sonar-­‐plugin-­‐${version}.jar	
  
4.  Run	
  walkmod	
  apply	
  -­‐-­‐offline	
  

Mais conteúdo relacionado

Mais procurados

Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricksOri Calvo
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptLivingston Samuel
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMashleypuls
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Better Code through Lint and Checkstyle
Better Code through Lint and CheckstyleBetter Code through Lint and Checkstyle
Better Code through Lint and CheckstyleMarc Prengemann
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)servicesRafael Winterhalter
 

Mais procurados (20)

Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Project Coin
Project CoinProject Coin
Project Coin
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Better Code through Lint and Checkstyle
Better Code through Lint and CheckstyleBetter Code through Lint and Checkstyle
Better Code through Lint and Checkstyle
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 

Semelhante a Sonar rules in action with walkmod

Code instrumentation
Code instrumentationCode instrumentation
Code instrumentationBryan Reinero
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introductionJaroslav Kubíček
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...Edureka!
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr DevelopersErik Hatcher
 
Profiling ruby
Profiling rubyProfiling ruby
Profiling rubynasirj
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherencearagozin
 
Solr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachSolr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachAlexandre Rafalovitch
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Lucidworks
 
Metamodeling of custom Pharo images
 Metamodeling of custom Pharo images Metamodeling of custom Pharo images
Metamodeling of custom Pharo imagesESUG
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
Hive Anatomy
Hive AnatomyHive Anatomy
Hive Anatomynzhang
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror MakerSimon Suo
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
 

Semelhante a Sonar rules in action with walkmod (20)

Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introduction
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
Curator intro
Curator introCurator intro
Curator intro
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Profiling ruby
Profiling rubyProfiling ruby
Profiling ruby
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherence
 
Solr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachSolr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approach
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
 
Metamodeling of custom Pharo images
 Metamodeling of custom Pharo images Metamodeling of custom Pharo images
Metamodeling of custom Pharo images
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Hive Anatomy
Hive AnatomyHive Anatomy
Hive Anatomy
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Java8
Java8Java8
Java8
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror Maker
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUG
 

Mais de Raquel Pau

technical debt management strategies
technical debt management strategiestechnical debt management strategies
technical debt management strategiesRaquel Pau
 
Real Impact Testing Analysis for JVM developers
Real Impact Testing Analysis for JVM developersReal Impact Testing Analysis for JVM developers
Real Impact Testing Analysis for JVM developersRaquel Pau
 
Real Impact Testing Analysis For JVM
Real Impact Testing Analysis For JVMReal Impact Testing Analysis For JVM
Real Impact Testing Analysis For JVMRaquel Pau
 
Impact Testing
Impact TestingImpact Testing
Impact TestingRaquel Pau
 
Git Workflow Strategies for Technical Debt Management
Git Workflow Strategies for Technical Debt ManagementGit Workflow Strategies for Technical Debt Management
Git Workflow Strategies for Technical Debt ManagementRaquel Pau
 
Design Patterns
Design PatternsDesign Patterns
Design PatternsRaquel Pau
 
Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategiesRaquel Pau
 

Mais de Raquel Pau (8)

technical debt management strategies
technical debt management strategiestechnical debt management strategies
technical debt management strategies
 
Real Impact Testing Analysis for JVM developers
Real Impact Testing Analysis for JVM developersReal Impact Testing Analysis for JVM developers
Real Impact Testing Analysis for JVM developers
 
Real Impact Testing Analysis For JVM
Real Impact Testing Analysis For JVMReal Impact Testing Analysis For JVM
Real Impact Testing Analysis For JVM
 
Impact Testing
Impact TestingImpact Testing
Impact Testing
 
Git Workflow Strategies for Technical Debt Management
Git Workflow Strategies for Technical Debt ManagementGit Workflow Strategies for Technical Debt Management
Git Workflow Strategies for Technical Debt Management
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Code review
Code reviewCode review
Code review
 
Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategies
 

Último

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Último (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Sonar rules in action with walkmod

  • 1. Sonar  rules  in  ac-on   with  Walkmod Raquel  Pau     rpau@walkmod.com  
  • 2. INTRODUCTION   FROM THE BOTTOM TO THE TOP
  • 3. The abstract syntax tree rpau/javalang rpau/javalang-compiler
  • 5. Exercise 1 •  Fork  &  Clone  walkmod/walkmod-sonar-plugin •  Run:  git checkout tutorial •   Open  from  src/test/java:   – org.walkmod.sonar.tutorial.Exercise1   •  Run  the  JUNIT  test  from  Eclipse   •  Create  the  HelloVisitor  in  the  same  package   that  modifies  the  class  name  “Foo”  per   “Hello”    
  • 7. How to create Plugins •  Create  a  Maven  project   – Ar-factId:  walkmod-­‐xxxx-­‐plugin   – Dependencies:  javalang-compiler  &  walkmod-core •  Plugin descriptor:   – META-­‐INF/walkmod/walkmod-­‐xxxx-­‐plugin.xml   – Spring  configura-on  file   •  Deployment  to  Maven  central  
  • 9. Syntactic rules Only  require  a  valid  AST   Collapsible "if" statements should be merged [sonar:CollapsibleIfStatements]     if (file != null) { if (file.isFile() || file.isDirectory()){ /* ... */ } } if (file != null && (file.isFile() || file.isDirectory())) { /* ... */ }
  • 10. Other syntactic rules •  String literals should not be duplicated •  Useless parentheses around expressions should be removed to prevent any misunderstanding [sonar:RemoveUselessParentheses]. •  Strings literals should be placed on the left side when checking for equality [sonar:StringCheckOnLeV]
  • 11. Semantic rules Require  type  or  symbol  resolu-on.   •  Collection#isEmpty() should be used to test for emptiness   if (myCollection.size() == 0) { /* ... */ } if (myCollection.isEmpty()) { /* ... */ } How  to  resolve  if  size() is  a  java.util.Collection#size()  ?  
  • 12. Example: UseCollectionIsEmpty … MethodCallExpr mce = (MethodCallExpr) methodExpr; MethodSymbolData msd = mce.getSymbolData(); if (msd != null) { if (mce.getName().equals("size") && ("0".equals(((IntegerLiteralExpr) numberExpr).getValue()))) { if(Collection.class.isAssignableFrom( msd.getMethod().getDeclaringClass())) { Expression newExpr = new MethodCallExpr(mce.getScope(), "isEmpty"); if (n.getOperator().equals(BinaryExpr.Operator.notEquals)) { newExpr = new UnaryExpr(newExpr, UnaryExpr.Operator.not); } n.getParentNode().replaceChildNode(n, newExpr); } } [sonar:UseCollec-onIsEmpty]  
  • 13. Symbol definitions and references Field names should comply with a naming convention   class MyClass { private int my_field; } class MyClass { private int myField; } All  my_field  references  need  to  be  updated!   this.my_field = my_field; this.myField = my_field;
  • 15. Semantic API •  SymbolDataAware#getSymbolData() •  SymbolDefinition#getUsages() •  SymbolReference#getSymbolDefinition() •  ScopeAware Interface  for  SymbolDefini-on,  SymbolReference  &  BlockStmt   –  #getVariableDefinitions() –  #getTypeDefinitions() –  #getMethodDefinitions() •  Refactorizable#rename() Interface  for  VariableDeclara-on  &  Parameter.   Applies  safe  updates  to  all  the  references  to  that  variable/parameter.   [sonar:LocalVarsShouldComplyWithNamingConvention] •  SemanticTest  
  • 16. Semantic rules testing   public class UseCollectionIsEmptyTest extends SemanticTest { @Test public void testEqualsToZero() throws Exception { CompilationUnit cu = compile( "import java.util.List; “+ ” public class Foo { “+ ”public boolean testIsEmpty(List list){“+ ” return list.size() == 0; }}"); UseCollectionIsEmpty visitor = new UseCollectionIsEmpty(); cu.accept(visitor, null); MethodDeclaration md = (MethodDeclaration) cu.getTypes() .get(0).getMembers().get(0); BlockStmt block = md.getBody(); ReturnStmt returnStmt = (ReturnStmt) block.getStmts().get(0); Assert.assertTrue(returnStmt.getExpr() instanceof MethodCallExpr); } }  
  • 17. exercise 2 •  Open  org.walkmod.sonar.tutorial.Exercise2     Try  to  implement  the  rule  #9   Useless imports should be removed  
  • 18. Other semantic rules •  Local variable and method parameter names should comply with a naming convention [sonar:LocalVarsShouldComplyWithNamingConvention] •  Useless imports should be removed [sonar:RemoveUselessImports] •  Redundant casts should not be used [sonar:RedundantCastsShouldNotBeUsed] •  String literals should not be duplicated •  Local variables should not shadow class fields  
  • 19. External symbol references •  PROBLEM:  Other  files  could  contain   references  to  the  desired  node  to  modify   •  It  is  necessary  to  design  a  two  step  process.   – First  step:  To  compute  the  required  refactorings.   Produces  refactoring  configuraCon   – Second  step:  To  apply  the  computed  refactorings.   Executes  walkmod-­‐refactoring-­‐plugin  
  • 20. External refactoring API It  is  necessary  to  create  a  new  refactoring  chain   dynamically   RefactorConfigurationController #getMethodRefactorRules   Returns  the  map  of  current  refactoring  rules  and   creates  a  refactoring  chain  if  it  is  missing.     {Foo:bar(java.lang.String s, int c) => Foo:bar(c)}  
  • 21. Sonar Rules examples •  Unused method parameters should be removed [sonar:RemoveUnusedMethodParameters]   •  Method names should comply with a naming convention •  Class variable fields should not have public accessibility  
  • 22. General working procedure 1.  Fork  walkmod/walkmod-sonar-plugin 2.  Git  checkout  master   3.  Create  a  new  visitor  per  rule   4.  Create  a  test   5.  Define  it  in  the  walkmod-sonar-plugin.xml 6.  Create  pull  request   7.  We  deploy  the  changes  under  a  new  version   to  the  maven  repository  
  • 23. Local integration tests 1.  Go  to  the  walkmod-­‐sonar-­‐plugin  directory   2.  Execute  mvn  install   3.  Replace  jars:   1.  Open  the  following  directory:    ${HOME}/.ivy2/cache/org.walkmod/walkmod-­‐sonar-­‐plugin/jars   2.  Replace  the  jar  that  has  the  same  name  than   walkmod-­‐sonar-­‐plugin/target/walkmod-­‐sonar-­‐plugin-­‐${version}.jar   4.  Run  walkmod  apply  -­‐-­‐offline