JAVA TIPS

命名

resolve

解決する

store

記憶させる

validate

検証する

update

更新する

copy

コピーする

select

選択する

insert

挿入する

replace

置換する

add

追加する

regist

登録する

delete

削除する

refer

参照する

get

取得する

create

生成する

set

設定する

remove

取り除く

compare

比較する

restore

復元する

contain

含む

transform

変換する

is

かどうか?

has

を持っているか

can

できるか?

フィールド変数

hoge_のように先頭小文字で最後に_をつける

ローカル変数

hogeのように先頭小文字

リストを指定のクラスの配列に変換

codetblBeans = (CodetblBean[]) (listRawData.toArray(new CodetblBean[0]));

ここでtoArrayの引数にその変換したいクラスを指定してやる

Preferences

JSFの本を読んでいるとこんなのが出てきましたので調べてますと、データのセーブとロードをしてくれる APIだそうです。JSFとは関係なかったです。値はなんとWindows ではレジストリでデータを保持してます。

Preferences prefs = Preferences.userNodeForPackage(this.getClass());
prefs.put("key", atai);

http://www5.airnet.ne.jp/sakuraba/java/laboratory/JDK1.4/MiscAPI/Preferences/Preferences.html

RowSet?

やっと待ち望んでいた機能がでてきました。なんとDBコネクション切断状態での使用が可能です。CachedRowSet?を使いますが、シリアライズ可能であるため、使用用途が非常に広がります。またResultSet?JavaBeansとして扱ったり、XMLでの入出力が可能であったりと、ほしかった機能が満載です!J2SE5からはサポートされていますが、今はEclipseでサポートされていないので、JDK1.4で使うためにhttp://java.sun.com/products/jdbc/download.htmlからJDBC RowSet? Implementations 1.0.1 をダウンロードします。

cookie

値取得

Cookie cookies[] = httpServletRequest.getCookies();
if (cookies.length > 0) {
 for (int i = 0; i < cookies.length; i++) {
  System.out.println(cookies[i].getName());
  System.out.println(cookies[i].getValue());
 }
}

値セット

// testという名前のクッキーを作成
Cookie cookie = new Cookie("test", "atai");
// クッキーの有効期間を1日に設定(秒単位で指定)
cookie.setMaxAge(60 * 60 * 24 * 1);
// cookie値セット
this.getHttpServletResponse().addCookie(cookie);

Properties

XML に対応した Properties

環境変数

request.getServerName();
request.getProtocol();
request.getMethod();
request.getPathInfo();
request.getServletPath();
request.getQueryString();
request.getRemoteAddr();
request.getRemoteHost();
request.getContentLength();
request.getHeader("User-Agent");
request.getHeader("Referer");

メール

/*メッセージを受け取る
 * @param   String pop3host POP3サーバ
 * @param   String pop3port pop3ポート
 * @param   String pop3user pop3ユーザ
 * @param   String pop3pass pop3パスワード
 */
public void ReceiveMail(String pop3host, String pop3port, String pop3user, String pop3pass) {
       try {
           //  初期設定
           Properties props = new Properties();
           Session sess = Session.getDefaultInstance(props, null);
           //  接続
           Store store = sess.getStore("pop3");
           store.connect(pop3host, Integer.parseInt(pop3port), pop3user, pop3pass);
           //  フォルダをひらく
           Folder rootFolder = store.getDefaultFolder();
           Folder inbox = rootFolder.getFolder("INBOX"); //  これのみ
           inbox.open(Folder.READ_ONLY);
           System.out.println("メール:" + inbox.getMessageCount() + "通");
           //  フォルダを閉じる
           inbox.close(false); //  メールは消さない
           store.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
/*  メールを送る
 * @param   String host SMTPサーバ
 * @param   String port SMTPサーバのポート
 * @param   String from 送信
 * @param   String to 受信
 * @param   String subject タイトル
 * @param   String content 内容
 */
public void sendMessage(String smtphost, String smtpport, String from,
String to, String subject, String content)
throws IOException, MessagingException {
       Properties props = System.getProperties();
       props.put("mail.smtp.host", smtphost);
       Session session = Session.getInstance(props);
       // Messageオブジェクトを構築します。
       MimeMessage msg = new MimeMessage(session);
       // 宛て先(To:)の設定
       msg.addRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(to, false));
       // From: Date: の設定
       msg.setFrom(InternetAddress.parse(from, false)[0]);
       msg.setSentDate(new Date());
       // Subject: 本文の設定
       msg.setSubject(subject, "ISO-2022-JP");
       msg.setText(content + "\015\012", "ISO-2022-JP");
       Transport.send(msg); //  送信
}

msg.setTextで\015\012をつけているのは改行コードを送っている。これがないとボディの最後にw)とかくっついてくる。activation.jar,mail.jarは必要になるので、tomcatを入れている場合は、CATALINA_HOME\common\libを参照すること。また~とか-とか文字化けする場合は、下の文字化け対策を施す。

HTTPSessionオブジェクトをクリーンアップ

strutsでscope="session"にしている場合、セッションに残ってしまいます。そこで消したい場合は、

//HTTPSessionオブジェクトをクリーンアップする
Enumeration enum = this.getSession().getAttributeNames();
while (enum.hasMoreElements()) {
   formName = (String) enum.nextElement();
   if (formName.endsWith("Form")) {
       this.getSession().removeAttribute(formName);
       enum = this.getSession().getAttributeNames();
   }
}

日付の差

((date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000));

1ヶ月前

calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); 
String strYY = String.valueOf(calendar.get(Calendar.YEAR));
String strMM = String.valueOf(calendar.get(Calendar.MONTH) + 1);
String strDD = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));

文字化け

~とか-とか決まって文字化けをおこしてくれます。そこで、

//~
convert = convert.replace('\uFF5E', '\u301C');
//-
convert = convert.replace('\uFF0D', '\u2212');

戻るボタン無効化

JAVAじゃないんですが、jspの頭に

<SCRIPT>
 history.forward();
</SCRIPT>

ファイルI/O

http://ash.jp/java/stream.htm

LDAP

package ldap;

import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;

public class Selector {

	public static void main(String[] args) {

		try {
			// InitialDirContextの作成
			Properties env = new Properties();
			env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, "ldap://192.168.1.1:389");

			//env.put(Context.SECURITY_PRINCIPAL, "foo@bar");
			//env.put(Context.SECURITY_CREDENTIALS, "hoge");
			//env.put(Context.SECURITY_AUTHENTICATION, "simple");

			//env.put(Context.PROVIDER_URL, "ldap://xxx.xxx.xxx.xxx:389/o=hoge");
			//env.put(Context.SECURITY_AUTHENTICATION, "simple");
			//env.put(Context.SECURITY_PRINCIPAL, "cn=hoge, ou=hoge, o=hoge");
			//env.put(Context.SECURITY_CREDENTIALS, "hoge");

			InitialDirContext ctx = new InitialDirContext(env);

			// 検索して結果を表示
			SearchControls ctrl = new SearchControls();
			ctrl.setSearchScope(ctrl.SUBTREE_SCOPE);

			NamingEnumeration topLvlSrch = ctx.search("ou=People,dc=my-domain,dc=com",
					"cn=Taro*", ctrl);
			while (topLvlSrch.hasMoreElements()) {

				SearchResult srchRslt = (SearchResult) topLvlSrch.next();
				Attributes atrs = srchRslt.getAttributes();
				NamingEnumeration atrSrch = atrs.getAll();

				while (atrSrch.hasMoreElements()) {

					Attribute atr = (Attribute) atrSrch.next();
					Enumeration elems = atr.getAll();

					while (elems.hasMoreElements()) {
						System.out.println(atr.getID() + " : "
								+ elems.nextElement());
					}
				}

				// 個別に取得
				// Attribute atr = atrs.get( "mail" );
				// System.out.println( atr.getID() + " : " + (String)atr.get()
				// );

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

http://www.nunokawa.soft.iwate-pu.ac.jp/java/14x/docs/ja/guide/jndi/jndi-ldap.html
LDAP接続用コード
LDAPとJNDIでシングルサインオン可能なWebを作る

キャッシュされたくない

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="-1">

もしくは、

<% response.setDateHeader("Date", System.currentTimeMillis()); %>
<% response.setDateHeader("Expires", 0); %>
<% response.setHeader("Pragma", "no-cache"); %>
<% response.setHeader("Cache-Control", "no-cache"); %>
<% response.addHeader("Cache-Control", "no-store"); %>
<% response.addHeader("Cache-Control", "max-age=0"); %>

http://bugzilla.mozilla.org/show_bug.cgi?id=176014より

小数点四捨五入

http://www.applitips.com/java/kiso/roundBigDecimal.htm

JDBC

http://www.hellohiro.com/datasource.htm

まとめてSQL

stmt = conn.createStatement();
stmt.addBatch(strSql) //ここでSQLを溜め込む
stmt.executeBatch()  //溜め込んだSQLを実行

WebアプリからExeが動かん

<%@ page import="java.lang.Runtime.*" %>
<%
Runtime rt;
Process pr;
rt = Runtime.getRuntime();
pr = rt.exec("c:\\test.exe");
%>

サービスのtomcatのプロパティからログオンを見るとローカルシステムアカウントになっているので、これをアカウントに変更して、それなりのアカウントで動かす。

正規表現

http://www.hellohiro.com/regex.htm

タグ

@inheritDoc コメントを継承

http://web.yl.is.s.u-tokyo.ac.jp/~ganat/java/javadoc.html

アノテーション

  • @SuppressWarnings? 警告を抑制できる。
    例: @SuppressWarnings("deprecation") 
    unchecked
    deprecation
    fallthrough
    finally
    serial
  • @Override メソッドがオーバーライドであることを示す。 オーバロードとかで間違っているときにエラーになる
  • @Deprecated 推奨されないAPIに対して使用するとエラーになる
    例:@Deprecated void hoge() {}

メモ

public static boolean containsHalfWidthKana(String str) { 
  if (str != null) { 
    char[] chars = str.toCharArray(); 
    for (int i = 0; i < chars.length; i++) {
      char target = chars[i];
      if (0xff61 <= target && target <= 0xff9f) { 
       return true; 
      }
    }
  } 
  return false; 
}

コメント

  • #comment

トップ   編集 凍結解除 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2008-03-15 (土) 16:10:00 (5906d)