snippetjournal

– notes, snippet codes, and my journal

Archive for June 2013

Hibernate Criteria : One To Many and Many To One

leave a comment »

Berikut ini snippet codes dari penggunaan hibernate criteria dengan kasus relation/cardinalitas one to many dan many to one.

Terdapat model/entity sebagai berikut :


....
 private Company company;
 private String isActive;
 private String proposalCode;
 private String proposalName;
 private Set<ProspectProposalManPower> prospectProposalManPowers = new HashSet<ProspectProposalManPower>(0);
 private Set<ProspectProposalCost> prospectProposalCosts = new HashSet<ProspectProposalCost>(0);

....

getter - setter

....
@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="company_id")
    public Company getCompany() {
        return this.company;
    }

....

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "prospectProposal")
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    public Set<ProspectProposalManPower> getProspectProposalManPowers() {
        return this.prospectProposalManPowers;
    }
....


Untuk Dao implementasi nya sebagai berikut:

public List<ProspectProposal> getAllDataActive(final Map searchParam, final int firstResult, final int maxResult, final boolean asc, final String sortField) {
 Object o;
 o = getHibernateTemplate().execute(new HibernateCallback() {

@Override
 public Object doInHibernate(Session sn) throws HibernateException, SQLException {
 Criteria criteria = sn.createCriteria(ProspectProposal.class);

 criteria.createAlias("prospectProposalManPowers", "manpower", Criteria.LEFT_JOIN );
 criteria.createAlias("prospectProposalCosts", "cost", Criteria.LEFT_JOIN);

criteria = searchFilters(criteria, searchParam);

 criteria.add(Restrictions.isNotNull("kode"));
 criteria.add(Restrictions.eq("isActive", "Y"));
 criteria.setFetchMode("company", FetchMode.JOIN);

if(asc == true){
 criteria.addOrder(Order.asc(sortField));
 }else{
 criteria.addOrder(Order.desc(sortField));
 }

 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
 criteria.setFirstResult(firstResult);
 criteria.setMaxResults(maxResult);

return criteria.list();
 }
 });

 return (List<ProspectProposal>)o;

 }

 protected Criteria searchFilters(Criteria criteria, Map searchParam){

 if(searchParam.get("searchCode") != null && !searchParam.get("searchCode").equals("")){
 criteria.add(Restrictions.like("proposalCode", searchParam.get("searchCode").toString(), MatchMode.ANYWHERE));
 }

 if(searchParam.get("searchName") != null && !searchParam.get("searchName").equals("")){
 criteria.add(Restrictions.like("proposalName", searchParam.get("searchName").toString(), MatchMode.ANYWHERE));
 }

 if(searchParam.get("searchDecsMaker") != null && !searchParam.get("searchDecsMaker").equals("")){
 criteria.add(Restrictions.like("decisionMaker", searchParam.get("searchDecsMaker").toString(), MatchMode.ANYWHERE));
 }

 if(searchParam.get("searchCompany") != null && (Integer)searchParam.get("searchCompany") != 0){
 criteria.add(Restrictions.eq("company.kode", searchParam.get("searchCompany")));
 }

 if(searchParam.get("searchEmployee") != null && (Integer)searchParam.get("searchEmployee") != 0){
 criteria.add(Restrictions.eq("manpower.employee.kode", searchParam.get("searchEmployee")));
 }

 if(searchParam.get("searchCurrency") != null && (Integer)searchParam.get("searchCurrency") != 0){
 criteria.add(Restrictions.eq("cost.currency.kode", searchParam.get("searchCurrency")));
 }

 return criteria;
 }

codes: criteria.setFetchMode(“company”, FetchMode.JOIN);
Penggunaan FetchMode.JOIN digunakan agar entity company (many to one) di ikut sertakan dalam pengambilan data untuk menghindari Lazy Initialization

codes :criteria.createAlias(“prospectProposalManPowers”, “manpower”, Criteria.LEFT_JOIN );
Penggunaan Criteria.LEFT_JOIN digunakan agar relasi dari entity one to many ikut disertakan dalam query.

codes: criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Penggunaan Criteria.DISTINCT_ROOT_ENTITY untuk menanggulangi pemakaian left join yang akan mengakibatkan data terduplikasi.

Written by snippetjournal

June 20, 2013 at 12:16 pm

Jasper Report : XLSX and PDF using Jasper Exporter

leave a comment »

This java codes are snippet to generate jasper report using DataSource, JasperPrint, JasperFillManager, Jasper Export Manager :

Cuplikan kode java di bawah ini untuk menghasikan report dengan ekstensi xlsx dan pdf dengan menggunakan DataSource, JasperPrint, JasperFillManager, Jasper Export Manager :

To Download XLSX file / Untuk mengunduh xlsx file


private void getDownloadReportXlsx(HttpServletRequest request, HttpServletResponse response, JRDataSource jrDataSource) throws JRException, IOException {

 //uncomment this codes if u are want to use servlet output stream
 //ServletOutputStream servletOutputStream = response.getOutputStream();

 //get real path for report
 String path = request.getSession().getServletContext().getRealPath("\\WEB-INF\\reports\\xxx.jrxml");
 JasperReport jasperReport = JasperCompileManager.compileReport(path);
 JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrDataSource);

 JRXlsxExporter xlsxExporter = new JRXlsxExporter();
 ByteArrayOutputStream os = new ByteArrayOutputStream();

 xlsxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
 xlsxExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "xxx.xlsx");

 //uncomment this codes if u are want to use servlet output stream
 //xlsxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream);

 xlsxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);

 xlsxExporter.exportReport();

 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
 response.setHeader("Content-Disposition", "attachment; filename=xxx.xlsx");

 //uncomment this codes if u are want to use servlet output stream
 //servletOutputStream.write(os.toByteArray());

 response.getOutputStream().write(os.toByteArray());
 response.getOutputStream().flush();
 response.getOutputStream().close();
 response.flushBuffer();

 }

To generate PDF file is more simple than generate XLSX, this are the snippet codes :

Untuk menghasil file pdf lebih mudah dari pada menghasilkan file xlsx :

private void getDownloadReportPdf(HttpServletRequest request, HttpServletResponse response, JRDataSource jrDataSource) {
 try {
 String path = request.getSession().getServletContext().getRealPath("\\WEB-INF\\reports\\xxx.jrxml");
 JasperReport jasperReport = JasperCompileManager.compileReport(path);
 JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrDataSource);
 byte[] pdfBytes = JasperExportManager.exportReportToPdf(jasperPrint);

 //uncomment this line to make browser download the file
 //response.setContentType("application/pdf");
 //response.setHeader("Content-Disposition", "attachment;filename=xxx.pdf");

 response.getOutputStream().write(pdfBytes);
 response.getOutputStream().flush();
 response.getOutputStream().close();
 response.flushBuffer();

 } catch (JRException ex) {
 log.error(ex.getMessage(), ex.getCause());
 } catch (IOException ex) {
 log.error(ex.getMessage(), ex.getCause());
 }

}

To make the browser download file (several browser has supported default pdf viewer in their engine), simply add thisattribute to HtttpServletRespones :

Agar browser dapat mengunduh file tambahkan attribute di bawah ini :


uncomment this line to make browser download the file
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=xxx.fileExtension");

if you get error servlet ouput stream that already called, you can use this trick, simply reset the response when your menu view get called.


response.reset();

this error caused because the codes using response.getOutputStream().write(Object).  when we using JSP the component that responsible for rendering JSP as HTML in browser is servlet.write using output stream resources.

so when we redirect to another view (example in spring mvc : return string_page.jsp) it will conflict the resources. because we already define the resource to write in byte


Updated :

In jasper report 6.xx version the xlsxExporter.setParameter is deprecated, so instead define jasper parameter we can define the configuration using jasper configuration :


xlsxExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
xlsxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputReportName));
xlsxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));

reference :

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

http://himtech-spring.blogspot.com/2012/07/spring-mvc-with-jasperreport.html

http://kristantohans.wordpress.com/tag/tutorial-jasper-report/

https://raymondhlee.wordpress.com/category/jasper-reports/

Written by snippetjournal

June 19, 2013 at 3:40 am

Posted in Programming

Tagged with , , , , , ,

PDF viewer Bugs In Chrome

leave a comment »

There is bugs from pdf viewer in chrome, in several cases user cant save or print pdf from pdf viewer in chrome.

refer to this link for chrome pdf viewer reported bugs:
https://code.google.com/p/chromium/issues/detail?id=65395
http://productforums.google.com/forum/#!topic/chrome/k-VZDIFa-Cw
https://productforums.google.com/forum/#!topic/chrome/Q00cPdz0rEs

http://theincidentaleconomist.com/wordpress/how-chrome-messed-up-pdf-viewing-and-how-to-fix-it/
http://simpro.co/blog/tips-tricks/google-chrome-cant-print-or-save-a-pdf-a-simple-fix/

step to fix it :

1) In your Chrome browser, simply type into the browser: about:plugins

2) This will display all the plugins for your browser. If you have a plugin called Adobe Reader – then click on the `Enable’ link under it.

3) This will disable the Chrome PDF Reader and enable Adobe Reader then you are all good to go.

 

 

Written by snippetjournal

June 19, 2013 at 3:32 am

Posted in Programming

Tagged with , ,

Your Body Shape Make Who Are

leave a comment »

Fake it till u become it

Written by snippetjournal

June 15, 2013 at 4:38 am

Posted in video

Mental illness

leave a comment »

salah satu Video menarik dari sekian banyak video menarik dari ted.
menjelaskan tentang penyakit kejiwaan, kenapa manusia terlalu sering merasa khawatir.

your minds make who you are

Written by snippetjournal

June 15, 2013 at 4:03 am

Posted in video

Tagged with ,

The Guerrilla Guide to Interviewing (version 3.0) by Joel Spolsky

leave a comment »

http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html

Artikel yang bagus tentang bagaimana cara menginterview seorang kandidat programmer, bagi yang akan interview artikel ini juga bagus sebagai materi pendukung, kita dapat memahami bagaimana sudut pandang interviewer sehingga kita sebagai kandidat pekerja dapat mempersiapkan dengan baik.

cheers 🙂

Written by snippetjournal

June 11, 2013 at 11:33 am

Posted in Collection Link, Personal

Tagged with ,

Trivial Date Problem 1 (postgres)

leave a comment »

Noted :

Mencari Tanggal antara tanggal satu dengan lain nya (between)

tipe data pada kolom yang akan menjadi acuan adalah timestamp. beberapa cara pengambilan data nya dengan SQL


select * from table c where c.create_Time >= '2013-06-08'::date and c.create_Time <= '2013-06-11'::date

select c.* from table c where (c.create_Time, c.create_Time) OVERLAPS ('2013-06-08'::DATE, '2013-06-09'::DATE)

select c.* from table c where c.create_Time between '2013-06-08' and '2013-06-09'

select * from table c where c.create_Time >= '2013-06-08 00:00:00.000' and c.create_Time <= '2013-06-10 23:59:59.999'

select * from table c where c.create_Time >= '2013-06-08 00:00:00' and c.create_Time <= '2013-06-10 23:59:59'

Menggunakan cara lain, dengan mengakali koding java dengan menggunakan SimpleDateFormat  :

note: snippet ini bukan best practice dari penggunaan date dan timestamp


Date endDate = new Date();
 Date startDate = new Date();

if( form.getStartDate() != null && !form.getStartDate().equals("") ){
 startDate = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS", Locale.ENGLISH).parse(form.getStartDate().concat(" 00:00:00.000"));
 }

if( form.getEndDate() != null && !form.getEndDate().equals("") ){
 endDate = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS", Locale.ENGLISH).parse(form.getEndDate().concat(" 23:59:59.999"));
 }

Convert Date to Timestamp

Catatan : dimungkinkan untuk mengubah date menjadi timestamp dengan mempertahankan format yang sudah di tentukan. lakukan seperti ini :


Timestamp time = new Timestamp(startDate.getTime());

Tanggal dengan Calendar

Dalam melakukan perubahan tipe data Date juga disarankan penggunaan Calendar, karena banyak method dari Date yang sudah depreceated. berikut snippet codes nya :

Calendar calendarStart = Calendar.getInstance();
 calendarStart.setTime(enrollmentReportForm.getStartDt());
 calendarStart.set(Calendar.HOUR, 00);
 calendarStart.set(Calendar.MINUTE, 00);
 calendarStart.set(Calendar.SECOND, 00);
 calendarStart.set(Calendar.MILLISECOND, 00);
 startDate = calendarStart.getTime();

 Calendar calendarEnd = Calendar.getInstance();
 calendarEnd.setTime(enrollmentReportForm.getEndDt());
 calendarEnd.set(Calendar.HOUR, 23);
 calendarEnd.set(Calendar.MINUTE, 59);
 calendarEnd.set(Calendar.SECOND, 59);
 calendarEnd.set(Calendar.MILLISECOND, 59);
 endDate = calendarEnd.getTime();

catatan :
pada saat inisialisasi jam (HOUR) pada instance calendar kode di atas menggunakan “Calendar.HOUR”, ini akan menghasilkan nilai jam berupa system jam 12 hour.  Jika ingin menggunakan system jam dengan 24 hour bisa menggunakan “Calendar.HOUR_OF_DAY”

 

Timestamp dan Calendar dalam SimpleDateFormat

Beberapa contoh di bawah ini beberapa type data yang merepresentasikan tanggal dan dilakukan format date, dengan simple date format.

Calendar calendar = Calendar.getInstance();
 java.sql.Timestamp timestamp = new java.sql.Timestamp(System.currentTimeMillis());

 SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");

 System.out.println(sdf.format(calendar.getTime()));
 System.out.println(sdf.format(timestamp.getDate()));

Written by snippetjournal

June 11, 2013 at 11:25 am

Posted in Programming

Tagged with , , , ,