## Thursday, December 12, 2013

Problem is

### Problem Statement

Fox Ciel has some items. The weight of the i-th (0-based) item is item[i]. She wants to put all items into bins.

The capacity of each bin is 300. She can put an arbitrary number of items into a single bin, but the total weight of items in a bin must be less than or equal to 300.

You are given the int[] item. It is known that the weight of each item is between 101 and 300, inclusive. Return the minimal number of bins required to store all items.

### Definition

 Class: BinPackingEasy Method: minBins Parameters: int[] Returns: int Method signature: int minBins(int[] item) (be sure your method is public)

### Limits

 Time limit (s): 2 Memory limit (MB): 64

### Constraints

- item will contain between 1 and 50 elements, inclusive.
- Each element of item will be between 101 and 300, inclusive.

### Examples

0)

 `{150, 150, 150, 150, 150}`
`Returns: 3`
 You have five items and each bin can hold at most two of them. You need at least three bins.
1)

 `{130, 140, 150, 160}`
`Returns: 2`
 For example, you can distribute the items in the following way: Bin 1: 130, 150 Bin 2: 140, 160
2)

 `{101, 101, 101, 101, 101, 101, 101, 101, 101}`
`Returns: 5`
3)

 `{101, 200, 101, 101, 101, 101, 200, 101, 200}`
`Returns: 6`
4)

 `{123, 145, 167, 213, 245, 267, 289, 132, 154, 176, 198}`
`Returns: 8`

and My Code is blow

public static int minBins2(int[] items){
Arrays.sort(items);

int sp = 0;
int ep = Math.max(items.length -1, 0);

int totalNum =0;
while(true){
if(items[ep] > 199){
totalNum ++;
ep--;
}else{
break;
}
}

while(ep >= sp){
if(items[ep] + items[sp] <= 300){
sp++;
}
ep--;
totalNum++;
}

}

## Access Step ##

1. Sort Items
2. if items are bigger than 199 add totalNum
3. sum of first item and last item are bigger than 300
last index -- and totalnum ++
.......

i think this is very easy

The Question is

### Problem Statement

Fox Ciel received a string as a birthday present. However, the string was too long for her, so she decided to make it shorter by erasing some characters.

The erasing process will look as follows:
1. Find the smallest i such that the i-th character and the (i+1)-th character of the string are same.
2. If there is no such i, end the process.
3. Remove the i-th and the (i+1)-th character of the string, and repeat from 1.

For example, if she receives "cieeilll", she will change the string as follows: "cieeilll" -> "ciilll" -> "clll" -> "cl". You are given a String s. Return the string she will get after she erases characters as described above.

### Definition

 Class: ErasingCharacters Method: simulate Parameters: String Returns: String Method signature: String simulate(String s) (be sure your method is public)

### Limits

 Time limit (s): 2 Memory limit (MB): 64

### Constraints

- s will contain between 1 and 50 characters, inclusive.
- Each character in s will be a lowercase letter ('a'-'z').

### Examples

0)

 `"cieeilll"`
`Returns: "cl"`
 This is the example from the statement.
1)

 `"topcoder"`
`Returns: "topcoder"`
 She won't erase any characters at all.
2)

 `"abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba"`
`Returns: ""`
3)

 `"bacaabaccbaaccabbcabbacabcbba"`
`Returns: "bacbaca"`
4)

 `"eel"`
`Returns: "l"`

My Solution is Below

public static String simulate(String str){
int start =0;

while(str.length()-1 >start){
char firstChar = str.charAt(start);
//   System.out.println(firstChar + " : fisrt");
char nextChar = str.charAt(start+1);
//   System.out.println(nextChar +" : next");
if(firstChar == nextChar){
str = str.substring(0, start) + str.substring(start+2, str.length());
//    System.out.println("complete:" + str);
if(start !=0){
start--;
}
}else{
start++;
}
}

//  System.out.println(str);
return str;
}

## Access Logic ##

my access is below but i don't think this is a good sample

because i just got 144point / 250 point

so other soultions are better than my solution

i attached other solution after my solution

 `cieeilll `
first point is c
first+1 point is i

c and i is differenct so first point will be 2

first point is i
first+1 point is e

c and i is differenct so first point will be 3

firtst point e
first+1 point is e

e and e is the same so cut before first point "ci" and cut after firstPoint +1 to end "ill"
and concat before string and after string

this will be ciill

first point changed first-1

Otheres are Below

public static String simulate(String s){
for(int i=0; i<s.length()-1 i++){
if(s.charAT(i) == s.charAT(i+1)){
s= s.substring(0, i) + s.substring(i+2, s.length);
i=-1;
}
}
}

sombody use StringBuffer.delete

and sombody use Stack

many different way i learend from topcoder --V

## Sunday, December 1, 2013

### Make small cafe DIY(Do it yourself)~

My name English Name is David Jung linving in korea.

2013/11/29 was just one year passed from meeting my girlFriend.

so I wanted make her surprized and mad samll cafe for her

complete
~

wow ~

## Wednesday, November 27, 2013

### Bubble Sort

 Sort Average Best Worst Space Stability Remarks Bubble sort O(n^2) O(n^2) O(n^2) Constant Stable Always use a modified bubble sort Modified Bubble sort O(n^2) O(n) O(n^2) Constant Stable Stops after reaching a sorted array Selection Sort O(n^2) O(n^2) O(n^2) Constant Stable Even a perfectly sorted input requires scanning the entire array Insertion Sort O(n^2) O(n) O(n^2) Constant Stable In the best case (already sorted), every insert requires constant time Heap Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Constant Instable By using input array as storage for the heap, it is possible to achieve constant space Merge Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Depends Stable On arrays, merge sort requires O(n) space; on linked lists, merge sort requires constant space Quicksort O(n*log(n)) O(n*log(n)) O(n^2) Constant Stable Randomly picking a pivot value (or shuffling the array prior to sorting) can help avoid worst case scenarios such as a perfectly sorted array.

this is bubble sort example

lets make it c language

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int arr[] = {5, 1, 12, -5, 16, 2, 12, 14};

int count;
int i=0, j=0, k=0, temp;
count = sizeof(arr)/sizeof(arr[0]);
for(j; j<count -1; j++){
for(i=0; i<count-1-j; i++){
if(arr[i]> arr[i+1]){
temp = arr[i];
arr[i]= arr[i+1];
arr[i+1]= temp;
}
}

k=0;
for(k=0; k<count; k++){
printf("%d ", arr[k]);
}
printf("\n");
}
return 0;
}

result :

1 5 -5 12 2 12 14 16
1 -5 5 2 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16

### Selection sort

Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort.

lets make it C language

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int arr[] = {5, 1, 12, -5, 16, 2, 12, 14};
int i=0;
int j=0;
int count=0;
int min=0;
int temp;

count = sizeof(arr)/sizeof(arr[0]);

for(i;i<count-1; i++){
min =i;
for(j=i+1;j<count; j++){
if(arr[min]>arr[j]){
min=j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
i=0;
for(i=0; i<count; i++){
printf("%d ", arr[i]);
}
return 0;
}

## Tuesday, November 12, 2013

this would be a good example

## Monday, November 11, 2013

### This is basic concept of Memoization in Javascript

<!DOCTYPE>
<html>
<body>
<script>
<!--  Basic use -->
function square(num){
return num*num;
}

console.log(square(10));

function squareMemoization(num){
var result= '';
if(!squareMemoization.cache[num]){
console.log("computing value..");
result = num * num;
squareMemoization.cache[num]= result;
}

return squareMemoization.cache[num];

}

squareMemoization.cache = {};

console.log(squareMemoization(10)); //First time when we call this function. It calculates the value &amp; cache it.
console.log(squareMemoization(10)); // Second time onwards it return the result from cache.
console.log(squareMemoization(20)); // square function will calculate again if its a new value.

var a = ["a", "b", "c"];

console.log('a.slice(1,2)');
console.log(a.slice(1,2));
console.log('a.slice(1)');
console.log(a.slice(1));
console.log(a);

console.log('Array.prototype.slice.call(a, 1)');
console.log(Array.prototype.slice.call(a, 1));

</script>
</body>
</html>

## Wednesday, November 6, 2013

### make javascript Speed Up (2)

Asynchronous Transfer Mode getting script

this is sample

<!DOCTYPE html>
<html>
<body>
<p>Hello</p>
<script>
var script = document.createElement("script");
script.type = "text/javascript";
callback();
}
};
}else{ //ELSE
callback();
};
}

script.src=url;

}

});
});
}
</script>
</body>
</html>

### make javascript Speed Up (1)

Do you Think which sample is better between two samples

1. <html>
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
<body>
...
</body>
<html>

2. <html>
<body>
...
//end of body
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</body>
<html>

First is well-known pattern when we use javascript, and also we learn like 1 sample

but until scripts are fully loaded we will see white page

Second sample is better than first
because after body is loaded javascript will run

## Tuesday, November 5, 2013

### how to compare string values using jstl fn

At first~!

in html we need to add Declare using jstl

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYE html>
<html>
....
</html>

this is really good i think

<jsp:useBean id="extension" class="java.util.HashSet" scope="request">
<%
%>
</jsp:useBean>
<c:choose>
<c:when test="\${fn:contains(extension, attach.contentType)}">
<img src="/neo/img/neo/theme/fileIcon/file_\${attach.contentType}.gif"/>\${attach.name} \${attach.size }bytes</a>
</c:when>
<c:otherwise>
<img src="/neo/img/neo/theme/fileIcon/file_unknown.gif"/>\${attach.name} \${attach.size }bytes</a>
</c:otherwise>
</c:choose>

## Monday, November 4, 2013

### make Callback function and check if it is undefine in javascript

<!DOCTYPE html>

<html>
<script>

function hello(){
test(function aaa(){
});

test();
}

function test(callback){
if(typeof callback  != 'undefined'){

callback();
}
}
</script>

</html>

## Sunday, November 3, 2013

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.

Here we will see each dialog box one by one:

An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:

 ``` ```

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.

# Confirmation Dialog Box:

A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.

If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:

 ``` ```

# Prompt Dialog Box:

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.

This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.

You can use prompt dialog box as follows:

 ``` ```

### Maven Using filter~ It is Awesome

When you use maven Filter is very good for user
We can easily control enviroment of the project

Let's use Porifle

Ex> pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<!-- Spring MVC framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5.6</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
<property>
<name>env</name>
<value>dev</value>
</property>
</activation>
<properties>
<appserver.home>dev</appserver.home>
</properties>
</profile>
<profile>
<id>real</id>
<activation>
<property>
<name>env</name>
<value>real</value>
</property>
</activation>
<properties>
<appserver.home>real</appserver.home>
</properties>
</profile>
</profiles>
<build>
<filters>
<filter>src/main/filter/\${appserver.home}/spring-views.properties</filter>
</filters>

<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

project tree
src/main/filter/dev-spring-views.properties
/real-spring-views.properties
src/main/java
src/resources/spring-views.properties

command line
\$ mvn clean package -P real

filters poperties will be injected into resources/spring-veiw.properties

if you want have sample

## Saturday, November 2, 2013

### Spring escapeXMl using StringEscapeUtils

escape xss from hacker

we have to  change value using  StringEscapeUtils.escapeXml(str)

this is apache library
import org.apache.commons.lang.StringEscapeUtils;

//handling xml special character & in Java String
String xmlWithSpecial = "Java & HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String in Java: "
+  StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling xml special character > in String on Java
xmlWithSpecial = "Java > HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String : " + StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling xml and html special character < in String
xmlWithSpecial = "Java < HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling html and xml special character " in Java
xmlWithSpecial = "Java \" HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling xml special character ' in String from Java
xmlWithSpecial = "Java ' HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

## Sunday, October 27, 2013

### Spring 3 Scheduler

Basic Schduler in spring 3

<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
">

<bean id="schedulerService" class="com.operation.service.SchedulerService"
scope="singleton"/>

/**
* @author jjhangu
*
*/
public class SchedulerService {
@Scheduled(fixedDelay = 5000)
public void doSomething() {
final long time = System.currentTimeMillis();
final SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
final String str = dayTime.format(new Date(time));
System.out.println("gap is 5 second" + str);
}
}

log gap is 5scond2013-06-28 02:06:44
log gap is 5scond2013-06-28 02:06:49

## Wednesday, October 23, 2013

### Let me make replaceAll in Javascript

There is no replaceAll in javascript

if you use replace

ex) var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.replace('to', 'ha');
console.log(orgStr);
output = "welcome ha my blog to have a fun"

It mean only first String will be replaced but otheres not,

So this is good solution

var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.split('to').join('ha');
console.log(orgStr);
output = "welcome ha my blog ha have a fun"

## Thursday, October 17, 2013

### Javascript get Max Width of element in childnode

this function will return that the max width of element from tag element to inner element

var mainDiv = document.getElementById('mainDiv');
contentWidth = document.getElementById('contentScroller').offsetWidth;
var maxVal = getMax (mainDiv, contentWidth);

function getMax (tag, val){
if(typeof tag.offsetWidth != "undefined"){
if(val < tag.offsetWidth){
val = tag.offsetWidth;
}
}

if(tag.children.length>0){
var i=0;
for (i=0;i<tag.children.length;i++){
var childVal = getMax(tag.children[i], val);
if(val < childVal){
val = childVal;
}
}
}
return val;
}

## Monday, October 14, 2013

### Search Tag in Iframe from out of Iframe

this is Just example

var frameHtml = document.getElementById("main_iframe").contentWindow.document.body.innerHTML;
}else{

}

};

<iframe src="" id="main_iframe" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="0" scrolling="no"></iframe>

### Call to Parent Function in Iframe

There are two ways call parent function in iframe

parent.functionName

or

window.top.functionName

This is only in my opinion, I would prefer to use  window.top.functionName.

because parent is not working well in sometime.

## Wednesday, October 9, 2013

### DOMWindow.js this is kind of popup in html

you can try example from below site http://swip.codylindley.com/DOMWindowDemo.html#inlineContentExample7

## Wednesday, September 11, 2013

### Install Openfire with Mssql

GO to openfire Website

Select Language

setting Dabase

Setting Profile

asdf﻿

## Tuesday, September 10, 2013

### Query time Count

you can fine result millisecond

DECLARE @start_time DATETIME, @end_time DATETIME
SET @start_time = CURRENT_TIMESTAMP;

SET @end_time = CURRENT_TIMESTAMP
SELECT DATEDIFF(ms, @start_time, @end_time),DATEDIFF(ms, @start_time, @end_time)/1000;

## Sunday, September 8, 2013

### Oracle backup exp

exp system/oracle file=/backup/export/test05.dmp owner=(scott, hr)

## Tuesday, September 3, 2013

### Oracle import dmp file

Step by Step

if not exist
1. create user {user_id} identified by {password}

2. GRANT CONNECT, DBA, RESOURCE TO {user_id};

\$ imp {user_id}/{password} file={filename}.dmp ignore=y full=y

wow very Easy~

## Sunday, September 1, 2013

### Apache Benchmark

[root@dev bin]# pwd

/usr/bin

[root@dev bin]# ab -n 500 -c 20 http://{testURL}

설명 : ab n Request개수(500) c 동시접속자 URL (API)

== 결과값 ==

This is ApacheBench, Version 2.3 <\$Revision: 655654 \$>

Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 203.233.82.229 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Finished 500 requests

Server Software:        Apache/2.2.21
Server Hostname:        203.233.82.229
Server Port:            80

Document Path:          //account/view/terms
Document Length:        4593 bytes

Concurrency Level:      20 (동시 접속자)
Time taken for tests:   0.513 seconds (총 소요시간)
Complete requests:      500
Failed requests:        0
Write errors:           0
Total transferred:      2511500 bytes
HTML transferred:       2296500 bytes
Requests per second:    975.44 [#/sec] (mean)
Time per request:       20.504 [ms] (mean)
Time per request:       1.025 [ms] (mean, across all concurrent requests)

Connection Times (ms)
min  mean[+/-sd] median   max
Connect:        5    6   0.8      6       9
Processing:     8   14   8.3     11     124
Waiting:        7   14   8.3     11     123
Total:         13   20   8.6     17     131

Percentage of the requests served within a certain time (ms)
50%     17
66%     19
75%     21
80%     22
90%     30
95%     34
98%     45
99%     55
100%    131 (longest request)

## Tuesday, August 27, 2013

### Difference Between Connection Time out and Socket Time out~!!!

this is easy but easily fogettable

Connection Timeout is is the timeout in making the initial connection

Socket Timeout is the timeout on waiting to read data.

don't forget it~!

## Monday, August 26, 2013

### oracle query trace

1. first of all need to find session id if you use any tool loke toad or sqldeveloper

SELECT * FROM v\$session

2. connect oracle by console

sqlplus '/as sysdba'
sessionid  , serial
execute sys.dbms_system.set_sql_trace_in_session(1151,29373,true);

find recently maed using
ls -ltr

tkprof filename.trc customname.txt explain=user/pw sys=no

ex)tkprof neosns_ora_7274.trc t1.txt explain=neo_sns/neo_sns_dba sys=no

execute sys.dbms_system.set_sql_trace_in_session(1151,29373,false);

## Wednesday, August 21, 2013

### Making Secure Communication With RSA, DES [java]

Today I tried to write secure communication between client and server

i want to use ssl way

step by step I make example

and you just this process if you want secure communication

## Client ##
1. making publicKey and privateKey using RSA
2, making publicKey to Base64 String
3. give it(publicKey) to Server

## Server ##
4. receive publicKey from client and decode Bas64String to byte[]
5. get object publicKey
6. making symmetric-key (Random 16 number)
7. encryting publickey symmetric-key and give it to client

.. and

you can make encrypted  message by using des or any with symmetric-key

The point is symmetric-key is exposed to only one client and one server

/**
*
* @description <br/>
*
* @create 2013. 8. 21.
* @author jjhangu
*/
package secure;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Formatter;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSACrypt {

final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
final KeyPair keyPair = generator.generateKeyPair();
final PublicKey publicKey = keyPair.getPublic();
final PrivateKey privateKey = keyPair.getPrivate();

/**
* 시나리오 1
*
* Client
* 1. make RSA keys (publicKey, priateKey)
* 2. give publicKey to Server
*
* Server
* 3. make Symmetric-key using publicKey given by client
* 4. give it to client
*
* Client and Server Communicate Using Symmetric-key using DES Algorithm
*
*/

// Client
// 1 making public and private key
final BASE64Encoder encoder = new BASE64Encoder();
final String pubKeyStr = encoder.encode(publicKey.getEncoded());
System.out.println("#######################################");
System.out.println("Client[publicKey] BASE64 ");
System.out.println("#######################################");
System.out.println(pubKeyStr);
System.out.println();
System.out.println();

final String priKeyStr = encoder.encode(privateKey.getEncoded());
System.out.println("#######################################");
System.out.println("Client[privateKey] BASE64 ");
System.out.println("#######################################");
System.out.println(priKeyStr);
System.out.println();
System.out.println();

// give it to public key to server

// Server
// 3. Get Public Key obejct

final BASE64Decoder decoder = new BASE64Decoder();
final byte[] sigBytes2 = decoder.decodeBuffer(pubKeyStr);

// PublicKey from client
final PublicKey publicServerKey = convertKeytoKeyObject(sigBytes2);

final String pubServerKeyStr = encoder.encode(publicServerKey.getEncoded());
System.out.println("#######################################");
System.out.println("Server [publicKey] BASE64 ");
System.out.println("#######################################");
System.out.println(pubServerKeyStr);
System.out.println();
System.out.println();

// 3. make Symmetric-key using publicKey given by client

final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicServerKey);
final String symmetricKey = "0123456789ABCDEF";

System.out.println("#######################################");
System.out.println("Server [symmetricKey] ");
System.out.println("#######################################");
System.out.println(symmetricKey);
System.out.println();
System.out.println();

final byte[] b0 = cipher.doFinal(symmetricKey.getBytes());

// give symmetricKey to Client

// client decode
cipher.init(Cipher.DECRYPT_MODE, privateKey);
final byte[] b1 = cipher.doFinal(b0);

System.out.println("Client Finally Decode SymmetricKey : " + new String(b1));

// only one client and server will know symmetricKey
// and Server Client will Have Same symmetricKey and Communucating message using des
// algorithm with this symmetricKey
}

public static String bytesToHexString(byte[] bytes) {
final StringBuilder sb = new StringBuilder(bytes.length * 2);

final Formatter formatter = new Formatter(sb);
for (final byte b : bytes) {
formatter.format("%02x", b);
}

return sb.toString();
}

private static PublicKey convertKeytoKeyObject(byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
final X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
final KeyFactory keyFact = KeyFactory.getInstance("RSA");
return keyFact.generatePublic(x509KeySpec);
}

}