OSDN Git Service

fix:Commandのマルチタスク化
authorhayashi yuu <hayashi.yuu@gmail.com>
Sat, 8 Aug 2015 03:48:26 +0000 (12:48 +0900)
committerhayashi yuu <hayashi.yuu@gmail.com>
Sat, 8 Aug 2015 03:48:26 +0000 (12:48 +0900)
importPicture/src/osm/jp/gpx/ImportPicture.java
importPicture/src/osm/jp/gpx/matchtime/gui/Command.java
importPicture/src/osm/jp/gpx/matchtime/gui/DoDialog.java

index 63668a3..afdf02b 100644 (file)
@@ -19,6 +19,7 @@ import java.util.logging.Logger;
 import javax.xml.parsers.*;\r
 import javax.xml.transform.OutputKeys;\r
 import javax.xml.transform.Transformer;\r
+import javax.xml.transform.TransformerException;\r
 import javax.xml.transform.TransformerFactory;\r
 import javax.xml.transform.dom.DOMSource;\r
 import javax.xml.transform.stream.StreamResult;\r
@@ -70,7 +71,7 @@ public class ImportPicture extends Thread {
         finally {\r
             try {\r
                 if (inStream != null) {\r
-                       inStream.close();\r
+                    inStream.close();\r
                 }\r
             } catch (IOException e) {\r
                 logger.warning("ログ設定: ログ設定プロパティファイルのストリームクローズ時に例外が発生しました。:"+ e.toString());\r
@@ -157,7 +158,7 @@ public class ImportPicture extends Thread {
         obj.start();\r
         try {\r
             obj.join();                            \r
-        } catch(InterruptedException e) {}\r
+        } catch(InterruptedException end) {}\r
     }\r
     \r
     public File gpxDir = new File(".");\r
@@ -274,8 +275,7 @@ public class ImportPicture extends Thread {
                 transformer.transform(source, result);\r
             }\r
         }\r
-        catch(Exception e) {\r
-            e.printStackTrace();\r
+        catch(ParserConfigurationException | DOMException | SAXException | IOException | ParseException | ImageReadException | ImageWriteException | IllegalArgumentException | TransformerException e) {\r
         }\r
     }\r
        \r
@@ -305,17 +305,12 @@ public class ImportPicture extends Thread {
                     if ((uktime.getTime() >= gpxStartTime) && (uktime.getTime() <= gpxEndTime)) {\r
                         Element trkpt = trkpt(map, uktime);\r
                         if (trkpt != null) {\r
-                            System.out.print(String.format("%12s|", image.getName()));\r
-                            System.out.print(String.format("%20s ", dfjp.format(itime)));\r
-                            System.out.print(String.format("%20s|", dfjp.format(uktime)));\r
-\r
                             Element wpt = createWptTag(image, uktime.getTime(), trkpt);\r
                             String latStr = wpt.getAttribute("lat");\r
                             String lonStr = wpt.getAttribute("lon");\r
-                            System.out.print(String.format("%12s %12s|", latStr, lonStr));\r
                             double latitude = Double.parseDouble(latStr);\r
                             double longitude = Double.parseDouble(lonStr);\r
-\r
+                            \r
                             String eleStr = "-";\r
                             String magvarStr = "-";\r
                             NodeList nodes = wpt.getChildNodes();      // 子ノードを取得\r
@@ -332,10 +327,15 @@ public class ImportPicture extends Thread {
                                     }\r
                                 }\r
                             }\r
-                            System.out.println(String.format("%8s|%6s|", eleStr, magvarStr));\r
-                            try {\r
-                                Thread.sleep(1);                            \r
-                            } catch(InterruptedException e) {}\r
+\r
+                            synchronized(System.out) {\r
+                                System.out.print(String.format("%12s|", image.getName()));\r
+                                System.out.print(String.format("%20s ", dfjp.format(itime)));\r
+                                System.out.print(String.format("%20s|", dfjp.format(uktime)));\r
+                                System.out.print(String.format("%12s %12s|", latStr, lonStr));\r
+                                System.out.println(String.format("%8s|%6s|", eleStr, magvarStr));\r
+                            }\r
+                            Thread.yield();                           \r
 \r
                             if (exifWrite) {\r
                                 TiffOutputSet outputSet = null;\r
index 93f1e1e..7b8f617 100644 (file)
@@ -35,6 +35,7 @@ class Command extends Thread {
     }
 
     @SuppressWarnings("unchecked")
+    @Override
     public void run() {
         System.out.println("[START:"+ (new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss")).format(new java.util.Date()) +"]\t"+ this.commandName);
         for (int i=0; i < args.length; i++) {
@@ -53,16 +54,15 @@ class Command extends Thread {
             }
             catch (InvocationTargetException e) {
                 System.out.println("[ERR!:"+ (new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss")).format(new java.util.Date()) +"]\t"+ this.commandName);
-                e.getCause().printStackTrace();
                 throw e;
             }
-            catch (Exception e) {
+            catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
                 System.out.println("[ERR!:"+ (new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss")).format(new java.util.Date()) +"]\t"+ this.commandName);
                 throw e;
             }
         }
-        catch(Exception e) {
-            e.printStackTrace();
+        catch(InvocationTargetException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
+            e.printStackTrace(System.out);
         }
         System.out.println();
     }
index 6e6f634..8e2e69e 100644 (file)
@@ -1,5 +1,11 @@
 package osm.jp.gpx.matchtime.gui;
-import java.awt.*;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Point;
+import java.awt.event.ActionEvent;
 import java.io.*;
 import javax.swing.*;
 
@@ -22,18 +28,6 @@ public class DoDialog extends JDialog {
     JTextArea textArea;      // 実行結果を表示するJTextArea   (中央)
     //}}
 
-    class SymAction implements java.awt.event.ActionListener {
-        public void actionPerformed(java.awt.event.ActionEvent event) {
-            Object object = event.getSource();
-            if (object == closeButton) {
-                closeButton_Action(event);
-            }
-            else if (object == doButton) {
-                doButton_Action(event);
-            }
-        }
-    }
-
     public DoDialog(JFrame parentFrame, String[] args) {
         super(parentFrame, true);   // モーダルダイアログを基盤にする
         this.parentFrame = parentFrame;
@@ -42,10 +36,9 @@ public class DoDialog extends JDialog {
         // INIT_CONTROLS
         Container container = getContentPane();
         container.setLayout(new BorderLayout());
-        setVisible(false);
-        setSize(getInsets().left + getInsets().right + 500,getInsets().top + getInsets().bottom + 480);
+        parentFrame.setVisible(false);
+        setSize(getInsets().left + getInsets().right + 980, getInsets().top + getInsets().bottom + 480);
         setTitle(DoDialog.TITLE);
-        setSize(500,480);
         
         // コントロールパネル
         buttonPanel = new JPanel();
@@ -53,10 +46,23 @@ public class DoDialog extends JDialog {
         doButton = new JButton("実行");
         doButton.setToolTipText("処理を実行します.");
         doButton.setEnabled(true);
+        doButton.addActionListener((ActionEvent event) -> {
+            // 処理中であることを示すため
+            // ボタンの文字列を変更し,使用不可にする
+            doButton.setText("処理中...");
+            doButton.setEnabled(false);
+            
+            // SwingWorker を生成し,実行する
+            LongTaskWorker worker = new LongTaskWorker(doButton);
+            worker.execute();
+        });
         buttonPanel.add(doButton);
 
         closeButton = new JButton("閉じる");
         closeButton.setToolTipText("処理を終了します.");
+        closeButton.addActionListener((ActionEvent event) -> {
+            dispose();
+        });
         buttonPanel.add(closeButton);
         
         this.getContentPane().add("South", buttonPanel);
@@ -66,30 +72,29 @@ public class DoDialog extends JDialog {
         JScrollPane sc=new JScrollPane(textArea);
         textArea.setFont(new Font(Font.MONOSPACED,Font.PLAIN,12));
         textArea.setTabSize(4);
+        this.getContentPane().add("Center", sc);
+        
         try {
             textArea.append("> java -cp importPicture.jar osm.jp.gpx.ImportPicture");
-            for (int i = 0; i < args.length; i++) {
-               textArea.append(" '"+ args[i] +"'");
+            for (String arg : args) {
+                textArea.append(" '" + arg + "'");
             }
             textArea.append("\n\n");
         }
         catch (Exception e) {
             System.out.println(e.toString());
         }
-        this.getContentPane().add("Center", sc);
 
-        //{{REGISTER_LISTENERS
-        SymAction lSymAction = new SymAction();
-        closeButton.addActionListener(lSymAction);
-        doButton.addActionListener(lSymAction);
-        //}}
+        // JFrameの表示
+        parentFrame.setVisible(true);
     }
-
+    
     /**
     * Shows or hides the component depending on the boolean flag b.
     * @param b trueのときコンポーネントを表示; その他のとき, componentを隠す.
     * @see java.awt.Component#isVisible
     */
+    @Override
     public void setVisible(boolean b) {
         if(b) {
             setLocation(80, 80);
@@ -97,6 +102,7 @@ public class DoDialog extends JDialog {
         super.setVisible(b);
     }
 
+    @Override
     public void addNotify()    {
         // Record the size of the window prior to calling parents addNotify.
         Dimension d = getSize();
@@ -109,56 +115,110 @@ public class DoDialog extends JDialog {
         // Adjust components according to the insets
         setSize(getInsets().left + getInsets().right + d.width, getInsets().top + getInsets().bottom + d.height);
         Component components[] = getComponents();
-        for (int i = 0; i < components.length; i++)    {
-            Point p = components[i].getLocation();
+        for (Component component : components) {
+            Point p = component.getLocation();
             p.translate(getInsets().left, getInsets().top);
-            components[i].setLocation(p);
+            component.setLocation(p);
         }
         fComponentsAdjusted = true;
     }
 
+    
     /**
-     * [実行]ボタンをクリックしたときの動作
-     * @param event
+     * JTextAreaに書き出すOutputStream
      */
-    void doButton_Action(java.awt.event.ActionEvent event) {
-        doButton.setEnabled(false);
+    public static class JTextAreaOutputStream extends OutputStream {
+        private ByteArrayOutputStream os;
         
-        PrintStream defOut = System.out;
-        PrintStream defErr = System.err;
+        /** 書き出し対象 */
+        private JTextArea textArea;
+        private String encode;
 
-       ByteArrayOutputStream stdout = new ByteArrayOutputStream();
-        try {
-            System.setOut(new PrintStream(stdout));
-            System.setErr(new PrintStream(stdout));
-
-            Command command = new Command(osm.jp.gpx.ImportPicture.class);
-            command.setArgs(args);
-            command.start();           // コマンドを実行
-            while (command.isAlive()) {
-                Thread.sleep(1000);
-                textArea.append(stdout.toString());
-                stdout.reset();
-            }
-            textArea.append(stdout.toString());
-            JOptionPane.showMessageDialog(this, "'"+ TITLE +"'処理を完了しました。", "処理完了", JOptionPane.INFORMATION_MESSAGE);
+        public JTextAreaOutputStream(JTextArea textArea, String encode) {
+            this.textArea = textArea;
+            this.encode = encode;
+            this.os = new ByteArrayOutputStream();
         }
-        catch(Exception e) {
-            e.printStackTrace();
-            JOptionPane.showMessageDialog(this, e.toString(), "Exception", JOptionPane.ERROR_MESSAGE);
+        
+        /** 
+         * OutputStream#write(byte[])のオーバーライド
+         * @param arg
+         */
+        @Override
+        public void write(int arg) throws IOException {
+            this.os.write(arg);
         }
-        finally {
-            System.setOut(defOut);
-            System.setErr(defErr);
-            doButton.setEnabled(true);
+        
+        /**
+         * flush()でJTextAreaに書き出す
+         */
+        @Override
+        public void flush() throws IOException {
+            // 文字列のエンコード
+            final String str = new String(this.os.toByteArray(), this.encode);
+            // 実際の書き出し処理
+            SwingUtilities.invokeLater(new Runnable(){
+                @Override
+                public void run() {
+                    JTextAreaOutputStream.this.textArea.append(str);
+                }
+            });
+            // 書き出した内容はクリアする
+            this.os.reset();
         }
     }
-
-    void closeButton_Action(java.awt.event.ActionEvent event) {
-        dispose();
-    }
     
-    void changeSQL_Action(java.awt.event.ActionEvent event) {
-        textArea.setText("");
+    // 非同期に行う処理を記述するためのクラス
+    class LongTaskWorker extends SwingWorker<Object, Object> {
+        private JButton button;
+
+        public LongTaskWorker(JButton button) {
+            this.button = button;
+        }
+
+        // 非同期に行われる処理
+        @Override
+        public Object doInBackground() {
+            // ながーい処理
+            PrintStream defOut = System.out;
+            PrintStream defErr = System.err;
+
+            OutputStream os = new JTextAreaOutputStream(textArea, "UTF-8");
+            PrintStream stdout = new PrintStream(os, true);      // 自動flushをtrueにしておく
+
+            // System.out にJTextAreaOutputStreamに書き出すPrintStreamを設定
+            System.setOut(stdout);
+            System.setErr(stdout);
+
+            try {
+                Command command = new Command(osm.jp.gpx.ImportPicture.class);
+                command.setArgs(args);
+                command.start();               // コマンドを実行
+                while (command.isAlive()) {
+                    try {
+                        Thread.sleep(1000);
+                    } catch (InterruptedException e) {}
+                }
+            }
+            catch(Exception e) {
+                e.printStackTrace(stdout);
+            }
+            finally {
+                System.setOut(defOut);
+                System.setErr(defErr);
+                doButton.setEnabled(true);
+            }
+
+            return null;
+        }
+
+        // 非同期処理後に実行
+        @Override
+        protected void done() {
+            // 処理が終了したので,文字列を元に戻し
+            // ボタンを使用可能にする
+            button.setText("実行");
+            button.setEnabled(true);
+        }
     }
 }