Why do I get NotOLE2FileException: Invalid header signature error?

When I was creating the code snippet for the How do I replace text in Microsoft Word document using Apache POI? I got the following error when running the snippet . As additional information, the code snippet for the Kodejava website is written as a Maven project.

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0xE011BDBFEFBDBFEF, expected 0xE11AB1A1E011CFD0 – Your file appears not to be a valid OLE2 document

This error message was produce when the code trying to open a Word document. The Apache POI reports that the Word document has an invalid header signature, not a valid OLE2 document. Comparing the original document with the document under maven’s target directory I found out that the file size was different. This could mean that something alter the document and corrupt the header.

After doing some googling, I found out that this error is due to maven resource filtering. The maven resource filtering process cause the Word document header corrupt during the copy phase. The solution to this problem is to make sure that the filtering process is set to false. The pom.xml of the maven project should be altered to have the following configuration.

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

Introduction to MongoDB Java Driver

In the past post Installing and Running MongoDB in Windows 7, you’ve seen how to install and running MongoDB database server. Now we are going to learn how to use the MongoDB Java Driver to access collections from the MongoDB database. To demonstrate this I am going to use Maven and IntelliJ IDEA. You can use other IDE of your choice of course, such as Eclipse or NetBeans which also support Maven.

Let’s begin by creating our project in IntelliJ IDEA. I am going to use the community edition of IntelliJ IDEA which is free to download. Here are the steps for creating a Maven project in IntelliJ IDEA.

Creating Maven Project

  • Start IntelliJ IDEA. From the Welcome Screen select Create New Project.
  • A New Project wizard will be shown. Select Maven on the Sidebar, check the Create from archetype check box and select maven-archetype-quickstart.
Maven Project From Archetype

Maven Project From Archetype

  • Press the Next button to continue.
  • In the next screen you can enter the Maven project information details including the GroupId, ArtifactId, and Version.
Maven Project Information

Maven Project Information

  • Press the Next button to continue.
  • In this screen you can override any Maven configuration setting if you want. And you also see the summary of Maven project to be created. We do not modify the setting in this screen.
Maven Project Summary

Maven Project Summary

  • Press the Next button to continue.
  • In the final screen we input the Project name and Project location directory.
  • After you input these two information, click the Finish button to generate the Maven project in IntelliJ IDEA.
Maven Project Name and Location

Maven Project Name and Location

  • Finally, you have the Maven project created in IntelliJ IDEA.
  • This is the Maven project structure generated in IntelliJ IDEA.
Maven Project Structure

Maven Project Structure

Editing the pom.xml File

  • To use the MongoDB Java Driver in our Java application, the first thing we need to do is to add the dependency to MongoDB Java Driver in our pom.xml file.
  • Add the following dependency configuration to the pom.xml.
<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.12.10</version>
    </dependency>
</dependencies>

IntelliJ IDEA will download all the required dependency files from the Maven Central repository if they are not available in you local Maven repository. After configuring the Maven, we are now ready to create a simple program to find a single collection from the MongoDB database.

If you are following the last post about installing and running MongoDB that I have mention in the beginning of this article you know that we have a peopledb and persons collections in our MongoDB database. Now we are going to read it using the MongoDB Java Driver in our Java application. So lets now create the application.

Create Java A Simple MongoDB Client

  • We create our class under the org.kodejava.mongodb package. Right-click on this package and choose New, Java Class to create a new class.
  • Type in the class name MongoDBHelloWorld, and press OK button.
  • And this is the full code snippet for the MongoDBHelloWorld class.
package org.kodejava.mongodb;

import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Objects;

public class MongoDBHelloWorld {
    public static void main(String[] args) {
        // Creates a new instance of MongoDBClient and connect to localhost
        // port 27017.
        MongoClient client = new MongoClient(
                new ServerAddress("localhost", 27017));

        // Gets the peopledb from the MongoDB instance.
        MongoDatabase database = client.getDatabase("peopledb");

        // Gets the persons collections from the database.
        MongoCollection<Document> collection = database.getCollection("persons");

        // Gets a single document / object from this collection.
        Document document = collection.find().first();

        // Prints out the document.
        System.out.println(Objects.requireNonNull(document).toJson());
    }
}
  • If you run this code, you will get the following output printed on the screen.
{"_id": {"$oid": "61910b09dd20c0a0d8f686cd"}, "firstName": "John", "lastName": "Doe", "cityOfBirth": "New York"}
  • This is the JSON document that we’ve store in our peopledb in the MongoDB database.

The Java class above is our first example of how to use the MongoDB Java Driver to access and read a document from the MongoDB database. I hope this example can be a good start for us to learn more about MongoDB. If you have any question, just submit it in the comment section below this article. See you on the next post. Thank you!

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.12.11</version>
    </dependency>
</dependencies>

Maven Central

Creating a simple project using Maven

In this post you will learn how to create a simple project, a Hello World project using Maven. If you haven’t installed Maven in your machine you can read Introduction to Apache Maven posted earlier in this blog. In this post you will see what the basic configuration for creating a maven project. Such as the basic of pom.xml file and how maven structure the directory of our project files.

At this time we won’t use any special IDE such as Eclipse, Netbeans or IntelliJ to create our project. We’ll just work using a simple text editor and the command prompt. Let us begin.

Step 1 – Create a project directory and the pom.xml file.

  • Create a directory where you will place the project files. As an example I’ll create my project in D:\Projects\HelloWorld.
  • Create a file called pom.xml in the HelloWorld directory. POM stands for Project Object Model, and it represents a Maven project.
  • Type the following information in the pom.xml file.
<project>
    <groupId>org.kodejava</groupId>
    <artifactId>HelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <modelVersion>4.0.0</modelVersion>
</project>
  • At this point we have our pom.xml file created. What you’ve seen above is the simplest example of a pom file. And here is a brief description of the pom file above:
    • groupId: the unique id of a Maven project. Typically, it uses your company name domain in reverse order just like how you would create a package for your Java project. For example here I use org.kodejava.
    • artifactId: is the name of the project, we’ll be using HelloWorld.
    • version: is the version number of our project.
    • packaging: the project artifact type. In this case we will ask Maven to package our example as a jar file.
    • modelVersion: is the version of the POM file we are using for this project.

Maven works by applying a concept called convention over configuration. This will apply for example on how the directory of a project is structured. All Maven project will use the same directory for organising the files in the project. There is a directory for Java source codes, unit testing codes, configuration files, etc. This will make easier for developer to jump from one Maven project to the other projects. Now let us continue to the next step.

Step 2 – Create the HelloWorld class.

  • Create a directory for Java source code in the project root directory. Actually you’ll create three directories. These directories are src\main\java.
  • Create a file HellWorld.java under the java directory you’ve created above.
  • Type the following code for the HelloWorld class.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
  • Now we have our class created we can start to use maven to build our project. But before we do let see what you should have after finishing these steps. You should see that you have a project structure that similar the screen capture below:

Maven HelloWorld

Steps 3 – Compiling the Project.

At this time we have our first Maven project created, and we are ready to build it. To build this basic project we don’t have to add anything to Maven. It already comes with a predefined sets of build related task such as clean, compile, test, package, etc.

  • Open a Command Prompt and go to your project directory. You should be in the HelloWorld directory where you can see the pom.xml file.
  • To compile your project type mvn compile in the command prompt.
D:\Projects\HelloWorld>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Compiling 1 source file to D:\Projects\HelloWorld\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.405s
[INFO] Finished at: Tue Sep 24 10:18:10 CST 2013
[INFO] Final Memory: 7M/23M
[INFO] ------------------------------------------------------------------------
D:\Projects\HelloWorld>
  • What you see above is the typical result of a success build. You might see longer message such as information about the artifact downloaded by Maven during the compile process.
  • If you list the project directory you’ll see a new directory called targetclasses is created. And inside the classes directory you’ll find your HelloWorld.class file.
  • To run the class cd to targetclasses and type java HelloWorld.

Steps 4 – Clean and Package the Project.

  • Now if you want to clean your previous built project you can use mvn clean. Make sure you are executing this command from the project root directory where the pom.xml file is located.
  • Executing this command will give you the similar output like this.
D:\Projects\HelloWorld>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ HelloWorld ---
[INFO] Deleting D:\Projects\HelloWorld\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.353s
[INFO] Finished at: Tue Sep 24 10:29:16 CST 2013
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
D:\Projects\HelloWorld>
  • As you can see it deleted the previously created target directory.
  • In the pom.xml file we have defined the packaging of our project as jar file. So let’s create it now.
  • To package a Maven project type mvn package command.
D:\Projects\HelloWorld>mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Compiling 1 source file to D:\Projects\HelloWorld\target\classes
[INFO] skip non existing resourceDirectory D:\Projects\HelloWorld\src\test\resources
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ HelloWorld ---
[INFO] No sources to compile
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ HelloWorld ---
[INFO] No tests to run.
[INFO] Surefire report directory: D:\Projects\HelloWorld\target\surefire-reports
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ HelloWorld ---
[INFO] Building jar: D:\Projects\HelloWorld\target\HelloWorld-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.040s
[INFO] Finished at: Tue Sep 24 10:32:41 CST 2013
[INFO] Final Memory: 8M/20M
[INFO] ------------------------------------------------------------------------
D:\Projects\HelloWorld>
  • The mvn package gives you a longer console output. From the output above you can see that executing the package command made Maven to compile the Java source code, unit test source code (we don’t have it at this time). It also runs the unit test and finally build the jar file.
  • The jar file is created under the target directory and named HelloWorld-1.0-SNAPSHOT.jar. The name comes from the artifactId, version and packaging information defined in the pom.xml file.

That are all the steps that you need to create and manage a simple project using Maven. We start by creating a pom.xml file and then create a directory structure for storing our classes file. And then we learn how to compile, clean and package our Maven project. In the next Maven post we’ll learn more on Maven dependency management and starting to use an IDE to set up our Maven project.

Thank your for reading and see you on the next Maven post.

Introduction to Apache Maven

In this post you will learn about Apache Maven. What is Maven? In simple words, Maven is a tool that we can use to build and manage a Java based project. Compare to the older type of build tool such as Ant, which is also an Apache project, Maven gives developers a standard way to build projects, a clear definition of the projects consisted of, an easy way to publish project information and an easy management of the project libraries dependency.

In Maven, the project libraries (Jars) will be maintained in the Maven repository and can be shared among projects. We don’t need to include the Jars in the project’s source code, as what we usually do when using tool like Ant. And here are the main objectives of the Apache Maven project:

  • Making the build process easy.
  • Providing a uniform build system.
  • Providing quality project information.
  • Providing guidelines for best practices development.
  • Allowing transparent migration to a new features.

After you know a little about Maven, let’s continue to the next step, installing the Apache Maven.

Step 1. Downloading Apache Maven

  • Go to Apache Maven and from the Get Maven section on the left sidebar click Download link.
  • Download the appropriate installer for your platform. For example, I am downloading the .zip file. The latest version when this post is written is Maven 3.1.0 (apache-maven-3.1.0-bin.zip).
  • Extract the downloaded zip file. For example, I am extracting it into D:\Toolbox\apache-maven-3.1.0 directory.

Step 2. Configuring Environment Variables

  • After extracting Maven distribution you have to define M2_HOME environment variable. The value of this variable is the path to your Maven installation.
  • You can create environment variable using the following steps:
    • Right click on My Computer.
    • Select Properties menu.
    • Select Advanced system settings.
    • In the System Properties window select the Advanced tab and click the Environment Variables button.
    • Add the variable in the System variables section.
    • Click OK to proceed.
  • Add the %M2_HOME%\bin; into your PATH environment variable so that you can execute Maven command from any path inside your command prompt. This PATH variable can also be updated in the System variables section.

  • Open your command prompt and type echo %M2_HOME%. Pressing Enter and you should see the value of the variable printed on the console. For example:
D:\>echo %M2_HOME%
D:\Toolbox\apache-maven-3.1.0
  • To check if Maven also in your Path variable you can execute echo %PATH% in your command prompt. You should see the path to Maven binary in the Path variable.
D:\>echo %PATH%
D:\Toolbox\apache-maven-3.1.0\bin;C:\Program Files (x86)\Java\jdk1.7.0_13\bin;

Step 3. Running Maven

  • Now you have Maven installed and configured. Let’s run Maven for the first time.
  • To run Maven we use the mvn command.
  • For example to check the version of the Maven we run mvn -version
  • You will see the following output, more or less, it depends on the JDK version you have in your machine.
D:\>mvn -version
Apache Maven 3.1.0 (893ca28a1da9d5f51ac03827af98bb730128f9f2; 2013-06-28 10:15:32+0800)
Maven home: D:\Toolbox\apache-maven-3.1.0
Java version: 1.7.0_13, vendor: Oracle Corporation
Java home: C:Program Files (x86)\Java\jdk1.7.0_13\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"

Congratulations! You’ve installed Apache Maven successfully on your development machine. On the next post I will show you how to create a new project using Maven.