HackerRank: Sparse Arrays

Problem Statement

There are N strings. Each string’s length is no more than 2020 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.

Constraints

1N1000
1Q1000
1lengtof anstring20

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

Here, “aba” occurs twice, in the first and third string. The string “xzxb” occurs once in the fourth string, and “ab” does not occur at all.

Solution

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

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

Easy Rules: Java™ rules engine

Easy Rules is a Java rules engine inspired by an article called Should I use a Rules Engine? by Martin Fowler in which he says:

You can build a simple rules engine yourself. All you need is to create a bunch of objects with conditions and actions, store them in a collection, and run through them to evaluate the conditions and execute the actions.

Core features

  • Lightweight library and easy to learn API
  • POJO based development with annotation programming model
  • Useful abstractions to define business rules and apply them easily with Java
  • The ability to create composite rules from primitive ones
  • Dynamic rule configuration at runtime using JMX

Example

Hello World tutorial

This tutorial shows how to use Easy Rules in a very simple application. The goal is to ask the user if he is a friend of duke and says ‘Hello duke’s friend!’ only if he replies ‘yes’.

Based on this requirement, the rule is pretty straightforward :

  • The condition is that the user input must be equal to ‘yes’
  • The action is to say ‘Hello duke’s friend!’ to the user

First, let’s create a rule class:

@Rule(name = "Hello World rule",
    description = "Say Hello to duke's friends only")
public class HelloWorldRule {

    /**
     * The user input which represents the data
     * that the rule will operate on.
     */
    private String input;

    @Condition
    public boolean checkInput() {
        //The rule should be applied only if
        //the user's response is yes (duke friend)
        return input.equalsIgnoreCase("yes");
    }

    @Action
    public void sayHelloToDukeFriend() throws Exception {
        //When rule conditions are satisfied,
        //prints 'Hello duke's friend!' to the console
        System.out.println("Hello duke's friend!");
    }

    public void setInput(String input) {
        this.input = input;
    }

}

Then, we have to register an instance of this rule in a Easy Rules engine and launch the tutorial with the following class:

public class Launcher {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Are you a friend of duke?[yes/no]:");
        String input = scanner.nextLine();

        /**
         * Declare the rule
         */
        HelloWorldRule helloWorldRule = new HelloWorldRule();

        /**
         * Set business data to operate on
         */
        helloWorldRule.setInput(input.trim());

        /**
         * Create a rules engine and register the business rule
         */
        RulesEngine rulesEngine = aNewRulesEngine().build();

        rulesEngine.registerRule(helloWorldRule);

        /**
         * Fire rules
         */
        rulesEngine.fireRules();

    }
}

You would get the following output:

Are you a friend of duke? [yes/no]:
yes
INFO: Rule 'Hello World rule' triggered.
Hello duke's friend!
INFO: Rule 'Hello World rule' performed successfully.

Source

How to fix: Unsupported major.minor version xy.z error?

Occasionally in certain new environments using some libraries, we face the following Exception:

java.lang.UnsupportedClassVersionError: test_hello_world :
 Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
       .........................................

The problem here is about versions; some version of Java may be old or too new.

The version number shown describes the version of the JRE the class file is compatible with.

The reported major numbers are:

J2SE 8 = 52,
J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45

(Source: wiki)

To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.

With newer versions of the Java compiler you are likely to get a warning about the bootstrap class path not being set. More information about this error is available in blog post New javac warning for setting an older source without bootclasspath.

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.

Bubble Sort Algorithm

Below is the code to do Bubble Sorting in Java for integer values

public class BubbleSort {
  
    // logic to sort the elements
    public static void srtbubble(int array[]) {
        int n = array.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) { k = i + 1; if (array[i] > array[k]) {
                    swap(i, k, array);
                }
            }
            print(array);
        }
    }
  
    private static void swap(int i, int j, int[] array) {
  
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
  
    private static void print(int[] input) {
          
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }
  
    public static void main(String[] args) {
        int[] input = { 14, 21, 19, 62, 233, 142, 134, 10, 41 };
        srtbubble(input);
    }
}


Output:

14, 19, 21, 62, 142, 134, 10, 41, 233, 

14, 19, 21, 62, 134, 10, 41, 142, 233, 

14, 19, 21, 62, 10, 41, 134, 142, 233, 

14, 19, 21, 10, 41, 62, 134, 142, 233, 

14, 19, 10, 21, 41, 62, 134, 142, 233, 

14, 10, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233,