How to print out the current project classpath

Java’s “SystemClassLoader” can use to pint out the current project classpath , indirectly display the library dependency as well. Example package com.mkyong.io; import java.net.URL; import java.net.URLClassLoader; public class App{ public static void main (String args[]) { ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)cl).getURLs(); for(URL url: urls){ System.out.println(url.getFile()); } } } Output /E:/workspace/HibernateExample/target/test-classes/ /E:/workspace/HibernateExample/target/classes/ /D:/maven/repo/antlr/antlr/2.7.7/antlr-2.7.7.jar …

Read more

How to get the standard input in Java

Note This post is duplicated, please refer to this – 3 ways to read input from console in Java. A quick example to show you how to read the standard input in Java. package com.mkyong.pageview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) { BufferedReader br = null; …

Read more

How to assign file content into a variable in Java

Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it 🙂 Example In this example, you will use DataInputStreamto convert all the content into bytes, and …

Read more

How to traverse a directory structure in Java

In this example, the program will traverse the given directory and print out all the directories and files absolute path and name one by one. Example package com.mkyong.io; import java.io.File; public class DisplayDirectoryAndFile{ public static void main (String args[]) { displayIt(new File("C:\\Downloads")); } public static void displayIt(File node){ System.out.println(node.getAbsoluteFile()); if(node.isDirectory()){ String[] subNote = node.list(); for(String …

Read more

How to open a PDF file in Java

In this article, we show you two ways to open a PDF file with Java. 1. rundll32 – Windows Platform Solution In Windows, you can use “rundll32” command to launch a PDF file, see example : package com.mkyong.jdbc; import java.io.File; //Windows solution to view a PDF file public class WindowsPlatformAppPDF { public static void main(String[] …

Read more

How to clear / delete the content of StringBuffer()

The StringBuffer is always been using for the String concatenation. However this class didn’t provide a method to clear the existing content. Why there are no clear() function? You can use the delete(int start, int end) as dirty trick : sb.delete(0, sb.length()); 1 . Example package com.mkyong.io; public class App{ public static void main (String …

Read more

How to convert HTML to Javascript (.js) in Java

For some security reasons, you may need to convert your HTML file into Javascript (js) file, and display the JS file instead of the HTML file directly. The concept is quite simple – using the document.write HTML <h1>Convert HTML to Javascript file</h1> Javascript (js) document.write(‘<h1>Convert HTML to Javascript file</h1>’); 1. Test.html Create a simple HTML …

Read more

How to get the current working directory in Java

In Java, we can use System.getProperty("user.dir") to get the current working directory, the directory from where your program was launched. String dir = System.getProperty("user.dir"); // directory from where the program was launched // e.g /home/mkyong/projects/core-java/java-io System.out.println(dir); One of the good things about this system property user.dir is we can easily override the system property via …

Read more

How to read an object from file in Java (ObjectInputStream)

This example shows how to use ObjectInputStream to read a serialized object from a file in Java, aka Deserialization. public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException { Object result = null; try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { result = ois.readObject(); } return result; } // Convert byte[] to …

Read more

How to write an object to file in Java (ObjectOutputStream)

This example shows how to use ObjectOutputStream to write objects to a file in Java, aka Serialization. public static void writeObjectToFile(Person obj, File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(obj); oos.flush(); } } Note More Java Serialization and Deserialization examples 1. Java object We can …

Read more

How to delete files with certain extension only

In Java, you can implements the FilenameFilter, override the accept(File dir, String name) method, to perform the file filtering function. In this example, we show you how to use FilenameFilter to list out all files that are end with “.txt” extension in folder “c:\\folder“, and then delete it. package com.mkyong.io; import java.io.*; public class FileChecker …

Read more

How to check if a file exists in Java

In Java, we can use Files.exists(path) to test whether a file exists. The path can be a file or a directory. It is better to combine with !Files.isDirectory(path) to ensure the existing file is not a directory. Path path = Paths.get("/home/mkyong/test/test.log"); // file exists and it is not a directory if(Files.exists(path) && !Files.isDirectory(path)) { System.out.println("File …

Read more

JMF – Unable to handle format: mpeglayer3

Problem You may encounter the following error while using Java media framework (JMF) to play a mp3 file. Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits Failed to realize: com.sun.media.PlaybackEngine@19ec4ed Error: Unable to realize com.sun.media.PlaybackEngine@19ec4ed server running at port: 4264 Solution This is because Java took out …

Read more

How to display hibernate sql parameter values – Log4j

Problem Hibernate has basic logging feature to display the SQL generated statement with show_sql configuration property. Hibernate: INSERT INTO mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) VALUES (?, ?, ?, ?, ?, ?) However , it just isn’t enough for debugging, the Hibernate SQL parameter values are missing. Solution – Log4j Log4J is required to …

Read more

log4j.properties example

I can’t find many log4j.properties examples, here are a few log4j.properties examples that are used in my project, just for sharing. 1. Output to Console All logging will be redirected to your console. log4j.properties # Root logger option log4j.rootLogger=INFO, stdout # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n …

Read more

Display Hibernate SQL to console – show_sql , format_sql and use_sql_comments

Hibernate has build-in a function to enable the logging of all the generated SQL statements to the console. You can enable it by add a “show_sql” property in the Hibernate configuration file “hibernate.cfg.xml“. This function is good for basic troubleshooting, and to see what’s Hibernate is doing behind. 1. show_sql Enable the logging of all …

Read more

How to access Windows shares in Ubuntu

Problem Ubuntu doesn’t has build-in tool for browsing or accessing the Windows share in network. Is there any ways to access the Windows share in Ubuntu? Solution Ubuntu has smb installed by default, you can use smb to access the Windows shares. 1. File Browser Open “Computer – File Browser”, Click on “Go” –> “Location…” …

Read more

Maven 2 + Hibernate 3.2 + MySQL Example (Annotation)

Note This article is outdated, and some information is no longer valid in latest Hibernate development. You should refer to this latest – Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (Annotation) tutorial. This tutorial will modify the previous Maven 2 + Hibernate 3.2 + MySQL Example (XML mapping), and replace the Hibernate XML …

Read more

How to configure logging in Hibernate – SLF4j + Log4j

Try logback Try logback logging framework, read this article for the “reasons to prefer logback over log4j. To integrate logback with Hibernate, refer this – How to configure logging in Hibernate – Logback Hibernate uses Simple Logging Facade for Java (SLF4J) to redirect the logging output to your perfer logging frameworkis (log4j, JCL, JDK logging, …

Read more

Hibernate Error – Exception in thread “main” java.lang.NoClassDefFoundError: antlr/ANTLRException

This is caused by missing of the antlr library. It’s usually happened when you did invoke Hibernate’s query statement. Exception in thread "main" java.lang.NoClassDefFoundError: antlr/ANTLRException at org.hibernate.hql.ast.ASTQueryTranslatorFactory.createQueryTranslator(ASTQueryTranslatorFactory.java:35) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:74) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623) at com.mkyong.common.App.main(App.java:23) Caused by: java.lang.ClassNotFoundException: antlr.ANTLRException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager

This is caused by missing of the Hibernate commons annotations library. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.ReflectionManager at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) …

Read more

Hibernate Error – An AnnotationConfiguration instance is required to use

The Hibernate annotation is required “AnnotationConfiguration” instead of normal “Configuration()” to build the session factory. INFO: Configuration resource: /hibernate.cfg.xml Initial SessionFactory creation failed.org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/> Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/> …

Read more

Hibernate SQL Dialects Collection

Hibernate SQL Dialect is telling your Hibernate application which SQL language should be use to talk with your database. 1. DB2 org.hibernate.dialect.DB2Dialect 2. DB2 AS/400 org.hibernate.dialect.DB2400Dialect 3. DB2 OS390 org.hibernate.dialect.DB2390Dialect 4. PostgreSQL org.hibernate.dialect.PostgreSQLDialect 5. MySQL org.hibernate.dialect.MySQLDialect 6. MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect 7. MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect 8. Oracle 8 org.hibernate.dialect.OracleDialect 9. Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect 10. …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources

Hibernate’s “C3P0” connection pool error, this is caused by the missing dependency library – C3P0. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources at org.hibernate.connection.C3P0ConnectionProvider.configure(C3P0ConnectionProvider.java:154) at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124) at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56) at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:410) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292) at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused …

Read more

How to add Hibernate XML mapping file (hbm.xml) programmatically

Hibernate XML mapping file contains the mapping relationship between Java class and database table. This is always named as “xx.hbm.xml” and declared in the Hibernate configuration file “hibernate.cfg.xml”. For example, the mapping file (hbm.xml) is declared in the “mapping” tag <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> …

Read more

Java – How to get current date time

In this tutorial, we will show you how to get the current date time from the new Java 8 java.time.* like Localdate, LocalTime, LocalDateTime, ZonedDateTime, Instant and also the legacy date time APIs like Date and Calendar. Table of contents 1. Get current date time in Java 2. java.time.LocalDate 3. java.time.LocalTime 4. java.time.LocalDateTime 5. java.time.ZonedDateTime …

Read more

How to configure the C3P0 connection pool in Hibernate

Connection Pool Connection pool is good for performance, as it prevents Java application create a connection each time when interact with database and minimizes the cost of opening and closing connections. See wiki connection pool explanation Hibernate comes with internal connection pool, but not suitable for production use. In this tutorial, we show you how …

Read more

How to load hibernate.cfg.xml from different directory

Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error : Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:25) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused …

Read more

How to read XML file in Java – (JDOM Parser)

JDOM is open-source Java-based XML parser framework built on top of DOM and SAX, also a document object model(DOM) in-memory representation of an XML document. JDOM makes navigating XML documents easier by providing more straightforward APIs and a standard Java-based collection interface. If you don’t mind downloading a small library to parse an XML file, …

Read more

How to convert InputStream to File in Java

Below are some Java examples of converting InputStream to a File. Plain Java – FileOutputStream Apache Commons IO – FileUtils.copyInputStreamToFile Java 7 – Files.copy Java 9 – InputStream.transferTo 1. Plain Java – FileOutputStream This example downloads the google.com HTML page and returns it as an InputStream. And we use FileOutputStream to copy the InputStream into …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter

A common Hibernate’s error, this is caused by the missing dependency library – cglib. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter at org.hibernate.bytecode.cglib.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:33) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:182) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:160) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:135) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:295) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap

A common Hibernate’s error, this is caused by the missing dependency library – Apache Common Collection. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap at org.hibernate.mapping.Table.<init>(Table.java:33) at org.hibernate.cfg.Mappings.addTable(Mappings.java:165) at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:290) at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:273) at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:144) at org.hibernate.cfg.Configuration.add(Configuration.java:669) at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:504) at org.hibernate.cfg.Configuration.addResource(Configuration.java:566) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

A common Hibernate’s error, this is caused by the missing dependency library – Common Logging. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:120) at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException

A common Hibernate’s error, this is caused by the missing dependency library – dom4j. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at …

Read more

How to search the Maven coordinates – pom.xml dependency?

If you want to include a library dependency in “pom.xml” file, you have to define the “Maven coordinate” <!– MySQL database driver –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> However, one of the annoying problem of this is you do not know what’s the Maven coordinate details – group id, artifactId and etc. Many Java developers …

Read more

How to generate Hibernate mapping files & annotation with Hibernate Tools

In this article, we show you how to use Hibernate / JBoss Tools to generate Hibernate mapping files (hbm) and annotation code from database automatically. Tools in this article Eclipse v3.6 (Helios) JBoss / Hibernate Tools v3.2 Oracle 11g JDK 1.6 Note Before proceed, please Install Hibernate / JBoss Tools in Eclipse IDE. 1. Hibernate …

Read more