2018년 4월 25일 수요일

[Java] JavaScript Interface


Download: J2V8

j2v8_linux_x86_64. (V4.8.0)
j2v8_win32_x86_64 (V4.6.0)
j2v8_win32_x86 (V4.6.0)
j2v8_macosx_x86_64 (V4.6.0)
j2v8_android (V3.0.5)


1. Execute simple expression

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import com.eclipsesource.v8.V8;

public class Expression {
    public static void main(String[] args) {
     V8 v8 = V8.createV8Runtime();
     Object result = v8.executeScript("1+1");
     System.out.println("Result: " + result);
     result = v8.executeScript("\"Hello\"");
     System.out.println("Result: " + result);
     v8.release();
    }
}

Result:
Result: 2
Result: Hello


2. Execute JSON expression

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Object;

public class Json {
    public static void main(String[] args) {
     V8 v8 = V8.createV8Runtime();
     V8Object v8obj = v8.executeObjectScript("var me = {First: 'Robert', Middle: 'Ian', Last: 'Bull', age: 38}; me;");
     String name = (String) v8obj.getString("Last");
     int age = v8obj.getInteger("age");
     System.out.println("Name: " + name);
     System.out.println("Age: " + age);
     v8obj.release();
     v8.release();
    }
}

Result:
Name: Bull
Age: 38


3. Construct JavaScript Object from Java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Object;
import com.eclipsesource.v8.utils.V8ObjectUtils;
import java.util.Map;

public class JSObject {
    public static void main(String[] args) {
     V8 v8 = V8.createV8Runtime();
     V8Object v8obj = new V8Object(v8);
     v8obj.add("First", "Robert");
     v8obj.add("Last", "Bull");
     v8obj.add("Age", 38);
        Map<String, Object> map = V8ObjectUtils.toMap(v8obj);
        System.out.println("Name: " + map.get("Last"));
        System.out.println("Age: " + map.get("Age"));
     v8obj.release();
     v8.release();
    }    
}

Result:
Name: Bull
Age: 38


4. Call Java function from Java Script (void)

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import com.eclipsesource.v8.JavaVoidCallback;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;

public class CallbackVoid {
    public static void main(String[] args) {
     V8 v8 = V8.createV8Runtime();
     v8.registerJavaMethod(new JavaVoidCallback() {
            @Override
            public void invoke(final V8Object receiver, final V8Array args) {
                if (args.length() > 0) {
                    for( int i=0; i < args.length(); i++ ) {
                        System.out.println(args.get(i));
                    }
                }
            }
        }, "foo");
     v8.executeScript("foo('a',false, undefined)");
     v8.release();
    }      
}

Result:
a
false
undefined


5. Call Java function from Java Script (Integer)


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import com.eclipsesource.v8.JavaCallback;
import com.eclipsesource.v8.V8;

public class CallbackInteger {
    public static void main(String[] mainArgs) {
     V8 v8 = V8.createV8Runtime();
     v8.registerJavaMethod( (JavaCallback) (receiver, args) -> {
            if (args.length() > 0) {
             for( int i=0; i < args.length(); i++ ) {
                 System.out.println(args.get(i));
             }
            }      
            return 100;
        }, "bar");
     int v = (int)(Integer)v8.executeIntegerScript("bar('a',false, undefined)");
     System.out.println("v =" + v);
     v8.release();
    }      
}

Result:
a
false
undefined
v =100










2018년 4월 11일 수요일

[Java] Event using wait() and notify()


1. Event using wait() and notify()


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class WaitNotify {
    public WaitNotify() {
        
    }
    public void waitEvent() throws InterruptedException {
        synchronized(this) {
            wait();
        }
    }
    public void notifyEvent() throws InterruptedException {
        synchronized(this) {
            notify();
        }
    }
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify();
        Thread thread1 = new Thread( () -> {
            int i = 0;
            while(true) {
                try { 
                    wn.waitEvent();
                    System.out.println("Wake: " + i++);
                } catch (InterruptedException e) {
                }
            }
        });
        Thread thread2 = new Thread( () -> {
            for( int i=0; i < 10; i++ ) {
                try { 
                    wn.notifyEvent();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        });        
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
        }
        
    }
}


Result:
Wake: 0
Wake: 1
Wake: 2
Wake: 3
Wake: 4
Wake: 5
Wake: 6
Wake: 7
Wake: 8
Wake: 9




[Java] Thread Message using BlockingQueue


1. Thread Message using BlockingQueue


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Queue {
    static BlockingQueue queue;
    public static void main(String[] args) {
        queue = new LinkedBlockingQueue();
        new Thread( () -> {
            for( int i=0; i < 10; i++ ) {
                try { 
                    queue.put( "Message: " + i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }).start(); 
        while(true) {
            try { 
                System.out.println(queue.take());
            } catch (InterruptedException e) {
            }
        }
    }
}


Result:
Message: 0
Message: 1
Message: 2
Message: 3
Message: 4
Message: 5
Message: 6
Message: 7
Message: 8
Message: 9


[Java] File, ByteArray, String, Stream Conversion Examples


1. ByteArray To File

1) JDK ByteArray To Path
1
2
3
static void byteArrayToFileName(byte[] data, String file) throws IOException {
        java.nio.file.Files.write(Paths.get(file), data);
    }

2) Commons(FileUtils) ByteArray To File
1
2
3
static void byteArrayToFile(byte[] data, File file ) throws IOException {
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, data);
    }

3) Guava ByteArray To File
1
2
3
static void guavaByteArrayToFile(byte[] data, File file ) throws IOException {
        com.google.common.io.Files.write(data, file);
    }


2. File To ByteArray

1) JDK Path to ByteArray
1
2
3
static byte[] fileNameToByteArray(String file ) throws IOException {
        return java.nio.file.Files.readAllBytes(Paths.get(file));
    }

2) Commons(FileUtils) File To ByteArray
1
2
3
static byte[] fileToByteArray( File file ) throws IOException {
        return org.apache.commons.io.FileUtils.readFileToByteArray(file);
    }



3. InputStream to ByteArray

1) Commons(IOUtils) InputStream To ByteArray
1
2
3
static byte[] inputStreamToByteArray( InputStream is ) throws IOException {
        return org.apache.commons.io.IOUtils.toByteArray(is);
    }

2) Guava InputStream To ByteArray
1
2
3
static byte[] guavaInputStreamToByteArray( InputStream is ) throws IOException {
        return ByteStreams.toByteArray(is);
    }

3) JDK InputStream To ByteArray using ByteArrayOutputStream
1
 2
 3
 4
 5
 6
 7
 8
 9
10
static byte[] inputStreamToByteStream( InputStream is ) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[16384];
        int len;
        while ((len = is.read(data)) >= 0 ) {
            buffer.write(data, 0, len);
        }
        buffer.flush();
        return buffer.toByteArray();        
    }



4. ByteArray to InputStream

1) JDK ByteArray To InputStream
1
2
3
static InputStream byteArrayToInputStream(byte[] data) {
         return new ByteArrayInputStream(data);
    }



5. File To LinesArray

1) File To LinesArray using Scanner
1
2
3
4
5
6
7
8
static String[] readFileLines(File file) throws FileNotFoundException {
        List<String> lines = new ArrayList<>();
        final Scanner s = new Scanner(file);
        while(s.hasNextLine()) {
            lines.add(s.nextLine());
        }      
        return lines.toArray(new String[lines.size()]);
    }

2) File To LinesArray using BufferedReader
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
static String[] fileToLinesArray(File file) throws FileNotFoundException, IOException {
        List<String> lines = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(file));
        while(true) {
            String line = br.readLine();
            if( line == null ) {
                break;
            }
            lines.add(line);
        }      
        br.close();
        return lines.toArray(new String[lines.size()]);
    }


6. List To Array


1
2
3
4
5
6
7
static void listToArray() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        Integer[] array = list.toArray(new Integer[list.size()]);
    }


7. Array To List


1
2
3
4
5
6
7
8
9
static void arrayToList() {
        Integer[] values = { 1, 2, 3 };
        List<Integer> list = new ArrayList<>(Arrays.asList(values));
        
        int[] values2 = new int[] { 1, 2, 3 };
        list = Arrays.stream(values2).boxed().collect(Collectors.toList());
        list = Arrays.stream(values2).boxed().collect(Collectors.toCollection(ArrayList::new));
        list = Arrays.stream(values2).boxed().collect(Collectors.toCollection(LinkedList::new));      
    }








2018년 4월 10일 화요일

[Java] Tar Compress,Decompress Example



Downloadcommons-compress-1.16.1


1. Tar Compress Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static void tar( File baseDir, List<File> list, File outFile ) throws IOException {
    TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(outFile));
    taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
    taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
    taos.setAddPaxHeadersForNonAsciiNames(true);
    if (list.size() > 0) {
        for (int i = 0; i < list.size(); i++) {
            String entryName = list.get(i).getPath().substring(baseDir.getPath().length()+1);
            taos.putArchiveEntry(new TarArchiveEntry(list.get(i), entryName));
            try (FileInputStream in = new FileInputStream(list.get(i))){
                byte[] buf = new byte[8 * 1024];
                int length;        
                while ((length = in.read(buf, 0, buf.length)) >= 0) {
                    taos.write(buf, 0, length);
                }  
                in.close();
                taos.closeArchiveEntry();
            }
        }        
    }
    taos.close();
}

static void tarTest() throws IOException {
    Compress cu = new Compress();
    List<File> filelist = new ArrayList<File>();
    filelist.add(new File("d:\\temp/qsort.c"));
    filelist.add(new File("d:\\temp\\a\\leaf.cpp"));
    File dir = new File("d:\\temp");
    File zippedFile = new File ( "d:\\temp\\test.tar");
    cu.tar(dir, filelist, zippedFile);  
}


2. Tar + gzip Compress Example

Put GzipCompressorOutputStream() when open TarArchiveOutputStream() 


1
TarArchiveOutputStream taos = new TarArchiveOutputStream(new GzipCompressorOutputStream(new FileOutputStream(name)));



3. Tar Decompress Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static void untar( File inFile, File destDir ) throws IOException {
    TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(inFile));
    TarArchiveEntry entry;
    destDir.mkdirs();
    while ( (entry = tais.getNextTarEntry()) != null ){
        String name = entry.getName();
        File target = new File (destDir, name);
        System.out.println ("Entry : " + name);
        if ( entry.isDirectory() ){
            target.mkdirs();
        } else {
            if( ! target.getParentFile().exists() ) {
                target.getParentFile().mkdirs();
            }
            target.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
            byte [] buf = new byte[1024 * 8];
            int len = 0;
            while ((len = tais.read(buf)) >= 0 ){
                bos.write(buf, 0, len);
            }
            bos.close();
            System.out.println ("File : " + name);
        }
    }
    tais.close();        
}

static void untarTest() throws IOException {
    Compress cu = new Compress();
    File dir = new File("d:\\temp_tar");
    File zippedFile = new File ( "d:\\temp\\test.tar");        
    cu.untar( zippedFile, dir);
}


4. Tar + gzip Decompress Example

Put GzipCompressorInputStream() when open TarArchiveInputStream() 


1
TarArchiveInputStream fin = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(in)))



[Java] SSH, SFTP Client Example



Download: jsch-0.1.54.jar  Java Secure Channel Library



1. SSH, SFTP Client Example


SSHClient.java
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
public class SSHClient {

    Session session = null;
    Channel channel = null;

    String host;
    String user;
    String password;
    byte[] privateKey;
    
    int exitStatus;

    public SSHClient(String user, String host, byte[] privateKey) {
        this.user = user;
        this.host = host;
        this.privateKey = privateKey;
    }

    public SSHClient(String user, String host, String password) {
        this.user = user;
        this.host = host;
        this.password = password;
    }
    
    public void connect() throws JSchException, IOException {
        connect(20000);
    }

    public void connect(int connectTimeout) throws JSchException, IOException {
        JSch jsch = new JSch();
        if( privateKey != null ) {
            final byte[] prvkey = privateKey;
            final byte[] emptyPassPhrase = new byte[0];
            jsch.addIdentity(user, prvkey, null, emptyPassPhrase);
        }
        
        session = jsch.getSession(user, host, 22);
        Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setTimeout(connectTimeout);
        if( password != null ) {
            session.setPassword(password);
        }
        session.connect();
    }

    public void disconnect() {
        if (session != null) {
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }
    }

    public void sftpGet(String sourceFile, String targetFile) throws JSchException, SftpException, IOException {
        Channel lchannel = session.openChannel("sftp");
        lchannel.connect();
        ChannelSftp chSftp = (ChannelSftp) lchannel;
        InputStream is = chSftp.get(sourceFile);
        InputStreamToFile(is, targetFile);
        chSftp.disconnect();
    }

    public void sftpPut(String sourceFile, String targetFile) throws JSchException, FileNotFoundException, SftpException {
        Channel lchannel = session.openChannel("sftp");
        lchannel.connect();
        ChannelSftp chSftp = (ChannelSftp) lchannel;
        chSftp.put(new FileInputStream(new File(sourceFile)), targetFile);
        chSftp.disconnect();
    }

    public String executeCommand(String command) throws JSchException, IOException {
     System.out.println("EXEC Mode : Command being executed -->"+command);
     
     StringBuilder commandOutput = new StringBuilder();
        ChannelExec execChannel = null;
        execChannel = (ChannelExec) session.openChannel("exec");

        execChannel.setPty(true);
        execChannel.setCommand(command);
        execChannel.setInputStream(null);
        execChannel.setErrStream(System.err);
        execChannel.connect();
        
        InputStream in = execChannel.getInputStream();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                commandOutput.append(new String(tmp, 0, i));
            }
            if (execChannel.isClosed()) {
                if (in.available() > 0) {
                    continue;
                }
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
        }
        exitStatus = execChannel.getExitStatus();
        execChannel.disconnect();
        System.out.println("Command response -->"+commandOutput.toString());
        return commandOutput.toString();
    }

    public int getExitStatus() {
        return exitStatus;
    }
    
    public static void InputStreamToFile(InputStream is, String fileName) throws IOException, IOException{
        OutputStream os = new FileOutputStream(new File(fileName));
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0){
           os.write(buf, 0, len);
        }
        os.close();
    }
}


Test.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
static void testCommand(String user, String host, String password) {
        try{
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            String fileContent = sshClient.executeCommand("cat test.txt");
            System.out.println("Content -->"+fileContent);
            sshClient.disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }   
    }
    
    static void testGet(String user, String host, String password) {
        try {
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            sshClient.sftpGet("test.txt", "test1.txt");
            sshClient.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    static void testPut(String user, String host, String password) {
        try {
            SSHClient sshClient = new SSHClient(user, host, password);
            sshClient.connect();
            sshClient.sftpPut("test1.txt", "test2.txt");
            sshClient.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testCommand("user", "192.168.0.1", "password");
        testGet("user", "192.168.0.1", "password");
        testPut("user", "192.168.0.1", "password");
    }