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 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:

HackerEarth: Battle Of Bots 6: Draughts

Problem:

Sample Game

Draughts is a two player board game which is played on a 8X8 grid of cells and is played on opposite sides of the game-board. Each player has an allocated color, Red ( First Player ) or White ( Second Player ) being conventional. Players take turns involving diagonal moves of uniform game pieces in the forward direction only and mandatory captures by jumping over opponent pieces.

Rules:

  • Player can only move diagonally to the adjacent cell and in forward direction, if the diagonally adjacent cell is vacant.
  • A player may not move an opponent’s piece.
  • If the diagonally adjacent cell contains an opponent’s piece, and the cell immediately beyond it is vacant, the opponent’s piece may be captured (and removed from the game) by jumping over it in the forward direction only.
  • If a player made a jump, then its mandatory to keep on jumping as long as the jump is possible.
  • Player cannot move to the diagonally adjacent cell once the player made a jump.

The game will end when any of the players don’t have any move left. At the end of the game the player with majority of pieces will win.

We will play it on an 8X8 grid. The top left of the grid is [0,0] and the bottom right is [7,7].

Input:
The input will be a 8X8 matrix consisting only of 0o2. Then another line will follow which will contain a number –  1 or 2 which is your player id. In the given matrix, top-left is [0,0] and bottom-right is [7,7]. The x-coordinate increases from left to right, and y-coordinate increases from top to bottom.

The cell marked 0 means it doesn’t contain any stones. The cell marked 1 means it contains first player’s stone which is Red in color. The cell marked 2 means it contains second player’s stone which is white in color.

Output:
In the first line print the coordinates of the cell separated by space, the piece he / she wants to move.
In second line print an integer N, number of steps or jumps the piece will make in one move.
In the next N lines print the coordinates of the cells in which the piece will make jump.
You must take care that you don’t print invalid coordinates. For example, [1,1] might be a valid coordinate in the game play if [1,1] in diagonal to the piece in which is going to jump, but [9,10] will never be. Also if you play an invalid move or your code exceeds the time/memory limit while determining the move, you lose the game.

Starting state
The starting state of the game is the state of the board before the game starts.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 2 0 2 0 2 0 2
2 0 2 0 2 0 2 0

First Input
This is the input give to the first player at the start of the game.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 2 0 2 0 2 0 2
2 0 2 0 2 0 2 0
1
SAMPLE INPUT
0 1 0 1 0 1 0 1
1 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0
0 0 2 0 0 0 0 0
0 0 0 2 0 0 0 2
2 0 2 0 2 0 2 0
1
SAMPLE OUTPUT
2 5
2
4 3
6 1

Explanation

This is player 1’s turn, and the player will move the piece at [2,5] and will make two jumps. First jump will be at [4,3and second jump will be at [6,1]

After his/her move the state of game becomes:

0 1 0 1 0 1 0 1
1 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 2 0 2 0 2
2 0 2 0 2 0 2 0

This state will be fed as input to program of player 2.

Other valid move for the first player is

2 5
1
3 6

But the following are invalid moves.
Case 1:

2 5
1
4 3

Because after making a jump its possible to jump again and its mandatory to jump as long as its possible to jump.

Case 2:

2 5
2
4 3
5 4

Because after making a jump its invalid to move to diagonally adjacent cell.

Here is the code of the Random Bot.

Time Limit:1.0 sec(s) for each input file.
Memory Limit:256 MB
Source Limit:1024 KB

Solution

This is the solution submitted by me

Apache Solr vs Elasticsearch: The Feature Smackdown

API

Feature Solr 5.3.0 ElasticSearch 2.0
Format XML,CSV,JSON JSON
HTTP REST API
Binary API SolrJ TransportClient, Thrift (through a plugin)
JMX support ES specific stats are exposed through the REST API
Official client libraries Java Java, Groovy, PHP, Ruby, Perl, Python, .NET, JavascriptOfficial list of clients
Community client libraries PHP, Ruby, Perl, Scala, Python, .NET, Javascript, Go, Erlang, Clojure Clojure, Cold Fusion, Erlang, Go, Groovy, Haskell, Java, JavaScript, .NET, OCaml, Perl, PHP, Python, R, Ruby, Scala, Smalltalk, Vert.x Complete list
3rd-party product integration (open-source) Drupal, Magento, Django, ColdFusion, WordPress, OpenCMS, Plone, Typo3, ez Publish, Symfony2, Riak (via Yokozuna) Drupal, Django, Symfony2, WordPress, CouchBase
3rd-party product integration (commercial) DataStax Enterprise Search, Cloudera Search, Hortonworks Data Platform, MapR SearchBlox, Hortonworks Data Platform, MapR etcComplete list
Output JSON, XML, PHP, Python, Ruby, CSV, Velocity, XSLT, native Java JSON, XML/HTML (via plugin)

Infrastructure

Feature Solr 5.3.0 ElasticSearch 2.0
Master-slave replication Only in non-SolrCloud. In SolrCloud, behaves identically to ES. Not an issue because shards are replicated across nodes.
Integrated snapshot and restore Filesystem Filesystem, AWS Cloud Plugin for S3 repositories, HDFS Plugin for Hadoop environments, Azure Cloud Plugin for Azure storage repositories

Indexing

Feature Solr 5.3.0 ElasticSearch 2.0
Data Import DataImportHandler – JDBC, CSV, XML, Tika, URL, Flat File [DEPRECATED in 2.x] Rivers modules – ActiveMQ, Amazon SQS, CouchDB, Dropbox, DynamoDB, FileSystem, Git, GitHub, Hazelcast, JDBC, JMS, Kafka, LDAP, MongoDB, neo4j, OAI, RabbitMQ, Redis, RSS, Sofa, Solr, St9, Subversion, Twitter, Wikipedia
ID field for updates and deduplication
DocValues
Partial Doc Updates with stored fields with _source field
Custom Analyzers and Tokenizers
Per-field analyzer chain
Per-doc/query analyzer chain
Synonyms Supports Solr and Wordnet synonym format
Multiple indexes
Near-Realtime Search/Indexing
Complex documents
Schemaless 4.4+
Multiple document types per schema One set of fields per schema, one schema per core
Online schema changes Schemaless mode or via dynamic fields. Only backward-compatible changes.
Apache Tika integration
Dynamic fields
Field copying via multi-fields
Hash-based deduplication Murmur plugin or ER plugin

Searching

Feature Solr 5.3.0 ElasticSearch 2.0
Lucene Query parsing
Structured Query DSL Need to programmatically create queries if going beyond Lucene query syntax.
Span queries via SOLR-2703
Spatial/geo search
Multi-point spatial search
Faceting Top N term accuracy can be controlled with shard_size
Advanced Faceting New JSON faceting API blog post
Geo-distance Faceting
Pivot Facets
More Like This
Boosting by functions
Boosting using scripting languages
Push Queries JIRA issue Percolation. Distributed percolation supported in 1.0
Field collapsing/Results grouping
Spellcheck Suggest API
Autocomplete
Query elevation workaround
Joins Joined index has to be single-shard and replicated across all nodes. via has_children and top_children queries
Resultset Scrolling New to 4.7.0 via scan search type
Filter queries also supports filtering by native scripts
Filter execution order local params and cache property
Alternative QueryParsers DisMax, eDisMax query_string, dis_max, match, multi_match etc
Negative boosting but awkward. Involves positively boosting the inverse set of negatively-boosted documents.
Search across multiple indexes it can search across multiple compatible collections
Result highlighting
Custom Similarity
Searcher warming on index reload Warmers API
Term Vectors API

Customizability

Feature Solr 5.3.0 ElasticSearch 2.0
Pluggable API endpoints
Pluggable search workflow via SearchComponents
Pluggable update workflow
Pluggable Analyzers/Tokenizers
Pluggable Field Types
Pluggable Function queries
Pluggable scoring scripts
Pluggable hashing
Pluggable webapps site plugin
Automated plugin installation Installable from GitHub, maven, sonatype or elasticsearch.org

 

Full article

HackerRank: Manasa and Stones

Problem

Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that two consecutive stones have a difference of either a or b. Legend has it that there is a treasure trove at the end of the trail and if Manasa can guess the value of the last stone, the treasure would be hers. Given that the number on the first stone was 0, find all the possible values for the number on the last stone.

Note: The numbers on the stones are in increasing order.

Input Format
The first line contains an integer T, i.e. the number of test cases. T test cases follow; each has 3 lines. The first line contains nn (the number of stones). The second line contains a, and the third line contains b.

Output Format
Space-separated list of numbers which are the possible values of the last stone in increasing order.

Constraints
1T10
1n,a,b10^3

Sample Input

2
3 
1
2
4
10
100

Sample Output

2 3 4 
30 120 210 300 

Explanation

All possible series for the first test case are given below:

  1. 0,1,2
  2. 0,1,3
  3. 0,2,3
  4. 0,2,4

Hence the answer 2 3 4.

Series with different number of final steps for second test case are the following:

  1. 0, 10, 20, 30
  2. 0, 10, 20, 120
  3. 0, 10, 110, 120
  4. 0, 10, 110, 210
  5. 0, 100, 110, 120
  6. 0, 100, 110, 210
  7. 0, 100, 200, 210
  8. 0, 100, 200, 300

Hence the answer 30 120 210 300.

Solution

Original solution source

Unable to find valid certification path to requested target

Most of you must be familiar with the below exception message:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

When trying to open an SSL connection to a host using Java.

Sample Code(source):

What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy.

Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.

To bypass this issue and be able to get the contents of a HTTPS url here is the steps:

First: use the below class code to install the required certificates(Source):

I was testing this on wikipedia.org, which is on https, thus facing the https issue.
You can modify the same as per requirement.

Next, set the following arguments while running JVM(source):

-Djavax.net.ssl.trustStore=<local path to certs>/jssecacerts

Next use the below code to get the contents(Source):

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

Oracle ADF Features

Oracle Application Development Framework (Oracle ADF) is an advanced Rapid Application Development(RAD) Framework for J2EE applications mainly targeted for B2B Applications.

It is a proprietary software maintained by Oracle in 3 flavors:

Features-

  • RAD Framework with most commonly used components of any Front End Application available as inbuilt feature
  • Model-View-Controller (MVC) design pattern and offers an integrated solution that covers all the layers of this architecture with solution to such areas as:
    • ORM and Data Persistence
    • Reusable Task-flow approach,
    • Rich Web user interface elements,
    • Data binding to UI,
    • Security
    • Customization via sandboxes etc
  • Separation of Business Logic implementation details, via metadata and use of this metadata-driven architecture enables developers to focus on the business logic and user experience.
  • Drag-n-Drop features, via JDeveloper IDE, provides the ease to use and customize.
  • ADF Skin Editor: New ADF Skin editor for visually creating and modifying the appearance of ADF Faces applications.(JDeveloper 11G and above)
  • JSF 2.0: JSF 2.0 support in the IDE and for ADF applications. (JDev 11g R2 release)
  • ADF Faces and Data Visualization Tools (DVT) support touch gestures for interactivity on the touch-enabled devices, such as touch support for drag and drop, tooltips, data tips, and context menus.
  • ADF Faces and DVT components are certified on iPad. Additionally, ADF DVT Graph and Gauge components support rendering in HTML5.
  • MDS is metadata service that is used to store metadata information. When you use ADF, it generates lot of internal files about its own components and DB binding details. All these are stored internally by ADF into MDS.
  • ADS (Active Data service)- This is used in ADF to push any data changes automatically from the back end into the portal layer. This is different from Ajax which is used to send request from UI to data service layer.

How to create multilevel menu’s in JSP using recursion..

There was a requirement where in I need to create multi-level menu’s in a JSP

A role has certain set of Privileges.
Each privilege may or may not have child privileges..

Where Privilege has child privileges, it was desired to display a sub menu..

So this is how I have achieved…
First thing you need to know about this is how to create multi level menu’s using HTML and CSS.
(http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html)

and once you learn that you’ll have to use recursion in JSP to achieve the above requirement.

I’ll just put the core logic here which is the base of this..

Create a parent jsp (lets say LoginSuccess.jsp)

Create a showPrivileges.jsp as follows:








Example of Decorator Pattern – LowerCaseInputStream

Create a LowerCaseInputStream class as follows

public class LowerCaseInputStream extends FilterInputStream 
{

    public LowerCaseInputStream(InputStream in) {
        super(in);
    }
    
    @Override
    public int read() throws IOException
    {
        int c = super.read();
        if(c==-1)
            return c;
        else
            return Character.toLowerCase(c);
    }
    @Override
    public int read(byte b[], int offset, int len) throws IOException
    {
        int result = super.read(b, offset, len);
        for (int i = offset; i < offset+result; i++) 
        {
            b[i] = (byte)Character.toLowerCase((char)b[i]);
        }      
        return result;
    }
    
}

Use LowerCaseInputStream as follows

public static void main(String[] args) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("D:\Yogesh.txt");
        BufferedInputStream bufin = new BufferedInputStream(fis);
        InputStream in = new LowerCaseInputStream(bufin);
        int c;
        try
        {
            while((c=in.read())!=-1)
            {
                System.out.print((char)c);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
            
    }

Find it really interesting? You can read more about Decorator pattern in Head First Design Pattern book.