2018년 11월 23일 금요일

[C#] WebView Example


1. WebView 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
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
using System;
using System.Windows.Forms;
using System.Collections.Generic;

namespace CsLib
{
    class CsWebView
    {
        Panel panel;
        WebBrowser web;
        ToolStripTextBox addr;

        public CsWebView()
        {
            Initialize();
        }

        public CsWebView(Boolean toolbar)
        {
            Initialize();
            if (toolbar)
            {
                makeToolbar();
            }
        }
        private void Initialize()
        {
            web = new WebBrowser();
            web.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            web.Dock = DockStyle.Fill;
            web.ScrollBarsEnabled = true;

            panel = new Panel();
            panel.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            panel.Dock = DockStyle.Fill;
            panel.Controls.Add(web);
        }

        public Panel get()
        {
            return panel;
        }

        public ToolStripButton addToolbarButton(ToolStrip tool, String text, EventHandler handler)
        {
            ToolStripButton button = new ToolStripButton();
            button.Name = text;
            button.Text = text;
            button.Click += handler;
            tool.Items.Add(button);
            return button;
        }

        public ToolStripTextBox addToolbarTextBox(ToolStrip tool, String text, KeyEventHandler handler)
        {
            ToolStripTextBox textbox = new ToolStripTextBox();
            textbox.Name = text;
            textbox.Text = "";
            textbox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            textbox.Dock = DockStyle.Fill;
            if (handler != null)
            {
                textbox.KeyDown += handler;
            }
            tool.Items.Add(textbox);
            return textbox;
        }

        public void makeToolbar()
        {
            ToolStrip tool = new ToolStrip();
            addToolbarButton(tool, "reload", reloadHandler);
            addToolbarButton(tool, "back", backHandler);
            addToolbarButton(tool, "forward", forwardHandler);
            addToolbarButton(tool, "text", textHandler);
            addToolbarButton(tool, "html", htmlHandler);

            ToolStrip tool2 = new ToolStrip();
            addr = addToolbarTextBox(tool2, "addr", addrHandler);
            addToolbarButton(tool2, "go", goHandler);

            panel.Controls.Add(tool2);
            panel.Controls.Add(tool);
        }

        public void loadUrl(String url)
        {
            web.Navigate(url);
        }

        public String getHtml()
        {
            return web.DocumentText;
        }

        public String getInnerText()
        {
            List<String> htmls = getText("html");
            return htmls[0];
        }

        public String getInnerHtml()
        {
            List<String> htmls = getHtmlText("html");
            return htmls[0];
        }

        public List<String> getText(String tag) //html, body, img ...
        {
            List<String> htmls = new List<String>();
            HtmlElementCollection elm = web.Document.GetElementsByTagName(tag);
            foreach (HtmlElement html in elm)
            {
                htmls.Add(html.InnerText);
            }
            return htmls;
        }

        public List<String> getHtmlText(String tag)
        {
            List<String> htmls = new List<String>();
            HtmlElementCollection elm = web.Document.GetElementsByTagName(tag);
            foreach (HtmlElement html in elm)
            {
                htmls.Add(html.InnerHtml);
            }
            return htmls;
        }

        private void reloadHandler(object source, EventArgs e)
        {
            web.Refresh();
        }

        private void backHandler(object source, EventArgs e)
        {
            if (web.CanGoBack)
            {
                web.GoBack();
            }
        }

        private void forwardHandler(object source, EventArgs e)
        {
            if (web.CanGoForward)
            {
                web.GoForward();
            }
        }

        private void textHandler(object source, EventArgs e)
        {
            Clipboard.SetText(getInnerText());
        }

        private void htmlHandler(object source, EventArgs e)
        {

            Clipboard.SetText(getInnerHtml());
        }

        private void addrHandler(object source, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                web.Navigate(addr.Text);
            }
        }

        private void goHandler(object source, EventArgs e)
        {
            web.Navigate(addr.Text);
        }
    }
}

[C#] WebView Form Example



1. WebView Form 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
using System;
using System.Drawing;
using System.Windows.Forms;

namespace CsLib
{
    class FormWebViewer : Form
    {
        CsWebView webView;
        CsTextBox textBox;
        CsStatusBar statusBar;

        public FormWebViewer()
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Name = "Window";
            this.Text = "Window";
            this.Size = new Size(800, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            makeStatusBar();
            makePanel();
            makeToolBar();
            makeMenuBar();
            this.Controls.Add(new CsButton("Hello", MyButtonClick));
        }

        private void makeMenuBar()
        {
            CsMenuBar menu = new CsMenuBar();
            menu.addMenu("File");
            menu.addMenuItem("Exit", showExitPopup);
            menu.addMenu("Help");
            menu.addMenuItem("About", showAboutPopup);
            this.Controls.Add(menu.get());
        }

        private void makeToolBar()
        {
            CsToolBar tool = new CsToolBar();
            tool.addToolItem("Exit", showExitPopup);
            this.Controls.Add(tool.get());
        }

        private void makeStatusBar()
        {
            statusBar = new CsStatusBar();
            statusBar.addPanel("Ready");
            statusBar.setText(0, "Ready");
            this.Controls.Add(statusBar.get());
        }
        private void makePanel()
        {
            webView = new CsWebView(true);
            webView.loadUrl("https://www.google.com");

            textBox = new CsTextBox();
            textBox.enableMultiLine();
            textBox.enableScrollBar();
            textBox.addText("Test");

            CsSplitContainer split = new CsSplitContainer();
            split.addLeftPanel(webView.get());
            split.addRightPanel(textBox.get());
            this.Controls.Add(split.get());
        }

        private void MyButtonClick(object source, EventArgs e)
        {
            MessageBox.Show("My First WinForm Application");
        }

        private void showExitPopup(object source, EventArgs e)
        {
            Application.Exit();
        }

        private void showAboutPopup(object source, EventArgs e)
        {
            MessageBox.Show("Windows Form Demo V0.1");
        }
    }
}

[C#] Main Example



1. Main Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using System;
using System.Windows.Forms;

namespace CsLib
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormWebViewer());
        }
    }
}


2018년 11월 22일 목요일

[C#] SplitContainer Example



1. SplitContainer 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
using System;
using System.Windows.Forms;
using System.Drawing;

namespace WindowsFormsApp3
{
    class CsSplitContainer
    {
        SplitContainer split;

        public CsSplitContainer()
        {
            split = new SplitContainer();
            split.Orientation = Orientation.Vertical;
            split.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            split.Dock = DockStyle.Fill;
            split.AutoScaleMode = AutoScaleMode.Inherit;
            //split.Size = new Size(100,200);
            split.SplitterDistance = 200;
            split.SplitterWidth = 6;
            split.Location = new Point(0, 0);


            split.FixedPanel = FixedPanel.Panel1;
            split.Panel1MinSize = 100;
            split.Panel1MinSize = 100;
            split.Panel1Collapsed = false;

            split.Show();
        }

        public SplitContainer get()
        {
            return split;
        }

        public void addLeftPanel(Control control)
        {
            SplitterPanel panel = split.Panel1;
            //panel.BackColor = Color.Green;
            //panel.ForeColor = Color.Yellow;
            panel.Controls.Add(control);
        }

        public void addRightPanel(Control control)
        {
            SplitterPanel panel = split.Panel2;
            //panel.BackColor = Color.OrangeRed;
            //panel.ForeColor = Color.White;
            panel.Controls.Add(control);
        }
    }
}

[C#] ListBox Example



1. ListBox 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
using System;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    class CsListBox
    {
        ListBox list;

        public CsListBox(EventHandler handler)
        {
            list = new ListBox();
            list.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            list.Dock = DockStyle.Fill;
            list.Show();
            //list.Click += handler;
        }

        public ListBox get()
        {
            return list;
        }

        public void addItem(String text)
        {
            list.Items.Add(text);
        }

        public int getSelectedIndex(String text)
        {
            return list.SelectedIndex;
        }

        public String getSelectedText()
        {
            return list.Items[list.SelectedIndex].ToString();
        }

    }
}

[C#] TextBox Example



1. TextBox 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
using System;
using System.Windows.Forms;
using System.Drawing;

namespace WindowsFormsApp3
{
    class CsTextBox
    {
        TextBox text;

        public CsTextBox()
        {
            text = new TextBox();
            text.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            text.Dock = DockStyle.Fill;
            text.Multiline = true;
            text.ScrollBars = ScrollBars.Both;
            text.Show();
        }

        public TextBox get()
        {
            return text;
        }

        public void addText(String s)
        {
            text.Text += s;
        }
    }
}

[C#] Button Example


1. Button Example
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    class CsButton : Button
    {
        public CsButton( String text, EventHandler handler)
        {
            this.Name = "button";
            this.Text = text;
            //this.Size = new Size(width, height);
            //this.Location = new Point(x, y);
            if (handler != null)
            {
                this.Click += new System.EventHandler(handler);
            }
        }
    }
}

[C#] StatusBar Example


1. StatusBar 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
using System;
using System.Windows.Forms;
using System.Drawing;

namespace WindowsFormsApp3
{
    class CsStatusBar
    {
        StatusBar statusbar;
        int currIndex;

        public CsStatusBar()
        {
            statusbar = new StatusBar();
            statusbar.ShowPanels = true;
            currIndex = 0;
        }

        public StatusBar get()
        {
            return statusbar;
        }

        public void addPanel(String text)
        {
            statusbar.Panels.Add(text);
            statusbar.Panels[currIndex].AutoSize = StatusBarPanelAutoSize.Spring; //.Contents;
            statusbar.Panels[currIndex].BorderStyle = StatusBarPanelBorderStyle.Raised;
            currIndex++;
        }

        public void setText(int index, String text)
        {
            statusbar.Panels[index].Text = text;
        }

        public void setIcon(int index, Icon icon)
        {
            statusbar.Panels[index].Icon = icon;
        }

    }
}

[C#] ToolStrip Example



1. ToolStrip 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
using System;
using System.Windows.Forms;

namespace CsLib
{
    class CsToolBar
    {
        ToolStrip toolbar;

        public CsToolBar()
        {
            toolbar = new ToolStrip();
            toolbar.Items.Clear();
        }

        public ToolStrip get()
        {
            return toolbar;
        }


        public ToolStripButton addToolbarButton(String text, EventHandler handler)
        {
            ToolStripButton button = new ToolStripButton();
            button.Name = text;
            button.Text = text;
            if (handler != null)
            {
                button.Click += handler;
            }
            toolbar.Items.Add(button);
            return button;
        }

        public ToolStripTextBox addToolbarTextBox(String text, KeyEventHandler handler)
        {
            ToolStripTextBox textbox = new ToolStripTextBox();
            textbox.Name = text;
            textbox.Text = "";
            textbox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
            textbox.Dock = DockStyle.Fill;
            if (handler != null)
            {
                textbox.KeyDown += handler;
            }
            toolbar.Items.Add(textbox);
            return textbox;
        }
        /*
        private void addrHandler(object source, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                web.Navigate(addr.Text);
            }
        }
        */

        public void addToolItem(String name, EventHandler handler)
        {
            ToolStripItem item = new ToolStripMenuItem();
            item.Tag = "toolitem";
            item.Name = name;
            item.Text = name;
            if (handler != null)
            {
                item.Click += handler;
            }
            toolbar.Items.Add(item);
        }
    }
}

[C#] MenuStrip Example



1. MenuStrip 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
using System;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    class CsMenuBar
    {
        MenuStrip menubar;
        ToolStripMenuItem currMenu;

        public CsMenuBar()
        {
            menubar = new MenuStrip();
            menubar.Items.Clear();
        }

        public MenuStrip get()
        {
            return menubar;
        }

        public void addMenu(String name)
        {
            currMenu = new ToolStripMenuItem();
            currMenu.Tag = "menuitem";
            currMenu.Name = name;
            currMenu.Text = name;
            menubar.Items.Add(currMenu);
        }

        public void addMenuItem(String name, EventHandler handler)
        {
            ToolStripMenuItem item = new ToolStripMenuItem();
            item.Tag = "menuitem";
            item.Name = name;
            item.Text = name;
            item.Click += new EventHandler(handler);
            currMenu.DropDownItems.Add(item);
        }
    }
}

[C#] Form Example





1. Form 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
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public class Program : Form
    {
        CsListBox listBox;
        CsTextBox textBox;
        CsStatusBar statusBar;

        public Program()
        {
            Initialize();
        }

        public static void Main(String[] args)
        {
            Application.Run(new Program());
        }

        private void Initialize()
        {
            this.Name = "Window";
            this.Text = "Window";
            this.Size = new Size(640, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            makeToolBar();
            makeMenuBar();
            makeStatusBar();
            makePanel();
            this.Controls.Add(new CsButton("Hello", MyButtonClick));
        }

        private void makeMenuBar()
        {
            CsMenuBar menu = new CsMenuBar();
            menu.addMenu("File");
            menu.addMenuItem("Exit", showExitPopup);
            menu.addMenu("Help");
            menu.addMenuItem("About", showAboutPopup);
            this.Controls.Add(menu.get());
        }

        private void makeToolBar()
        {
            CsToolBar tool = new CsToolBar();
            tool.addToolItem("Exit", showExitPopup);
            this.Controls.Add(tool.get());
        }

        private void makeStatusBar() {
            statusBar = new CsStatusBar();
            statusBar.addPanel("Ready");
            statusBar.setText(0, "Ready");
            this.Controls.Add(statusBar.get());
        }
        private void makePanel()
        {
            listBox = new CsListBox(showSelectedList);
            for (int i = 0; i < 10; i++)
            {
                listBox.addItem("Item" + i);
            }

            textBox = new CsTextBox();
            textBox.addText("Test");

            CsSplitContainer split = new CsSplitContainer();
            split.addLeftPanel(listBox.get());
            split.addRightPanel(textBox.get());
            this.Controls.Add(split.get());
        }

        private void MyButtonClick(object source, EventArgs e)
        {
            MessageBox.Show("My First WinForm Application");
        }

        private void showExitPopup(object source, EventArgs e)
        {
            Application.Exit();
        }

        private void showAboutPopup(object source, EventArgs e)
        {
            MessageBox.Show("Windows Form Demo V0.1");
        }

        private void showSelectedList(object source, EventArgs e)
        {
            statusBar.setText(0, listBox.getSelectedText());
        }
    }
}

2018년 11월 9일 금요일

[Java] Html Parser Example



1. Html Parser Example (JSoup)
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
import java.io.File;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlParser {

    Document doc;
    
    public HtmlParser() {
        
    }
    
    public void loadUrl(String url) throws IOException {
        doc = Jsoup.connect(url).get(); //"http://example.com/"
    }

    public void loadFile(String file) throws IOException {
        File input = new File(file); //"/tmp/input.html"
        doc = Jsoup.parse(input, "UTF-8"); //, baseUrl
    }
    
    public void loadString(String string) throws IOException {
        doc = Jsoup.parse(string); //, baseUrl
    }
    
    public String getTitle() {
        return doc.title();
    }

    public Elements getElementsByTag(String tag) {
        return doc.getElementsByTag(tag);
    }
    
    public Elements getLinks() {
        Elements links = doc.getElementsByTag("a");
        /*
        for (Element link : links) {
          String linkHref = link.attr("href");
          String linkText = link.text();
          System.out.println(linkHref + ", " + linkText);
        }
        */
        return links;
    }
    
    public Elements getImages() {
        Elements links = doc.getElementsByTag("img");
        /*
        for (Element link : links) {
          String linkHref = link.attr("href");
          String linkText = link.text();
          System.out.println(linkHref + ", " + linkText);
        }
        */
        return links;
    }

}

[Java] URL Download



1. URL To File (Redirect)
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
public static void urlToFile_red(String fileURL, String saveFilePath) throws IOException {
 File file = new File(saveFilePath);
 if( file.getParentFile().exists() == false ) {
  file.getParentFile().mkdirs();
 }
 URL url = new URL(fileURL);
 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
 httpConn.setConnectTimeout(30000);
 httpConn.setReadTimeout(30000);
 httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
 int responseCode = httpConn.getResponseCode();
 if (responseCode == HttpURLConnection.HTTP_OK) {
  InputStream inputStream = httpConn.getInputStream();
  FileOutputStream outputStream = new FileOutputStream(saveFilePath);
  int bytesRead = -1;
  byte[] buffer = new byte[1024];
  while ((bytesRead = inputStream.read(buffer)) != -1) {
   outputStream.write(buffer, 0, bytesRead);
  }
  outputStream.close();
  inputStream.close();

  //System.out.println("File downloaded");
 } else {
  System.out.println("No file to download. Server replied HTTP code: " + responseCode);
 }
 httpConn.disconnect();
}



2. URL To String (Redirect)
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
public static String urlToString_red(String webUrl) throws IOException {
 HttpURLConnection httpConn;
 int responseCode;
 
 while (true) {
  URL resourceUrl = new URL(webUrl);
  httpConn = (HttpURLConnection) resourceUrl.openConnection();
  httpConn.setConnectTimeout(30000);
  httpConn.setReadTimeout(30000);
  httpConn.setInstanceFollowRedirects(false);   // Make the logic below easier to detect redirections
  httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
  responseCode = httpConn.getResponseCode();
  switch( responseCode ) {
   case HttpURLConnection.HTTP_MOVED_PERM:
   case HttpURLConnection.HTTP_MOVED_TEMP:
    String location = httpConn.getHeaderField("Location");
    location = URLDecoder.decode(location, "UTF-8");
    URL base = new URL(webUrl);               
    URL next = new URL(base, location);  // Deal with relative URLs
    webUrl   = next.toExternalForm();
   continue;
  }
  break;
 }
 String html = null;
 if (responseCode == HttpURLConnection.HTTP_OK) {
  InputStream inputStream = httpConn.getInputStream();
  html = InputStreamToStringByRead(inputStream);
  
 } else {
  System.out.println("No file to download. Server replied HTTP code: " + responseCode);
 }
 httpConn.disconnect();
 return html;
}



3. URL To String (No Redirect)
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public String urlToString_nored(String webUrl) throws IOException {
 String html = null;
 URL url = new URL(webUrl);
 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
 httpConn.setInstanceFollowRedirects(true); 
 httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
 int responseCode = httpConn.getResponseCode();
 if (responseCode == HttpURLConnection.HTTP_OK) {
  InputStream inputStream = httpConn.getInputStream();
  html = InputStreamToStringByRead(inputStream);
  
 } else {
  System.out.println("No file to download. Server replied HTTP code: " + responseCode);
 }
 httpConn.disconnect();
 return html;
}



4. URL To File (Apache)
1
2
3
4
5
public static void urlToFileApache(String url, String fileName) throws MalformedURLException, IOException {
 int CONNECT_TIMEOUT = 30000;
 int READ_TIMEOUT = 30000;
 FileUtils.copyURLToFile(new URL(url), new File(fileName),CONNECT_TIMEOUT,READ_TIMEOUT);
}



2018년 11월 7일 수요일

[Java] Collections Sort Example (String with Numbers)


1. Collections Sort 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
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;

import net.lingala.zip4j.model.FileHeader;

public class SortUtil {
    
    public static int compareStringNumber(String s1, String s2) {
        String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        int i = 0;
        while(i < s1Parts.length && i < s2Parts.length){
            if(s1Parts[i].compareTo(s2Parts[i]) == 0){ //if parts are the same
                ++i;
            }else{
                try{
                    int intS1 = Integer.parseInt(s1Parts[i]);
                    int intS2 = Integer.parseInt(s2Parts[i]);
                    int diff = intS1 - intS2; 
                    if(diff == 0){
                        ++i;
                    }else{
                        return diff;
                    }
                }catch(Exception ex){
                    return s1.compareTo(s2);
                }
            }
        }
        if(s1.length() < s2.length()){
            return -1;
        }else if(s1.length() > s2.length()){
            return 1;
        }else{
            return 0;
        }
    }  

    public static void sortStringNumber(List<String> strings) {
        Collections.sort(strings, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return compareStringNumber(s1, s2);
            }
        });
    }
    
    public static void sortFiles(List<File> strings) {
        Collections.sort(strings, new Comparator<File>() {
            public int compare(File s1, File s2) {
                return compareStringNumber(s1.getPath(), s2.getPath());
            }
        });
    }
    
    public static void sortZipFileHeader(List<FileHeader> strings) {
        Collections.sort(strings, new Comparator<FileHeader>() {
            public int compare(FileHeader f1, FileHeader f2) {
                return compareStringNumber(f1.getFileName(), f2.getFileName());
            }
        });
    }
    
    public static void sortZipEntry(List<ZipArchiveEntry> strings) {
        Collections.sort(strings, new Comparator<ZipArchiveEntry>() {
            public int compare(ZipArchiveEntry f1, ZipArchiveEntry f2) {
                return compareStringNumber(f1.getName(), f2.getName());
            }
        });
    }

}

2018년 11월 1일 목요일

[JavaFx] Toast Example


1. Toast 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
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;

public final class FxToast {
    
    public static void makeText(Stage ownerStage, String toastMsg, int toastDelay, int fadeInDelay, int fadeOutDelay) {
        Stage toastStage=new Stage();
        toastStage.initOwner(ownerStage);
        toastStage.setResizable(false);
        toastStage.initStyle(StageStyle.TRANSPARENT);

        Text text = new Text(toastMsg);
        text.setFont(Font.font("Verdana", 40));
        text.setFill(Color.RED);

        StackPane root = new StackPane(text);
        root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.2); -fx-padding: 50px;");
        root.setOpacity(0);

        Scene scene = new Scene(root);
        scene.setFill(Color.TRANSPARENT);
        toastStage.setScene(scene);
        toastStage.show();

        Timeline fadeInTimeline = new Timeline();
        KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(fadeInDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 1)); 
        fadeInTimeline.getKeyFrames().add(fadeInKey1);   
        fadeInTimeline.setOnFinished((ae) -> {
            new Thread(() -> {
                try {
                    Thread.sleep(toastDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Timeline fadeOutTimeline = new Timeline();
                KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(fadeOutDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 0)); 
                fadeOutTimeline.getKeyFrames().add(fadeOutKey1);   
                fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); 
                fadeOutTimeline.play();
            }).start();
        }); 
        fadeInTimeline.play();
    }

    public static void makeText(Stage ownerStage, String toastMsg, int msec ) {
        makeText( ownerStage, toastMsg, msec, 500, 500 );
    }
    
    public static void makeText(Stage ownerStage, String toastMsg ) {
        makeText( ownerStage, toastMsg, 3500, 500, 500 );
    }

}