Java Code to Zip all folders in a particular folder.

A small utility code to create multiple zip files for all folders in the a particular folder.

for example

- c:/path/to/folder
    -> folder 1
    -> folder 2
    -> folder 3
    -> folder 4

Output:

- c:/path/to/folder
    -> folder 1
    -> folder 2
    -> folder 3
    -> folder 4
    -> folder 1.zip
    -> folder 2.zip
    -> folder 3.zip
    -> folder 4.zip

original source: https://goo.gl/sp0bqr

LDAP Connector

Below is a sample code to perform LDAP Queries. Just modify the configuration information and then provide any valid query to get the search results.

You can also modify the code to get custom business logic as required.

 

Apache Ignite: What is Ignite?

Apache Ignite(TM) In-Memory Data Fabric is a high-performance, integrated and distributed in-memory platform for computing and transacting on large-scale data sets in real-time, orders of magnitude faster than possible with traditional disk-based or flash-based technologies.

apache-ignite

FEATURES

You can view Ignite as a collection of independent, well-integrated, in-memory components geared to improve performance and scalability of your application. Some of these components include:


Apache Ignite APIs

Apache Ignite has a reach set of APIs that are covered throughout the documentation. The APIs are implemented in a form of native libraries for such major languages and technologies as Java, .NET and C++ and by supporting a variety of protocols like REST, Memcached or Redis.

The documentation that is located under this domain is mostly related to Java. Refer to the following documentation sections and domains to learn more about alternative technologies and protocols you can use to connect to and work with an Apache Ignite cluster:

Fork It on GIT

Apache Commons DbUtils Mini Wrapper

This is a very small DB Connector code in Java as a wrapper class to Apache DBUtils.

The Commons DbUtils library is a small set of classes designed to make working with JDBC easier. JDBC resource cleanup code is mundane, error prone work so these classes abstract out all of the cleanup tasks from your code leaving you with what you really wanted to do with JDBC in the first place: query and update data.

Some of the advantages of using DbUtils are:

  • No possibility for resource leaks. Correct JDBC coding isn’t difficult but it is time-consuming and tedious. This often leads to connection leaks that may be difficult to track down.
  • Cleaner, clearer persistence code. The amount of code needed to persist data in a database is drastically reduced. The remaining code clearly expresses your intention without being cluttered with resource cleanup.
  • Automatically populate Java Bean properties from Result Sets. You don’t need to manually copy column values into bean instances by calling setter methods. Each row of the Result Set can be represented by one fully populated bean instance.

DbUtils is designed to be:

  • Small – you should be able to understand the whole package in a short amount of time.
  • Transparent – DbUtils doesn’t do any magic behind the scenes. You give it a query, it executes it and cleans up for you.
  • Fast – You don’t need to create a million temporary objects to work with DbUtils.

DbUtils is not:

  • An Object/Relational bridge – there are plenty of good O/R tools already. DbUtils is for developers looking to use JDBC without all the mundane pieces.
  • A Data Access Object (DAO) framework – DbUtils can be used to build a DAO framework though.
  • An object oriented abstraction of general database objects like a Table, Column, or Primary Key.
  • A heavyweight framework of any kind – the goal here is to be a straightforward and easy to use JDBC helper library.

Wrapper:

How to determine which jar a class is loaded from?

When the method that contains this sniplet is called, it will print out something like:

file://path/to/deployment/lib/detected.jar

Will the codeSource be null? The answer is yes. When a jar file is loaded by the system class loader, it’s codeSource will be null. What jars will be loaded by the system class loader? the rule of thumb is that all the jars in the class path (not the ones you package in your application) will be loaded by the system class loader. Obviously the above code can’t used to find out which jar a class is loaded from, if the jar is loaded by the system class loader. You can use the “verbose” java command line argument when you start the application:

java -verbose app

it will print out every class in each jar the system class loader loads, ie:

[Opened C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.lang.Object from C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.io.Serializable from C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.lang.Comparable from C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.lang.CharSequence from C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.lang.String from C:\dev\bea\JDK160~1\jre\lib\rt.jar]
[Loaded java.lang.reflect.GenericDeclaration from C:\dev\bea\JDK160~1\jre\lib\rt.jar]

Source

Unirest: Lightweight HTTP Request Client Libraries

UniRest

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by the Mashape team.

Unirest.post("http://httpbin.org/post")
  .queryString("name", "Mark")
  .field("last", "Polo")
  .asJson()

Features

  • Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
  • Both syncronous and asynchronous (non-blocking) requests
  • It supports form parameters, file uploads and custom body entities
  • Easily add route parameters without ugly string concatenations
  • Supports gzip
  • Supports Basic Authentication natively
  • Customizable timeout, concurrency levels and proxy settings
  • Customizable default headers for every request (DRY)
  • Customizable HttpClient and HttpAsyncClient implementation
  • Automatic JSON parsing into a native object for JSON responses
  • Customizable binding, with mapping from response body to java Object

Installing

Is easy as pie. Kidding. It’s about as easy as doing these little steps:

With Maven

You can use Maven by including the library:

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.7</version>
</dependency>

There are dependencies for Unirest-Java, these should be already installed, and they are as follows:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpasyncclient</artifactId>
  <version>4.0.2</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

If you would like to run tests, also add the following dependency along with the others:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
  <scope>test</scope>
</dependency>

Without Maven

Alternatively if you don’t use Maven, you can directly include the JAR file in the classpath:http://oss.sonatype.org/content/repositories/releases/com/mashape/unirest/unirest-java/1.4.7/unirest-java-1.4.7.jar

Don’t forget to also install the dependencies (org.json, httpclient 4.3.6, httpmime 4.3.6,httpasyncclient 4.0.2) in the classpath too.

There is also a way to generate a Unirest-Java JAR file that already includes the required dependencies, but you will need Maven to generate it. Follow the instructions at http://blog.mashape.com/post/69117323931/installing-unirest-java-with-the-maven-assembly-plugin

Creating Request

So you’re probably wondering how using Unirest makes creating requests in Java easier, here is a basic POST request that will explain everything:

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .field("parameter", "value")
  .field("foo", "bar")
  .asJson();

Requests are made when as[Type]() is invoked, possible types include Json, Binary, String, Object.

If the request supports and it is of type HttpRequestWithBody, a body it can be passed along with.body(String|JsonNode|Object). For using .body(Object) some pre-configuration is needed (see below).

If you already have a map of parameters or do not wish to use seperate field methods for each one there is a.fields(Map<String, Object> fields) method that will serialize each key – value to form parameters on your request.

.headers(Map<String, String> headers) is also supported in replacement of multiple header methods.

Full Documentation @ unirest.io

jSoup: Java HTML Parser

jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.

jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.

  • scrape and parse HTML from a URL, file, or string
  • find and extract data, using DOM traversal or CSS selectors
  • manipulate the HTML elements, attributes, and text
  • clean user-submitted content against a safe white-list, to prevent XSS attacks
  • output tidy HTML

jsoup is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; jsoup will create a sensible parse tree.

Example

Fetch the Wikipedia homepage, parse it to a DOM, and select the headlines from theIn the news section into a list of Elements (online sample):

Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");

Open source

jsoup is an open source project distributed under the liberal MIT license. The source code is available at GitHub.

Getting started

  1. Download the jsoup jar (version 1.8.3)
  2. Read the cookbook introduction
  3. Enjoy!

Resources

Code to merge list of PDFs using Itext Library

Here is the code to merge and output a single pdf from a set of PDFs in a folder.

In order to run and get the output just pass the folder path in the main method and the output will be saved in the same folder as the files.

Please share comments…:)

How to read a properties file in a web application

Let’s consider that you have a war file named SampleApp.war which has a properties file named MyApp.properties at it’s root

SampleApp.war
   |- myApp.properties
   |- WEB-INF
     |- classes
       |- org
          |- myApp
          |- MyPropertiesReader.class


Here root folder in war is equivalent to Source Folder in Netbeans.
That means you have to keep your properties file in default package of your Source Files folder.
Let’s assume that you want to read the property named “abc” present in the properties file:


myApp.properties:

abc=some value
xyz=some other value

Let’s consider that the class org.myApp. MyPropertiesReader present in your application wants to read the property. Here’s the code for the same:

package org.myapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyPropertiesReader {

    public MyPropertiesReader() {
    }

    public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }
}

Now suppose the properties file is not at the root of the application, but inside a folder (let’s name it config) in the web application, something like:

SampleApp.war
   |- config
    |- myApp.properties   
   |- WEB-INF
    |- classes
      |- org
         |- myApp
           |- MyPropertiesReader.class

There will just be one line change in the above code:

public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("config/myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }

 

Source