スライドショーおよび正規表現の使い方

戻る



::::::::::::::
AbsolutePathObtainer.java
::::::::::::::
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.net.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
* 絶対URLに変換する
*/

public class AbsolutePathObtainer {

    /** 相対パスから絶対パスに変更する
    @param currentUrl 処理しているURL	
    @param path リンク先のパス
    @return 絶対パス
    */
    static public String getAbsolutePath( URL currentUrl, String path ) {
        if ( path.toLowerCase().startsWith( "http:" )
                || path.toLowerCase().startsWith( "https:" )
                || path.toLowerCase().startsWith( "ftp:" )
                || path.toLowerCase().startsWith( "mailto:" )
           ) {
            /* do nothing */
        } else if ( path.startsWith( "/" ) ) {
            /* / でスタートするのは、ホスト内の絶対パス表記であるので、プロトコルとホスト名を頭に付ける */
            path = currentUrl.getProtocol() + "://" + currentUrl.getHost() + path;
        } else if ( path.startsWith( "./" ) ) {
            // 先頭の "./" を削除する
            path = path.replaceAll( "^./", "" );
            path = getDirName( currentUrl ) + path;
        } else if ( path.startsWith( "../" ) ) {
            path = getParentPath( currentUrl, path );
        } else {
            path = getDirName( currentUrl ) + path;

        }

        return path;
    }

    /** URLからディレクトリ名を得る
    @param url URL
    @return ディレクトリ名	
    */
    static private String getDirName( URL url ) {

        String dirName = null;

        Pattern p;
        Matcher m;

        p = Pattern.compile( "^(.+/).*$" );
        m = p.matcher( url.toString() );
        if ( m.find() ) {
            dirName = m.group( 1 );
        }

        // System.err.println( " *** DEBUG *** in getDirName :");
        // System.err.println( "\t" + "urlString = " + urlString + " dirName = " + dirName
        // 			+ " プロトコル = " + url.getProtocol() );

        if ( dirName.equals( url.getProtocol() + "://" ) ) {
            dirName = url.toString() + "/";
        }

        return dirName;
    }

    /** 上位の相対パスを処理する
    @param url 処理しているURL
    @param relativePath ../などが先頭に付いたパス
    @return ../などを削除して書き直したもの
    */
    static private String getParentPath( URL url, String relativePath ) {

        Pattern p;
        Matcher m;

        String parentPath = null;
        String tempPath = url.getProtocol() + "://" + url.getHost() + url.getPath();

        int count = 0;
        while ( relativePath.startsWith( "../" ) ) {

            //==========================================================================
            // 末尾のディレクトリ名あるいはディレクトリ名+"/"+ファイル名を削除
            //==========================================================================
            p = Pattern.compile( "(.+/).+/.*$" );
            m = p.matcher( tempPath );
            if ( m.find() ) {
                tempPath = m.group( 1 );
            }

            //==========================================================================
            // 相対パスの先頭の"../"を削除する
            //==========================================================================
            p = Pattern.compile( "^\\.\\./(.*)$" );
            m = p.matcher( relativePath );
            if ( m.find() ) {
                relativePath = m.group( 1 );
            }

        }

        return tempPath + relativePath;
    }

    /**
    * テストコード
    */
    public static void main( String[] args ) throws Exception {
        URL url = new URL( "http://www.abc.co.jp/xxx/yyy/" );

        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "../../test.jpg" ) );
        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "../test.jpg" ) );
        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "./test.jpg" ) );
        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "test.jpg" ) );
        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "/test.jpg" ) );
        System.out.println( AbsolutePathObtainer.getAbsolutePath( url, "http://www.abc.co.jp/OPQ/test.jpg" ) );
    }
}
::::::::::::::
CenterPanel.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.io.*;
import java.util.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class CenterPanel extends JPanel implements Observer {

    private JTextArea responseBody = null;

    public CenterPanel() {
        super();
        setPreferredSize( new Dimension( 640, 600 ) );
        setBackground( new Color( 0xff, 0xcc, 0x33 ) );

        ContentObtainer obtainer = ContentObtainer.getInstance();
        obtainer.addObserver( this );

        /** レスポンスボディ表示エリア */
        responseBody = new JTextArea( );
        responseBody.setWrapStyleWord( true );
        responseBody.setLineWrap( true );
        responseBody.setEditable( false ); // 編集不可
        responseBody.setForeground( Color.blue );
        responseBody.setBackground( Color.white );

        JScrollPane responseBodyScrollPane = new JScrollPane( responseBody );
        responseBodyScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        responseBodyScrollPane.setPreferredSize( new Dimension( 620, 580 ) );

        this.add( responseBodyScrollPane );

    }

    public void update( Observable obj, Object arg ) {

        System.out.println( this.getClass().getName() + ": UPDATED" );
        // System.out.println( arg );

        responseBody.setText( ( String ) arg );

    }

}
::::::::::::::
ContentObtainer.java
::::::::::::::
import java.net.*;
import java.io.*;
import java.util.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
*/

public class ContentObtainer extends Observable {

    private static ContentObtainer uniqueInstance = null;

    public static ContentObtainer getInstance() {

        if ( uniqueInstance == null ) {
            // 初めて呼ばれたときだけインスタンス化
            uniqueInstance = new ContentObtainer();
            System.out.println( uniqueInstance.getClass().getName() + "がインスタンス化されました!" );
        }

        return uniqueInstance;
    }

    public void getResponseBodyAsString( String urlString ) throws Exception {

        StringBuilder sb = new StringBuilder();

        URL url;
        try {
            url = new URL( urlString );
            // URLにアクセス
            HttpURLConnection connection = ( HttpURLConnection ) url.openConnection();

            BufferedReader reader = new BufferedReader( new InputStreamReader(
                                        connection.getInputStream(), "JISAutoDetect" ) );

            String line;
            while ( ( line = reader.readLine() ) != null ) {
                // System.out.println(line);
                sb.append( line + "\n" );
            }
            reader.close();

            // 処理が正常終了したことをObserverに通知、さらに取り出したコンテンツを引き渡す
            setChanged();
            notifyObservers( sb.toString() );

        } catch ( Exception e ) {
            throw e;
        }


    }

}

::::::::::::::
EastPanel.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.net.*;
import java.io.*;
import java.util.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class EastPanel extends JPanel implements Observer, ActionListener {

    private JTextField urlTF;

    public EastPanel() {
        super();
        setBackground( new Color( 0x99, 0x00, 0xff ) );

        ContentObtainer obtainer = ContentObtainer.getInstance();
        obtainer.addObserver( this );

        setLayout( new BoxLayout( this, BoxLayout.PAGE_AXIS ) );
    }

    public void setUrlTF( JTextField urlTF ) {
        this.urlTF = urlTF;
    }

    public void update( Observable obj, Object arg ) {

        removeAll();

        System.out.println( this.getClass().getName() + ": UPDATED" );
        // System.out.println( arg );

        // IMGのURLのみ取り出す
        java.util.List result = ImageURLObtainer.obtain( ( String ) arg );

        Iterator iterator = result.iterator();
        while ( iterator.hasNext() ) {

            String path = ( String ) iterator.next();
            // System.out.println( path );

            try {
                // 必要に応じて絶対パスに変換
                path = AbsolutePathObtainer.getAbsolutePath( new URL( urlTF.getText() ), path );
            } catch ( Exception e ) {
                e.printStackTrace();
            }

            JButton button = new JButton( path );
            button.addActionListener( this );
            this.add( button );

        }

        this.validate();
        this.repaint();

        this.getParent().validate();
        this.getParent().repaint();

    }

    public void actionPerformed( ActionEvent event ) {
        JComponent component = ( JComponent ) event.getSource();
        String urlString = ( ( JButton ) component ).getText();

        System.out.println( "URL=" + urlString );

        new SingleImageViewer( urlString );

    }
}

::::::::::::::
ImageURLObtainer.java
::::::::::::::
import java.util.*;
import java.util.regex.*;
import java.io.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
* 正規表現を使って、画像URLを抽出する
*/

public class ImageURLObtainer {

    /**
    * @param in 処理対象文字列
    * @return 取り出した結果のリスト
    */
    public static List obtain( String in ) {

        List result = new LinkedList();

        // 先頭がIMGでそれ以降に初めて出現したSRC属性の値を求める
        // ただしシングルクォートあるいはダブルクォートで挟み込まれてなくてはいけない
        Pattern p = Pattern.compile( "<IMG.*?\\s+?SRC=(\"|\')(.*?)(\"|\')(.*?>)",
                                     Pattern.CASE_INSENSITIVE | Pattern.DOTALL );

        Matcher m = p.matcher( in );
        while ( m.find() ) {
            // パターンが見つかり続けるまで処理を続ける
            // System.out.println( m.group( 2 ) );
            result.add( m.group( 2 ) );
        }

        return result;
    }

    /**
    * テストコード
    */
    public static void main( String[] args ) {
        String str = "...............<img src=\"AAA.jpg\">.................";
        str += "<img    src=\"test.gif\" alt=\"aaa\">";
        str += "<img    width='1000' src=\"test2.gif\" alt=\"aaa\">\n";
        str += "<img width='333' src='/test3.ping' alt=\"aaa\">\n";

        List result = ImageURLObtainer.obtain( str );

        Iterator iterator = result.iterator();
        while ( iterator.hasNext() ) {
            System.out.println( iterator.next() );
        }
    }
}
::::::::::::::
MyDialog.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class MyDialog extends JDialog {

    // コンストラクタ
    public MyDialog( String message ) {
        super( );

        setBounds( 256, 256, 640, 480 );

        Container cp = getContentPane();

        // フォントの指定
        Font f = new Font( "MS 明朝", Font.PLAIN, 10 );

        /** ステータス表示エリア */
        JTextArea status = new JTextArea( );
        status.setWrapStyleWord( true );
        status.setLineWrap( true );
        status.setEditable( false ); // 編集不可
        status.setForeground( Color.white );
        status.setBackground( Color.black );

        JScrollPane statusScrollPane = new JScrollPane( status );
        statusScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        statusScrollPane.setPreferredSize( new Dimension( 400, 600 ) );

        status.setText( message );

        cp.add( statusScrollPane );

        setVisible( true );

        addWindowListener( new WindowAdapter() {
                               public void windowClosing( WindowEvent e ) {
                                   setVisible( false );
                               }
                           }
                         );
    }

}

::::::::::::::
NorthPanel.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.io.*;
import java.util.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class NorthPanel extends JPanel implements ActionListener {

    private JTextField urlTF = null;
    private JLabel statusLabel = null;
    private JLabel myLabel = null;

    public NorthPanel() {
        super();
        setPreferredSize( new Dimension( 960, 50 ) );
        setBackground( Color.cyan );

        JLabel label = new JLabel( "URL" );
        this.add( label );

        urlTF = new JTextField( 50 );
        this.add( urlTF );

        JButton button = new JButton( "ダウンロード" );
        this.add( button );
        button.setActionCommand( "DOWNLOAD" );
        button.addActionListener( this );

        myLabel = new JLabel( "***" );
        this.add( myLabel );

    }

    public JTextField getUrlTF() {
        return urlTF;
    }

    public void actionPerformed( ActionEvent event ) {
        String command = event.getActionCommand();
        if ( "DOWNLOAD".equals( command ) ) {

            // タイマーを設定
            java.util.Timer timer = new java.util.Timer();

            try {
                ElaspedTimeMonitor monitor = new ElaspedTimeMonitor( myLabel );
                timer.schedule( monitor, 0, 10 ); // タスクの実行間隔

                // 対象URLからレスポンスボディを取得
                ContentObtainer obtainer = ContentObtainer.getInstance();
                obtainer.getResponseBodyAsString( urlTF.getText() );

            } catch ( Exception e ) {

                StackTraceElement[] ste = e.getStackTrace();
                StringBuilder sb = new StringBuilder();
                for ( int i = 0;i < ste.length;i++ ) {
                    sb.append( ste[ i ].toString() + "\n" );
                }

                MyDialog dialog = new MyDialog( sb.toString() );
                dialog.setTitle( e.getMessage() );

            } finally {
                // タイマーを終了させる
                timer.cancel();
            }

        }

    }

    private class ElaspedTimeMonitor extends TimerTask {
        private long startTime;
        private JLabel label;

        public ElaspedTimeMonitor( JLabel label ) {
            startTime = System.currentTimeMillis();
            this.label = label;
        }

        public void run() {
            String str = new Long( System.currentTimeMillis() - startTime ).toString();
            System.out.println( str + " msec elasped" );

            // statusLabel.setText( str + " msec elasped" );
            label.setText( str + " msec elasped" );
            Container parent = ( Container ) label.getParent();
            parent.repaint();

        }
    }
}

::::::::::::::
RegionObtainer.java
::::::::::::::
import java.io.*;
import java.util.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
* 処理が遅いので使用しないことに決定
*/

public class RegionObtainer {

    private String str;

    public RegionObtainer( String str ) {
        this.str = str;
    }

    public java.util.List getRegions() {
        LinkedList list = new LinkedList();

        StringReader sr = new StringReader( str );
        boolean isStarted = false;

        try {
            int c;
            int from = 0;
            int to = 0;
            int offset = 0;
            while ( ( c = sr.read() ) != -1 ) {

                if ( !isStarted && c == '<' ) {

                    isStarted = true;
                    // System.out.println( "タグが開始しました!" );

                    from = offset;
                }

                if ( isStarted && c == '>' ) {

                    isStarted = false;
                    // System.out.println( "タグが閉じられました!" );
                    to = offset;

                    int[] region = new int[ 2 ];
                    region[ 0 ] = from;
                    region[ 1 ] = to;

                    list.add( region );
                }

                offset++;
            }

        } catch ( IOException e ) {
            e.printStackTrace();
        }

        return list;
    }

}


::::::::::::::
SingleImageViewer.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.io.*;
import java.net.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class SingleImageViewer extends JFrame {
    public SingleImageViewer( String urlString ) {
        super( urlString );

        setBounds( 240, 240, 640, 480 );

        getContentPane().add( new MyPanel( urlString ) );

        setVisible( true );

    }

    private class MyPanel extends JPanel {
        private String urlString;
        private BufferedImage image = null;
        private final Color bgColor = Color.black;

        public MyPanel( String urlString ) {
            this.urlString = urlString;

            System.out.println( "画像URLを読み取り中・・・" );
            try {
                image = ImageIO.read( new URL( urlString ) );

            } catch ( IOException ex ) {
                ex.printStackTrace();
            }
            System.out.println( "完了しました!" );

        }

        public void paint( Graphics g ) {

            int width = getWidth();
            int height = getHeight();

            g.setColor( bgColor );
            // 背景色でこのコンポーネントを全て塗りつぶす
            g.fillRect( 0 , 0 , width , height );

            Graphics2D g2 = ( Graphics2D ) g;

            int xSize = image.getWidth();
            int ySize = image.getHeight();

            double ratio = 1.0;
            if ( xSize > width || ySize > height ) {
                // 表示幅をはみ出す場合
                if ( ySize > xSize ) {
                    // 縦長の場合は、高さの最大値に合わせる
                    ratio = height * 1.0 / ySize;
                } else {
                    // 横長の場合は、幅の最大値に合わせる
                    ratio = width * 1.0 / xSize;
                }

            }
            g2.drawImage( image, 0, 0, ( int ) ( ratio * xSize ), ( int ) ( ratio * ySize ), this );

        }

    }
}
::::::::::::::
SlideShowMain.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.io.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class SlideShowMain extends JFrame {

    public SlideShowMain () {
        super( "スライドショー" );
        setLayout( new FlowLayout() );

        try {
            // 外観を設定します
            UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
            // 外観を変更します
            SwingUtilities.updateComponentTreeUI( this );
        } catch ( Exception e ) {
            e.printStackTrace();
            System.exit( -1 );
        }

        setBounds( 0, 0, 1024, 720 );

        //-----------------------------------------------------
        // 全ての部品をContainerに配置する
        //-----------------------------------------------------
        Container container = getContentPane();
        JPanel panel = new JPanel();
        panel.setLayout( new BorderLayout() );
        this.add( panel );

        /** 最上部のパネル */
        NorthPanel northPanel = new NorthPanel();
        /** 中央部のパネル */
        CenterPanel centerPanel = new CenterPanel();

        /** 右のパネル */
        EastPanel eastPanel = new EastPanel();
        eastPanel.setUrlTF( northPanel.getUrlTF() );

        JScrollPane theEastSP = new JScrollPane();
        // スクロールペインにパネルを追加する
        theEastSP.getViewport().setView( eastPanel );
        theEastSP.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        theEastSP.setPreferredSize( new Dimension( 384, 500 ) );

        /** 最下部のパネル */
        SouthPanel southPanel = new SouthPanel();

        // 配置する
        panel.add( northPanel, BorderLayout.PAGE_START );
        panel.add( centerPanel, BorderLayout.CENTER );
        panel.add( theEastSP, BorderLayout.EAST );
        panel.add( southPanel, BorderLayout.SOUTH );

        setVisible( true );

        addWindowListener( new WindowAdapter() {
                               public void windowClosing( WindowEvent ev ) {
                                   dispose();
                                   System.exit( 0 );
                               }
                           }
                         );

    }

    /**
    * GUIを作成し表示する
    */
    private static void createAndShowGUI() {
        JFrame frame = new SlideShowMain();
    }

    public static void main( String[] args ) {
        javax.swing.SwingUtilities.invokeLater( new Runnable() {
                                                    public void run() {
                                                        createAndShowGUI();
                                                    }
                                                }
                                              );
    }

}


::::::::::::::
SouthPanel.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;

import javax.imageio.*;

import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.io.*;

/**
* $Id: SlideShow.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
* @author KISHI Yasuhiro
*/

public class SouthPanel extends JPanel {

    public SouthPanel() {
        super();
        setPreferredSize( new Dimension( 960, 50 ) );
        setBackground( new Color( 0x66, 0xcc, 0x99 ) );

        // JPanel内で右寄せで配置していく
        setLayout( new FlowLayout( FlowLayout.RIGHT ) );

        JButton button = new JButton( "スライドショー実行" );
        this.add( button );

    }

}


戻る inserted by FC2 system