2013/09/18

memcached command

★telnetしてmemcachedに接続する
localhost:11211:telnet


★command
・物を取る(stats items=>stats cachedump ? 1000=>get ?)
stats
・stats items=>slab(データを保存する領域)の番号を取得する
    ーーーー
    STAT items:1:number 2
    STAT items:1:age 1
    ーーーー
    items[?]はslabの番号である。
   
・stats cachedump 1 1000
    ITEM SESSION_ID_1 [32 b; 1378719089 s]=>500日?
    ITEM bak:D36A7CC0E3529F7F25741EC34F4EF950-n2 [368 b 1378719089 s]
   
・get SESSION_ID_1

・set key1 0 3600 6   =>set <key> <flags> <exptime>秒数!! <bytes>
    value1
    STORED

・memcachedを -vv オプション付きで起動した際や,統計出力を行うstatsコマンドなので参照することができる
 memcached -p TCPのポートを指定する

2013/09/17

linux 特定文字列含むプロセスをkillする

kill $(ps -ef | grep "tail" | grep -v "grep" | awk '{print $2}' | tr '\n' ' ')

・grep 複数条件 

・grep -v not条件
・awk 特定列
・tr 縦を横に変更
・kill 複数プロセス



リモートの場合、特定文字の前に\付ける
kill \$(ps -ef | grep "tail" | grep "?" | awk '{print \$2}' | tr '\n' ' ')


2013/09/16

ant copy exclude folder ,if not exists

<copy todir="${remployDeploy}">
            <fileset dir="${deploy}">
                <include name="**" />
                <exclude name="logs/**" />
                <exclude name="db/**" />
            </fileset>
        </copy>


<condition property="hasToCreateDb">
            <not>
                <available file="${remployDeploy}/db" type="dir" />
            </not>
        </condition>

        <antcall target="copyDbDir" />    
==>

<target name="copyDbDir" unless="${hasToCreateDb}">
        <copy todir="${remployDeploy}/db">
            <fileset dir="db" />
        </copy>
   </target>



derby jdbc 相対パス


jdbc:derby:C:/temp/javadb/sample1;create=true

コネクションURLの先頭は「jdbc:derby:」(プロトコルとサブプロトコル)で固定。
その後にDBの場所(パス)を書く。上記の例では「C:\temp\javadb\sample1」。
もし「sample1」の様に書くと、相対パスとして認識される。つまり実行時のカレントディレクトリー直下のsample1を指定したことになる。

2013/09/15

2013/09/13

java reflect (from tomcat)


        Class<?> startupClass =
            catalinaLoader.loadClass
            ("org.apache.catalina.startup.Catalina");
        Object startupInstance = startupClass.newInstance();

        // Set the shared extensions class loader
        if (log.isDebugEnabled())
            log.debug("Setting startup class properties");
        String methodName = "setParentClassLoader";
        Class<?> paramTypes[] = new Class[1];
        paramTypes[0] = Class.forName("java.lang.ClassLoader");
        Object paramValues[] = new Object[1];
        paramValues[0] = sharedLoader;
        Method method =
            startupInstance.getClass().getMethod(methodName, paramTypes);
        method.invoke(startupInstance, paramValues);
       
       ★paramTypes[0] = Boolean.TYPE;

org.apache.catalina.Lifecycle

 *            start()
 *  -----------------------------
 *  |                           |
 *  | init()                    |
 * NEW ->-- INITIALIZING        |
 * | |           |              |     ------------------<-----------------------
 * | |           |auto          |     |                                        |
 * | |          \|/    start() \|/   \|/     auto          auto         stop() |
 * | |      INITIALIZED -->-- STARTING_PREP -->- STARTING -->- STARTED -->---  |
 * | |         |                                                  |         |  |
 * | |         |                                                  |         |  |
 * | |         |                                                  |         |  |
 * | |destroy()|                                                  |         |  |
 * | -->-----<--       auto                    auto               |         |  |
 * |     |       ---------<----- MUST_STOP ---------------------<--         |  |
 * |     |       |                                                          |  |
 * |    \|/      ---------------------------<--------------------------------  ^
 * |     |       |                                                             |
 * |     |      \|/            auto                 auto              start()  |
 * |     |  STOPPING_PREP ------>----- STOPPING ------>----- STOPPED ---->------
 * |     |                                ^                  |  |  ^
 * |     |               stop()           |                  |  |  |
 * |     |       --------------------------                  |  |  |
 * |     |       |                                  auto     |  |  |
 * |     |       |                  MUST_DESTROY------<-------  |  |
 * |     |       |                    |                         |  |
 * |     |       |                    |auto                     |  |
 * |     |       |    destroy()      \|/              destroy() |  |
 * |     |    FAILED ---->------ DESTROYING ---<-----------------  |
 * |     |                        ^     |                          |
 * |     |     destroy()          |     |auto                      |
 * |     -------->-----------------    \|/                         |
 * |                                 DESTROYED                     |
 * |                                                               |
 * |                            stop()                             |
 * --->------------------------------>------------------------------

java transient

フィールドの定義にtransientを付けると、Serializableをimplementsしたクラスであっても
そのフィールドはシリアライズの対象外になる。
受け渡しには使わないが一時的に使うフィールド等に利用する。

    public transient final String TEST = "abc";

また、staticなフィールドもシリアライズの対象外となる。

なぜなら、staticなフィールドの値は 該当クラスが存在しているJavaVM内で共通な為。
つまり復元する時に、staticフィールドは復元先VMのクラスの値がそのまま使われる

2013/09/12

tomcat apache loadblancer worker

エラーが出った。。
The attribute 'worker.loadbalancer.balanced_workers' is deprecated - please check the documentation for the correct replacement.
=>loadbalancerはworkerであり、更に代表なworkerである



mod-jk.conf:
--------
#URLマッピング
JkMount /* loadbalancer
----------



workers.properties
--------
worker.list=tomcat1,tomcat2,loadbalancer

#tomcat1ワーカー
worker.tomcat1.port=18009
worker.tomcat1.host=localhost
worker.tomcat1.type=ajp13
worker.tomcat1.lbfactor=1

#tomcat2ワーカー
worker.tomcat2.port=28009
worker.tomcat2.host=localhost
worker.tomcat2.type=ajp13
worker.tomcat2.lbfactor=1

# Load-balancingワーカー
worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcat1,tomcat2
worker.loadbalancer.sticky_session=1


!!!
worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node1,node2
worker.loadbalancer.sticky_session=True
#worker.loadbalancer.sticky_session_force=True

We’re defining a worker named loadbalancer with it’s type set to lb (obviously short for loadbalancer) and assign node1 and node2 to handle the load.

Sticky sessions are an important feature if you rely on jSessionIDs and are not using any session-replication layer. If sticky_session is True a request always gets routed back to the node which assigned this jSessionID. If that host should get disconnected, crash or become unreachable otherwise the request will be forwarded to another host in our cluster (although not too successfully as the session-id is invalid in it’s context).
You can prevent this from happening by setting sticky_session_force to True. In this case if the host handling the requested session-id fails, Apache will generate an internal server error 500.

Now we’ve told mod_jk about our setup. If you are using sticky sessions, you’ll need to tell Tomcat to append its node-id to the session id. This needs to be the same as worker.name.jvm_route, which by default is the worker’s name (in our case node1 and node2).



tomcatのserver.xml:
 <!-- You should set jvmRoute to support load-balancing via AJP ie :-->
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">

memcached command

★telnetしてmemcachedに接続する
localhost:11211:telnet



★command
・物を取る(stats items=>stats cachedump ? 1000=>get ?)
stats
・stats items=>slab(データを保存する領域)の番号を取得する
    ーーーー
    STAT items:1:number 2
    STAT items:1:age 1
    ーーーー
    items[?]はslabの番号である。
   
・stats cachedump 1 1000
    ITEM SESSION_ID_1 [32 b; 1378719089 s]=>500日?
    ITEM bak:D36A7CC0E3529F7F25741EC34F4EF950-n2 [368 b 1378719089 s]
   
・get SESSION_ID_1

・set key1 0 3600 6   =>set <key> <flags> <exptime>秒数!! <bytes>
    value1
    STORED

・memcachedを -vv オプション付きで起動した際や,統計出力を行うstatsコマンドなので参照することができる
 memcached -p TCPのポートを指定する

c3p0 parameters

acquireIncrement-->一回同時に新たに取得するコレクション数
acquireRetryAttempts-->新コレクションを取得するのに失敗したときのリトライ回数
acquireRetryDelay-->リトライ間隔時間



autoCommitOnClose-->名前通り
automaticTestTable



breakAfterAcquireFailureーー>一回失敗したら、閉鎖して試しない。
checkoutTimeoutーー>プールが使い尽くされている場合のコレクションの最大待つ時間。タイムアウト時SQLExceptionが投げる
idleConnectionTestPeriodー>接続プール内のアイドル状態のコレクションを時間間隔「0以外の数字」でチェックする



initialPoolSize
maxPoolSize
minPoolSize

maxConnectionAge
numHelperThreads


★c3p0.idle_test_period、hibernate.c3p0.timeout、hibernate.c3p0.min_size
 
The database server may close a connection on its side after a certain amount of time - causing some error in your application, because it'll attempt to send a query on a connection which is no longer available on the server side.
In order to avoid this you can let the pool periodically check a connection (Think of a ping) for it's validity. This is what idle_test_period is for.
timeout is the timespan after which the pool will remove a connection from the pool, because the connection wasn't checked out (used) for a while and the pool contains more connections than c3pO.min_size.
 

ant jar

<jar basedir="${bin}" jarfile="${deploy}/HelpYou.jar">
            <manifest>
                <attribute name="Main-Class" value="com.syuu.automic.MainWindow" />
            </manifest>
  </jar>
jarファイルをまとめて、一つにする
<zipgroupfileset dir="libs" includes="**/*.jar" />

2013/09/11

ant javac classpathなど

    <path id="classpath">
        <fileset dir="libs">
            <include name="*.jar" />
        </fileset>
    </path>
<javac srcdir="${src}" destdir="${bin}" encoding="UTF-8" >
            <classpath refid="classpath" />
 </javac>


※    [javac] 注意:入力ファイルの操作のうち、未チェックまたは安全ではないものがあります。
    [javac] 注意:詳細は、-Xlint:uncheckedオプションを指定して再コンパイルしてください。

<javac debug="on" destdir="${classes}" srcdir="${src}">
<compilerarg value="-Xlint:unchecked" />
</javac>

ant delete

The * wildcard should only delete the files at the top level
------------- 
<delete>
   <fileset dir="${dist.dir}">
      <include name="*"/>
   </fileset>
</delete>
 -------------
the subdirectories will be deleted,you'd need to use **/* instead. 


<delete includeEmptyDirs="true">
  <fileset dir="dir_name" includes="**/*" defaultexcludes="no"/>
</delete>

2013/09/09

Tomcat timeout config

Apache-Tomcat間コネクションのタイムアウト値が設定されておらず、
デフォルトのままだったために、コネクションを無制限に維持する
最新のは60秒、ゴロゴロ変わるね。。。

Tomcatのserver.xmlのconnectionTimeoutを明示的に設定し、
connectionTimeoutはミリ秒単位なので、以下の例だと5分
<Connector port=”8083″maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
    enableLookups=”false” redirectPort=”443″ acceptCount=”100″
    debug=”0″ connectionTimeout=”30000″
    disableUploadTimeout=”true” />


The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. Use a value of -1 to indicate no (i.e. infinite) timeout. The default value is 60000 (i.e. 60 seconds) but note that the standard server.xml that ships with Tomcat sets this to 20000 (i.e. 20 seconds).



Connection timeout and session timeout are two totally different things.

Connection timeouts have to do with how long the server will leave a connection between the browser and server open after a response is complete.

Session-timeout is what controls the length of time that an idle session will last.

As to the session-timeout setting in conf/web.xml; I can't say for sure, but I'm guessing that 30 minutes is the default whether that entry is there or not and that the entry is there to make it easier for folks who want to change it to find it.
Out of curiosity, why do you care if there is a default value? 

mysql slave skip

stop slave
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1
start slave

2013/09/06

bash for

for VARIABLE in 1 2 3 4 5 .. N
do
    command1
    command2
    commandN
done



#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done




#!/bin/bash
for i in $(seq begin step end)
do
   echo "Welcome $i times"
done

seqはfor i in 'seq 1 10' のように書いて、from〜toの値を順に+1して返す。'seq 1 2 10'と書くと1〜10で増分+2を表す。

mysql Replication and User Privileges

User privileges are replicated only if the mysql database is replicated. That is, the GRANT, REVOKE, SET PASSWORD, CREATE USER, and DROP USER statements take effect on the slave only if the replication setup includes the mysql database.

If you are replicating all databases, but do not want statements that affect user privileges to be replicated, set up the slave not to replicate the mysql database, using the --replicate-wild-ignore-table=mysql.% option. The slave recognizes that privilege-related SQL statements have no effect, and thus it does not execute those statements.

2013/09/04

Error on uploading file in java to ftp server recv failed

because of the fillwall.....
=>client.enterLocalPassiveMode()
 
直らない。。。。Windowでjava7のバグみたいで、
cmdで下記を実行する 
netsh advfirewall set global StatefulFTP disable
 
治った。。。
ハマった。。。時間無駄にされた。。。。 

ftp protocal windows java common-net

意外に知らなかった。。。。。。。。


★サーバへの接続時のコマンド用とは別にデータ転送用のコネクションを確立するが、この確立方法にアクティブモード、パッシブモードという2種類の方式がある。

・アクティブモード(ポートモードとも言う)では、クライアントがサーバへ待ち受けIPアドレスとポート番号を通知し、サーバがクライアントから通知されたIPアドレスのポート番号へコネクションを確立しに行く。このとき利用するポート番号が毎回異なるので、ファイアーウォール、NAT(IPマスカレード)などを使った環境では場合によってはうまく接続できないこともある。この場合はパッシブモードを用いる。

・パッシブモードではサーバがクライアントへ待ち受けポート番号を通知し、待ち受けポート番号の通知を受けたクライアントがサーバへコネクションを確立しに行く。

いずれのモードでも、コマンド用とデータ用で別々のコネクションを張ることには変わりはない。 サーバ側にファイアーウォールがある場合、データコネクションのためにどのポート番号を使うかを設定してファイアーウォールとの整合を確認する必要がある。 パッシブモードを使っている限りにおいては、クライアント側のファイアーウォールは気にする必要がない。
=>ftpClient.enterLocalPassiveMode();



★windowsのFTPを作成(windowの機能)
window にFTP用ユーザの作成
ftp localhost
?=>コマンドの一覧
ls=>ファイルの一覧
put<=>get、 del、rename、quitなど。。。。
・get <取得元ファイル名>  [<保存先ファイル名>]
第2引数を省略すると、ローカルのカレント・フォルダ(場所はlcdコマンドで変更できる)に、取得元と同じ名前のファイルが作成される。

java InetAddress class

Java ネットワーク API では、コンピュータを識別する IP を
java.net.InetAddress クラスにパッケージ化している

public final class InetAddress extends Object implements Serializable

このクラスは、コンストラクタを公開していない
これは、IP の初期化には様々な手続きが必要だからと考えられる
そのため、InetAddress クラスのインスタンスを作成するためには
静的メソッド InetAddress.getByName() メソッドを使う

指定したアドレスが発見できなかった場合は UnkownHostException が発生する
また、セキュリティによっては SecurityException が発生する可能性もある

=>取得した後、
public String getHostAddress()
public String getHostName()


・複数のIPを持つホスト
public static InetAddress[] getAllByName(String host)
                throws UnknownHostException
・ローカルホスト
public static InetAddress getLocalHost()
            throws UnknownHostException

・InetAddress クラスは、成功したホスト名解決と失敗したホスト名解決を格納するためのキャッシュを備えている

2013/09/03

linux tomcat user password

デフォルト的なpasswordはない
ユーザーはロックされてた。。
passwd -hで確認

sudo su tomcatでユーザを変更できる。。

jvm memory system jconsole

★jvm memory model
・eden領域 (ヒープ)-> エデンの園 人類の始祖 Adam と Eveのが住んでいる楽園、ほとんどのオブジェクトにメモリーが最初に割り当てられるプール

・Survivor領域 (ヒープ)->生き残った人。Eden 領域のガベージコレクションで残ったオブジェクトを含むプール。

・Tenured世代 (ヒープ)->終身在職権のある(いわゆる正社員)。Survivor 領域である程度の期間存続したオブジェクトを含むプール

Permanent 世代 (非ヒープ)->永久的な。クラスやメソッドオブジェクトなど、仮想マシン自体を反映したデータをすべて保持するプール。Java VM でクラスデータ共有を使用する場合、この世代は読み取り専用領域と読み取り/書き込み領域に分割される

コードキャッシュ (非ヒープ):HotSpot Java VM には、ネイティブコードのコンパイルと保存に使用するメモリーを含むコードキャッシュも含まれる



★ヒープおよび非ヒープのメモリー
Java VM が管理するメモリーには、ヒープメモリーと非ヒープメモリーの 2 種類があり、いずれも VM の起動時に作成される
ヒープメモリーは実行データ領域で、Java VM はそこからすべてのクラスのインスタンスと配列にメモリーを割り当てる。ヒープのサイズは可変の場合と固定の場合がある。ガベージコレクタは、ヒープメモリーをオブジェクトに再利用する自動メモリー管理システムである
非ヒープメモリーには、Java VM の内部処理や最適化に必要なメモリーと、すべてのスレッドで共有されるメソッド領域が含まれる。非ヒープメモリーには、実行定数プール、フィールドおよびメソッドデータ、メソッドおよびコンストラクタのコードなど、クラス単位の構造体が格納される。メソッド領域は論理的にはヒープの一部が、実装方法によっては、Java VM がこの領域のガベージコレクトや圧縮を行わない場合もある。ヒープと同様に、メソッド領域のサイズは固定の場合と可変の場合がある。メソッド領域のメモリーは連続している必要はない。
=>動的物をビーフに、静的な物を非ビーフに。。。



★メモリープール メモリーマネージャー
メモリープールとは、Java VM が管理するメモリー領域である。Java VM には少なくとも 1 つのメモリープールがあり、実行中にメモリープールを作成または削除できる。メモリープールは、ヒープメモリーと非ヒープメモリーのどちらかに属する。

・メモリーマネージャーは、1つまたは複数のメモリープールを管理する。ガベージコレクタは、メモリーマネージャーの一種で、アクセスできなくなったオブジェクトが使用していたメモリーの再利用を管理する。Java VM が装備するメモリーマネージャーは 1 つの場合も複数の場合もある。実行中にメモリーマネージャーを追加または削除できる。メモリープールは、複数のメモリーマネージャーによって管理できる。
=>ガベージコレクタは、メモリーマネージャーの一種



★ガベージコレクション
ガベージコレクション (GC) は、参照されていないオブジェクトが使用していたメモリーを解放する。アクティブな参照をもつオブジェクトを「生きている」と考え、参照されていない (アクセスできない) オブジェクトを「死んでいる」と考えるのが一般的である。GC によって使用されるアルゴリズムとパラメータがパフォーマンスに劇的な効果をもたらす可能性がある

Java HotSpot VM ガベージコレクタは、世代別 GC を使用する。世代別 GC は、ほとんどのプログラムには次のような傾向があるという所見に基づいている
    !!!生成する多くのオブジェクトは短命である (反復子やローカルの変数など)。
    !!!生成する一部のオブジェクトは非常に長い寿命をもつ (高度な持続性オブジェクトなど)。
そのため、世代別の GC は、メモリーをいくつかの世代に分け、それぞれにメモリープールを割り当てる。ある世代が割り当てられたメモリーを使用すると、VM はメモリープール上で部分的な GC (マイナーコレクションともいう) を実行し、死んだオブジェクトによって使用されたメモリーを再利用する。この部分的な GC は、通常、フル GC よりもはるかに高速である
=====>あ、ああ。。。JVMも格差社会だ。。。

Java HotSpot VM は、若い世代 (「nursery」ともいう) と古い世代という 2 つの世代を定義している。若い世代は、1 つの「Eden 領域」と 2 つの「Survivor 領域」で構成される。VM は最初にすべてのオブジェクトを Eden 領域に割り当て、ほとんどのオブジェクトはそこで死にする。マイナー GC を実行するとき、VM は残りのオブジェクトを Eden 領域から Survivor 領域の 1 つに移す。VM は、Survivor 領域で十分に長く生きるオブジェクトを古い世代の「Tenured」領域に移す。Tenured 世代がいっぱいになると、フル GC が実行される。これは生きているオブジェクトをすべて含むため、通常は マイナー GC よりも時間がかかる。Permanent 世代は、クラスやメソッドオブジェクトなどの仮想マシン自体を反映したデータをすべて保持する
====>要は、非正規雇用の若い世代(楽園と生存者)のリストラはやりやすく、正社員(Tenured)は時間かかるね。。。

-Xms初期ヒープサイズ(全体)
-Xmx最大ヒープサイズ(全体)
-Xmn (-XX:NewSize)young generation領域サイズ
-XX:NewRatioyoung generation領域とtenured generation 領域の比率
-XX:SurvivorRatioeden領域とsurvivor領域の比率
-XX:TargetSurvivorRatioyoung generation が full になるまでに survivor space で利用可能なスペースの比率
-XX:MinHeapFreeRatioGC 後に拡張されるまでに消費されるヒープの比率
-XX:MaxHeapFreeRatioGC 後にシュリンクされるまでに消費されるヒープの比率


★jconsole memory display
・USED「使用済み」: 現在使用中のメモリー容量。
・COMMITTED「確保済み」:Java VM で利用できることが保証されたメモリー容量、確定メモリーの容量は必ず使用中のメモリー容量以上である
・MAX「最大」:メモリー管理に使用できる最大メモリー容量。ava VM で使用メモリー容量を確定メモリー容量より大きくしようとすると、使用量が最大メモリ容量以下の場合 (たとえば、システムの仮想メモリーが少ない場合)でも、メモリー割り当てに失敗することがある==>いわゆる、保証がない。。
・GC time「GC 時間」: ガベージコレクションに要した累積時間とその呼び出しの総数。複数行に及ぶ場合もあります。各行は Java VM で使用するガベージコレクタの 1 つのアルゴリズムを示す
==>VM で使用するガベージコレクタのアルゴリズム


★そもそも、GC プロセスは、メモリ(セントラル・ストレージ)上の物理アドレスに依存する処理を実行するスレッドで、実行時には
アプリケーションの処理を停止させるものです
=>incremental、すこしずつの意味

★ヒープサイズが大きいと、GC の起動回数は減りますが、一回の GC に必要な時間が長くなり、その過程の、アプリケーション停止時間 (stop-the-world) も長くなって、レスポンスタイムに問題が発生する可能性があります。

2013/09/02

javafx combobox color

  ComboBox emailComboBox = new ComboBox();
    emailComboBox.getItems().addAll("A","B","C","D","E");
    emailComboBox.setCellFactory(
        new Callback<ListView<String>, ListCell<String>>() {
            @Override public ListCell<String> call(ListView<String> param) {
                final ListCell<String> cell = new ListCell<String>() {
                    {
                        super.setPrefWidth(100);
                    }    
                    @Override public void updateItem(String item, 
                        boolean empty) {
                            super.updateItem(item, empty);
                            if (item != null) {
                                setText(item);    
                                if (item.contains("A")) {                                    
                                    setTextFill(Color.RED);
                                }
                                else if (item.contains("B")){
                                    setTextFill(Color.GREEN);
                                }
                                else {
                                    setTextFill(Color.BLACK);
                                }
                            }
                            else {
                                setText(null);
                            }
                        }
            };
            return cell;
        }
                    
    });

jave read file to String

apache common io を使って、便利。。
 
 
 File file = new File("/commons/io/project.properties");
 List lines = FileUtils.readLines(file, "UTF-8");
 
String content= FileUtils.readFileToString(file)