スキップしてメイン コンテンツに移動

投稿

2011の投稿を表示しています

Java実装のWeb Browser

Lobo: Java Web Browser Cobra CSSBox : Pure JavaのHtml, CSS2.1レンダーを行えるライブラリ Pure Javaでないものですと、SWTやJava FXで使用可能なWeb Browserのコンポーネントがあります。 org.eclipse.swt.browser.Browser javafx.scene.web.WebView

ActionScript 3.0: Test Tools

Test Suite AsUnit : FlashDevelop からでも使えます。 AS3Unit :ActionScript 3のためのテストフレームワークです。JUnitのActionScript 3.0版といったところでしょうか。 Spark Project 上で公開されています。 FlexUnit : AdobeLabs で公開されているTestSuitです。 FlexMonkey : FlexのためのUIのテストフレームワークです。 FlexPMD : Javaで有名なPMDのFlex版といったところでしょうか。 Code Coverage Tool flexcover :Code Coverage Tool for Flex and AIR applications.

Java: Resize Image Using Graphics2D

Here is a code for resizing image using Graphics2D. I also put bunch of rendering hints in the example code. Hope it helps for your understanding. private static BufferedImage resize(BufferedImage image, int width, int height) { BufferedImage shrinkImage = new BufferedImage(width,height, image.getType()); Graphics2D g2d = shrinkImage.createGraphics(); // rendering hints g2d.setRenderingHint(KEY_ALPHA_INTERPOLATION, VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g2d.setRenderingHint(KEY_COLOR_RENDERING, VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(KEY_DITHERING, VALUE_DITHER_ENABLE); g2d.setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(KEY_RENDERING, VALUE_RENDER_QUALITY); g2d.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(KEY_FRACTIONALMETRICS, VALUE_FRACTIONALME

C#でExcelファイルの読み書き

C#でExcelファイルを読み書きするためには、まず以下の2つの準備が必要です。 Microsoft Office (Excel)のインストール Visual Studioから「参照の追加」=> 「COM」タブからMicrosoft Excel 11 Object Libraryを追加(COMのバージョン部分は、インストールしたOfficeのバージョンに依存します) サンプルコード 以下は、実際にExcelファイルを開いて、Cellへの読み書き、sheetの追加を行うサンプルコードです。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; namespace Example { class ExcelExample { private static void RunExcelExample() { Excel.Workbook book = null; Excel.Application excel = null; try { excel = new Excel.Application(); book = excel.Workbooks.Open(@"c:\test.xls", Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,

ActionScript3.0: Reflection Example

I introduce some tips for reflection (not reflection of image but "programatic") of ActionScript 3.0. getDefinitionByName If you would like to Class object getDefinitionByName function should help. var c:Class = getDefinitionByName("flash.display.Sprite") as Class; If you would like to know details information of Class you can use describeType , which returns class information as Xml format. Reflective Class Instantiation import flash.utils.getDefinitionByName; public class Instantiator { private var classRef:Class; public function Instantiator(className:String) { this.classRef = getDefinitionByName(className) as Class; } public function newInstance(...args):Object { if(args.length == 0){ return new classRef(); } else { return new classRef(args); } } } Example usage: import flash.display.Sprite; import seedion.io.XMLExporter; // class will be instantiated at line with (*) import utils.tool.Instantiat

JavaでCMYK Color SpaceのJPEGを読み込む

Read CMYK JPEG Image CMYKのJPEG画像をJavaで読む方法ではまったので、Google先生で色々調べて見ました。 Problem reading JPEG image using ImageIO.read(File file) によるとImageIOで読めないJPEGファイルはほとんどCMYK Color Spaceの画像のようです。 私の場合もまず読めないJPEGがあることでCMYKのJPEGであることに気がつきました。 という訳で、CMYKのJPEGをどうやって読み込めばいいのということで色々調べてみました。 以下のstackoverflowによると、基本的にまずCMYKのColor Spaceで読み込んで、それからRGB系のColor Spaceに変換することでJavaでも読み込みができるようです。 Pure Java alternative to JAI ImageIO for detecting CMYK images How do I convert images between CMYK and RGB in ColdFusion (Java)? How to convert from CMYK to RGB in Java correctly? ただし、このCMYKのColor Spaceインスタンスを作るのが結構面倒です。 前述のstackoverflowによると、以下の方法があるようです。 CMYKのColorSpaceをSanselanライブラリを使って画像から抜き出す ICC_Profile iccProfile = Sanselan.getICCProfile(new File("filename.jpg")); ColorSpace cs = new ICC_ColorSpace(iccProfile); 自分でCMYKColorSpaceクラスを定義して、インスタンス化する iccプロファイルから、ColorSpaceインスタンスを生成する。ただしiccプロファイルはどこかから自前に用意する必要があります。 ICC_Profile iccProfileCYMK = ICC_Profile.getInstance(new FileInputStre

JavaでDirectoryをZIP圧縮・解凍

JavaでDirectoryをZIP圧縮するためのソースコード private static final int _4K_BYTES = 4096; // core part... piece of cake.... public final static void zipDirecory(File dir, File zipFile) throws IOException { if (!dir.isDirectory()) { throw new IllegalArgumentException("Not directory :" + dir); } try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) { File parentFile = dir.getParentFile(); Path baPath = parentFile == null ? dir.toPath() : parentFile.toPath(); zipDirectory(dir, new byte[_4K_BYTES], out, baPath); } } private static void zipDirectory(File dir, byte[] bs, ZipOutputStream out, Path basePath) throws IOException { for (File f : dir.listFiles()) { if (f.isDirectory()) { zipDirectory(f, bs, out, basePath); } else { out.putNextEntry(new ZipEntry(basePath.relativize(f.toPath()).toFile().getPath())); copy(new FileInputStream(f), out, bs); } } } // trivial helper methods... please use java c

ActionScript 3.0: Play Sound with Drawing FFT Spectrum

I have written simple example for playing mp3 sound with drawing sound FFT spectrum. Here is the code. package utils.sound { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.utils.ByteArray; import flash.media.SoundMixer; import flash.media.Sound; import ui.Button; import flash.net.URLRequest; import flash.media.SoundChannel; public class SoundPlayerTemp extends Sprite { private static const MAX_CHANEL :int = 256; private var w:int = 1; private var maxSize:int = 400; private const OFFSET_Y:int = 20; private var urlReq :URLRequest = new URLRequest("file://c:/temp/test.mp3"); // any button is fine.... private var startButton:Button = new Button(maxSize - 50, 100, OFFSET_Y); private var snd:Sound = new Sound(); private var sndCh:SoundChannel; private var playState:B

Java: Reflection Example: Get All Static Field Names in Class

This post is just as I wrote in the title - "get all static field names in class". I think you can easily imagine how to get other similar information by reflection... public final static Collection<String> getStaticFieldNames(Class<?> classObj){ ArrayList<String> list = new ArrayList<String>(); Field[] fields = classObj.getFields(); for(Field field: fields){ if(Modifier.isStatic(field.getModifiers())){ list.add(field.getName()); } } return list; }

Collection内の重複を見つけるJavaコード

Collection内の重複を見つけるJavaコードをGoogleのMultimapを使って書いてみました。 引数のkeyGeneratorによって、重複したとみなす要素の戦略を変更できます。実装にMapを使っていますので、keyGegerator関数で生成されるKeyオブジェクトは、equalsメソッドとhashCodeメソッドが正しく実装されている必要があります。 import java.util.Collection; import java.util.Map.Entry; import com.google.common.base.Function; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class DuplicationFinder { public static Multimap findDuplication(Collection c, Function keyGenerator){ return toResult(createMultimap(c, keyGenerator)); } private static Multimap toResult(final Multimap temp) { final Multimap result = ArrayListMultimap.create(); for(Entry > entry : temp.asMap().entrySet()){ if(entry.getValue().size() > 1){ result.putAll(entry.getKey(), entry.getValue()); } } return result; } private static Multimap createMultimap(Collection c, Function keyGenerator) { final Multimap map = ArrayListMultimap.create(); for(V v : c){ map

C#からOutlookを操作

「メールを受信したときに実行するプログラム」と「メールボックス内のフォルダ情報やinbox内にあるメールを表示する」サンプルコードです。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Outlook; namespace OutlookExample { public class OutlookExample { public static void RunOutlookExample() { ApplicationClass appClass = new ApplicationClass(); appClass.NewMail += new ApplicationEvents_10_NewMailEventHandler(outLookApp_NewMailEx); PrintInbox(appClass); } private static void outLookApp_NewMailEx(string EntryIDCollection) { // do something nice when mail is coming } public static void PrintInbox(ApplicationClass o) { // get items in my inbox (using MAPI) NameSpace outlookNS = o.GetNamespace("MAPI"); MAPIFolder inboxFolder = outlookNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox); foreach (MA

ActionScript 3.0: String Utility Methods (trim, startsWith, endsWith etc.)

public class StringUtils { public function StringUtils() { } public static function concatAsString(array:Array):String { var ret:String = ""; for each(var str:String in array) { ret += str; } return ret; } public static function concatAllAsString(delimita:String, ...strs):String { if (strs == null || strs.length == 0) { return ""; } var ret:String = ""; for each(var str:String in strs) { ret += delimita + str } return ret.substr(1, ret.length - 1); } public static function trim(src:String):String { return src.replace(/^[\s\t]+(.+)[\s\t]+$/, "$1"); } public static function endsWith(str:String, seacrh:String):Boolean { return str.length > seacrh.length && str.substr(seacrh.length-1, seacrh.length) === seacrh; } public static function startsWith(prefix:String, testStr:String):Boolean { return testStr.length >= prefix.length && testStr.substr(0, prefix.len

Javaで全画面表示

Javaで全画面表示する方法です。GraphicsDeviceのsetFullScreenWindow メソッドの引数に全画面表示させたいWindowオブジェクトを渡すことで実現できます。サンプルコードを以下に示します。 public static GraphicsDevice setFullScreen(Window window) {    GraphicsDevice graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();    graphicsDevice.setFullScreenWindow(window);    return graphicsDevice; // not necessary to return but... easy to reuse GraphicsDevice  object after this method is called } 全画面表示を終了させるときは、GraphicsDeviceにnullをセットします。 GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .graphicsDevice.setFullScreenWindow(null); 例えばこんな感じで使います。 public class FullScreenTest {     @Test     public void testFullScreen() throws Exception {         JWindow window = createTestWindow();         window.setVisible(true);                 GraphicsDevice graphicsDevice = AwtUtils.setFullScreen(window);         try {             Thread.sleep(1000);         } catch (InterruptedException e) {}

HTML related library for Java

HTML Parser JavaのHTML Parser でいまだにしっくりくるライブラリを見つけられないのですが、私がいくつか試したものを紹介します。 JTidy 特にXHTML形式のファイルの解析で威力を発揮します。 HTMLEditorKit : Swingに付属しているものです。個人的にはSwingのライブラリをHTMLの解析の目的で使うのはどうかなあと感じています。 NekoHTML 残念ながらまだ試していませんが、これが使いやすそうです。機会があればBlogに書こうと思います。 StackOveflow  の Java HTML Parsing の議論が参考になりそうです。 Htm Parser jsoup   HTML Validator JTidy

Helpful Development Tools & Software (Build, Test, Inspection, CI, etc....)

Test Tools JUnit JMeter FIT Testing Eclipse Test & Performance Tools Platform Project : Eclipseで使えるパフォーマンステストツール JUnitPerf : Performance Test tool Selenium : Web系の自動テストの決定版 zohhak : JUnit標準のparameterizedテストは色々と書くのが面倒ですが、これを使うとかなりsimpleにテストを書けます!以下はサイトに載っていたコードの例です。 @TestWith({ "clerk, 45'000 USD, GOLD", "supervisor, 60'000 GBP, PLATINUM" }) public void canAcceptDebit(Employee employee, Money money, ClientType clientType) { assertTrue( employee.canAcceptDebit(money, clientType) ); } Mock JMock EasyMock Mockito : 個人的にはこれがお勧め。使いやすいです。 Behavior Driven Development http://jbehave.org/ JDave Instinct Wikipedia にJava以外の言語のBDDツールも大量に載っています。 Code Coverage Tools ここ が参考になります。以下、代表的なものを2つあげておきます。 ATLASSIAN 社の Clover EMMA :私はこのツールを使っています。Cloverのようにグラフが表示されないのが、ちょっと残念。データ自体はあるので簡単に作れそうですが(汗)。ちなみに私は、 EMMA Reference Manual や Emma+Antをofflineモードで実行する の記事を参考にAnt scriptを書きました。 Matching hamcrest : テスト時に可読性を上げた

Books for Refactoring

I read some books for software refactoring. The followings are my recommendations. Refactoring to Patterns Refactoring Improving the Design of Existing Code Working Effectively With Legacy Code