The document summarizes Michael Pellaton's presentation on annotation processors and Spring configuration classes. It discusses using annotation processors to validate Spring @Configuration classes, and unit testing annotation processors by programmatically compiling sample classes and checking the compiler output. The presentation covers Spring @Configuration classes, the JSR-269 annotation processing API, implementing a validating annotation processor, and unit testing it using the Java compiler API.
Spring 3.1 introduces several eagerly awaited features including bean definition profiles (a.k.a., environment-specific beans), enhanced Java-based application and infrastructure configuration (a la XML namespaces), a new cache abstraction, and MVC improvements. This session will provide attendees an in-depth look at these major new features as well as an overview of additional enhancements to the framework such as the new c: namespace for constructor arguments, updates regarding Servlet 3.0, and improvements to Spring's integration testing support.
This session will give attendees an overview of the new testing features in Spring 3.1 as well the new Spring MVC test support. Sam Brannen will demonstrate how to use the Spring TestContext Framework to write integration tests for Java-based Spring configuration using @Configuration classes. He'll then compare and contrast this approach with XML-based configuration and follow up with a discussion of the new testing support for bean definition profiles. Next, Rossen Stoyanchev will show attendees how testing server-side code with annotated controllers and client-side code with the RestTemplate just got a whole lot easier with the new Spring MVC test support. Come to this session to see these new Spring testing features in action and learn how you can get involved in the Spring MVC Test Support project.
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
Java Annotation is quite a handy tool and has the ample potential to make developer's life a lot easier(and exciting!). Learning and using custom Java Annotation Processor takes the power of Annotation even a class higher. This slide goes over a few fundamental things of an Annotation Processor to get someone started to write his/her own Annotation Processor in Java.
Key topics are,
- Java Annotation
- Usage of Annotation
- Custom Java Annotation
- Java Annotation Processor
- Usefulness of Annotation Processor
- Dive into the core of Annotation Processor
- Solve a validation problem with Custom Annotation Processor
- Get to know some exciting Annotation Processing tools that already exist
this ppt tells you about what is spring in java. how to use spring? and what are the main methods of spring class? For more info and free java projects visit : http://s4al.com/category/study-java/
This ppt tells about spring class in java. what spring class have, all the methods in brief. for more info please visit : http://s4al.com/category/study-java/
Spring 3.1 introduces several eagerly awaited features including bean definition profiles (a.k.a., environment-specific beans), enhanced Java-based application and infrastructure configuration (a la XML namespaces), a new cache abstraction, and MVC improvements. This session will provide attendees an in-depth look at these major new features as well as an overview of additional enhancements to the framework such as the new c: namespace for constructor arguments, updates regarding Servlet 3.0, and improvements to Spring's integration testing support.
This session will give attendees an overview of the new testing features in Spring 3.1 as well the new Spring MVC test support. Sam Brannen will demonstrate how to use the Spring TestContext Framework to write integration tests for Java-based Spring configuration using @Configuration classes. He'll then compare and contrast this approach with XML-based configuration and follow up with a discussion of the new testing support for bean definition profiles. Next, Rossen Stoyanchev will show attendees how testing server-side code with annotated controllers and client-side code with the RestTemplate just got a whole lot easier with the new Spring MVC test support. Come to this session to see these new Spring testing features in action and learn how you can get involved in the Spring MVC Test Support project.
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
Java Annotation is quite a handy tool and has the ample potential to make developer's life a lot easier(and exciting!). Learning and using custom Java Annotation Processor takes the power of Annotation even a class higher. This slide goes over a few fundamental things of an Annotation Processor to get someone started to write his/her own Annotation Processor in Java.
Key topics are,
- Java Annotation
- Usage of Annotation
- Custom Java Annotation
- Java Annotation Processor
- Usefulness of Annotation Processor
- Dive into the core of Annotation Processor
- Solve a validation problem with Custom Annotation Processor
- Get to know some exciting Annotation Processing tools that already exist
this ppt tells you about what is spring in java. how to use spring? and what are the main methods of spring class? For more info and free java projects visit : http://s4al.com/category/study-java/
This ppt tells about spring class in java. what spring class have, all the methods in brief. for more info please visit : http://s4al.com/category/study-java/
탑크리에듀교육센터(http://www.topcredu.co.kr)에서 제공하는
스프링프레임워크 & 마이바티스(Spring Framework, MyBatis)교육강좌입니다. Spring DI(Dependency Injection),세터 주입(Setter Injection) – XML 기반, 어노테이션기반 등에 대하여 설명한 교육자료이니 참고 바랍니다^^.
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)DevelopIntelligence
Kelby Zorgdrager from DevelopIntelligence explains the differences between the variations of Java and what's new in Java 7.
If you need help with Java training DevelopIntelligence and provide on-site training within two weeks. Customized and affordable for any organization.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
탑크리에듀교육센터(http://www.topcredu.co.kr)에서 제공하는
스프링프레임워크 & 마이바티스(Spring Framework, MyBatis)교육강좌입니다. Spring DI(Dependency Injection),세터 주입(Setter Injection) – XML 기반, 어노테이션기반 등에 대하여 설명한 교육자료이니 참고 바랍니다^^.
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)DevelopIntelligence
Kelby Zorgdrager from DevelopIntelligence explains the differences between the variations of Java and what's new in Java 7.
If you need help with Java training DevelopIntelligence and provide on-site training within two weeks. Customized and affordable for any organization.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
This lecture describes how we set up the environment for executing Java Application and also describes the tools that are required. This lecture also contains a simple java program and the description.
CLASSINDEX - SZYBKA ALTERNATYWA DLA SKANOWANIA KLAS
W Javie częstym problemem jest potrzeba znalezienia klas oznaczonych daną adnotacją. Choć oficjalnie Java nie wspiera takiej funkcjonalności, de facto standardowym rozwiązaniem tego problemu jest skanowanie klas. W tej prezentacji chciałbym przedstawić dużo szybszą alternatywę - autorski projekt oparty na mechanizmach procesowania adnotacji.
Gradle is a flexible general purpose build system with a build-by-convention framework a la Maven on top. It uses Apache Ivy under the hood for its dependency management. Its build scripts are written in Groovy.
Java : Components
Java : Features
Java : Security
Java better than C++
Basic Data Types
Applications : Types
Life Cycle of Java Code
Java Development Kit
Java Example
Mechanism of Applets
Significance of downloading Applets
Used Java Main Packages
Checklist AR is an application which improves the maintenance processes by augmenting the physical world with digital content. This application guides the workers through a list of real-world checkpoints, providing relevant information at the right physical place. During this session, you will be able to learn more about the solution, the technologies that we used, the challenges we had to overcome and some best practices when developing AR applications for Magic Leap. Additionally, you will be able to experience the Magic Leap One device and learn more about its possibilities.
Aleksandra Hristova's presentation at JavaSkop 2019.
Topics touched:
- Using pattern libraries to improve the communication between designers and developers and the importance of including the whole team and the client into the planning phase.
- How to plan and build components that can be used in different contexts and within other components with examples from real projects.
- How we have used UX design principles to ease our front-end implementations with code examples using the latest CSS features and Angular.
At the UXCamp.ch barcamp on May 11, 2019 in Zurich, Marcel Kessler talked about what he thinks is the future of prototyping: Using coded react components in tools like UXPin (Merge), FramerX (Bridge), Alva and Modulz.
Merchant tokenization and EMV® Secure Remote CommerceNetcetera
Talk by our expert Kurt Schmid about merchant tokenization and EMV® Secure Remote Commerce, held at MPE on 19 February 2019. Merchant Payments Ecosystems is a leading payment conference for merchants and PSPs.
Talk by our expert Suzana Kordumova Nikolova about a seamless 3-D Secure e-commerce experience, held at MPE on 19 February 2019. Merchant Payments Ecosystems is a leading payment conference for merchants and PSPs.
Inselspital is one of the first augmented reality products that we have developed in Netcetera. It allows the doctors to visualize scan results in 3D and to plan neurosurgeries using state of the art technology. During this session, you will be able to learn more about the solution, the technologies that we used, the challenges we had to overcome and some best practices when developing AR applications for HoloLens. Additionally, you will be able to experience the HoloLens device and learn more about its possibilities.
Driving transactional growth with 3-D SecureNetcetera
3-D Secure SDK allows PSD2 compliant strong customer authentication to increase transactions for merchants, banks and issuers.
Presentation by Peter Frick, Managing Director Payment Security at Netcetera at the Swiss Payment Forum, November 2018.
Presentation by Kurt Schmid, Managing Director Digital Payment at Netcetera, at the Swiss Payment Forum, November 2018.
- Where we are coming from?
- Wallets, OEM Pays versus Issuer Pays?
- Proximity and eCommerce payment trends
- The business case and strategic value for issuers?
Schafft die Kreditkartenindustrie mit SRC doch
noch die Wallet-Kurve?
Präsentation von Dr. Thomas Fromherz, Chief Strategy Officer, Payments bei Netcetera, am Swiss Payment Forum in Zürich, November 2018.
Context: The missing ingredient in multilingual software translationNetcetera
Take a look at how automated end-to-end tests can be involved to support and speed up the software translation process. Mirjana’s quest at Selenium Conf 2018 in Chicago is to show you with examples how to feel the content and, in the same time, also feel the context of that content.
An important phase in multilingual software systems is text translation. Since same text may be used in different contexts, it is difficult to determine whether the translation is proper in the context of the environment in which the text is used. Sharing only text keys and values with translators usually is not enough. Simple screenshots showing only the text content, also didn't help in situations where text keys were re-used on multiple places, or when there are highly generic templates. This presentation contains an efficient automated way of delivering the necessary artifacts to translation experts. These artefacts contain text keys, text values and also the context where they are used.
https://www.seleniumconf.us/talks#mirjana-andovska
Digital Payments - Netcetera Innovation Summit 2018Netcetera
Kurt Schmid, our Managing Director Digital Payment, asked: “Merchant Tokenization and SRC – the next BUZZ words – how do these change eCommerce Payments?”.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
2. AGENDA
> Spring @Configuration classes
> An Annotation Processor for Validation
> Unit Testing the Annotation Processor
2
3. Code Examples
The code in this presentation is simplified and doesn’t compile.
Full length, compiling version of the code:
http://github.com/pellaton/jazoon2012-talk
3
4. Spring @Configuration Classes
> Java-based Spring application context configuration
> An alternative to XML or annotation based configurations
> Example:
@Configuration
public class ExampleConfiguration {
@Bean
public Example exampleBean() {
return new ExampleImpl();
}
}
4
5. Let’s Read the Javadoc…
Must not Must have a visible
be final no-arg constructor
@Configuration
Must not
public class ExampleConfiguration {
be Private
...
@Bean
public Example exampleBean() {
return new ExampleImpl();
Must not }
be final } ...
Must not should be static if returning
return void a BeanFactoryPostProcessor
5
6. What If There’s Something Wrong?
Exception in thread "main"
org...BeanDefinitionParsingException:
Configuration problem: @Configuration class
'ExampleConfiguration' may not be final.
Remove the final modifier to continue.
6
8. Annotation Processors
> Annotations can be processed at
– Runtime reflection (methods on Class, Method & Co)
– Compile time annotation processor
> JSR-269 “Pluggable Annotation Processing API”
– Introduced with Java 6
– Replaces “Annotation Processing Tool APT” of Java 5
8
9. JSR-269 Annotation Processors
> A Java compiler plugin
> An implementation of Processor
> Interacts through ProcessingEnvironment injected in init()
– Messenger to emit compiler messages
– Filer to create classes and resources
> Works with the Mirror (Model) API
– Element represents a static Java language-level construct
(class, package, method, …)
– TypeMirror represents a Java type
> process() is called in rounds to process an annotation on a type
– Access to current compilation/processing state through
RoundEnvironment
– May claim an annotation: subsequent processors are not called
9
10. The Validating Annotation Processor
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@SupportedAnnotationTypes(value = "org...Configuration")
public class JazoonProcessor extends AbstractProcessor {
private Elements elementUtils;
private Messager messager;
private TypeElement configurationTypeElement;
public synchronized void init(ProcessingEnvironment env) {
elementUtils = env.getElementUtils();
messager = env.getMessager();
configurationTypeElement = elementUtils.getTypeElement(
"org.springframework...Configuration");
}
10
11. The Validating Annotation Processor
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
if (!roundEnv.errorRaised() && !roundEnv.processingOver()) {
for (TypeElement ann : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(ann)) {
if (element instanceof TypeElement) {
processElement((TypeElement) element);
}
}
}
}
// don’t consume the annotation type
return false;
} 11
12. The Validating Annotation Processor
private void processElement(TypeElement typeElement) {
for (AnnotationMirror ann : typeElement.getAnnotationMirrors()) {
Element annTypeElement = ann.getAnnotationType().asElement();
if (annTypeElement.equals(configurationTypeElement)) {
if (typeElement.getModifiers().contains(Modifier.FINAL)) {
messager.printMessage(Kind.ERROR,
"@Configuration classes must not be final.",
typeElement);
}
}
}
}
12
14. The Result
$ mvn clean compile
...
[ERROR] Failed to execute goal ...: compile
Compilation failure:
[ERROR] /.../ExampleConfiguration.java:[7,13]
error: @Configuration classes must not be final.
[ERROR] /.../ExampleConfiguration.java:[10,16]
error: @Bean methods must not be private.
14
16. The Java Programming Language Compiler API
> Idea: A unit test that compiles (faulty) classes and checks
the compiler output produced by the annotation processor
> JSR-199 The Java Programming Language Compiler API
(Java 6)
> Programmatic interface to the Java compiler
> Requires a JDK
16
17. The Java Compiler API : Main Components
> The JavaCompiler is the
– interface to the Java compiler
– Factory for CompilationTasks
– Instance is obtained through ToolProvider
> The CompilationTask is a future of a compilation task
> Source and class files are read and written using the
JavaFileManager
> A message emitted during compilation is called a
Diagnostic
> Diagnostics are stored by the DiagnosticCollector
17
18. The Java Compiler API : Main Components
ToolProvider
creates
JavaCompiler
creates
CompilationTask
reads/writes
emits listens
java/class files
holds
JavaFileManager Diagnostic DiagnosticCollector
18
19. Compiling Classes in Unit Tests for Processors
/** Tests the detection of final @Configuration classes. */
@Test
public void finalConfigurationClass() throws IOException {
List<Diagnostic> diagnostics =
AnnotationProcessorTestCompiler.compileClass(
"/com/github/pellaton/jazoon2012/FinalTestConfiguration.java",
new JazoonProcessor());
DiagnosticsAssert.assertContainsSingleMessage(Kind.ERROR, 16,
diagnostics);
}
19
20. Compiling Classes in Unit Tests for Processors
public static List<Diagnostic> compileClass(String clazzName,
Processor processor) {
DiagnosticCollector<> collector = new DiagnosticCollector<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Locale locale = Locale.getDefault();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager(collector, locale, null);
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(classToCompile);
// the infrastructure is now ready 20
21. Compiling Classes in Unit Tests for Processors
// compile the class and return the result
CompilationTask task = compiler.getTask(null, fileManager,
collector, "-proc:only", null, compilationUnits);
task.setProcessors(processor);
task.call();
return collector.getDiagnostics();
}
21
23. Conclusion
> Annotation processors can be used to extend the tooling and build beyond the
traditional purposes like code generation
> To unit test an annotation processor, employ the Java compiler API
> @Configuration and other annotation-based frameworks:
try hard to find problems as early as possible
23
24. Michael Pellaton www.netcetera.com
Netcetera michael.pellaton@netcetera.ch
Examples & Links: github.com/pellaton/jazoon2012-talk