Monday, June 29, 2015

Invoking Secured Restful Web Services with HTTPS

Unable to Connect to SSL Services due to PKIX Path Building Failed sun.security.provider.certpath.SunCertPathBuilderException

Problem

Attempting to access URLs that are encrypted with SSL (for example HTTPS, LDAPS, IMAPS) throws an exception, below program will by pass the certificate and access the https data on the url.


package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.codec.binary.Base64;

public class HCSLDAPData {
private final String baseUrl;
private final String username;
private final String password;
private String hostName;

public HCSLDAPData(String baseUrl, String username, String password) {
this.baseUrl = baseUrl;
this.username = username;
this.password = password;
this.hostName = null;
}

public static void main(String args[]) {
String https_url = "https://198.18.133.254/api/v0/relation/HcsLdapServerREL/?policy_name=HcsLdapServerRelFDP&template_name=HcsLdapServerRelCFT&count=false&hierarchy=551cbc26acba0a1691197134&format=json";
new HCSLDAPData(https_url,"DCloudSPAdmin@dcloud.cisco.com", "C1sc0123").getHCSLdapData();
}

private TrustManager[ ] getTrustManager() {
TrustManager[ ] certs = new TrustManager[ ] {
new X509TrustManager() {
public X509Certificate[ ] getAcceptedIssuers() { return null; }
public void checkClientTrusted(X509Certificate[ ] certs, String t) { }
public void checkServerTrusted(X509Certificate[ ] certs, String t) { }
}
};
return certs;
}

private String getHCSLdapData() {
String https_url = this.baseUrl;
URL url;
try {
// Create a context that doesn't check certificates.
SSLContext ssl_ctx = SSLContext.getInstance("TLS");
TrustManager[ ] trust_mgr = getTrustManager();
ssl_ctx.init(null,           // key manager
trust_mgr,           // trust manager
new SecureRandom()); // random number generator
HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());

url = new URL(https_url);

this.hostName =  url.getHost();
System.out.println("Host Name: " + url.getHost());

HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
String authString = username + ":" + password;
String authStringEnc = new String(Base64.encodeBase64(authString.getBytes()));
con.setRequestProperty("Authorization", "Basic " + authStringEnc);

// Guard against "bad hostname" errors during handshake.
con.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String host, SSLSession sess) {
if(hostName != null) {
if (host.equals(hostName)) 
return true;
else 
return false;
} else {
return false;
}
}
});

//dumpl all cert info
displayHttpsConnectionSettings(con);

//dump all the content
return getCustoerLDAPData(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}

private void displayHttpsConnectionSettings(HttpsURLConnection con){
System.out.println("****** URL Specifications ********");
if(con!=null) {
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");

Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}   
}
System.out.println("****** URL Specifications ********");
}

private String getCustoerLDAPData(HttpsURLConnection con){
String ldapContent = null;
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br = 
new BufferedReader(
new InputStreamReader(con.getInputStream()));
ldapContent = br.toString();
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
System.out.println("****** Content of the URL ********");
br.close();
return ldapContent;
} catch (IOException e) {
e.printStackTrace();
}
}
return ldapContent;
}
}

Tuesday, June 23, 2015

Un-Root Original Samsung Firmware & Installing Android Lollipop 5.0.1 Samsung Galaxy Grand Duos GT-i9082.



This video is only for the users with new Samsung Galaxy Grand Duos GT-i902 with latest Jelly Bean Update and also it will fix the issue previously some users had with their Device while rooting that said “Warning: No Command”. The complete process takes around 20 to 30 minutes; I have executed same steps in two phones both were successfully updated to Lollipop 5.0.2.
Before going to start this process we need to download the following files.

Files required for Un-rooting Original Samsung Firmware.

Files required for installing Android Lollipop 5.0.1 Samsung Galaxy Grand Duos GT-i9082
gapps-lp-20141220-signed Download Link: https://www.androidfilehost.com/?fid=95864024717068610
Steps for Un-rooting Original Samsung Galaxy Grand Duos GT-i9082 Firmware.
1.       Connect your Samsung Galaxy Phone and Laptop or Desktop with the Cable and copy the following files into SD Card, without SD Card and the below files you cannot do this process.
a.       Super SU - UPDATE-SuperSU-v1.25.zip
b.      Customer ROM - cm-12-20150502-UNOFFICIAL-i9082.zip
c.       Gapps - gapps-lp-20141220-signed.zip
2.       Install Samsung Kies in your PC.
3.       Switch off your Samsung Galaxy Grand Duos and unplug the cable
4.       Press Volume Key Down + Power + Home keys at the same time and keep hold it until Reboot Screen appears.
5.       Now Tap Volume Button Up button to Continue, after this go ahead and connect the phone to PC via the data cable.
a.       Extract the Odin folder in your PC. Then go to Odin file and mouse right click on it and select Run as Administrator.
b.      Now Extract the CWM-touch_i9082_chotu.tar.rar file which has CWM-touch_i9082_chotu.tar.md5 file.
6.       Then if you have installed Samsung Kies properly the top button will turn blue so that is perfect. Now click on PDA, and then navigate to the other file with the name " CWM-touch_i9082_chotu.tar.md5, Now make sure in this ODIN opened window. The "Auto Reboot" and "F.Reset Time" checkboxes is checked, then Click on Start Button.
7.       Now you observe Download Process bar on your phone and once it is complete you can see your phone will restart, DO NOT allow your phone to restart in full at this time, so Take out the Battery and wait for 60 Seconds.
8.       Press the Volume Up + Home + Power buttons at the same time to go to the kernel of the phone. Hold the button pressing until you see Samsung Galaxy Grand...... text is displayed again on your phone.
9.       Now you will be in recovery mode and the Volume Buttons are used to navigate and Power button is to select.  Select "Install zip from SD Card". Choose from SD Card and select the zip folder called "UPDATE-SuperSU-v1.25.zip " file and click install. Once done please press "Go Back" button and select restart the phone, DO NOT allow your phone to restart in full at this time, so Take out the Battery and wait for 60 Seconds.
1.   Once you complete the above 1-9 Steps you have completed Un-Rooting Process Successfully.


Steps for Installing Cyanogenmod 12 Custom ROM and GApps in Samsung Galaxy Grand Duos GT-i9082
1.       Restart the Phone by pressing Volume Up + Home + Power buttons hold the buttons pressing until you see Samsung Galaxy Grand...... text is displayed again on your phone.
2.       Volume Buttons are used to navigate and Power button is to select.  Select "Install zip from SD Card". Choose from SD Card and select the zip folder called "cm-12-20150502-UNOFFICIAL-i9082.zip" file and click install, Once done please press "Go Back" button.
3.       And again install “gapps-lp-20141220-signed.zip” by selecting "Install zip from SD Card" and once installation is completed then Choose “Go Back” button and choose the restart.
4.       That’s it your phone is successfully un-rooted and installed latest Lollipop 5.0.2, it will take couple of minutes to start your applications.

Friday, June 19, 2015

How to Instal Ubuntu on Windows with Oracle Virtual Machine?

Steps to install Ubuntu on windows with the Oracle Virtual Machine.

1. Download the Oracle Virtual Machine from the below site, and choose the appropriate bit based on your operating system.

https://www.virtualbox.org/wiki/Downloads

2. Download Ubuntu from http://www.ubuntu.com/download/desktop site.

3. Install Oracle Virtual Machine into your system and run "Oracle Virtual Machine" the screen will looks like below
4. Click on New and it will prompt you to enter the name and choose the type and version and click on next button.

5. Based on your system requirement provide the memory options and click on Next button.


6. select "Create a Virtual Hard Drive Now" option and click on Create button.
7. select "Hard Drive File types", you just leave the defaults and click next.
8. Create Virtual Drive, Select "Dynamically Allocated " option and click on next.


9. Provide the fie location and size, click on Create Button.
10. Once you are done with the steps from 3 to 9, your Ubuntu instance will be created into the Virual Machine, next you need to provide the Ubutu Engine i.e Ubutu .iso file.


11. Configuring Ubuntu .iso file into Oracle Virtual Machine.
  • Mouse Right click on UbuntLinux i.e the Ubuntu Virtual Instance which you have given while creating virtual machine.
  • Click on Settings and choose the "Storage" Option from the left menu, there you can see "Controller IDE" Next to that there will be a"+" symbol click on the button and choose the existing disk and choose the .iso file, that's it you are done.
  • Now mouse right click on "UbuntuLinux" virtual instance which is displayed in the left Menu and click on start option you can see your Ubuntu running in Oracle Virtual Machine.




Thursday, June 18, 2015

Download Files and Directories from FTP

Download Files and Directories from FTP by using Apache Commons-net 3.3

Below java file will be used to download files or folders from FTP, to setup this program running in eclipse you need to setup the required jar files into the class path, for that you need to have Apache-Commons-net 3.3 jar files.

Please find the link here to download the jars.

https://drive.google.com/file/d/0BxIDTv_7kcnfMFJiTlUwYzl4aWs/view?usp=sharing

This program needs a properties file as a input to the FTP_Utility.java main method.

ftpproperties.properties

serverAddress=127.0.0.1
userId=demo   
password=demo
remoteDirectory=/
localDirectory=/filesinFTP
savedDirectory = C:\\downloadedfiles

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTP_Utility {

    public static void main(String[] args) {
        GetCDRFilesFromFTP getMyFiles = new GetCDRFilesFromFTP();
        if (args.length < 1) {
            System.err.println("Usage: java " + getMyFiles.getClass().getName() + " Properties_file");
            System.exit(1);
        }
        String propertiesFile = args[0].trim();
        getMyFiles.startFTP(propertiesFile);
    }
}


class GetCDRFilesFromFTP {

static Properties props;
public boolean startFTP(String propertiesFile){

        props = new Properties();

        try {

            props.load(new FileInputStream("properties/" + propertiesFile));
            String serverAddress = props.getProperty("serverAddress").trim();
            String userId = props.getProperty("userId").trim();
            String password = props.getProperty("password").trim();
            String remoteDirectory = props.getProperty("remoteDirectory").trim();
            String localDirectory = props.getProperty("localDirectory").trim();
            String savedDirectory = props.getProperty("savedDirectory").trim();
            //new ftp client
            FTPClient ftp = new FTPClient();
            //try to connect
            ftp.connect(serverAddress);
            //login to server
            if(!ftp.login(userId, password))
            {
                ftp.logout();
                return false;
            }
            int reply = ftp.getReplyCode();
            //FTPReply stores a set of constants for FTP reply codes.
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                return false;
            }

            //enter passive mode

            ftp.enterLocalPassiveMode();
            //get system name
            System.out.println("Remote system is " + ftp.getSystemType());
            //change current directory
            ftp.changeWorkingDirectory(remoteDirectory);
            System.out.println("Current directory is " + ftp.printWorkingDirectory());
       
            downloadDirectory(ftp, localDirectory, remoteDirectory, savedDirectory);
       
            ftp.logout();
            ftp.disconnect();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        return true;
    }




/**
 * Download a whole directory from a FTP server.
 * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
 * @param parentDir Path of the parent directory of the current directory being
 * downloaded.
 * @param currentDir Path of the current directory being downloaded.
 * @param saveDir path of directory where the whole remote directory will be
 * downloaded and saved.
 * @throws IOException if any network or IO error occurred.
 */
public static void downloadDirectory(FTPClient ftpClient, String parentDir,
        String currentDir, String saveDir) throws IOException {
    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }

    FTPFile[] subFiles = ftpClient.listFiles(dirToList);

    System.out.println(subFiles.length);
    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                // skip parent directory and the directory itself
                continue;
            }
            String filePath = parentDir + "/" + currentDir + "/"
                    + currentFileName;
            if (currentDir.equals("")) {
                filePath = parentDir + "/" + currentFileName;
            }

            String newDirPath = saveDir + parentDir + File.separator
                    + currentDir + File.separator + currentFileName;
            if (currentDir.equals("")) {
                newDirPath = saveDir + parentDir + File.separator
                          + currentFileName;
            }

            if (aFile.isDirectory()) {
                // create the directory in saveDir
                File newDir = new File(newDirPath);
                boolean created = newDir.mkdirs();
                if (created) {
                    System.out.println("CREATED the directory: " + newDirPath);
                } else {
                    System.out.println("COULD NOT create the directory: " + newDirPath);
                }

                // download the sub directory
                downloadDirectory(ftpClient, dirToList, currentFileName,
                        saveDir);
            } else {
                // download the file
                boolean success = downloadSingleFile(ftpClient, filePath,
                        newDirPath);
                if (success) {
                    System.out.println("DOWNLOADED the file: " + filePath);
                } else {
                    System.out.println("COULD NOT download the file: "
                            + filePath);
                }
            }
        }
    }
}

/**
 * Download a single file from the FTP server
 * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
 * @param remoteFilePath path of the file on the server
 * @param savePath path of directory where the file will be stored
 * @return true if the file was downloaded successfully, false otherwise
 * @throws IOException if any network or IO error occurred.
 */
public static boolean downloadSingleFile(FTPClient ftpClient,
        String remoteFilePath, String savePath) throws IOException {
    File downloadFile = new File(savePath);

    File parentDir = downloadFile.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdir();
    }
    
    OutputStream outputStream = new BufferedOutputStream(
            new FileOutputStream(downloadFile));
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        return ftpClient.retrieveFile(remoteFilePath, outputStream);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

}

Thursday, December 28, 2006

XML Parsers

XML Parsers

What is a parser? It's a piece of software whose job description is to check that an XML document is valid or, failing that, well-formed. Not very interesting to the average user, perhaps, but a vital part of the picture if validity and well-formedness are to have any real meaning in the XML world. Any software package that is XML-aware will have a parser built into it in the form of an XML processor. As a minimum, the XML processor checks the XML documents you are about to work on, and checks them again when you have finished. Ideally, it is interactive; any errors you introduce are reported and can be sorted out while you work.
You also can get standalone XML parsers, which are important if you take the plain text editor route for your XML authoring. When you have finished working on an XML document in an uncontrolled environment (one that doesn't know about XML tagging conventions), you should always run an XML parser on it to check that it is still valid.
Kinds of parsers
There are several different ways to categorize parsers:
• Validating versus non-validating parsers
• Parsers that support the Document Object Model (DOM)
• Parsers that support the Simple API for XML (SAX)
• Parsers written in a particular language (Java, C++, Perl, etc.)

XML Schema

XML Schema

The W3C XML Schema Language (schemas for short, though it’s hardly the only schema language) addresses several limitations of DTDs. First schemas are written in XML instance document syntax, using tags, elements, and attributes. Secondly, schemas are fully namespace aware. Thirdly, schemas can assign data types like integer and date to elements, and validate documents not only based on the element structure but also on the contents of the elements. With XML schemas, you have more power to define what valid XML documents look like.
They have several advantages over DTDs:
XML schemas use XML syntax. In other words, an XML schema is an XML document. That means you can process a schema just like any other document. For example, you can write an XSLT style sheet that converts an XML schema into a Web form complete with automatically generated JavaScript code that validates the data as you enter it.
XML schemas support datatypes. While DTDs do support datatypes, it's clear those datatypes were developed from a publishing perspective. XML schemas support all of the original datatypes from DTDs (things like IDs and ID references).
They also support integers, floating point numbers, dates, times, strings, URLs, and other datatypes useful for data processing and validation.
XML schemas are extensible. In addition to the datatypes defined in the XML schema specification, you can also create your own, and you can derive new datatypes based on other datatypes.

What is XML?

What is XML

XML is a text-based markup language that is fast becoming the standard for data interchange on the Web. As with HTML, you identify data using tags (identifiers enclosed in angle brackets, like this: <...>). Collectively, the tags are known as "markup".

But unlike HTML, XML tags tell you what the data means, rather than how to display it. Where an HTML tag says something like "display this data in bold font" (...), an XML tag acts like a field name in your program. It puts a label on a piece of data that identifies it (for example: ...).

XML is an open, text-based markup language that provides structural and semantic information to data. This "data about data," or metadata, provides additional meaning and context to the application using the data and allows for a new level of management and manipulation of Web-based information. XML, a subset of the popular Standard Generalized Markup Language (SGML), has been optimized for the Web. This helps make XML a powerful, standards-based complement to HTML that could be as important to the future of information delivery on the Web as HTML was to its beginning.

XML is intended to be used by content creators as well as by programmers. Since XML is text-based, it can be read and worked with easily in relatively nontechnical situations, but its ability to organize, describe, and structure data also makes it ideal for use in highly technical applications. XML thus provides common ground for creating structured data and making it available for manipulation and display.