[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
|
1 2 3 4 5 6 7 8 9 10 | <!-- 管理者用ページ --> < security-constraint > < web-resource-collection > < web-resource-name >admin</ web-resource-name > < url-pattern >/admin.html</ url-pattern > </ web-resource-collection > < auth-constraint > < role-name >admin</ role-name > </ auth-constraint > </ security-constraint > |
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html > < head > < meta http-equiv = "content-type" content = "text/html; charset=UTF-8" > < title >administrator page</ title > </ head > < body > 管理者用ページです </ body > </ html > |
(ログインせずにアクセスした場合) |
|
(管理権限でログインした場合) |
(一般権限でログインした場合) |
1 2 3 4 5 6 7 8 | < servlet > < servlet-name >LoginGoogle</ servlet-name > < servlet-class >com.appspot.karu_lab.LoginGoogleServlet</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >LoginGoogle</ servlet-name > < url-pattern >/LoginGoogle</ url-pattern > </ servlet-mapping > |
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 | package com.appspot.karu_lab; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; /** * Googleアカウントのログイン・ログアウトを行う画面 * @author karura * */ public class LoginGoogleServlet extends HttpServlet { /** * GETパラメータによるURL起動 */ public void doGet( HttpServletRequest req, HttpServletResponse resp ) throws IOException { // ページURLを取得 String url = req.getRequestURI(); // ユーザ情報を取得 UserService userService = UserServiceFactory.getUserService(); // 画面出力開始 PrintWriter out = resp.getWriter(); resp.setContentType( "text/html" ); out.println( "<html>" ); out.println( "<title>login / logout</title>" ); out.println( "<a href=\"./\">home</a><br/><br/>" ); // ログイン状態か確認 if ( userService.isUserLoggedIn() ) { // ユーザ情報とログアウト用リンクの取得 String name = userService.getCurrentUser().getNickname(); String email = userService.getCurrentUser().getEmail(); String domain = userService.getCurrentUser().getAuthDomain(); String identity = userService.getCurrentUser().getFederatedIdentity(); String userID = userService.getCurrentUser().getUserId(); String logoutURL = userService.createLogoutURL( url ); // ユーザ情報を出力 out.println( String.format( "user : %s - <a href=\"%s\">logout</a><br/>" , name , logoutURL ) ); out.println( String.format( "userID : %s<br/>" , userID ) ); out.println( String.format( "email : %s<br/>" , email ) ); out.println( String.format( "domain : %s<br/>" , domain ) ); out.println( String.format( "identity : %s<br/>" , identity ) ); // 管理者の場合は更に出力 if ( userService.isUserAdmin() ){ out.println( "you are the administrator.<br/>" ); } } else { // ログインURLを作成 String loginURL = userService.createLoginURL( url ); // ログインリンクを表示 out.println( String.format( "user : none - <a href='%s'>login</a>" , loginURL ) ); } // フッター out.println( "</html>" ); } } |
(ログイン前) |
(ログイン画面) |
(管理者権限でログイン後) |
(一般権限でログイン後) |
|
項目 | 内容 |
スコープ | https://www.googleapis.com/auth/userinfo.profile |
利用サービス | ユーザ情報取得 https://www.googleapis.com/oauth2/v2/userinfo |
1 2 3 4 5 6 7 8 9 10 11 | <!-- Javaクラスの定義 --> < servlet > < servlet-name >OAuth2Test</ servlet-name > < servlet-class >com.appspot.karu_lab.TestOAuth2Servlet</ servlet-class > </ servlet > <!-- URLマッピング --> < servlet-mapping > < servlet-name >OAuth2Test</ servlet-name > < url-pattern >/OAuth2Test</ url-pattern > </ servlet-mapping > |
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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | package com.appspot.karu_lab; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * OAuth 2.0を利用して、Googleサービスの情報を取得 * @author karura * */ public class TestOAuth2Servlet extends HttpServlet { // 定数 static final String ENDPOINT = "https://accounts.google.com/o/oauth2" ; // GoogleでOAuth 2.0 認証を行うページのURL static final String CLIENT_ID = "××××××××××××××××××××××××××××××××××××" ; // OAuth2クライアントID。Google Developers consoleに表示されている値 static final String CLIENT_SECRET = "××××××××××××" ; // OAuth2クライアント・シークレット(暗号化のソルトにあたるもの)。Google Developers consoleに表示されている値 static final String REDIRECT_URI = "http://localhost:8888/OAuth2Test" ; // リダイレクト先URL。Google Developers consoleに表示されている値。 static final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile" ; // スコープ(使用権限を求めるアプリ。複数の場合はカンマで区切る) static final String SERVICE_URI = "https://www.googleapis.com/oauth2/v2/userinfo" ; // OAuth2認証によって利用するサービスのURL /** * GETパラメータによるURL起動 */ public void doGet( HttpServletRequest req, HttpServletResponse resp ) throws IOException { // GETパラメータの取得 String state = req.getParameter( "state" ); // 現在の状態 String authorizationCode = req.getParameter( "code" ); // 「authorization code」の取得 String error = req.getParameter( "error" ); // エラー // エラーがある場合はエラー画面を表示 if ( error != null ) { // エラー表示 resp.setContentType( "text/plain" ); resp.getWriter().println( String.format( "error : %s" , error ) ); } // 正常処理 try { // OAuth 2.0 認証処理 if ( state == null ) { // OAuth 2.0 によるユーザ認証が行われていない場合は // まずユーザ認証を行う StringBuilder b = new StringBuilder(); b.append( "response_type=code" ); b.append( "&client_id=" ).append( URLEncoder.encode( CLIENT_ID , "utf-8" ) ); b.append( "&redirect_uri=" ).append( URLEncoder.encode( REDIRECT_URI , "utf-8" ) ); b.append( "&scope=" ).append( URLEncoder.encode( SCOPES , "utf-8" ) ); b.append( "&state=dummy" ); // Googleの認証サイトにリダイレクト resp.sendRedirect( ENDPOINT + "/auth?" + b.toString() ); } else if ( state.equals( "dummy" ) ) { // OAuth 2.0 によるユーザ認証が行われた場合は // Googleのサービスにアクセスする // authorization codeを元に各種トークンを取得する Map<String,String> tokenMap = getTokenMap( authorizationCode); // accessトークンを利用して、Googleサービスからユーザ情報を取得 Map<String,String> jsonMap = getJSONMap( SERVICE_URI , tokenMap.get( "access_token" ) ); // POSTパラメータを書き込み resp.setContentType( "text/plain" ); PrintWriter out = resp.getWriter(); out.println( "print your userinfo." ); out.println( "" ); // ユーザ情報をすべて出力 Iterator<String> ite = jsonMap.keySet().iterator(); while ( ite.hasNext() ) { // キー取得 String key = ite.next(); // 値 String value = jsonMap.get( key ); // 出力 out.println( String.format( "%s = %s" , key , value ) ); } } else { // 不明なステータスとなった場合はエラー表示 resp.setContentType( "text/plain" ); resp.getWriter().println( "state is not found!" ); } } catch (Exception e) { e.printStackTrace(); } } /** * OAuth 2.0 のauthorization codeを利用して、各種トークンを作成する。 * 結果のJSONデータは連想配列(Map)として返す * @param authorizationCode * @return * @throws Exception */ public Map<String,String> getTokenMap( String authorizationCode ) throws Exception { // 戻り値変数を準備 Map<String,String> jsonMap = null ; // パラメータを組み立てる StringBuilder b = new StringBuilder(); b.append( "code=" ).append(URLEncoder.encode(authorizationCode, "utf-8" )); b.append( "&client_id=" ).append(URLEncoder.encode(CLIENT_ID, "utf-8" )); b.append( "&client_secret=" ).append(URLEncoder.encode(CLIENT_SECRET, "utf-8" )); b.append( "&redirect_uri=" ).append(URLEncoder.encode(REDIRECT_URI, "utf-8" )); b.append( "&grant_type=authorization_code" ); byte [] payload = b.toString().getBytes(); // POST メソッドでリクエストする HttpURLConnection c = (HttpURLConnection) new URL(ENDPOINT + "/token" ).openConnection(); c.setRequestMethod( "POST" ); c.setDoOutput( true ); c.setRequestProperty( "Content-Length" , String.valueOf(payload.length)); c.getOutputStream().write(payload); c.getOutputStream().flush(); // トークン類が入ったレスポンスボディを解析する StringBuilder json = new StringBuilder(); BufferedReader reader = new BufferedReader( new InputStreamReader( c.getInputStream() ) ); String line = null ; while ( (line = reader.readLine() ) != null ) { json.append(line).append( "\n" ); } reader.close(); c.disconnect(); // 文字列をハッシュマップに変換 jsonMap = cnvJSONToMap( json.toString() ); return jsonMap; } /** * OAuth 2.0 のaccessTokenを利用して、サービスにアクセスする。 * 結果のJSONデータは連想配列(Map)として返す * @param url * @param accessToken * @return * @throws Exception */ public Map<String,String> getJSONMap( String url , String accessToken ) throws Exception { // Google API からユーザ情報を取得 HttpURLConnection c = (HttpURLConnection) new URL( url ).openConnection(); c.setRequestMethod( "GET" ); c.setRequestProperty( "Authorization" , "OAuth " + accessToken ); // トークン類が入ったレスポンスボディを解析する Map<String,String> jsonMap = null ; StringBuilder json = new StringBuilder(); BufferedReader reader = new BufferedReader( new InputStreamReader( c.getInputStream() ) ); String line = null ; while ( (line = reader.readLine() ) != null ) { json.append(line).append( "\n" ); } reader.close(); c.disconnect(); if ( c.getResponseCode() == 200 ){ jsonMap = cnvJSONToMap( json.toString() ); } else { System.out.println( "Response Code : " + c.getResponseCode() ); } return jsonMap; } /** * 簡易JSONパーサー * @param strJSON * @return */ protected Map<String,String> cnvJSONToMap( String strJSON ) { // 入力チェック if ( strJSON == null || strJSON.equals( "" ) ){ return null ; } // 戻り値を作成 HashMap<String,String> map = new HashMap<String,String>(); // 括弧を消す String json = strJSON.replaceAll( "\\{" , "" ).replaceAll( "\\}" , "" ); // 文字列を解析して、連想配列(マップ)に格納 String[] jsons = json.split( "," ); for ( String line : jsons ) { // すべてのダブルクオーテーションを消す line = line.replaceAll( "\"" , "" ); // Key値を取得 int keyStart = 0 ; int keyEnd = line.indexOf( ":" , keyStart ) ; String key = line.substring( keyStart , keyEnd ).trim(); // Value値を取得 int valueStart = keyEnd + 1 ; int valueEnd = line.length(); String value = line.substring( valueStart , valueEnd ).trim(); // 連想配列に格納 map.put( key , value ); } // 戻り値を返す return map; } } |
1 2 3 4 5 6 7 8 | print your userinfo. name = ○○ ○○ id = ○○ ○○ given_name = ○○ locale = ja family_name = ○○ picture = https://○○/○○.jpg |
|
|
ライブラリ名 | 必要ファイル | ダウンロード場所 |
ROME 1.7 | rome-1.7.0-SNAPSHOT.jar | ・Github 「rometools/rome」 →最新ソース。コンパイルにはMavenが必要。 ・MVN Repository →コンパイル済Jar。ただしver1.6 |
ROME-utils 1.6 | rome-utils-1.7.0-SNAPSHOT.jar | ・MVN Repository →ページ下部のリンク |
JDOM 2.0.6 | jdom2-2.0.6.jar | ・MVN Repository →ページ下部のリンク |
SLF4J 1.7.21 | slf4j-api-1.7.21.jar slf4j-simple-1.7.21.jar |
・MVN Repository →ページ下部のリンク |
Apache HTTPClient(*) | commons-codec-1.9.jar commons-logging-1.2.jar httpclient-4.5.2.jar httpclient-cache-4.5.2.jar httpclient-win-4.5.2.jar httpcore-4.4.4.jar httpmime-4.5.2.jar |
・Apache Software「HttpComponents Downloads」 →最新版のzipファイルを解凍し、左記のファイルを取得 |
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 | package application; import java.awt.Desktop; import java.io.InputStream; import java.net.URI; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TestRomeRead extends Application { // 定数 protected static final int WIDTH = 300 ; protected static final int HEIGHT = 500 ; public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 ScrollPane scroll = new ScrollPane(); VBox root = new VBox(); scroll.setContent( root ); scroll.setHbarPolicy( ScrollBarPolicy.NEVER ); scroll.setVbarPolicy( ScrollBarPolicy.ALWAYS ); // シーンの作成 Scene scene = new Scene( scroll , WIDTH , HEIGHT ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); // RSSの取込・表示を遅延実行タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override public Boolean call() throws Exception { // RSSのURLを指定 SyndFeed feed = null ; // RSSフィードを読み込み(キャッシュ機能付き)。 // try-with-resources構文での記述 try ( CloseableHttpClient client = HttpClients.createMinimal() ) { // HTTPリクエストの作成 HttpUriRequest method = new HttpGet(uri); // HTTPリクエストを発行 try ( CloseableHttpResponse response = client.execute(method); InputStream stream = response.getEntity().getContent() ) { // フィードを読込 SyndFeedInput input = new SyndFeedInput(); feed = input.build( new XmlReader(stream)); } } // 画面表示 for ( Object entry : feed.getEntries() ) { // エントリーの取得 SyndEntryImpl e = (SyndEntryImpl) entry; // エントリーを順次表示 Node node = createDrawrEntry( e ); Platform.runLater( () -> root.getChildren().add( node ) ); } return null ; } }; // RSS取込・表示の遅延実行開始 Thread t = new Thread( task ); t.setDaemon( true ); t.start(); } /** * DrawrのRSSフィードから表示用のノードを作成する * @param e * @return */ protected Node createDrawrEntry( SyndEntryImpl e ) { // エントリーの取得 String author = e.getAuthor(); String title = e.getTitle(); String link = e.getLink(); String value = e.getDescription().getValue(); // 画像URL解析 String imgUrl = value.substring( value.indexOf( "http" ) , value.lastIndexOf( "\"" ) ); // 画目出力 Image img = new Image( imgUrl ); ImageView view = new ImageView( img ); Hyperlink hyperLink = new Hyperlink(); hyperLink.setText( title + "(" + author + ")" ); hyperLink.setGraphic( view ); hyperLink.setOnAction( arg -> { try { // デフォルト・ブラウザを起動 Desktop desktop = Desktop.getDesktop(); desktop.browse( new URI( link ) ); } catch (Exception e1) { e1.printStackTrace(); } }); // 表示ノードを返す return hyperLink; } } |
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 | package application; import java.io.File; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.SyndFeedOutput; public class TestRomeCreate { // 定数 protected static final int WIDTH = 300 ; protected static final int HEIGHT = 500 ; protected static final String [] RSS_TYPE = { "rss_1.0" , "rss_2.0" , "rss_0.9" , "rss_0.92" , "atom_1.0" , "atom_0.3" }; public static void main( String [] args) throws Exception { // 変数 final String filename = "rss.xml" ; // 出力先RSS // フィードの全体情報を設定 SyndFeed feed = new SyndFeedImpl(); feed.setTitle( "RSSのタイトルです" ); feed.setDescription( "RSSの内容を表す紹介文です" ); feed.setFeedType( RSS_TYPE[ 1 ] ); // フィードの記事を作成 List<SyndEntry> entries = new ArrayList<SyndEntry>(); for ( int i= 0 ; i< 10 ; i++ ) { // 1つ分の記事を作成 SyndEntry entry = new SyndEntryImpl(); SyndContent desc = new SyndContentImpl(); entry.setDescription( desc ); entry.setTitle( String .format( "%d番目の記事のタイトル" , i ) ); entry.setPublishedDate( Date.valueOf( LocalDate.now() ) ); desc.setType( "text/plain" ); desc.setValue( String .format( "%d番目の記事の内容" , i ) ); // 一覧に記事を追加 entries.add( entry ); } // 記事一覧をフィードに追加 feed.setEntries( entries ); // RSSフィードライタを作成し、ファイル出力 SyndFeedOutput o = new SyndFeedOutput(); o.output(feed, new File( filename ) ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <? xml version = "1.0" encoding = "UTF-8" ?> < channel > < title >RSSのタイトルです</ title > < description >RSSの内容を表す紹介文です</ description > < item > < title >0番目の記事のタイトル</ title > < description >0番目の記事の内容</ description > < pubDate >Sat, 09 Apr 2016 15:00:00 GMT</ pubDate > < dc:date >2016-04-09T15:00:00Z</ dc:date > </ item > < item > < title >1番目の記事のタイトル</ title > …中略 </ item > </ channel > </ rss > |
|
場所 | URL |
ソースコード | GitHub 「Zxing」 |
コンパイル済みjarファイル | Nexus Repository Manager 「Zxing」 |
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 | package application; import com.google.zxing.BarcodeFormat; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.oned.EAN13Writer; import com.google.zxing.qrcode.QRCodeWriter; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TestZxing extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 VBox root = new VBox(); root.getChildren().add( createBarcode( "1234567890128" , 200 , 40 ) ); // 1次元バーコードの作成 root.getChildren().add( createQRcode( "http://krr.blog.shinobi.jp/" , 100 , 100 ) ); // QRコード( 2 次元バーコード)の作成 // シーンの作成 Scene scene = new Scene( root , 250 , 200 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); } /** * 1次元バーコードの作成 * * @param str QRコード化する文字列 * @param width QRコードの横幅 * @param height QRコードの高さ * @return QRコードイメージ * @throws Exception */ protected Node createBarcode( String str, int width , int height ) throws Exception { // ルートノードの作成 VBox root = new VBox(); // バーコード作成 EAN13Writer writer = new EAN13Writer(); BitMatrix mat = writer.encode( str , BarcodeFormat.EAN_13, width, height); // ビット情報からJavaFXのImageクラスに変換 Image img = SwingFXUtils.toFXImage( MatrixToImageWriter.toBufferedImage( mat ) , null ); // シーングラフ用ノードに登録 ImageView view = new ImageView( img ); Label label = new Label( str ); root.getChildren().addAll( view , label ); return root; } /** * QRコードの作成 * * @param str QRコード化する文字列 * @param width QRコードの横幅 * @param height QRコードの高さ * @return QRコードイメージ * @throws Exception */ protected Node createQRcode( String str , int width , int height ) throws Exception { // QRコード作成 QRCodeWriter writer = new QRCodeWriter(); BitMatrix mat = writer.encode( str , BarcodeFormat.QR_CODE , width , height ); // ビット情報からJavaFXのImageクラスに変換 Image img = SwingFXUtils.toFXImage( MatrixToImageWriter.toBufferedImage( mat ) , null ); // シーングラフ用ノードに登録 ImageView view = new ImageView( img ); return view; } } |
ファイル名 | リソース |
multiple1.png | |
multiple2.png | |
ean13.png |
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 | package application; import java.awt.image.BufferedImage; import java.io.File; import java.util.Hashtable; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Reader; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.multi.GenericMultipleBarcodeReader; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TestZxingDecode extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 VBox root = new VBox(); // バーコードを取り込み、結果を画面に表示 // 正常に読み込める場合1 File file1 = new File( "img/multiple1.png" ); Image img1 = new Image( file1.toURI().toString() ); root.getChildren().add( readBarcode( img1 ) ); // 正常に読み込める場合2 File file2 = new File( "img/ean13.png" ); Image img2 = new Image( file2.toURI().toString() ); root.getChildren().add( readBarcode( img2 ) ); // 失敗する場合 File file3 = new File( "img/multiple2.png" ); Image img3 = new Image( file3.toURI().toString() ); root.getChildren().add( readBarcode( img3 ) ); // シーンの作成 Scene scene = new Scene( root , 500 , 300 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); } /** * バーコードの取込 * @param img * @return * @throws Exception */ protected Node readBarcode( Image fxImg ) throws Exception { // ルートノードの作成 HBox root = new HBox(); // 画像フォーマット変換 // JavaFXのImageクラス→SwingのImageクラス→Zxing用の画像クラス BufferedImage swImg = SwingFXUtils.fromFXImage( fxImg , null ); LuminanceSource source = new BufferedImageLuminanceSource( swImg ); BinaryBitmap bitmap = new BinaryBitmap( new HybridBinarizer( source ) ); // バーコード読込 String str = "" ; try { // デコード準備 Reader reader = new MultiFormatReader(); GenericMultipleBarcodeReader mr = new GenericMultipleBarcodeReader( reader ); Hashtable<DecodeHintType, Object> decodeHints = new Hashtable<DecodeHintType, Object>(); decodeHints.put(DecodeHintType.TRY_HARDER, Boolean .TRUE); // デコード Result[] result = mr.decodeMultiple( bitmap , decodeHints ); if ( result == null ){ throw new Exception( "バーコードを認識できませんでした" ); } // 結果取得 for ( Result r : result ) { // 文字列を取得 BarcodeFormat format = r.getBarcodeFormat(); str += format.name() + " : " + r.getText() + ";\n" ; } } catch (Exception e1) { e1.printStackTrace(); str = "失敗" ; } // シーングラフ用ノードに登録 ImageView view = new ImageView( fxImg ); Label label = new Label( str ); root.getChildren().addAll( view , label ); return root; } } |
|
(11/14) | JavaFX 画面キャプチャ(コマ撮り) |
(11/11) | JavaFX WebP画像ファイルを開く(webp-imageioライブラリ) |
(11/07) | EclipseでJavaFX入門(Java17での環境構築) |
(06/29) | Java DeepLearning4j 単語のベクトル化(Word2Vec) |
(06/11) | Java DeepLearning4j パラメータの設定 |