Java Tools for Developers
Total Page:16
File Type:pdf, Size:1020Kb
JAVA TOOLS FOR DEVELOPERS 2ND EDITION by Cheng-Hung Chou To My Wife 7 years 2557 days 61,368 hours 3,682,080 minutes 2 Cute Daughters TABLE OF CONTENTS Preface Apache Commons Commons Lang StringUtils ArrayUtils ExceptionUtils WordUtils Commons IO IOUtils FileUtils FilenameUtils Commons CSV CSVParser Commons Codec DigestUtils Commons Net FTPClient Commons Compress Zip Commons CLI Commons FileUpload iText Creating a PDF document Basic text elements Paragraph Phrase Chunk Fonts Creating a table PdfPTable PdfPCell Encryption Adding watermarks Creating multiple columns Merging documents Filling forms Servlet Apache POI Creating an Excel document Adding formulas Formula evaluation Plotting a chart Creating a Word document JFreeChart Creating a simple chart Creating a bar chart Creating a scatter plot Creating a combined chart Making a chart clickable Displaying a chart in a web page EasyMock, JUnit, and PowerMock An introduction to JUnit Annotations Assertions Test Runners A sample JUnit test case An introduction to EasyMock Verifying behavior Expectations EasyMockSupport Class mocking Partial mocking Using EasyMock with JUnit Using Annotations Using expectations PowerMock Test coverage analysis JMeter Building a JMeter test plan Starting JMeter Adding test elements Running a test plan Saving a test plan Debugging a test plan Remote testing Test elements Samplers Logic controllers Listeners Configuration elements Assertions Timers Pre-processors Post-processors Testing a web application Testing with authentication Using regular expressions Using HTTP proxy server Testing web applications using GWT Adding Java classes JUnit Request Java Request JAVACC Structure of a grammar file Options Class declaration Token manager declarations Lexical specifications Production rules A simple calculator EBNF grammars JavaCC grammars Generating code A formula calculator A text processor Apache Solr Getting started Basic directory structure Solr home directory Solr core directory Creating a new core SolrCloud Document schema Document fields Field types Field analysis Updating data XML messages add commit delete CSV Querying data Request handler Query parameters Fields Boolean operators Grouping searches Wildcard searches Regular expression searches Proximity searches Range searches Boosting terms Special characters Sorting Hit highlighting Faceted search Field faceting Query faceting Range faceting Pivot Faceting Result Grouping Indexing rich documents Accessing Solr programmatically Updating data Querying data Query Field faceting Result grouping Apache James Installing James Server Configuring James Server config.xml environment.xml james-fetchmail.xml A quick test Mailets and matchers Creating a custom matcher GenericMatcher GenericRecipientMatcher Creating a custom mailet Reading an object store file Jackson POJO model JSON Properties Property naming and inclusion Property exclusion Ordering Map Enum Formatting Polymorphic types Filtering Views Filters Custom Serializers and Deserializers Custom Serializers Custom Deserializers Configurations Hibernate Validator Applying Constraints Field-level constraints Error messages Property-level constraints Validating Parameters Inheritance Grouping Constraints Programmatic constraints Creating a Custom Constraint Creating a constraint annotation Creating an validator Preface When working on a project, sometimes you face the following questions during the design phase: Should we include this task in this phase? It seems risky. Should we adopt this technology and do code refactoring on existing programs? Should we use this framework instead of writing our own? Incorporating right development tools into your products can increase productivity of developers and expand functionality on products. You do not need to reinvent everything from scratch. You are not an expert on everything. Leave the job to the expert. But, searching and evaluating right tools can be time consuming. Especially those not well- written or maintained can put your products at risk. Finding well-proven 3rd party tools is the key since they have been using in many products and still improving regularly. A good development tool even can be part of coding practice for developers. To learn a new technology or tool, the most difficult part is to find where to start with. Sometimes, it is not even well-documented. Or, you do not want to spend time to read the whole book. This book is not trying to teach you how to write Java programs. It assumes you already have basic idea about Java programming language. The main purpose of this book is to broaden your knowledge as a professional Java developer and save you time in finding and learning useful development tools. Topics in this book cover a variety of development tools in Java. They include APIs, testing tools and servers. In the second edition, it includes the following updates: Adding to the chapter of Apache Commons: Commons CSV and Commons Codec Adding PowerMock to the chapter of EasyMock, JUnit, and PowerMock Rewriting the chapter of Apache Solr to cover Solr 5 Adding two new chapters: Jackson, Hibernate Validator The following are quick summaries of topics in this book: Apache Commons The purpose of Apache Commons is to focus on all aspects of reusable Java components. Component interfaces will keep as stable as possible and try to be independent from other components. There are over 40 active components in the Apache Commons so far. Some implementations in the Apache Commons even are included in the core Java API. iText Usually, PDF documents are created or updated manually through some kind of end-user applications such as Adobe Acrobat. But, that is only suitable for static documents. If you need to generate PDF documents dynamically based on requests or to generate personalized contents, you need to use different approaches. iText is an API that helps developers to generate or update PDF documents on the fly programmatically without manual process. Apache POI Apache POI is the Java API for Microsoft Documents, which allows you to read and write MS Office documents such as Excel, Word and PowerPoint using Java. Through POI, you can generate MS Office documents dynamically based on requests or to generate personalized reports on the fly. POI supports OLE2 files such as XLS, DOC and PPT and new XML based standard Office OpenXML files such as XLSX, DOCX and PPTX. JFreeChart JFreeChart is a chart library that helps you to create a variety of chart types such as pie charts, bar charts, line charts or scatter plots in your Swing applications. Many output types such as images (JPEG or PNG) are supported. JFreeChart is not just limited to desktop applications. It can be used on the server side such as servlets or JSPs too. EasyMock, JUnit, and PowerMock Unit tests are written by programmers to test classes or methods internally in programmer’s perspective. Each test should be independent from each other and should be tested without any dependencies. How do we do unit testing in isolation without any dependencies? Mock objects are objects that mimic the real objects in controlled ways for different scenarios. They can help to decide if a test is either failed or passed. EasyMock is a framework that can save you time in hand wiring mock objects and can create mock objects at runtime. JUnit is a unit testing framework. JUnit and EasyMock can work together easily. PowerMock is a mock framework that extends other mock frameworks. PowerMock extends EasyMock with features such as mocking on private, static, or final methods. Currently, it supports EasyMock and Mockito. Apache JMeter Apache JMeter is a Java-based desktop application, which can be used for load testing to measure the performance of a system or used for stress testing to see if a system is crashed gracefully. JMeter provides a variety of test elements. They are quite handy and can save you time in writing your own Java programs for testing. Using JMeter is quite intuitive because it provides a nice GUI to create and run tests. You also can run JMeter tests in non-GUI mode. Tests can be run either locally or remotely. JavaCC JavaCC is an open source lexical analyzer generator and a parser generator for use with the Java applications, which takes a grammar specification (e.g., EBNF) and generates the Java source code of a lexical analyzer and a parser. A lexical analyzer breaks a sequence of characters into tokens and identifies the type of each token. A parser takes a sequence of tokens from a lexical analyzer and then analyzes them to determine the structure and generates output depending on your need. Apache Solr Apache Solr is an open source search platform based on Apache Lucene running as a standalone server. Solr provides features like full-text indexing, hit highlighting, faceted search, rich documents (e.g., PDF, MS Word) indexing and database integration. Solr provides REST-like APIs which can be called over HTTP to make it easy to use. Solr allows customization through configuration and plugin architecture. Apache James Apache James Server is a Java-based mail server, which supports SMTP and POP3 protocols. Also, it can serve as an NNTP news server. Something special about James Server is that it provides a mailet container. Just like servlets are used to process HTTP requests for a servlet container. Mailets are used to process emails for a mailet container. Through configurations, you can use mailets to do complex email processing tasks. That is what makes James Server flexible and powerful. There are standard mailets provided by James Sever. Also, you can build your own mailets by using the Mailet API. Jackson JSON (JavaScript Object Notation) is based on the object notation from the JavaScript programming language. Just like XML, JSON is a format that is used for data storage and data exchange. But, the advantage of JSON is that you can use it in the JavaScript programs easily because a JSON string can be converted to a JavaScript object. A common use case is to use JSON data between back end and front end in web-based applications. Modern browsers have native support on JSON. In Java, you can use Jackson API to convert Java objects to and from JSON.