quinta-feira, 22 de fevereiro de 2018

Relatorio jasper com multiplos dataSources JSF


Essa código faz parte de um biblioteca utilizada em uma aplicação JSF



Dependências utilizadas:

<dependencies>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.olap4j</groupId>
<artifactId>olap4j</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>


Classe:



import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class ServicoImpressao {

private static final Logger LOGGER = Logger.getLogger(ServicoImpressao.class);

private static JasperPrint print;

public void generateReport(final Collection lista, final Map parameters, final String reporterFile) throws Exception {

try {
JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(lista, false);

InputStream stream = this.getClass().getClassLoader().getResourceAsStream(reporterFile);

Map parametersLocal = parameters;
if (ServicoImpressao.print == null) {
if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}
java.util.Locale locale = new Locale("pt", "BR");
parametersLocal.put(JRParameter.REPORT_LOCALE, locale);
ServicoImpressao.print = JasperFillManager.fillReport(stream, parametersLocal, source);
} else {
JasperPrint jasperPrint_next = JasperFillManager.fillReport(stream, parametersLocal, source);
List pages = jasperPrint_next.getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage) pages.get(j);
ServicoImpressao.print.addPage(object);
}
}

} catch (Exception e) {
LOGGER.error("ERRO AO GERAR RELATORIO", e);
throw e;
}
}

public void generateReport(final Map<String, Collection> map, final Map parameters, final String reporterFile) throws Exception {

try {
Map parametersLocal = parameters;

if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}

InputStream stream = this.getClass().getClassLoader().getResourceAsStream(reporterFile);

JRBeanCollectionDataSource dataSourceDefault = null;
JRBeanCollectionDataSource dataSource = null;

Iterator<Entry<String, Collection>> entries = map.entrySet().iterator();

while (entries.hasNext()) {
Map.Entry<String, Collection> entry = (Map.Entry<String, Collection>) entries.next();

dataSource = new JRBeanCollectionDataSource((Collection) entry.getValue(), false);
// MAP KEY VAZIA OU DEFAULT = DATASOURCE DEFAULT
if ("".equals(entry.getKey()) || "default".equalsIgnoreCase(entry.getKey())) {
dataSourceDefault = dataSource;
} else {
dataSource = new JRBeanCollectionDataSource((Collection) entry.getValue(), false);
parametersLocal.put(entry.getKey(), dataSource);
}
}
if (ServicoImpressao.print == null) {
if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}
Locale locale = new Locale("pt", "BR");
parametersLocal.put(JRParameter.REPORT_LOCALE, locale);
ServicoImpressao.print = JasperFillManager.fillReport(stream, parametersLocal, dataSourceDefault);
} else {
JasperPrint jasperPrint_next = JasperFillManager.fillReport(stream, parametersLocal, dataSourceDefault);
List pages = jasperPrint_next.getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage) pages.get(j);
ServicoImpressao.print.addPage(object);
}
}

} catch (Exception e) {
LOGGER.error("ERRO AO GERAR RELATORIO", e);
throw e;
}
}

public Integer getNumeroPaginas() {
return ServicoImpressao.print.getPages().size();
}

public void imprime() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
try {
response.reset();
response.setContentType("application/pdf");
java.io.OutputStream outputStream = null;
outputStream = response.getOutputStream();
outputStream.write(JasperExportManager.exportReportToPdf(print));
outputStream.close();
} catch (IOException | JRException e) {
e.printStackTrace();
} finally {
ServicoImpressao.print = null;
}
facesContext.responseComplete();
}
}

Chamador:

try {
Map<String,Collection> mapJasper = new HashMap<String,Collection>();

mapJasper.put("", relatorioOut.getGrupos());
mapJasper.put("SUB_REPORT", relatorioOut.getGruposReajustes());

impressao.generateReport(mapJasper, parameters, nomeJasper);
impressao.imprime();

} catch (Exception e) {
LOGGER.error(e, e);
}



terça-feira, 20 de fevereiro de 2018

How to Iterate Over a Map in Java

How to Iterate Over a Map in Java

Java
There are several ways of iterating over a Map in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Mapinterface, following techniques will work for any map implementation (HashMapTreeMapLinkedHashMapHashtable, etc.)

Method #1: Iterating over entries using For-Each loop.

This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for nullreferences.

Method #2: Iterating over keys or values using For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or valuesinstead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}
//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant but it has its own advantages. First of all it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to javadoc.
From performance point of view this method is equal to For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1 but in practice it is pretty slow and inefficient as getting values by a key might be time consuming (this method in different Mapimplementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.

Conclusion

If you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

ref: http://www.sergiy.ca/how-to-iterate-over-a-map-in-java/

segunda-feira, 19 de fevereiro de 2018

Java Exceptions

Hi,
This section is about exception handling in Java. I will try to cover as much use cases as I can. The best way to learn exceptions is to play with different exception types, especially handling multiple exceptions, by yourself.
We are responsible for following specific classes for Java 8 Programmer I exam: Error, Unchecked Exception, and Checked Exception.

Error

They should not be handled by a programmer.
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError

Unchecked Exception (Runtime Exception)

They are called as “Runtime Exceptions” as well. It is optional to handle them.
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
NullPointerException
NumberFormatException

Checked Exception

Exception and all subclasses that do not extend RuntimeException. They should be either declared or handled.
FileNotFoundException
IOException
Declare:  “Throws” Declares An Exception That Might Be Throwed.
static void foo() throws Exception {
}
Handle: “Throw” Means You Want To Throw Exception. 
static void foo() throws Exception {
      throw new Exception();
}
If you throw exception without declaring, you will get a compiler error “Unhandled exception type Exception”. In this case, we can handle exception in either caller or called function with try/catch.
static void foo() {
     throw new Exception(); // Compile Error
}
(Solution 1) Handling an exception in called function (caller).
/**
 * Throwing an exception in called function surround called function with try/catch
 * 
 * @author suleyman.yildirim
 *
 */
public class UnhandledExceptionSolution1 {

 public static void main(String[] args) {
    foo();
 }

 static void foo() {
    try {
       throw new Exception();
    } catch (Exception e) {
       // TODO: handle exception
    }
  }
}
(Solution 2) Handling an exception in caller function (callee).
/**
 * Throwing an exception in caller function
 * 
 * Surround the caller function with try/catch
 * Declare and throw exception without using try/catch in called function
 * 
 * @author suleyman.yildirim
 *
 */
public class UnhandledExceptionSolution2 {

  public static void main(String[] args) {
    try {
        foo();
    } catch (Exception e) {
        // TODO: handle exception
    }
  }
  
  static void foo() {
    throw new Exception();
  }
}
A short remark on the previous example is that you can avoid compile error by declaring exception in main function. However, you will get runtime error as you do not actually “handle” the exception you throwed. Try following code and see what happens 🙂
/**
 * Runtime Error!
 * 
 * Once you throw exception in a function, you should either handle it in caller
 * or called function. Otherwise, you get runtime exception.
 * 
 * @author suleyman.yildirim
 *
 */
public class RuntimeError {

 public static void main(String[] args) throws Exception {
   foo();
 }

 static void foo() throws Exception {
   throw new Exception();
 }
}

Handling Multiple Exception Types

If there is an IS-A relationship between exception classes, the order is important. The derived most class should be caught first. Otherwise, compiler warns us like “Unreachable catch block for ArithmeticException. It is already handled by the catch block for RuntimeException”. Consider following example.
 try {
  ...
 } catch (RuntimeException e) {
     throw e;
 } catch (ArithmeticException e) { // Compile error 
     throw e;
 } catch (Exception e) {
    throw e;
 }

If there is not an IS-A relationship, the order is not important. Consider two classes below, ExceptionA and ExceptionB, which are inherited from different type of exceptions.
class ExceptionA extends RuntimeException {
}

class ExceptionB extends ArithmeticException {
}
void f() {
  try {
    ...
  } catch (ExceptionA e) {
     throw e;
  } catch (ExceptionB e) { 
     throw e;
  }
}

Core Java APIs


In this post, I will cover a some of the Core Java APIs (String, StringBuilder, Wrapper classes, and Date Time API) that we are responsible for Java 8 Programmer I exam.

Immutability

I think the first thing that we need to know is immutability. String class is immutable, meaning that the state of the string literal cannot be modified after it is created. Once a string literal is created, it is located into the string pool for future use.
Let’s consider the following example. The first line created a string literal “string pool”, and it is assigned to “x”. At the second line, the same literal is assigned to “y”, but a new object is not allocated in memory. Since both references points to the same memory location, “x == y” is true.
In the next example, the “string” and “pool” are different literals, which are allocated to different addresses in memory. In this case, the references are not the same. Therefore, “x == y” is false.
A string created with StringBuilder class is mutable, which can be modified after it is created. When we created a StringBuilder object, a new object is created in heap. We can manipulate the content of the same object. Consider following example:
There is only one object created at the first line. The append operation is performed on the existing object.

String Vs StringBuilder

I saw many tricky questions, which mix String and StringBuilder functions, in practice tests. For example, following example checks if you know the append method doesn’t belong to String class.
String s = new String("tricky");
s.append(" question"); // String class doesn't have append method
System.out.println(s);
According to the book, OCA Oracle Certified Associate Java SE 8 Programmer I Study Guide, we need to know the most used functions in both classes for the exam. The first 4 functions are common, the rest are different.
StringStringBuilder
charAt()charAt()
indexOf()indexOf()
length()length()
substring()substring()
toLowerCase() and toUpperCase()append()
equals() and equalsIgnoreCase()insert()
startsWith() and endsWith()delete() and deleteCharAt()
contains()reverse()
replace()toString()
trim() 

Wrapper Classes

Java provides wrapper classes for each primitive data types. We need to know following table. Remember that Character class doesn’t have parse and valueOf functions.
Primitive typeWrapper class                           
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble
Passing invalid value to wrapper functions causes NumberFormatException
int x = Integer.parseInt(“1”);  // valid
int x = Integer.parseInt(“sdf”);  // runtime exception
Autoboxing and Unboxing
Unboxing: Converting from wrapper to primitive type.
  •  public static boolean parseBoolean(String s)
Autoboxing: Converting from primitive type to wrapper class.

Date And Time APIs

All classes in the Date Time API
  • are in java.time package
  • are immutable (we need to reassign values to the reference)
  • are thread-safe (good for multi-threaded environments)
We must use static methods since they have private constructors, which prevents you to create an instance of a class.
LocalDate d = new LocalDate(); // compile error. 
use LocalDate.of() instead

Manipulating Dates And Times (LocalDate, LocalTime, LocalDateTime)

LocalDate contains just a date (2015-01-20) , no time methods
LocalDate date1 = LocalDate.of(2017, Month.MAY, 28);
LocalDate date2 = LocalDate.of(2017, 5, 28);
LocalDate date1 = LocalDate.of(2017, Month.MAY, 28);
LocalTime contains just a time (13:11:10.03) , no date methods
LocalDate date2 = LocalDate.of(2017, 5, 12);
LocalTime time1 = LocalTime.of(3, 25); // hour and minute
LocalTime time2 = LocalTime.of(8, 25, 20); // + seconds
LocalTime time3 = LocalTime.of(7, 25, 20, 200); // + nanoseconds
LocalDateTime contains both a date and time but no time zone 2017-02-06T13:12:14.10
LocalDateTime dateTime = LocalDateTime.of(2017, Month.MAY, 20, 6, 15, 30);

//or

LocalDate date = LocalDate.of(2017, Month.MAY, 28);
LocalTime time = LocalTime.of(6, 15);
LocalDateTime dateTime = LocalDateTime.of(date1, time1);

Adding To A Date (PlusDays, PlusWeeks…)

The date and time classes are immutable. This means that we need to remember to assign the results of these methods to a reference variable so they are not lost.
LocalDate date = LocalDate.of(2017, Month.MAY, 20);
System.out.println(date); // 2017-05-20 Output format (year–month-day)
date = date.plusDays(2);
System.out.println(date); // 2017-05-22
date = date.plusWeeks(1);
System.out.println(date); // 2017-05-29
date = date.plusMonths(1);
System.out.println(date); // 2017-02-28
date = date.plusYears(5);
System.out.println(date); // 2059-02-28

Go Backward In Time (MinusDays,MinusHours, MinusSeconds)

LocalDate date = LocalDate.of(2017, Month.MAY, 28);
LocalTime time = LocalTime.of(5, 15);
LocalDateTime dateTime = LocalDateTime.of(date, time);
System.out.println(dateTime); // 2017-05-28T05:15
dateTime = dateTime.minusDays(1);
System.out.println(dateTime); // 2017-05-19T05:15
dateTime = dateTime.minusHours(10);
System.out.println(dateTime); // 2017-05-18T19:15
dateTime = dateTime.minusSeconds(30);
System.out.println(dateTime); // 2017-05-18T19:14:30

Method Chaining

We can use method chaining with LocaleDate, LocalTime, and LocalDateTime classes.
LocalDate date2 = LocalDate.of(2007, Month.MAY, 20);
LocalTime time = LocalTime.of(4, 10);
LocalDateTime dateTime = LocalDateTime.of(date2, time).minusDays(2).minusHours(1).minusSeconds(3);
Periods (ofYears, ofMonths…)
Period class models a quantity or amount of time in terms of years, months and days.
Period annually = Period.ofYears(1); // every 1 year
Period quarterly = Period.ofMonths(3); // every 3 months
Period everyThreeWeeks = Period.ofWeeks(3); // every 3 weeks
Period everyOtherDay = Period.ofDays(2); // every 2 days
Period everyYearAndAWeek = Period.of(1, 0, 7); // every year and 7 days
Be careful with method chaining when creating a Period. The first line in the following example obtains a Period representing every week, not every year and 7 weeks.
Period wrong = Period.ofYears(1).ofWeeks(1); // every week
Period right= Period.of(1, 0, 7); // every year and 7 weeks
You can add period to LocaeDateTime and LocaleDate but LocalTime. Adding period to LocalTime results in “UnsupportedTemporalTypeException”.
LocalDate date = LocalDate.of(2017, 5, 28);
LocalTime time = LocalTime.of(6, 5);
LocalDateTime dateTime = LocalDateTime.of(date, time);
Period period = Period.ofMonths(1);
System.out.println(date.plus(period)); // 2017-06-28
System.out.println(dateTime.plus(period)); // 2017-06-28T06:05
System.out.println(time.plus(period)); // UnsupportedTemporalTypeException
Formatting Dates and Times
You are only responsible for SHORT and MEDIUM predifined formats for the exam.
  • SHORT is completely numeric, such as 12.13.52 or 3:30pm
  • MEDIUM is longer, such as Jan 12, 1952
DateTimeFormatter shortDateTime = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
System.out.println(shortDateTime.format(dateTime)); // 1/20/20
System.out.println(shortDateTime.format(date)); // 1/20/20
System.out.println(shortDateTime.format(time)); // UnsupportedTemporalTypeException. Time cannot be formatted as a date
DateTimeFormatter shortF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(shortF.format(dateTime)); // 1/20/20 10:33 AM
System.out.println(mediumF.format(dateTime)); // May 28, 2017 11:12:34 AM

DateTimeFormatter.OfPattern(“MMMM Dd, Yyyy, Hh:mm”);

DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy, hh:mm");
System.out.println(dateTime.format(f)); // May 20, 2010, 11:12
DateTimeFormatter f = DateTimeFormatter.ofPattern("hh:mm"); // We can only use this formatter with objects containing times
f.format(dateTime); // ok
f.format(date); // throw an exception.
f.format(time); // ok

Parsing Dates And Times (_____.Parse())

DateTimeFormetter f = DateTimeFormatter.ofPattern(“MM dd yyyy”);
LocalDate date = LocalDate.parse("08 11 2017", f);
LocalTime time = LocalTime.parse("11:22");
System.out.println(date); // 2017-08-11
System.out.println(time); // 11:22

 References

  1. OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808, Jeanne BoyarskyScott Selikoff
  2. https://en.wikipedia.org/wiki/Immutable_object
  3. https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

How To Run Docker Container On Your Local Machine

How To Run Docker Container On Your Local Machine

Introduction

I have been working on a hobby project, Nutrition Tracking App, to practice the latest Continuous Integration tools. This post is about dockerizing an Angular2 app and using in your local machine. I skipped the basic definitions about Docker, Containers and CI for the sake of simplicity.

Docker Commands

Frequently used docker commands.
Build docker an image
docker build -t image-name .
Run docker an image
docker run -p 80:80 -it image-name
Stop all docker containers
docker stop $(docker ps -a -q)
Remove all docker containers
docker rm $(docker ps -a -q)
Remove all docker images
docker rmi $(docker images -q)
Port bindings of a specific container
docker inspect [container-id]
Pull an image from Docker Hub 
docker pull sy456/angular2webpack -->sy456 is my account name at dockerhub
Push an image to Docker Hub 
docker push sy456/angular2webpack -->sy456 is my account name at dockerhub

Dockerfile

Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Simple dockerfile that copies “dist” folder to /usr/share/nginx/html
FROM nginx
COPY dist /usr/share/nginx/html
EXPOSE 80

Project Structure

Dockerfile should be located in the root of the project. Here is an example from my project.

How To Run Docker Container On Your Local Machine

Build 
docker build -t angular-webpack .
Run
docker run -p 9000:80 -t angular-webpack
This will create a container with the image ‘angular-webpack’ and bind the container’s port 80 to the host machine’s port 9000. After “docker run -p 9000:80 -it angular-webpack” command, docker container runs on Linux virtual machine. So we can’t run Docker natively on Windows or a Mac. Following properties must be set.
Set environment properties
set USERPROFILE = C:\Users\xxx  --> set your user proile 

set DOCKER_CERT_PATH=%USERPROFILE%\.docker\machine\machines\default

set DOCKER_HOST=tcp://192.168.99.100 --> find this IP in Docker Quick Start terminal

set DOCKER_MACHINE_NAME=default

set DOCKER_TLS_VERIFY=1
Test
For Troubleshooting
https://stackoverflow.com/questions/41208782/docker-localhost-process-not-working-on-windows