User:Vald/JavaNotes

<!-- Java notes: 1. Creating a memory leak with Java http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java 2. Classloader http://stackoverflow.com/questions/23815485/java-classloader-default-classloader 3. Writing to a existing xls file using POI http://stackoverflow.com/questions/9359913/writing-to-a-existing-xls-file-using-poi The first method will create an xls file using apache POI and will put the headers for the columns. All the other methods has to write a record into this file. 4. Referencing sheets in Apache POI Formulas http://stackoverflow.com/questions/3083420/referencing-sheets-in-apache-poi-formulas I am using apache POI 3.6 to generate excel (2003) sheets. I want to insert a formula to a cell which calculates a sum of a certain cells on several sheets. I have sheets named a, b and c and want to calculate the sum the cells A1 Does anyone have an idea how to use formulas using multiple sheets in POI. 5. Java apache poi setting the cell formula http://stackoverflow.com/questions/2518981/java-apache-poi-setting-the-cell-formula You can work around this problem by using dynamic evaluation ot the reference, via the INDIRECT function. The INDIRECT function evaluates the value of a cell, where the cell to evaluate is fetched from the value of another cell. See http://www.cpearson.com/excel/indirect.htm 6. Apache POI Color cell with formula http://stackoverflow.com/questions/828721/apache-poi-color-cell-with-formula Q. I want create a excel with Apache POI in java and I must insert in a cell a formula: A3=B3+C3. Is possible to insert another formula in A3 that color the cell if his value is> 0? A. You will need a conditional formatting. 7. How to set formulas in cells using Apache POI? http://stackoverflow.com/questions/2339238/how-to-set-formulas-in-cells-using-apache-poi Q. I am currently using Apache POI for Java to set formulas in cells. But after I run the program and open the Excel file that I created and processed, the cells with the formula include the formula as a string, rather than the value the formula should have returned. A. The HSSFCell object has methods .setCellType and .setCellFormula which you need to call like this: cell.setCellType(Cell.CELL_TYPE_FORMULA); cell.setCellFormula("SUM(C70:C76)"); 8. Apache poi Excel: Creating a formula based on the integer index of the column http://stackoverflow.com/questions/23013023/apache-poi-excel-creating-a-formula-based-on-the-integer-index-of-the-column Say that my column number is 26, when I create a formula my formula should look like, say: SUM(AA1:AA3) for example. but how do I translate 26 to AA? Or say 27 to AB? Is there a way for Apache POI to use Column index as an integer and translate it into its letter representation? 9. Apache POI evaluate formula http://stackoverflow.com/questions/5716664/apache-poi-evaluate-formula Q. I have some formulas in cells of my sheet, and I want to evaluate them after I insert some values. A. FormulaEvaluator evaluator = wb.getCreationHelper.createFormulaEvaluator; evaluator.evaluateFormulaCell(cell); 10. I'm getting the formula instead of the cell content 	http://stackoverflow.com/questions/19225662/im-getting-the-formula-instead-of-the-cell-content Q. String fname = "C:/Users/slim/Desktop/xlsxFiles/plan.xlsx"; InputStream inp = new FileInputStream(fname); Workbook wb = new XSSFWorkbook(inp); Sheet sheet = wb.getSheetAt(0);

for (Row row : sheet) { System.out.println(row.getCell(0)); System.out.println(row.getCell(11)); } A1. getCell(11).getNumericCellValue Note that this method throws exceptions when being used on cells with text. A2. for (Row row : sheet) { System.out.println(row.getCell(0).getRichStringCellValue.getString); System.out.println(row.getCell(11).getRichStringCellValue.getString); } http://poi.apache.org/spreadsheet/formula.html In org.apache.poi.hssf.usermodel.HSSFCell setCellFormula("formulaString") is used to add a formula to sheet and getCellFormula is used to retrieve the string representation of a formula. We aim to support the complete excel grammar for formulas. Thus, the string that you pass in to the setCellFormula call should be what you expect to type into excel. Also, note that you should NOT add a "=" to the front of the string. Also, see http://www.openoffice.org/sc/excelfileformat.pdf and http://poi.apache.org/apidocs/ Also, see http://poi.apache.org/spreadsheet/eval.html 11. Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor http://stackoverflow.com/questions/9354791/java-error-default-error-cannot-handle-exception-type-filenotfound-exception 12. http://poi.apache.org/spreadsheet/eval-devguide.html Briefly, a formula string (along with the sheet and workbook that form the context in which the formula is evaluated) is first parsed into RPN tokens using the FormulaParser class. (If you dont know what RPN tokens are, now is a good time to read this. http://www-stone.ch.cam.ac.uk/documentation/rrf/rpn.html) 13. http://poi.apache.org/spreadsheet/quick-guide.html Apache POI evaluate formula http://stackoverflow.com/questions/5716664/apache-poi-evaluate-formula HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook); How to read cell value from formula cell using apache poi http://stackoverflow.com/questions/17510112/how-to-read-cell-value-from-formula-cell-using-apache-poi Q. I am trying to read all the data from a excel file, which also have some formula cell, but i have no idea that which cell is formula cell. how can i read all the values from the cells irrespective of the type of the cell. A. Use Cell.getCachedFormulaResultType; see also the Iterating vs Fetching docs http://poi.apache.org/spreadsheet/quick-guide.html#Iterator 14. How to get row count in an Excel file using POI library? http://stackoverflow.com/questions/16234486/how-to-get-row-count-in-an-excel-file-using-poi-library Try Sheet.getPhysicalNumberOfRows 15. POI says Cell is empty but cell has a value http://stackoverflow.com/questions/12892654/poi-says-cell-is-empty-but-cell-has-a-value Q. POI says Cell is empty but cell has a value. The Value is a Date. A. Make sure you set the same Date format for all cells in column (select column and set format explicity) And i belive using DataUtil class to get data is more appropriate, than call cell.getDateCellValue. 16. Reading date values from excel cell using POI HSSF API http://stackoverflow.com/questions/861877/reading-date-values-from-excel-cell-using-poi-hssf-api You could take a look at: HSSFDateUtil.isCellDateFormatted at http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html 17. Apache POI Excel - how to configure columns to be expanded? http://stackoverflow.com/questions/4611018/apache-poi-excel-how-to-configure-columns-to-be-expanded Q. I am using Apache POI API to generate excel spreadsheet to output some data. The problem I am facing is when the spreadsheet is created and opened, columns are not expanded so that some long text like Date formatted text is not showing up on first glance. A. After you have added all your data to the sheet, you can call autoSizeColumn(columnNumber) on your sheet to autofit the columns to the proper size 18. Problem in fitting the excel cell size to the size of the content when using apache poi http://stackoverflow.com/questions/4015623/problem-in-fitting-the-excel-cell-size-to-the-size-of-the-content-when-using-apac Q. I am trying to create excel sheet using arraylist. When the excel sheet is generated, the column does not fit to the size of the content correctly. A. You just need to move the call to sheet.autoSizeColumn(5); to a point in your code after the data has been added, so right after your while loop should work. 19. How to speed up autosizing columns in apache POI? http://stackoverflow.com/questions/18983203/how-to-speed-up-autosizing-columns-in-apache-poi 20. how to set comments for 3 cells using apache poi http://stackoverflow.com/questions/3855779/how-to-set-comments-for-3-cells-using-apache-poi Q. while run the program, comments set only for last cell.but i printed the comments for the first two cells it was printed fine.but not shown in the excel sheet. A. Your problem is this line appears 3 times, once before each comment. patr = sheet.createDrawingPatriarch; From the docs for this method, Creates the top-level drawing patriarch. This will have the effect of removing any existing drawings on this sheet. So whats happening is that your earlier comments are getting removed each time you create the DrawingPatriarch. So do this only once, before comment1. The other 2 times, remove or comment out this line. 21. How to get more than 255 columns in an excel sheet using Apache POI 3.6 http://stackoverflow.com/questions/2326668/how-to-get-more-than-255-columns-in-an-excel-sheet-using-apache-poi-3-6 A. Pre-2007 excel sheets had a limitation of 256 columns. Those sheets also generate ".xls" extension. Excel 2007 and onwards can accommodate 16K columns, are based on an XML format and generate ".xlsx" format. The POI object model for pre-2007 sheets is org.apache.poi.hssf.usermodel while the object model for 2007 onwards sheets is org.apache.poi.xssf.usermodel The package org.apache.poi.ss.usermodel provides a uniform interface covering both the object models. So to create more than 256 columns, you will have to use classes within the org.apache.poi.xssf.usermodel package or within org.apache.poi.ss.usermodel. 22. Calculating the value of a recursion formula in EXCEL using POI http://stackoverflow.com/questions/12944161/calculating-the-value-of-a-recursion-formula-in-excel-using-poi 23. http://poi.apache.org/spreadsheet/index.html HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. For people converting from pure HSSF usermodel, who wish to use the joint SS Usermodel for HSSF and XSSF support, then see the ss usermodel converting guide. http://poi.apache.org/spreadsheet/converting.html

24. http://poi.apache.org/spreadsheet/how-to.html#sxssf SXSSF is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document. Older rows that are no longer in the window become inaccessible, as they are written to the disk. In auto-flush mode the size of the access window can be specified, to hold a certain number of rows in memory. When that value is reached, the creation of an additional row causes the row with the lowest index to to be removed from the access window and written to disk. Or, the window size can be set to grow dynamically; it can be trimmed periodically by an explicit call to flushRows(int keepRows) as needed. Due to the streaming nature of the implementation, there are the following limitations when compared to XSSF: •Only a limited number of rows are accessible at a point in time. •Sheet.clone is not supported. •Formula evaluation is not supported

See more details at SXSSF How-To

25. http://poi.apache.org/spreadsheet/quick-guide.html and http://poi.apache.org/spreadsheet/how-to.html Busy Developers' Guide to HSSF and XSSF Features

Creating Two-Dimensional Array http://stackoverflow.com/questions/12231453/creating-two-dimensional-array Variable must provide either dimension expressions or an array initializer--ErroR http://stackoverflow.com/questions/9162344/variable-must-provide-either-dimension-expressions-or-an-array-initializer-error 'Must Override a Superclass Method' Errors after importing a project into Eclipse http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips What issues should be considered when overriding equals and hashCode in Java? http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java The theory (for the language lawyers and the mathematically inclined):

equals (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode (javadoc) must also be consistent (if the object is not modified in terms of equals, it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode must be same as b.hashCode.

In practice:

If you override one, then you should override the other. Use the same set of fields that you use to compute equals to compute hashCode.

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library.

Effective Java: Programming Language Guide - This book consists of fifty-seven items, each of which conveys one rule. http://java.sun.com/docs/books/effective effective-java-programming-language-guide.pdf Unlike The Java Language Specification, this book uses inheritance as a synonym for subclassing. Instead of using the term inheritance for interfaces, this book simply states that a class implements an interface or that one interface extends another. To describe the access level that applies when none is specified, this book uses the descriptive term package-private instead of the technically correct term default access. Item 1: Consider providing static factory methods instead of constructors. One advantage of static factory methods is that, unlike constructors, they have names. A class can have only a single constructor with a given signature. Programmers have been known to get around this restriction by providing two constructors whose parameter lists differ only in the order of their parameter types. This is a bad idea. Because static factory methods have names, they do not share with constructors the restriction that a class can have only one with a given signature. In cases where a class seems to require multiple constructors with the same signature, you should consider replacing one or more constructors with static factory methods whose carefully chosen names highlight their differences. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they're invoked. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. This gives you great flexibility in choosing the class of the returned object. One application of this flexibility is that an API can return objects without making their classes public. Two names for static factory methods are becoming common: • valueOf— Returns an instance that has, loosely speaking, the same value as its parameters. Static factory methods with this name are effectively type-conversion operators. • getInstance— Returns an instance that is described by its parameters but cannot be said to have the same value. In the case of singletons, it returns the sole instance. This name is common in provider frameworks. Item 2: Enforce the singleton property with a private constructor. A singleton is simply a class that is instantiated exactly once.

There are two approaches to implementing singletons. Both are based on keeping the constructor private and providing a public static member to allow clients access to the sole instance of the class. In one approach, the public static member is a final field.

In a second approach, a public static factory method is provided instead of the public static final field.

To make a singleton class serializable (Chapter 10), it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you must also provide a readResolve method (Item 57). // readResolve method to preserve singleton property private Object readResolve throws ObjectStreamException { /* return INSTANCE; }
 * Return the one true Elvis and let the garbage collector
 * take care of the Elvis impersonator.

Item 3: Enforce noninstantiability with a private constructor. Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such utility classes were not designed to be instantiated: An instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs. Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated.

There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a single explicit private constructor.

Item 4: Avoid creating duplicate objects It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable.

Item 5: Eliminate obsolete object references

Item 6: Avoid finalizers. (Finalizer Guardian) There is no guarantee that finalizers will be executed promptly.

Unfortunately, the finalizer thread was running at a lower priority than another thread in the application, so objects weren't getting finalized at the rate they became eligible for finalization. The JLS makes no guarantees as to which thread will execute finalizers, so there is no portable way to prevent this sort of problem other than to refrain from using finalizers.

Also: If an uncaught exception is thrown during finalization, the exception is ignored, and finalization of that object terminates [JLS, 12.6]. Uncaught exceptions can leave objects in a corrupt state. If another thread attempts to use such a corrupted object, arbitrary nondeterministic behavior may result.

So what should you do instead of writing a finalizer for a class whose objects encapsulate resources that require termination, such as files or threads? Just provide an explicit termination method, and require clients of the class to invoke this method on each instance when it is no longer needed. One detail worth mentioning is that the instance must keep track of whether it has been terminated: The explicit termination method must record in a private field that the object is no longer valid, and other methods must check this field and throw an IllegalStateException if they are called after the object has been terminated.

Finalizer Guardian. A single instance of the anonymous class, called a finalizer guardian, is created for each instance of the enclosing class. The enclosing instance stores the sole reference to its finalizer guardian in a private instance field so the finalizer guardian becomes eligible for finalization immediately prior to the enclosing instance. When the guardian is finalized, it performs the finalization activity desired for the enclosing instance, just as if its finalizer were a method on the enclosing class.

Methods Common to All Objects Although Object is a concrete class, it is designed primarily for extension. All of its nonfinal methods (equals, hashCode, toString, clone, and finalize) have explicit general contracts because they are designed to be overridden. It is the responsibility of any class overriding these methods to obey their general contracts; failure to do so will prevent other classes that depend on these contracts from functioning properly in conjunction with the class.

Classes and Interfaces Item 12: Minimize the accessibility of classes and members

57. Defensive readResolve

http://www.javapractices.com/topic/TopicAction.do?Id=29 Immutable objects

1. Type-Safe Enumerations 2. Class for constants 3. Copy an array

Drools http://docs.jboss.org/drools/release/5.2.0.Final/drools-expert-docs/html/ch02.html Stateless Knowledge Session A Knowledge Base is what we call our collection of compiled definitions, such as rules and processes, which are compiled using the KnowledgeBuilder. Both the KnowledgeBuilder and KnowledgeBase can be created from the factories KnowledeBuilderFactory and KnowledgeBaseFactory.

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder; kbuilder.add( ResourceFactory.newClassPathResource( "licenseApplication.drl", getClass ),             ResourceType.DRL ); if ( kbuilder.hasErrors ) { System.err.println( kbuilder.getErrors.toString ); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase; kbase.addKnowledgePackages( kbuilder.getKnowledgePackages );

StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession; Applicant applicant = new Applicant( "Mr John Smith", 16 ); assertTrue( applicant.isValid ); ksession.execute( applicant ); assertFalse( applicant.isValid );

A CommandFactory is used to create commands

List cmds = new ArrayList; cmds.add( CommandFactory.newInsert( new Person( "Mr John Smith" ), "mrSmith" ); cmds.add( CommandFactory.newInsert( new Person( "Mr John Doe" ), "mrDoe" ); BatchExecutionResults results = ksession.execute( CommandFactory.newBatchExecution( cmds ) ); assertEquals( new Person( "Mr John Smith" ), results.getValue( "mrSmith" ) );

CommandFactory supports many other Commands that can be used in the BatchExecutor like StartProcess, Query, and SetGlobal.

Stateful Knowledge Session

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder; kbuilder.add( ResourceFactory.newClassPathResource( "fireAlarm.drl", getClass ),             ResourceType.DRL ); if ( kbuilder.hasErrors ) { System.err.println( builder.getErrors.toString ); } kbase.addKnowledgePackages( kbuilder.getKnowledgePackages ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession;

Drools Basics simple use cases: 1. Stateless Knowledge Session - Validation, Calculation, Routing and Filtering rule when then end To make the engine aware of data, so it can be processed against the rules, we have to insert the data, much like with a database. When the Applicant instance is inserted into the engine it is evaluated against the constraints of the rules, in this case just two constraints for one rule. We say two because the type Applicant is the first object type constraint, and age < 18 is the second field constraint. An object type constraint plus its zero or more field constraints is referred to as a pattern. When an inserted instance satisfies both the object type constraint and all the field constraints, it is said to be matched. The $a is a binding variable which permits us to reference the matched object in the consequence. There its properties can be updated. The dollar character ('$') is optional, but it helps to differentiate variable names from field names. The process of matching patterns against the inserted data is, not surprisingly, often referred to as pattern matching.

Let's assume that the rules are in the same folder as the classes, so we can use the classpath resource loader to build our first KnowledgeBase. A Knowledge Base is what we call our collection of compiled definitions, such as rules and processes, which are compiled using the KnowledgeBuilder. Both the KnowledgeBuilder and KnowledgeBase can be created from the factories KnowledeBuilderFactory and KnowledgeBaseFactory.

Learning. Item 14 -->