Code to Encrypt Folder Structure Completely

Below is the code to encrypt/decrypt complete folder structure in java

The Code takes 3 parameters:

  • in: String: input path of the folder that u want to encrypt
  • password: String: Used to encrypt/decrypt the files
  • output: String: Folder path in which u wish to publish the encrypted/decrypted files

Code to Download File from URL in Java

Below is the code to download the complete contents of a URL to your local hard drive.

//IMPORTS
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.io.File;
METHOD CODE
    private static void download(String url) throws IOException {

        String fileName="Path\to\File.extn";//The file that will be saved on your computer
        
        URL link = new URL(url); //The file that you want to download

        //Code to download
        InputStream in = new BufferedInputStream(link.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[2048];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
            System.out.print("|");//Progress Indicator
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();

        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(response);
        fos.close();
        //End download code
        System.out.println("#");

    }

Note: For large file downloads, the JVM may throw OutOfMemoryError

How to Decompile Class/Jar Files

For Decompiling Java Classes or Complete Jar files, JD-GUI is very useful.

Download Link

jd-gui#1

jd-gui#2

 

Since it is Open Source, no worries for Licencing fees as well

Insert Rows in ADF View Object Programatically

Suppose that I have EmpVO view object which have below attributes
EmpId, FirstName, LastName

We can do inserting rows by two ways in data model layer (Application Model or View Object classes)
I will write my code in ApplicationModuleImpl class

try
{
    ViewObject vo=this.getEmpVO();
    Row r=vo.createRow();
    r.setAttribute("EmpId","id#1");
    r.setAttribute("FirstName","fn#1");
    r.setAttribute("LastName","ln#1");
    vo.insertRow(r);
    this.getDBTransaction().commit();
}catch(Exception e){
    e.printStackTrace();
}

When and how much to mix technologies for a project?

The main idea behind using a technology is to harness the power of code re-usability and libraries that have already been worked on and trusted to be working and functional with minimal or no issues.

The term “Technology” does not just refer to Java or C++ or JavaScript. It also refers to the frameworks that can be used to suffice some or the other requirements with minimum cost and minimal effort investment. One example can be any Application Development Framework Like Oracle ADF, Pega or Drupal, etc. The framework itself provides functionalities that are most common and also takes cares of the issues that people face while developing an application.

Any application which has to be developed from scratch needs a lot of work just to be useful enough to be used in Production environment. Basic Non-functional requirements such as MVC Architecture, Security safeguards, Application Performance, etc. are the basic and most common features of the application. In addition, Secure Login, User Registration and authentication, role mapping and similar features are also mandatory features of the application.

Most frameworks provide features such as configurable work flows, built in UI Elements, security aspects and many other features. Features such as SQL Escaping, HTML Tag Escaping and MVC Pattern architecture are generally already inbuilt to the framework. The developers can simply configure the workflows, create screens and corner out application logic and then the application is good to go.

But is that enough that we may need??

This the main question that we need to ask when trying to select technologies and try to mix them to achieve the application requirement. The Case study can be a sample B-2-B Application say Business-2-Go (B2G).

Advantage of Techs to be selected:

The B2G can be based on 3 major technology products namely an Identity Management System, an Application Development Framework, and a Content Management Service. The technologies in combination provide the architecture to harness the features out of the box.

The IDM would provide Session Maintenance, Role Mappings, Access Authentications and invalid access handling.

CMS on the other hand takes care of the static content of the application. This technology handles the application content which needs to be configurable but would be changed in very rare scenarios. The main usefulness lies in the fact that the CMS portal can be exposed to the customer admin team as well and be comfortable as the code base will not be touched by the Non Development User.

The ADF constitutes to the application flow of the B2G. All user interactions and other business logic is handled by this technology. The flexibility of the framework helps create applications quickly and more efficiently than the older technologies/frameworks such as J2EE Servlets/JSP or struts and so on.

Further technologies like JavaScript, jQuery, CSS have been used to achieve the look and feel that was decided by the client.

Disadvantages of Techs to be selected:

The disadvantages or rather limitations of the tech or the team using the tech is the one that decides whether the tech can be used or not.

The major factors can be:

  • Cost: The technology that has been perfected and supported may be in most cases be licensed. Thus incurring costs to the budget of the project. The alternative may be using Open Source technologies/frameworks. But there the problem exists of the credibility of the source, issue support and whether documentation is enough or not.
  • Resource Availability: Assuming that the cost barrier of the license has been overcome. Now the major concern is whether the resources for the technology are available or not. If not, then can existing resources be trained or can new resources can be acquired. Again the cost factor is affected in this concern.
  • Technology Limitations: Technologies have limitations in themselves also. The limitation may not be a feature that cannot be achieved, but the effort that may be involved in achieving the feature. A simple example may be a particular look and feel of a B2G. Many of the UI Elements may or may not be achievable with the selected core ADF. Or even if they are achievable, it is after a lot of R&D or with lot of hit and trials. Though this is not something that may rule out the technology itself, but may be enough to include other technologies like jQuery into the picture.
  • Interfacing efforts: While mixing technologies, spots/hooks need to be found where 1 tech may latch on to or may be placed in with the other. For example, jQuery is an Independent Tech and in the selected ADF, generally has an internal client side scripts are functioning on its own end. There may be provisions which execute scripts that achieve the UI functionalities. Similarly the CMS may not have stable out of the box connectors to code layer of the application. Thus interfaces are written to implement make this possible. This effort may also turn out to be a concern for using a tech.

An example of tech selection may be PHP. The technology PHP can also be used for creating a complete application and 99% of the same application can be achieved using PHP frameworks. In fact the cost of the tech is 0 (Open Source) and resource costing would be way lower than those of licensed application framework. But the efforts and timescale needed to achieve all the functionalities required will be humongous. Thus ruling out the tech.

Another concern that can be raised is how much the technologies can be mixed. Surely each of the frameworks will be providing some or the other comfort or a feature. Even if they are published in open source or you may have license available. Does that mean that all technologies should be mixed..??

Interfacing technologies uses effort. It also invokes limitations. An example may be the various attempts to integrate popular front-end framework like AngularJS with Oracle ADF. Oracle ADF is a mainly a Server Side Technology, maintaining all functionalities server side and providing a wide palette of features for an application. AngularJS on the other hand is a completely UI framework. It is completely Client Side Intensive Tech. Both frameworks are completely in the opposite directions. Both are unaware of the other. There are blogs showing way how to integrate both the technologies. But all can point out the issues in the integration. This is a small example, but scaling this, similar issues may be faced and thus may be counted as factors in Tech Selection.

In Conclusion, the trade-offs govern the selections of the technologies to be used in a project. Proper selections must be made in order to plan out the architecture. Improper selection may lead to issues, crashes, late deliveries or redundant costs.

References:

Image: https://www.systrends.com/sites/default/files/banner/appdev_banner2.jpg

Util Method to get all attributes printed in System.out.println()

This small util override is to allow developers to view all instance variable values as a CSV format in Java. It is similar to the one seen as var_dump in PHP:

    @Override
    public String toString() {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder sbNote = new StringBuilder();
        sbNote.append("{");
        for (int i = 0; i < fields.length; i++) {
            try {
                sbNote.append(fields[i].getName() + " - " + fields[i].get(this)+", ");
            } catch (java.lang.IllegalAccessException e) {
                System.out.println(e);
            }
        }
        sbNote.append("}");
        return sbNote.toString();
    }

override the toString() method to the above code to get a comma separated description enclosed in {}

Another useful library is the Apache commons –

public String toString() {
       return ToStringBuilder.reflectionToString(this);
}

How to Left pad Zeros to integer to get String in Java

The below is the code as to how to add 0 Padding to the left of an integer to format it to string:

import java.text.DecimalFormat; 

public String padZeros(int i) { 
     DecimalFormat df = new DecimalFormat("00"); 
     return df.format(start); 
}

Change the Number format instead of “00” to any other format for getting more paddings.

How to do an LDAP Search of Various fields

Requirement: retrieving various values such as Description, Office, etc. from LDAP after authentication.

An LDAP client retrieves attribute values (referred to as “fields” in the question) by transmitting a search request to the server and then reading the server’s response. A search request consists of at a minimum the following components:

  • base DN – the object at which to begin the search. No objects above the base DN are returned
  • scope – the scope of the search; this is base, one, or subtree
  • filter – a filter which limits the entries that are returned by the server

Additionally, a list of requested attributes can be transmitted with the search request. Many LDAP SDKs will simply return all user attributes and no operational attributes if no requested attributes list is provided. In this case, request the attributes description and office and any others that are required.

LDAP-compliant servers enforce an access control scheme which might cause the server to not return certain attributes. Consult with the LDAP administrators to determine if the authentication state of the LDAP client connections have permission to access the attributes desired.

see also

  • LDAP: Using ldapsearch: this article refers to the ldapsearch command line tool, but the concepts are the same as for programmatic access.

Code Ref:

public boolean authenticate(String userid, String pass, String domain) {
        boolean retval = false;
        String searchFilter ="(&(objectClass=user)(" + LDAP_UID_ATTR + "=" + userid + "))";


        try {
            System.out.println("Start: getLDAPAttrs");
            NamingEnumeration answer =
                getLDAPAttrs(userid, pass, searchFilter, domain);
            String uid = "";

            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult)answer.next();

                Attributes attrs = sr.getAttributes();

                try {
                    uid = attrs.get(LDAP_UID_ATTR).toString();
                    System.out.println("uid: " + uid);
                    System.out.println(attrs.get("mail"));
                    uid = uid.substring(uid.indexOf(':') + 2);
                } catch (Exception err) {
//                    uid = "";
                    System.out.println(err.getMessage());
                    err.printStackTrace();
                }

                // verify userid
                if (userid.equalsIgnoreCase(uid)) {
                    retval = true;

                    break;
                }
            }
        } catch (NamingException ne) {
            System.out.println("In authenticateWithLDAP, LDAP Authentication NamingException : " +
                               ne.getMessage());
        } catch (Exception ex) {
            System.out.println("In authenticateWithLDAP, LDAP Authentication Exception : " +
                               ex.getMessage());
        }

        return retval;
        //        return retval;
    }

    private NamingEnumeration getLDAPAttrs(String userid, String pass,
                                           String searchFilter,
                                           String domain) throws NamingException,
                                                                 Exception {
        String host = getServerName();
        String port = getIP_Port();
        String dcPart1 = getDcPart1();
        String dcPart2 = getDcPart2();
//        String attrUserID = getLDAP_UID_ATTR();
//        String attrUserName = getLDAP_UNAME_ATTR();

        // set attribute names to obtain value of
        String[] returnedAtts = { "sAMAccountName", "cn","mail" };
        SearchControls searchCtls = new SearchControls();
        searchCtls.setReturningAttributes(returnedAtts);

        // specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // set search base
        String searchBase = "DC=" + dcPart1 + ",DC=" + dcPart2;

        // set ldap env values
        Hashtable environment = new Hashtable();
        environment.put(Context.INITIAL_CONTEXT_FACTORY,
                        "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, userid + "@" + domain);
        environment.put(Context.SECURITY_CREDENTIALS, pass);

        // set ldap context
        DirContext ctxGC = new InitialDirContext(environment);

        // perform search to obtain values
        NamingEnumeration answer =
            ctxGC.search(searchBase, searchFilter, searchCtls);
        return answer;
    }

Email Validation

CHALLENGE DESCRIPTION:

You are given several strings that may/may not be valid emails. You should write a regular expression that determines if the email id is a valid email id or not. You may assume all characters are from the english language.

INPUT SAMPLE:

Your program should accept as its first argument a filename. This file will contain several text strings, one per line. Ignore all empty lines. E.g.

foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com

OUTPUT SAMPLE:

Print out ‘true’ (all lowercase) if the string is a valid email. Else print out ‘false’ (all lowercase). E.g.

true
false
false
true

Solution:

import java.io.File;
import java.io.FileNotFoundException;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.startFileRead(args[0]);
    }

    public void startFileRead(String filePath) throws FileNotFoundException {
        File file = new File(filePath);


        if (file.exists()) {
            Scanner s = new Scanner(file);
            int n = 0;

            boolean tmp = false;
            while ((s.hasNextLine())) {
                tmp = EmailValidation(s.nextLine());
                System.out.println(tmp);
            }

        }
    }

    public boolean EmailValidation(String line) {
        Pattern pattern;
        Matcher matcher;
        String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(line);
        return matcher.matches();
    }
}

Swaps letters’ case in a sentence. All non-letter characters should remain the same.

INPUT SAMPLE:

Your program should accept as its first argument a path to a filename. Input example is the following

Hello world!
JavaScript language 1.8
A letter

OUTPUT SAMPLE:

hELLO WORLD!
jAVAsCRIPT LANGUAGE 1.8
a LETTER

Solution

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public Main() {
        super();
    }

    public static String reverseCase(String text) {
        char[] chars = text.toCharArray();
        for (int i = 0; i  0) {
                    System.out.println(Main.reverseCase(line));
                    ;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}