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

Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 

Último (20)

Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 

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