Sunday, February 8, 2015

Read and Write a File Azure Cloud

Cloud storage means Storing data online in cloud ,Windows Azure blob storage is often used for keeping backup data by personal users and enterprises.


Azure Blob  data that can be accessed from anywhere in the world via HTTP or HTTPS

Containers=In Azure Storage Account will consist of one or more Containers, which are created and named by the user to hold Blobs.

blob=(Binary Large OBject ) data stored by user


Maven dependency

 <dependency>
<groupId>com.microsoft.windowsazure</groupId>
<artifactId>microsoft-windowsazure-api</artifactId>
<version>0.2.2</version>
</dependency>


or can use

azure-storage-1.1.0.jar

program in java to perform create ,read ,delete a file from azure


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URI;
import com.microsoft.windowsazure.services.blob.client.CloudBlobClient;
import com.microsoft.windowsazure.services.blob.client.CloudBlobContainer;
import com.microsoft.windowsazure.services.blob.client.CloudBlockBlob;
import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount;

/**

 * @author Rohan Kamat
 */

public class CloudUtil {


public static void main(String[] args) throws Exception {

CloudUtil cloudutil = new CloudUtil();
String azureconString = "connect string with key ";
CloudStorageAccount storage = CloudStorageAccount.parse(azureconString);
String container = "container or directory on which blob/file is saved";
String fileName = "name of the file";
File file = new File(" path of the filr");
// save file to cloud
cloudutil.uploadBlob(file, storage, container, fileName);
// download file from cloud
cloudutil.downloadBlob(storage, container, fileName);
// delete a file from cloud
cloudutil.deleteBlob(storage, container, fileName);
}

// save file to cloud on specific container or directory

public URI uploadBlob(File file, CloudStorageAccount storageAccount,
String containerName, String referenceName) throws Exception {
CloudBlockBlob blob = null;
CloudBlobClient blobClient = null;
CloudBlobContainer container = null;
blobClient = storageAccount.createCloudBlobClient();
container = blobClient.getContainerReference(containerName);
container.createIfNotExist();
blob = container.getBlockBlobReference(referenceName);
FileInputStream fileInputStream = new FileInputStream(file);
blob.upload(fileInputStream, file.length());
fileInputStream.close();

return blob.getUri();

}

// download file from cloud of specific container or directory

public File downloadBlob(CloudStorageAccount storageAccount,
String containerName, String filename) throws Exception {
CloudBlockBlob blob = null;
CloudBlobClient blobClient = null;
CloudBlobContainer container = null;
blobClient = storageAccount.createCloudBlobClient();
container = blobClient.getContainerReference(containerName);
blob = container.getBlockBlobReference(filename);
File file = new File(blob.getName());
FileOutputStream fileOutputStream = new FileOutputStream(file);
blob.download(fileOutputStream);
return file;

}


// delete file from cloud of specific container or directory

public boolean deleteBlob(CloudStorageAccount storageAccount,
String containerName, String referenceName) throws Exception {
boolean isdelete = false;
CloudBlockBlob blob = null;
CloudBlobClient blobClient = null;
CloudBlobContainer container = null;
blobClient = storageAccount.createCloudBlobClient();
container = blobClient.getContainerReference(containerName);
blob = container.getBlockBlobReference(referenceName);
isdelete = blob.deleteIfExists();
return isdelete;
}

}


Thursday, February 5, 2015

ResourceBundle



ResourceBundle class contain locale-specific objects,its easy way to storing and access key/value .

Properties file in java used to store application related configuration details .
Properties file contains pair of strings (key=value),


here is example for properties file

propertiesfile.properties

product_url=http://localhost:8080
adminname=rohan


with this example you retrieve the key values



import java.util.ResourceBundle;

public class Resourcebundle {
/**
* @author Rohan Kamat
*/
private static ResourceBundle services = null;
public  String getServiceUrl(String service) {

String value = null;
String filepath="D:\\";
try {
if (services == null) {
services = ResourceBundle.getBundle(filepath+"properties.propertiesfile");
}
value =services.getString(service);
} catch (Exception exception) {
exception.printStackTrace();
}
return value;
}

public static void main(String args[]){
Resourcebundle resource=new Resourcebundle();
resource.getServiceUrl("adminname");
}
}

Conversion on excel to json.

to converting excel to json , we require two steps 

1)parse the excel , fetch the header
2) json construction with header as key and corresponding values


/**
 * @author Rohan Kamat
 */

public class ExcelToJson{

/**
 * @author Rohan Kamat
 */
 
public JSONArray constructJsonArrayFromExcel(File file) throws Exception{
JSONArray result=new JSONArray();
JSONArray json= processExcelFile(file);
System.out.println(json);
if(!json.isEmpty()){
JSONObject ColumnNames=(JSONObject) json.get(0);
for(int i=1;i<json.size();i++){
JSONObject exelobject=new JSONObject();
JSONObject object=(JSONObject) json.get(i);
for(int j=0;j<ColumnNames.size();j++){
exelobject.put(ColumnNames.get(j), object.get(j));
}
result.add(exelobject);
}
}
return result;
}

private JSONArray processExcelFile(File file) throws Exception{
  JSONArray rows = new JSONArray();
     try{
         FileInputStream myInput = new FileInputStream(file);
         XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
         XSSFSheet mySheet = myWorkBook.getSheetAt(0);
         Iterator<Row> rowIter = mySheet.rowIterator();
         while(rowIter.hasNext()){
             XSSFRow myRow = (XSSFRow) rowIter.next();
             Iterator<Cell> cellIter = myRow.cellIterator();
             JSONObject jRow = new JSONObject();
             while(cellIter.hasNext()){
                 XSSFCell myCell = (XSSFCell) cellIter.next();
                 switch (myCell.getCellType()) {
                 case XSSFCell.CELL_TYPE_NUMERIC :
                     jRow.put(myCell.getColumnIndex(), myCell.getNumericCellValue());
                     break;
                 case XSSFCell.CELL_TYPE_STRING:   
                     jRow.put(myCell.getColumnIndex(), myCell.getStringCellValue());
                     break;
                 default:   
                     jRow.put(myCell.getColumnIndex(), myCell.getRawValue());
                     break;   
                 }
             }
             rows.add(jRow);
         }
     }
     catch (Exception ex){
    System.out.println(ex);
     }
     return rows;
 }

 }

Tuesday, February 3, 2015

Json hierarchy Parser

JSON or JavaScript Object Notation 
java programs which helps to encode or decode JSON text





import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

//break json-hierarchy into key-value pair
public class JsonhierarchyParser {

/**
* @author Rohan Kamat
*/


private JSONObject result=new JSONObject();

public JSONObject getResult() {
return result;
}

public void setResult(String key,Object value) {
this.result .put(key, value);
}

public void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();

                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = (JSONArray) data.get(key);
                        int size = arry.size();
                        for (int i = 0; i < size; i++) {
                        try{
                        parseJson((JSONObject)arry.get(i));
                        }
                        catch(Exception ex){
                        System.out.println("" + key + " : " + data.get(key));
                        setResult(key, data.get(key));
                        }
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                    try{
                    parseJson((JSONObject)data.get(key));
                    }
                    catch(Exception ex){
                    setResult(key, data.get(key));
                    System.out.println("" + key + " : " + data.get(key));
                    }
                    } else {
                    setResult(key, data.get(key));
                    System.out.println("" + key + " : " + data.get(key));
                 
                    }
                } catch (Throwable e) {
                setResult(key, data.get(key));
                    e.printStackTrace();

                }
            }
        }
    }


}

Java Kerberos multiple domain

Kerberos  protocol, can authenticate the client by examining credentials presented by the client.


Kerberos is a network authentication protocol,Kerberos authenticate the client by examining credentials presented by the client.

It is designed to provide strong authentication for client/server applications by using secret-key cryptography.

The concept depends on a trusted third party – a Key Distribution Center (KDC). The KDC is aware of all systems in the network and is trusted by all of them,
It performs mutual authentication, where a client proves its identity to a server and a server proves its identity to the client



This program demonstrate  how to authenticate  Kerberos  against  multiple domain  



import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

public class KerberosAuth {


     **
* @author rohan kamat
* @version 1.0

*/


   public static void main(String[] args) {
   System.setProperty("javax.security.auth.useSubjectCredsOnly", "true"); 
   System.setProperty("java.security.krb5.conf", "\\krb5.conf"); // path to Domain configuration
   System.setProperty("java.security.auth.login.config", "\\gss.conf"); //path to GSS configuration
// Kerberos login
LoginContext lc = null;
try {
lc = new LoginContext("Gss",
new UserNamePasswordCallbackHandler("LOGIN NAME",
"PASSWORD".toCharArray()));
lc.login();
lc.getSubject();
System.out.print("login success");
} catch (LoginException le) {
le.printStackTrace();
}
    }


public static class UserNamePasswordCallbackHandler implements
CallbackHandler {
private String _userName;
private char[] _password;

public UserNamePasswordCallbackHandler(String userName, char[] password) {
_userName = userName;
_password = password;
}

@Override
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback && _userName != null) {
((NameCallback) callback).setName(_userName);
} else if (callback instanceof PasswordCallback
&& _password != null) {
((PasswordCallback) callback).setPassword(_password);
}
}
}
}

}




///gss.conf
Mutual {
  com.sun.security.auth.module.Krb5LoginModule required client=TRUE  ;
};
Gss{
  com.sun.security.auth.module.Krb5LoginModule required client=TRUE ;
};



///krb5.conf

[libdefaults]
default_realm = ABC.LOCAL
ticket_lifetime = 600
[realms]
ABC.LOCAL = {
kdc = cd.abc.local
default_domain = ABC.LOCAL
}
XYZ.NET = {
kdc = ad.xyz.net
}
[domain_realm]
.abc.local = .ABC.LOCAL
abc.local = ABC.LOCAL
.xyz.net = .XYZ.NET
xyz.net = XYZ.NET