2018년 11월 1일 목요일

[JavaFx] ImageView Example


1. ImageView 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
35
36
37
38
39
40
41
import java.io.File;

import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public class FxImageView implements FxNode {

    ImageView imageView;
    String imageFile;

    public FxImageView() {
        imageView = new ImageView();
    }

    public FxImageView(String image) {
        imageFile = new File(image).toURI().toString();
        imageView = new ImageView(new Image(imageFile));
    }

    public FxImageView(int width, int height) {
        imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setFitWidth(width);
        imageView.setFitHeight(height);
    }

    public FxImageView(String imageFile, int width, int height) {
        imageView = new ImageView(new Image(new File(imageFile).toURI().toString(), width, height, true, true));
        imageView.setPreserveRatio(true);
    }

    @Override public Node get() {
        return imageView;
    }

    public void load(String imageFile) {
        imageView.setImage(new Image(new File(imageFile).toURI().toString()));
    }
    
}

[JavaFx] ContextMenu Example


1. ContextMenu 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
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
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;

public class FxContextMenu {

    ContextMenu rootMenu;
    Menu currMenu;
    int fontSize = 12;
    
    public FxContextMenu(int fontsize) {
        rootMenu = new ContextMenu();
        currMenu = null;
        fontSize = fontsize;
    }
    
    public FxContextMenu() {
        this(12);
    }
    
    public ContextMenu getMenu() {
        return rootMenu;
    }
    
    public void addMenu(String text) {
        currMenu = new Menu(text);
        currMenu.setStyle("-fx-font-size: " + fontSize + " pt;");
        rootMenu.getItems().add(currMenu);
    }
    
    public void addMenuItem(Menu menu, String text, Runnable runnable) {
        MenuItem item;
        if( text != null ) {
            item = new MenuItem(text);
            if( runnable != null ) {
                item.setOnAction(e -> runnable.run());
            }
        } else {
            item = new SeparatorMenuItem();
        }
        if( fontSize > 0 ) {
            item.setStyle("-fx-font-size: " + fontSize + " pt;");
        }
        if( menu != null ) {
            menu.getItems().add(item);
        } else {
            rootMenu.getItems().add(item);
        }
    }
    
    public void addMenuItem(String text, Runnable runnable) {
        addMenuItem( currMenu, text, runnable );
    }
    
    public void addRootMenuItem(String text, Runnable runnable) {
        currMenu = null;
        addMenuItem( currMenu, text, runnable );        
    }
}


[Java] Properties Load and Save Example



1. Properties Load and Save 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
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
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class Settings {

    Properties settings;
    
    public Settings() {
        settings = new Properties();
        load();
    }
    
    public void load() {    
        InputStream input = null;
        try {
            input = new FileInputStream("config.properties");
            settings.load(input);
        } catch (IOException ex) {
                ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public void save() {
        OutputStream output = null;
        try {
            output = new FileOutputStream("config.properties");
            settings.store(output, null);
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public void set(String name, String value) {
        settings.setProperty(name, value);
    }
    
    public String get(String name) {
        return settings.getProperty(name);
    }
}

[Java] Thread Pool Example


1. Thread Pool
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThreadPool<T> {

 ExecutorService executorService;
 CompletionService<T> completionService;
 
 public void createFixedThreadPool(int nThreads) {
  createService(nThreads);
 }

 public void createFixedThreadPool() {
  createService(Runtime.getRuntime().availableProcessors());
 }

 private void createService(int nThreads) {
  executorService = Executors.newFixedThreadPool(nThreads);
  completionService = new ExecutorCompletionService<T>(executorService); 
 }
 
 public void shutdown() {
  executorService.shutdown();
 }

 public List<Runnable> shutdownNow() {
  return executorService.shutdownNow();
 }
 
 public Boolean awaitTermination( long timeout, TimeUnit unit ) throws InterruptedException {
  return executorService.awaitTermination(timeout, unit);
 }

 public void execute(Runnable task) {
  executorService.execute(task);
 }

 public Future<Result> submit(Runnable task, Result result) {
  return executorService.submit(task, result);
 }
 
 public Future<T> submit(Callable<T> task) {
  return executorService.submit(task);
 }

 public Future<T> submitCompletion(Callable<T> task) {
  return completionService.submit(task);
 }

 //----------------------------------------------------------------------
 // Test Code - Start
 //----------------------------------------------------------------------
 public static Runnable newRunnable(int id) {
  Runnable task = new Runnable() {
   @Override
   public void run() {
    String threadName = Thread.currentThread().getName();
    for( int i=0; i < 10; i++ ) {
     try {
      Thread.sleep(1000);
      System.out.println( "[" + threadName + "] Runnable_" + id + ": " + i);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  };
  return task;
 }

 public static Callable<Integer> newCallable(int id) {
  Callable<Integer> task = new Callable<Integer>() {
   @Override
   public Integer call() throws Exception {
    String threadName = Thread.currentThread().getName();
    for( int i=0; i < 10; i++ ) {
     try {
      Thread.sleep(1000);
      System.out.println( "[" + threadName + "] Callable_" + id + ": " + i);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    return id*100;
   }
  };
  return task;
 }

 public static void sleep(int sec) {
  try {
   Thread.sleep(sec*1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 public static void println(String s) {
  System.out.println( "[" + LocalDateTime.now() + "] " + s);
 }
 
 public static void runnableTest() {
  println("runnableTest() start !");
  ThreadPool<Integer> threads = new ThreadPool<Integer>();
  threads.createFixedThreadPool();
  for( int i=0; i < 10; i++ ) {
   threads.execute(newRunnable(i));
  }
  println("runnableTest() shutdown !");
  threads.shutdown();
  println("runnableTest() end !");
 }

 @SuppressWarnings("unchecked")
 public static void callableTest() {
  println("callableTest() start !");
  ThreadPool<Integer> threads = new ThreadPool<Integer>();
  threads.createFixedThreadPool();
  Future<Integer>[] future = new Future[10];
  for( int i=0; i < 10; i++ ) {
   future[i] = threads.submit(newCallable(i));
  }
  println("callableTest() shutdown !");
  threads.shutdown();
  Integer[] result = new Integer[10];
  for( int i=0; i < 10; i++ ) {
   try {
    result[i] = (Integer)future[i].get();
    println("callableTest() result[" + i + "] = " + result[i]);
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  }
  println("callableTest() end !");
 }
 
 public static void callableWithCompletionServiceTest() {
  println("callableWithCompletionServiceTest() start !");
  ThreadPool<Integer> threads = new ThreadPool<Integer>();
  threads.createFixedThreadPool();
  for( int i=0; i < 10; i++ ) {
   threads.submitCompletion(newCallable(i));
  }
  println("callableWithCompletionServiceTest() shutdown !");
  threads.shutdown();
  for( int i=0; i < 10; i++ ) {
   try {
    Future<Integer> future = threads.completionService.take();
    Integer result = (Integer)future.get();
    println("callableWithCompletionServiceTest() result[" + i + "] = " + result);
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  }
  println("callableWithCompletionServiceTest() end !");
 }
 
 public static void main(String[] args) {
  runnableTest();
  callableTest();
  callableWithCompletionServiceTest();
 }
}



[Java] FTP Server Example (MinimalFtp)


MinimalFtp Home: https://github.com/Guichaguri/MinimalFTP

1. FTP Server 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import com.guichaguri.minimalftp.FTPConnection;
import com.guichaguri.minimalftp.FTPServer;
import com.guichaguri.minimalftp.IFTPListener;
import com.guichaguri.minimalftp.IFileSystem;
import com.guichaguri.minimalftp.IUserAuthenticator;
import com.guichaguri.minimalftp.NativeFileSystem;

public class FtpServer implements IFTPListener {

    public static void main(String[] args) throws IOException {
        User auth = new User("user", "1234", "D:\\Temp" ); 
        FTPServer server = new FTPServer();
        server.setAuthenticator(auth);
        server.addListener(new FtpServer());
        server.listenSync(21); //server.listen(21);
        server.close();
    }
    
    @Override
    public void onConnected(FTPConnection con) {
        System.out.println("[Connected] Host: " + con.getAddress().getHostAddress());
    }

    @Override
    public void onDisconnected(FTPConnection con) {
        System.out.println("[Disconnected] Host: " + con.getAddress().getHostAddress() + ", User: " + con.getUsername());
    }
}

class User implements IUserAuthenticator {
    String username;
    String password;
    String homedir;
    public User(String user, String pw, String home) { 
        username = user; 
        password = pw; 
        homedir = home; 
    }
    @Override public boolean needsUsername(FTPConnection con) { return true; }
    @Override public boolean needsPassword(FTPConnection con, String username, InetAddress address) { return true; }
    @Override public IFileSystem<?> authenticate(FTPConnection con, InetAddress address, String user, String pw) throws AuthException {
        if( ! username.equals(user) ) {
            throw new AuthException(); 
        }
        if( ! password.equals(pw) ) { 
            throw new AuthException(); 
        }
        return new NativeFileSystem(new File(homedir));
    }
}

[Java] WebServer Example (NanoHttpd)


NanoHttpd Home: https://github.com/NanoHttpd/nanohttpd

Tiny, easily embeddable HTTP server in Java. (single source file)



1. WebServer 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
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
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;

public class WebServer extends NanoHTTPD {
    
    NanoHTTPD nano;
    String baseFolder;

    public static void main(String[] args) {
        try {
            WebServer nano = new WebServer(8880);
            nano.setBaseFolder("D:\\Temp");
            nano.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    public WebServer(int port) throws IOException {
        super(port);
        System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
    }

    public void setBaseFolder(String folder) {
        baseFolder = folder;
    }

    private String trimPrefix(String text, String prefix) {
        if( text.startsWith(prefix) ) {
            text = text.substring(prefix.length());
        }
        return text;
    }
    
    private String getDirectoryList(File folder, String uri) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        File[] files = folder.listFiles();
        StringBuilder sb = new StringBuilder();
        sb.append("<html><head><style type=\"text/css\" scoped>\r\n" + 
                " table, th, td { border: 1px solid gray; border-collapse: collapse; } \r\n" + 
                " a { text-decoration: none;\r\n" + 
                " } \r\n" + 
                "</style></head><body>\r\n"+
                "<h5> Folder: "+uri+"</h5>\r\n" +
                "<table><thead>\r\n" + 
                "<tr>\r\n" + 
                "  <th>Filename</th>\r\n" + 
                "  <th>Size <small>(bytes)</small></th>\r\n" + 
                "  <th>Date Modified</th>\r\n" + 
                "</tr>\r\n" + 
                "</thead><tbody>");
        
        if( ! folder.equals(new File(baseFolder)) ) {
            sb.append("<tr>\r\n");
            sb.append("<td><a href=\"" + trimPrefix(folder.getParent(), baseFolder) + "\">..</a></td>");
            sb.append("<td align=\"right\">&lt;DIR&gt;</td>");
            sb.append("<td>&nbsp;</td>");
            sb.append("</tr>\r\n");
        }
        
        for( File file : files ) {
            sb.append("<tr>\r\n");
            sb.append("<td><a href=\"" + trimPrefix(file.getPath(), baseFolder) + "\">"); sb.append(file.getName()); sb.append("</a></td>");
            if( file.isDirectory() ) {
                sb.append("<td align=\"right\">&lt;DIR&gt;</td>");
            } else {
                sb.append("<td align=\"right\">"); sb.append(""+file.length()); sb.append("</td>");
            }
            sb.append("<td>"); sb.append(""+sdf.format(file.lastModified())); sb.append("</td>");
            sb.append("</tr>\r\n");
        }
        sb.append("</tbody></table></body></html>");
        System.out.println("RESPONSE: " + sb.toString());
        return sb.toString();
    }
    
    @Override
    public Response serve(IHTTPSession session) {
        System.out.println("URI: " + session.getUri());
        String uri = session.getUri();
        File file = new File(baseFolder, uri);
        if( file.isDirectory() ) {
            return newFixedLengthResponse(getDirectoryList(file,uri));
        } else {
            try {
                return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, new FileInputStream(file), file.length());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return newFixedLengthResponse("");
            }
        }
    }
}


Output:



2018년 10월 31일 수요일

[JavaFx] TextField Example


1. TextField 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
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
import java.io.File;
import java.util.List;

import javafx.event.EventHandler;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class FxTextField implements FxNode {
    
    TextField text;
    
    public FxTextField(Runnable runnable) {
        text = new TextField();
        FxDrop.setDropHandler(text, new FxRunnable() {
            @SuppressWarnings("unchecked")
            @Override public void run(Object... object) {
                if( object[0] instanceof List<?> ) {
                    List<File> files = (List<File>) object[0];
                    text.setText( files.get(0).getPath() );
                }
            }
        });
        if( runnable != null ) {
            text.textProperty().addListener((observable, oldValue, newValue) -> {
                runnable.run();
            });
        }
    }
    
    public FxTextField() {
        this(null);
    }

    @Override
    public TextField get() {
        return text;
    }
    
    public void setOnEnterHandler(Runnable runnable) {
        text.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override public void handle(KeyEvent event) {
                if (event.getCode().equals( KeyCode.ENTER) ) {
                    runnable.run();
                }                
            }
        });
    }
    
    public void clear() {
        text.clear();
    }
    
    public String getText() {
        return text.getText();
    }
    
    public void setText(String value) {
        text.setText(value);
    }
    
    public void setFontSize(int size) {
        if( size > 0 ) {
            text.setStyle("-fx-font-size: " + size + ";"); //1em = 50px
        }
    }
    
    public void clearAllText() {
        text.clear();
    }
    
    public void copyAllText() {
        text.selectAll();
        text.copy();
        text.deselect();
    }
    
    public void pasteAllText() {
        text.selectAll();
        text.paste();
        text.deselect();
    }
    
    public void pasteAllHtml() {
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        String data;
        if( clipboard.hasHtml() ) {
            data = clipboard.getHtml();
        } else {
            data = clipboard.getString();
        }
        text.setText(data);          
    }
}