2014年12月10日水曜日

jQueryでバインドさせたいファンクションにパラメータを渡すには?

jQueryでバインドさせたいファンクションにパラメータを渡すには、event.dataを使えるよう。例えば、

element.bind('click', {'id':3}, function(event) {
    console.log(event.data.id);
});

のようにしてパラメータとして渡せます。

参考リンク
http://stackoverflow.com/questions/3994527/passing-parameters-to-click-bind-event-in-jquery

WordpressのXMLRPC.phpへのDoSを防ぐには?

WordpressのXMRPC.phpを悪用してDoS攻撃を受ける場合、攻撃元のIPをブロックする以外にもWordpressのプラグインで無効化できるようです。

参考リンク
https://wordpress.org/support/view/plugin-reviews/disable-xml-rpc-pingback

2014年11月7日金曜日

jQueryでブラウザで表示中のビューポートの情報を得るには?

getViewport = function() {
    var $w = $(window);
    return {
        l: $w.scrollLeft(),
        t: $w.scrollTop(),
        w: $w.width(),
        h: $w.height()
    }
}

参考リンク
http://stackoverflow.com/questions/10324753/jquery-function-to-get-the-curren-viewport

d3でcssのクラスを複数追加するには

d3.selectAll(".someDiv").attr("test1 test2");

参考リンク
http://stackoverflow.com/questions/13188125/d3-add-multiple-classes-with-function

MavenでWeb Applicationプロジェクトの作成方法

1.mvnコマンドで以下をEclipseのworkspaceで実行

$ mvn archetype:generate -DgroupId=com.test
-DartifactId=TestApp
-DarchetypeArtifactId=maven-archetype-webapp
-DinteractiveMode=false

2.WTPプロジェクトに変換

$ mvn eclipse:eclipse -Dwtpversion=2.0

3.pom.xml、web.xmlを自分用に編集していく

参考リンク
http://www.mkyong.com/maven/how-to-create-a-web-application-project-with-maven/


Spring MVCでreCaptchaを使うには?

1.GoogleでreCaptchを使用するのに必要なプライベートキー、パブリックキーを取得。

http://www.google.com/recaptcha


2.pom.xmlに追加。

<dependency>
 <groupId>net.tanesha.recaptcha4j<groupId>
     <artifactId>recaptcha4j<artifactId>
   <version>0.0.7<version>
<dependency>

3.JSPでタグを追加。

<tags:captcha privateKey='XXXX' publicKey='YYYY'><tags:captcha>

4.コントローラー(サーブレット)でのパラメータと認証。

@RequestMapping(value='', method=RequestMethod.POST)
 public String submitForm(@ModelAttribute('userInfo') UserInfo userInfo, @RequestParam('recaptcha_challenge_field') String challangeField, @RequestParam('recaptcha_response_field') String responseField, ServletRequest servletRequest) {
 String remoteAddress = servletRequest.getRemoteAddr();

 ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(remoteAddress, challangeField, responseField);

 if(reCaptchaResponse.isValid()) {
  return 'success';
 } else {
  return 'fail'; 
 }
}

参考リンク
http://www.javacodegeeks.com/2012/11/use-recaptcha-in-a-spring-mvc-web-application.html
https://code.google.com/p/recaptcha/wiki/HowToSetUpRecaptcha#Java/JSP

2014年10月14日火曜日

Tomcatでベーシック認証

tomcat-users.xml

<tomcat-users>
    <role rolename="aaaa" />
    <user username="bbb" password="ccc" roles="aaaa" />
</tomcat-users>


web.xml

<web-app>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>
                Authentication of BasicAuth
            </web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>basic</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>ProtectedRealm</realm-name>
    </login-config>
</web-app>

参考リンク
http://www.javaroad.jp/opensource/js_tomcat9.htm
http://www.coderanch.com/t/465990/java-Web-Component-SCWCD/certification/HTTP-Status-Access-requested-resource

2014年10月8日水曜日

JavaMailでsmtp-authでメールを送信する方法

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");  <----25か587のサブミッションポートでもok
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true")

    Authenticator auth = new SMTPAuthenticator();
    Session mailSession = Session.getDefaultInstance(props, auth);

    // パスワード認証のプライベートクラス
    private class SMTPAuthenticator extends javax.mail.Authenticator {  
        public PasswordAuthentication getPasswordAuthentication() {
           String username = SMTP_AUTH_USER;
           String password = SMTP_AUTH_PWD;
           return new PasswordAuthentication(username, password);
        }
    }


http://www.rgagnon.com/javadetails/java-0538.html

2014年10月4日土曜日

Postfixで587のサブミッションポートでsmtp-auth設定をした上で、25ポートでのsmtp-authをさせないように設定するには。

Postfixで587のサブミッションポートでsmtp-auth設定をした上で、25ポートでのsmtp-authをさせないように設定するには、/etc/postfix/master.cfを以下のように編集。

smtp      inet  n       -       -       -       -       smtpd

  -o smtpd_sasl_auth_enable=no  <---------- ここをno

submission inet n       -       -       -       -       smtpd
  -o smtpd_sasl_auth_enable=yes       <---------- ここをyes

参考リンク:

2014年10月3日金曜日

MySQLでデータのダンプとリストアをCSVファイルでやりとりする方法

MySQLでデータのダンプとリストアをCSVファイルでやりとりする方法を簡単にメモ。

ダンプ

SELECT * FROM tableA INTO OUTFILE "/tmp/dump.csv" FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"';

リストア

LOAD DATA INFILE "/tmp/dump.csv" INTO TABLE tableA FIELDS TERMINATED BY ',' ENCLOSED BY '"';

http://sasuke.main.jp/sqlcsv.html

注意した点として、Ubuntuなどではデフォルトで/tmp/ 以下からでしかCSVファイルを扱えなかったので、ダンプ・リストア時のエラーに注意。確かerrorno 13だった気が。。。

Javaのサーブレットでブラウザの戻るボタンを防ぐ方法

Javaのサーブレットでブラウザの戻るボタンを防ぐには、フィルターでレスポンスを制御する。

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, 
    FilterChain chain) throws IOException, ServletException 
    {
        HttpServletResponse response=(HttpServletResponse)res;
        response.setHeader("Cache-Control", "no-cache, no-store, "
        + "must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
        chain.doFilter(req, res);

    }


Postfixでsaslauthdにハマった。。。のでメモ。

UbuntuのPostfixでsmtp-auth認証を設定する時に一番ハマったのがsaslauthdの設定。結論からすると設定ファイルのミスという単純なものだったのだが、結構ハマったのでメモ。

/etc/default/saslauthdの中身

# Should saslauthd run automatically on startup? (default: no)

START=yes <-------ここをyesにするのだが、大文字のYESにしてしまうとsaslauthdは起動しない。

起動時のエラーメッセージで気付くべきだったのだが、、、、ハマってしまった。

チェックポイント:
/var/log/mail.log
/usr/sbin/testsaslauthd -u username -p password



参考リンク
https://forums.ubuntulinux.jp/viewtopic.php?id=6750



Postfixのsmtp-auth設定でRelay Access Denied 554エラーが出る

UbuntuでPostfixのsmtp-auth設定でRelay Access Denied 554エラーが出た場合の対処法。

/etc/postfix/main.cf


smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

ポイントはpermit_sasl_authenticatedをreject_unauth_destinationの前に追加してやること。これがないとsmtp-authでのリレーアクセスができない。

参考リンク
http://askubuntu.com/questions/390401/relay-access-denied-error-554

telnetでsmtp-authの動作確認方法

telnetでsmtp-authの動作確認をしたかったのでメモ。クライアントサイドの入力のみでサーバー側の応答は省く。

% telnet mail.test.com 25

% helo mail.test.com

% auth login      <----------- SMTP-AUTHをすることを伝える。

% xxxxxxxx      <----------- base64エンコードされたユーザアカウント。

% xxxxxxxx      <----------- base64エンコードされたパスワード。

% mail from: <sender@abc.com>

% rcpt to: <reciver@efg.com>

% data
% Subject: abcded
% abcdefg
%
% This is a test message....
% .     <---------- ピリオドで終える。

% quit


ハマったとこはbase64エンコードされたID/PASSの設定。どうもパスワードに特殊記号が含まれているとbase64が失敗しているのか、認証に失敗してしまっていた。ここは精製方法を要調査。

参考リンク
http://www.anta.net/misc/telnet-troubleshooting/smtp.shtml
https://www.ndchost.com//wiki/doku.php?id=mail/test-smtp-auth-telnet
http://vogel.at.webry.info/201308/article_1.html

2014年9月27日土曜日

UbuntuでBashのアップデート方法

UbuntuでBashのアップグレード方法をメモ。

1. bashに問題ありかチェック。echo vulnerableがプリントされたらアウト。

env x='() { :;}; echo vulnerable' bash -c 'echo hello'

2. bashをapt-get installでアップデート

sudo apt-get update && sudo apt-get install bash

3. リリースが古いとアップデートできない場合があるので、その時は思い切ってリリースのアップグレードすると解決された。

http://askubuntu.com/questions/528101/what-is-the-cve-2014-6271-bash-vulnerability-and-how-do-i-fix-it

Ubuntuでアップデートしようとした場合、/bootの空き容量が無くて困った場合。

Ubuntuでアップデートしようとした場合、/bootの空き容量が無くて困った場合、/bootから以下の手順で対処。なぜこんなに古いカーネルが溜まっていくのかよく分からないが、、、

1. uname -r で今使用中のカーネル・リリース番号をチェック
2. /boot から使用していない古いカーネル、initrd.img-xxxxxを削除。(ちょっと怖いので削除でなく他のスペースにmv。
3. apt-get update, installができるようになるまで繰り返して/bootスペースを確保。
4. ひとまずapt-get update, installはできるようになる

参考リンク
http://askubuntu.com/questions/324029/unable-to-remove-older-images-from-boot


ただ、このやり方はイマイチしっくりなので、調べてみると以下のようなやり方もあり。違う機会に試そうと思う。




別のやり方。
http://askubuntu.com/questions/345588/what-is-the-safest-way-to-clean-up-boot-partition
http://askubuntu.com/questions/142926/cant-upgrade-due-to-low-disk-space-on-boot/142937#142937

サポートが終わったUbuntuパッケージのアップグレード方法

Ubuntuでサポートが終わった古いパッケージをアップグレードする方法。意外と簡単だったので簡単にメモ。

1. /etc/apt/sources.listをコピーしてバックアップする
2. /etc/apt/sources.listを以下で書き換える

## EOL upgrade sources.list
# Required
deb http://old-releases.ubuntu.com/ubuntu/ CODENAME main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ CODENAME-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ CODENAME-security main restricted universe multiverse

# Optional
#deb http://old-releases.ubuntu.com/ubuntu/ CODENAME-backports main restricted universe multiverse

3. CODENAMEを適切なリリース名に変更。例えばraringとかpreciseとか。
4. do-release-updateを実行
5. 適宜コンフィグファイルを現状維持するか書き換えるか聞かれるので応答。個人的にはデフォルトの現状維持で編集したファイルを維持。

手間はかかるがバージョンを順にアップグレードしていけば、最新のパッケージにアップグレードできた。但し、12.04 --> 12.10 --> 13.04 --> ..... という順でアップグレードしておくので、最新までの距離が長いと時間はかかる。

以下リンクを参考。
https://help.ubuntu.com/community/EOLUpgrades

2014年9月16日火曜日

Hibernateで関連性のあるエンティティでフィルタをかけたい場合

Hibernateで関連性をもつエンティティ同士があり、関連先のフィールドで検索(フィルタ)をかけたい場合は以下のようにする。

この例ではCat(一)に対してkittens(多)はCatのコレクションであるような1対多の関連の場合、Catを抽出するのに関連先のkittenのフィールドでフィルタをかけた例。createCritearia.add(Restrictions.like)を併用してやる。

http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/querycriteria.html#querycriteria-associations

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens")
        .add( Restrictions.like("name", "F%") )
    .list();

MavenでOutOfMemoryが出る場合の対処法

MavenでOutOfMemoryが出る場合、MAVEN_OPTSでVMの最大値を大きく取ってやると解決する。

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

https://cwiki.apache.org/confluence/display/MAVEN/OutOfMemoryError

2014年9月4日木曜日

Javaで画像ファイルをリサイズしたい場合はBufferedImageとGraphics2Dを使う

Javaで画像ファイルをリサイズしたい場合はBufferedImageとGraphics2Dを使う。

http://www.mkyong.com/java/how-to-resize-an-image-in-java/


BufferedImage originalImage = null;
BufferedImage resizedImage = null;
Graphics2D g = null;
try {
int width = 200;
int height = 200;

originalImage = ImageIO.read(originalFile);
int type = originalImage.getType() == 0 
? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

resizedImage = new BufferedImage(width, height, type);
g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();

ImageIO.write(resizedImage, "jpg", 
new File(imageFolder.getAbsolutePath()+"/"+iconName));

// post process
if( originalImage != null ) {
originalImage.flush();
originalImage = null;
}

// post process
if( resizedImage != null ) {
resizedImage.flush();
resizedImage = null;
}
 
} catch(Exception e) {
System.out.println("Can not generate " + originalFile.getName());
e.printStackTrace();
} finally {
if( originalImage != null ) {
originalImage.flush();
originalImage = null;
}
if( resizedImage != null ) {
resizedImage.flush();
resizedImage = null;
}
}

ImageIO.readeで java.lang.OutOfMemoryの例外が発生する場合に注意しておく点

ImageIO.readeで java.lang.OutOfMemoryの例外が発生する場合、以下の点に注意する。


  1. VMの-Xmxを充分な値に設定しているかどうか。
  2. BufferedImageを使用後にflushやnullを設定するなどの後処理をしているか。(特にファイルを連続で読み込んだりする場合は注意。)

画像のエンコーディングをJavaで検知するには?

ImageIO.getImageReadersを使う。
ImageInputStream imageInputStream = ImageIO.createImageInputStream(
    myInputStream);
Iterator<ImageReader> iter = ImageIO.getImageReaders(imageInputStream);
if (!iter.hasNext()) {
    // this always happens
}
ImageReader reader = (ImageReader) iter.next();
if (!reader.getFormatName().equals("jpeg")) {

}
http://stackoverflow.com/questions/4530348/detecting-image-encoding-in-java

jQueryでフォームの値をクリアするには?

// Call it on your <form>
$('form').clearForm();
http://jquery-howto.blogspot.com/2013/08/jquery-form-reset.html

jQueryでフォームのバリデートをするにはjQuery Form Validatorが便利

フォームのバリデーションをjQueryでやるにはjQuery Form Validatorが便利だ。

2014年7月11日金曜日

MySQLでテーブル作成でエラーが出た時の詳細ログチェックの方法

MySQLで例えばテーブルを作成する時に外部キー制約などが間違ってた場合、error no 150と言われてもさっぱり分からないので、以下のコマンドで詳細をチェック。

>SHOW ENGINE INNODB STATUS

外部キーであれば、テーブル名が存在しないなどと詳しいエラーを教えてくれる。

http://stackoverflow.com/questions/17812616/mysql-error-1005-cant-create-table-errno-150

2014年7月10日木曜日

ELF header smaller than expectedがUbuntuのアップデート後の再起動で出た場合

ELF header smaller than expectedがUbuntuのアップデート後の再起動で出た場合、以下の手順で治します。


  1. UbuntuのブータブルUSBスティックを作る
  2. USBスティックからブート
  3. boot-repairをインストール
    • sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
  4. boot-repairを実行
    • sudo apt-get install -y boot-repair && (boot-repair &)
  5. リブートしてOK


http://askubuntu.com/questions/401105/elf-header-smaller-than-expected

2014年6月27日金曜日

mysqlでダンプファイルから特定の列をリストアするには?

idを指定してやる場合。

mysqldump -uroot -p db_name table_name --where='id<1000000'

http://stackoverflow.com/questions/5658284/how-to-use-mysqldump-for-a-portion-of-a-table

MySQLでカラムの値を分割して抽出するには?

MySQLでカラムの値を分割して抽出するには、SUBSTRING_INDEX関数を使ってやる。

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2); -> 'www.mysql' mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2); -> 'mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index

3つめの数値の引数がポイント。正の数は左から数えて、負の数は右から数えて、いくつめの分割された値かを指す。

MySQLでのフロー制御関数の扱い方

MySQLでIF-ELSE IF-ELSE的な事をしたい場合、こうする。

mysql> SELECT CASE 1 WHEN 1 THEN 'one'
    ->     WHEN 2 THEN 'two' ELSE 'more' END;
        -> 'one'
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
        -> 'true'
mysql> SELECT CASE BINARY 'B'
    ->     WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
        -> NULL

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

2014年6月3日火曜日

SpringでJSONを返す場合に、特定のフィールドを表示させ無いようにするにはObjectMapperのaddMixInAnnotationsを使う。

SpringでJSONを返す場合に、特定のフィールドを表示させ無いようにするには、JacksonのObjectMapperで、addMixInAnnotationsに表示させたく無いフィールドを設定した抽象クラス、もしくはインターフェイスを大元のJSONオブジェクトにマップしたクラスに教えてやる。

Snippet

@Controller
public class SubjectController

{
    private ObjectMapper _objectMapper = new ObjectMapper();

    public Controller()
    {
    _objectMapper.getSerializationConfig().addMixInAnnotations(Base.class, FieldsNotAvailable.class);

    }

    @RequestMapping(value="/path", method={RequestMethod.GET})
    public @ResponseBody String getJson(ModelMap model)
    {
        return _objectMapper.writeValueAsString(subject);
    }
}

public abstract class FiledsNotAvailable
{
    @JsonIgnore
    public abstract String getSomeField();
}

http://stackoverflow.com/questions/22609079/how-to-filter-the-json-response-returning-from-spring-rest-web-service
http://fasterxml.github.io/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/ObjectMapper.html#addMixInAnnotations(java.lang.Class, java.lang.Class)

2014年4月11日金曜日

Ubuntuでheartbleedで問題となっているOpenSSLのパッケージを確認する方法

OpenSSLのバージョンを確認するには

% openssl version -a 

OpenSSL 1.0.1e 11 Feb 2013
built on: Mon Apr  7 20:33:19 UTC 2014 ---------->ここの日付を確認する。4月7日以降であれば最新らしい。
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx) 
compiler: cc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DOPENSSL_NO_TLS1_2_CLIENT -DOPENSSL_MAX_TLS1_2_CIPHER_LENGTH=50 -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

http://askubuntu.com/questions/444848/why-unattended-upgrades-does-not-fix-heartbleed-bug


10.04 LTSは古いOpenSSLなので更新しなくても大丈夫なようです。
http://askubuntu.com/questions/445164/update-openssl-to-1-x-on-10-04-lts-to-avoid-heartbleed-vulnerability

Ubuntuのアップデートは、

% sudo apt-get upgrade
% sudo apt-get update

それでもアップデートされない場合は、
% sudo dist-upgrade ---->これは現在使ってるパッケージが削除される場合があるので注意。

https://blog.pay4bugs.com/2014/04/08/howto-update-ubuntu-to-fix-heartbleed-ssl-bug/
http://askubuntu.com/questions/215267/will-apt-get-dist-upgrade-upgrade-my-system-to-newer-version
https://wiki.ubuntu.com/Security/Upgrades

Ubuntuでapt-get updateでパッケージがFetchできないエラーが出る場合の対処

apt-get updateをして"Failed to fetch http://....."でなる場合があります。アップデートをしようとするマシンがいけてないDNSサーバーを使ってる可能性があるので、それを変更すれば解決されます。

Googleのネームサーバーを使うと確実。
8.8.8.8
8.8.4.4

http://askubuntu.com/questions/135932/apt-get-update-failure-to-fetch-cant-connect-to-any-sources
http://www.cyberciti.biz/faq/ubuntu-linux-configure-dns-nameserver-ip-address/

resolv.confの内容が勝手に書き換わるのを防ぐには

/etc/resolvconf/resolv.conf.d/baseに/etc/resolv.confの内容を書く。

% sudo resolvconf -u

http://askubuntu.com/questions/157154/how-do-i-include-lines-in-resolv-conf-that-wont-get-lost-on-reboot

NFSをすぐマウントしたい場合

/etc/fstabの内容をすぐマウントしたい場合。

% sudo mount -a

http://takuya-1st.hatenablog.jp/entry/20101201/1291187213

2014年2月7日金曜日

linuxのrenameコマンドがファイル名の置換に便利

フォルダにあるファイル名を一括して置換したい場合などに、コマンドラインで便利に置換できるのがrenameコマンド。スクリプトを書かなくてもできず、単純なのでとても楽です。

rename 's/ABC/XYZ/' *.dat

http://stackoverflow.com/questions/1392768/rename-part-of-filename

2014年1月29日水曜日

Mavenでテストのフェーズを無視して実行するには

Mavenでテストのフェーズは完了してるので、ここをスキップしてパッケージしたwarファイルをサーバーにインストールしたい場合などには、便利なオプションがあったのでメモしておきます。

% mvn install -Dmaven.skip.test=true
% mvn package -Dmaven.skip.test=true

結構単純なフラグを指定してやるだけで、テストフォーズをとばしてくれます。便利。

http://www.mkyong.com/maven/how-to-skip-maven-unit-test/