URL Encoding

URL Encodeing
----------------
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLEncoding
{
    public static void main(String[] args)
    {
        try
        {
            String encodedString = URLEncoder.encode("dra!123", "UTF-8");
            System.out.println(encodedString);
            System.out.println(URLDecoder.decode(encodedString, "UTF-8"));
        } catch (UnsupportedEncodingException ex)
        {
            ex.printStackTrace();
        }
    }

}
===================================================================
URL Decoding
---------------
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public class TokenizeUrl
{
    public static void main(String[] args) throws UnsupportedEncodingException, MalformedURLException
    {
        URL url=new URL("http://Dev:dev%40123@10.29.161.84:7180/api/v6/cm/deployment");
        String userName=url.toString().split("@")[0].split(":")[1];
        String password=url.toString().split("@")[0].split(":")[2];
        String userNameAndPwd=userName+":"+URLDecoder.decode(password, "UTF-8");
        String userNameAndPwd1=userNameAndPwd.replace("//", "");
        System.out.println(userNameAndPwd1);
    }
}
==============================================================
Units Calculation
-----------------
public class SomeCalcUnits
{
    public static void main(String[] args)
    {
        // less that 512 means pass 512,lly less than 1024 means 1024
        long capacityInBytes = 500;
        long cliunits;
        if (capacityInBytes % 512 == 0)
        {
            capacityInBytes = ((capacityInBytes / 512)) * 512;
        } else
        {
            capacityInBytes = ((capacityInBytes / 512) + 1) * 512;
        }
        System.out.println(capacityInBytes / 512);
        System.out.println(capacityInBytes);
    }
}
============================================================
String Latest Integer value increase
-------------------------------------
import java.util.LinkedList;
import java.util.List;

public class Sample
{
    public static void main(String[] args)
    {
        List NumberList = new LinkedList();
        int l = 0;
        int pos;
        String main = "main123kumar435kumar";
        char[] charList = main.toCharArray();
        for (int i = 0; i < charList.length; i++)
        {
            pos = (int) charList[i];

            if (47 < pos && pos < 58)
            {

                NumberList.add(charList[i]);
                l = i;
            }
        }

        if (NumberList.isEmpty())
        {
            main = main + "1";
            System.out.println(main);
        } else
        {

            String stringVal = String.valueOf(charList[l]);
            Integer val = Integer.parseInt(stringVal) + 1;
            System.out.println(main.replaceAll(String.valueOf(charList[l]), String.valueOf(val)));// main123kumar436kumar

        }

    }
}
==================================================================
Sort the map Based On value of the Map
----------------------------------------
public class Volume {

private String volumeId;
private String  volumeName;
private  String volumeDetails;
private  String capacity;
//getters and getters
}

------------------------------
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class MapValueSort
{
public static void main(String[] args)
{
    List<Volume> volList = new ArrayList<Volume>();
    HashMap<String,BigDecimal> map = new HashMap<String,BigDecimal>();
    Volume v1=new Volume();
    Volume v2=new Volume();
    Volume v3=new Volume();

    v1.setVolumeId("1"); v1.setVolumeName("Volume1"); v1.setVolumeDetails("volumeOne");v1.setCapacity("10GB");
    v2.setVolumeId("2"); v2.setVolumeName("Volume2");v2.setVolumeDetails("volumeTwo");v2.setCapacity("2GB");
    v3.setVolumeId("3"); v3.setVolumeName("Volume3");v3.setVolumeDetails("volumeThree");v3.setCapacity("5GB");
    volList.add(v1); volList.add(v2);  volList.add(v3);
    map.put(v1.getVolumeId(), MapValueSort.convertToBytes(v1.getCapacity()));
    map.put(v2.getVolumeId(), MapValueSort.convertToBytes(v2.getCapacity()));
    map.put(v3.getVolumeId(), MapValueSort.convertToBytes(v3.getCapacity()));
   System.out.println("unsorted map: "+map);
   Map<String, BigDecimal> sorted_map = sortByComparator(map);
   System.out.println("Sorted Map based on Value of map : "+sorted_map);
    List<String> top2MdiskIds=new ArrayList<String>();
    int count=0;
    for (Map.Entry<String,BigDecimal> entry:sorted_map.entrySet()) {
       if (count >1) break;
       top2MdiskIds.add(entry.getKey());      
       count++;
    }

    List<Volume> top2VolumeInfo=new LinkedList<Volume> ();

    for (String voliIdentity : top2MdiskIds) {
        for (Volume volumeInfo : volList) {
            if(voliIdentity.equalsIgnoreCase(volumeInfo.getVolumeId()))
            {
                top2VolumeInfo.add(volumeInfo);
            }
        }
    }
    System.out.println("VolID"+" "+"VolName "+" VolDetails ");
    for (Volume volume : top2VolumeInfo)
    {
        System.out.println("  "+volume.getVolumeId()+"   "+volume.getVolumeName()+"   "+volume.getVolumeDetails());
    }
}
private static Map<String, BigDecimal> sortByComparator(Map<String, BigDecimal> unsortMap) {

    // Convert Map to List
    List<Map.Entry<String, BigDecimal>> list =
        new LinkedList<Map.Entry<String, BigDecimal>>(unsortMap.entrySet());

    // Sort list with comparator, to compare the Map values
    Collections.sort(list, new Comparator<Map.Entry<String, BigDecimal>>() {
        public int compare(Map.Entry<String, BigDecimal> o1,
                                       Map.Entry<String, BigDecimal> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }
    });

    // Convert sorted map back to a Map
    Map<String, BigDecimal> sortedMap = new LinkedHashMap<String, BigDecimal>();
    for (Iterator<Map.Entry<String, BigDecimal>> it = list.iterator(); it.hasNext();) {
        Map.Entry<String, BigDecimal> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}
public static BigDecimal convertToBytes(String capacity)
{
    long sizeInBytesValue=0;
    String tempCapactiy1=capacity;//30.00KB or 512
    Double temp=1.00;
    long TBvalue=1099511627776l;//1024*1024*1024*1024=1099511627776,
    long GBvalue=1073741824l;//1024*1024*1024=1073741824,1073741824
    Double MBvalue=1048576.00;//1024*1024=1048576
    Double KBvalue=1024.00;//1024
    BigDecimal capacityInBigDecimal;
    BigInteger capacityInBigInteger;
    if(tempCapactiy1.contains("TB"))
    {
        tempCapactiy1=tempCapactiy1.replace("TB", "");
        temp=TBvalue*Double.parseDouble(tempCapactiy1);
    }
    else if(tempCapactiy1.contains("GB"))
    {
    tempCapactiy1=tempCapactiy1.replace("GB", "");
     temp=GBvalue*Double.parseDouble(tempCapactiy1);
    }
    else if(tempCapactiy1.contains("MB"))
    {
    tempCapactiy1=tempCapactiy1.replace("MB", "");
    temp=MBvalue*Double.parseDouble(tempCapactiy1);
    }
    else if(tempCapactiy1.contains("KB"))
    {
    tempCapactiy1=tempCapactiy1.replace("KB", "");
    temp=KBvalue*Double.parseDouble(tempCapactiy1);
    }
    else
    {
        temp=Double.parseDouble(tempCapactiy1);
    }
    capacityInBigDecimal=new BigDecimal(temp);
    return capacityInBigDecimal;
}
}
==================================================================



@Entity
public class College
{
@ID
@GeneratedValue
private int collegeId;
private String studentname;
private List<Student> students;

@oneToMany(targetEntity=Student.class,
mappedBy="college",
cascade=CascadeType.ALL, //if college object deleted then all the student objcet to be deleted/updated
fetch=FetchType.Lazy //it not recommended for fecthType is Eager for 1-m or m-1
)
public List<Student> getStudents()
{
return students;
}
}
@Entity
public class Student{//multiple students are associated with college
@ID
@GeneratedValue
private int studentId;
private String studentName;
private College college

@ManyToOne //we need join coloum for the foriegn Key
@JoinColoumn(name="college_id")//we can give any Name
public College getCollege()
{
return college;
}
}
public class TestStudent
{
public static void main(String[] args)
{
AnnotationConfiguration config=AnnotationConfiguration();
config.addAnnotatedClass(College.class);
config.addAnnotatedClass(Student.class);
config.configure("hibernate.cfg.xml")

new SchemaExport(config).create(true,true);
SF sf=config.buildSessionFactory();
Session s=sf.getCurrentSession();
s.beginTrascation();


}
}
CollegeTable
collegeID and collegeName
StudentTable
studentID,studentName,College_ID
===================================
Many-to Many
https://www.youtube.com/watch?v=zbH59X281f4
@Entity
public class Event{
@id
@GeneratedValue
private int ententid
List<Delegate> delegates=new ArrayList<Delegate>();
@ManyToMany
@JoinTable(name="JOIN_DELEGATE_EVENT",
joinColums={@JoinColoumn(name="eventId")},
inverseJoinColoums={@JoinColumn(name="delegatedID")}
 )  //3rd Table
public List<Delegate> getDelegates()
{
return delegates;
}

@Entity
public class Deletage{
@id
@GeneratedValue
private int delegateid
List<Event> envents=new ArrayList<Event>();
@ManyToMany
@JoinTable(name="JOIN_DELEGATE_EVENT",
joinColums={@JoinColoumn(name="delegatedID")},delegatedID
inverseJoinColoums={@JoinColumn(name="eventId")}
public List<Event> getEvents()
{
return events;
}
===============================================================
org-apache-commons-codec.jar
Gson jar download

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

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JSONRest {
 public static Object JsonGetUrlObj(URL url, Class cl) throws IOException
    {

        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;

        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            if (url.getUserInfo() != null)
            {
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }

            InputStream inputStream = urlConnection.getInputStream();

            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//             logger.debug(buffer.toString());

            Gson gson = new Gson();
            // SCluster sClust = gson.fromJson(buffer.toString(),
            // SCluster.class);
            // logger.info(sClust.theName + ":" + sClust.dnsRes /* + ":" +
            // sClust.acceptLic
            // */);

            obj = gson.fromJson(buffer.toString(), cl);

        } /*
           * catch (JsonSyntaxException e) { e.printStackTrace(); }
           */finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }
        return obj;
    }

    public static Object JsonPostUrlObj(URL url, Class cl, String urlParameters) throws Exception
    {

        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;

        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            // Set http request method to POST Type.
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            if (url.getUserInfo() != null)
            {
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }

            // Output Stream
            urlConnection.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            wr.flush();
            wr.close();

            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'POST' request to URL : " + url);
            logger.info("Post parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/
            InputStream inputStream = null;
            boolean isError = false;
            if (responseCode >= 400 && responseCode <= 500)
            {
                inputStream = urlConnection.getErrorStream();
                isError = true;
            } else
            {
                inputStream = urlConnection.getInputStream();
            }

            // Input Stream

            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();

int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//             logger.debug(buffer.toString());
            Gson gson = new Gson();
            if (isError)
            {
                obj = gson.fromJson(buffer.toString(), ErrorPojo.class);
                if (reader != null)
                    reader.close();
                urlConnection.disconnect();
                ErrorPojo error = (ErrorPojo) obj;
                throw new Exception(error.getMessage());

            } else
            {
                obj = gson.fromJson(buffer.toString(), cl);
            }

        } finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }
        return obj;
    }

    public static void JsonPutUrlObj(URL url, String urlParameters) throws IOException
    {

        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("PUT");
            if (url.getUserInfo() != null)
            {
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }
            // Output Stream
            ((HttpURLConnection) urlConnection).setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(((HttpURLConnection) urlConnection).getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            wr.flush();
            wr.close();
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
//             logger.info("\nSending 'PUT' request to URL : " + url);
//             logger.info("Put parameters : " + urlParameters);
//             logger.info("Response Code : " + responseCode);
//             logger.info("Response Message : " + responseMessage);

            if (responseCode >= 400 && responseCode <= 500)
            {
                InputStream inputStream = urlConnection.getErrorStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1)
                    buffer.append(chars, 0, read);
                if (reader != null)
                    reader.close();
                inputStream.close();
                urlConnection.disconnect();
                throw new Exception(buffer.toString());
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();

        }

    }

    public static Object JsonDeleteUrlObj(URL url, Class cl, String urlParameters) throws IOException
    {

        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        Object obj = null;

        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("DELETE");
            if (url.getUserInfo() != null)
            {
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }

            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'DELETE' request to URL : " + url);
            logger.info("Delete parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/

            // Input Stream
            InputStream inputStream = urlConnection.getInputStream();
            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//             logger.info("output" + buffer.toString());
            Gson gson = new Gson();
            obj = gson.fromJson(buffer.toString(), cl);

        } finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }
        return obj;
    }

    public static Object JsonPutUrlObj(URL url, Class cl, String urlParameters) throws Exception
    {
        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("PUT");
            if (url.getUserInfo() != null)
            {
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }
            // Output Stream
            ((HttpURLConnection) urlConnection).setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(((HttpURLConnection) urlConnection).getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            wr.flush();
            wr.close();
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'PUT' request to URL : " + url);
            logger.info("Put parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/
            // Input Stream
            InputStream inputStream = null;
            boolean isError = false;
            if (responseCode >= 400 && responseCode <= 500)
            {
                inputStream = urlConnection.getErrorStream();
                isError = true;
            } else
            {
                inputStream = urlConnection.getInputStream();
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//             logger.debug(buffer.toString());
            Gson gson = new Gson();
            if (isError)
            {
                obj = gson.fromJson(buffer.toString(), ErrorPojo.class);
                if (reader != null)
                    reader.close();
                urlConnection.disconnect();
                ErrorPojo error = (ErrorPojo) obj;
                throw new Exception(error.getMessage());

            } else
            {
                obj = gson.fromJson(buffer.toString(), cl);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();

        }
        return obj;
    }

}
====================================================================
private static boolean checkCommand(String imHostname, String commandID) throws Exception
    {
        String userNamepwd = getManagementConsolePwd(imHostname);
        String strUrl = "http://" + userNamepwd + "@" + imHostname + ":7180/api/v6/commands/" + commandID;
        try
        {
            URL url = new URL(strUrl);
            CMCommandResponse response = (CMCommandResponse) JsonGetUrlObj(url, CMCommandResponse.class);
            return response.isActive();
        } catch (Exception e)
        {
            return false;
        }
    }
    public static boolean enableHighAvailability(String inputJson,String clusterName,String serverIp, int maxTryTimeLimit, int sleepTimeMillis) throws Exception{
        //http://10.29.161.89:7180/api/v6/clusters/CL56/services/hdfs/commands/hdfsDisableNnHa
       

        String userNamepwd = getManagementConsolePwd(serverIp);
        String strUrl = "http://" + userNamepwd + "@" + serverIp + ":7180/api/v6/clusters/" + clusterName
                + "/services/hdfs/commands/hdfsEnableNnHa";
        URL disableHAURL = new URL(strUrl);
        CMCommandResponse response = (CMCommandResponse) ClouderaRestUtilTest.JsonPostUrlObj(disableHAURL,
                CMCommandResponse.class, inputJson);
        boolean statusCheck = checkCommandStatus(serverIp, String.valueOf(response.getId()), sleepTimeMillis,
                maxTryTimeLimit);
        logger.info( + response.getId() + "  " + response.isActive());
       
        return statusCheck;
    }
 public static void putserviceRoleConfigGroup(String serverIP, String roleName, String servicerolesJson)
            throws Exception
    {
        /*
         * ref :
         * http://10.29.160.45:7180/api/v6/cm/service/roleConfigGroups/mgmt-SERVICEMONITOR-BASE
         * /config
         */
        String userNamepwd = getManagementConsolePwd(serverIP);
        String strUrl = "http://" + userNamepwd + "@" + serverIP + ":7180/api/v6/cm/service/roleConfigGroups/"
                + roleName + "/config";
        logger.info(strUrl);
        URL clusterUrl = new URL(strUrl);
        JsonPutUrlObj(clusterUrl, servicerolesJson);
    }
 public static CMHostId deleteNodeFromCMHosts(String imHostNm, String hostId) throws Exception
    {
        String userNamepwd = getManagementConsolePwd(imHostNm);
        String deleteNodeurl = "http://" + userNamepwd + "@" + imHostNm + ":7180/api/v6/hosts/" + hostId;
        URL url = new URL(deleteNodeurl);
        CMHostId deleteNode = (CMHostId) JsonDeleteUrlObj(url, CMHostId.class, "");
        logger.info("Deleted Node from CM" + deleteNode.getHostId());
        return deleteNode;
    }
public static CMHost moveNodeToOtherRack(String serverIp, String hostName, String rackID) throws Exception
    {
        String userNamepwd = getManagementConsolePwd(serverIp);
        Gson gson = new Gson();
        CMHostList cmHostList = getAllCMHosts(serverIp);
        Map<String, CMHost> hostMapping = new HashMap<String, CMHost>();
        for (CMHost node : cmHostList.getNodeList())
        {
            hostMapping.put(node.getHostname(), node);
        }
        CMHost hostToEdit = hostMapping.get(hostName);
        hostToEdit.setRackId(rackID);
        String strURL = "http://" + userNamepwd + "@" + serverIp + ":7180/api/v6/hosts/" + hostToEdit.getHostId();
        URL url = new URL(strURL);
        String inputJson = gson.toJson(hostToEdit, CMHost.class);
        CMHost cmHost = (CMHost) JsonPutUrlObj(url, CMHost.class, inputJson);
        return cmHost;

    }

No comments:

Post a Comment