2016年5月24日火曜日

heroku postgresql

herokuでDB追加(無料)する方法

heroku login状態で行う

<追加>
heroku addons:add heroku-postgresql:hobby-dev

heroku pg:info --app XXX

psqlで接続
heroku pg:psql DATABASE_URL --app XXX

ログ確認
heroku logs --app XXX -t


いつの間にか--appでアプリ指定が必要になっているかも?

2016年5月19日木曜日

Windows10時刻同期(ntp)

これを行うとよい
Slewモードで設定をする

1.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient
SpecialPollInterval

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\Config
UpdateInterval


30分なら10進数で1800に変更する。

2.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time\Config
MaxAllowedPhaseOffset

10進数で300
Slewのパラメータに影響

3.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time\Parameters
NtpServer

ntp.nict.jp,0x8
NTPで同期できるっぽい

ntp.nict.jp,0x9
でもよいかもしれない NTP+Winオリジナルのmix?

4.
Windows Time サービスのスタートアップの種類を [手動] から [自動 (遅延開始)] に変更


確認方法
w32tm /query /status

2016年5月5日木曜日

javaで画像操作

主に備忘 画像を新規で作る 線を引くだけ ピクセルを配列変換もする
 public static void main(String[] args) throws IOException {
  BufferedImage img = new BufferedImage(200, 200,
    BufferedImage.TYPE_INT_BGR);
  int w = img.getWidth(null); // Imageの幅
  int h = img.getHeight(null);
  Graphics g = img.getGraphics();
  g.setColor(Color.WHITE); // 白
  g.fillRect(0, 0, w, h);

  g.setColor(Color.BLACK); // 黒
  g.drawLine(10, 10, 100, 100);
  g.dispose();

  ImageIO.write(img, "png", new File("test.png"));

  int[] px = img.getRGB(0, 0, w, h, null, 0, w);

 }

2016年4月19日火曜日

powershellでファイル名変更

powershell を使ったファイル名の変更 正規表現を使って「1.1.あいうえお.txt」というファイル名があった場合には、「1.01.あいうえお.txt」に変更する
@powershell -NoProfile -ExecutionPolicy Unrestricted "$s=[scriptblock]::create((gc \"%~f0\"|?{$_.readcount -gt 1})-join\"`n\");&$s" %*&goto:eof

$ary=ls|%{$_.name}
foreach($i in $ary){
  if($i -match "^[0-9]\.[0-9]\."){
    Get-ChildItem $i | Rename-Item -NewName { $_.Name -replace '^([0-9])\.([0-9])\.','$1.0$2.' }
  }
}

2015年6月20日土曜日

Javaでクライアント認証の読込み 


Javaでクライアント認証を読込み PKCS#12

証明書は以下を見て作るとよい
http://server-setting.info/centos/apache-ssl-auth-setting.html

下記は、だいたいこんな感じぐらいで
環境を忘れて確認できなくなったので間違っているかも。。。。。

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;


public class App
{

    static final String P12FILE = "cert.p12";
    static final char[] PASSWORD = "pass".toCharArray();

    private static SSLContext getSslContext() {
        // PKCS12ファイル読み込み
        KeyManagerFactory keyManagerFactory;
        try (FileInputStream inputStream = new FileInputStream(P12FILE)) {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(inputStream, PASSWORD);

            keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            keyManagerFactory.init(keyStore, PASSWORD);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
            return sslContext;

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

    public static void main(String[] args) throws Exception {
        int socketTimeout = 60000;
        int connectionTimeout = 60000;
        String userAgent = "My Http Client 0.1";
        // request configuration
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        // headers
        List<Header> headers = new ArrayList<Header>();
        headers.add(new BasicHeader("Accept-Charset", "utf-8"));
        headers.add(new BasicHeader("Accept-Language", "ja, en;q=0.8"));
        headers.add(new BasicHeader("User-Agent", userAgent));
        // create client
        HttpClient httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setDefaultHeaders(headers).setSSLContext(getSslContext())
                .build();

        HttpGet httpGet = new HttpGet("https://mixi.jp/");
        HttpResponse response = httpClient.execute(httpGet);
        int responseStatus = response.getStatusLine().getStatusCode();
        String body = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(body);
    }
}

2015年1月20日火曜日

某ソース


import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;

public class Test {

 static Map, Map> relationMap = new HashMap, Map>();
 static Map, Serializable>> seachResult = new HashMap, Serializable>>();
 static Map> endEntity = new HashMap>();

 static {
  List list = new ArrayList();
  Map map2 = new HashMap();
  relationMap.put(list, map2);
  list.add("led");
  list.add("m");
  list.add("r");
  map2.put("m", "m");
  map2.put("c", "c");
 }

 public static void main(String[] args) {
  try {

   List searchList = new ArrayList();
   for (Serializable serializable : searchList) {
    loadRoleEntity(serializable);
   }
  } catch (Exception e1) {
   e1.printStackTrace();
  }
 }

 private static void loadRoleEntity(Serializable serializable)
   throws Exception {
  Set idSet = endEntity.get(serializable.getClass().getCanonicalName());
  if (idSet == null) {
   idSet = new HashSet();
   endEntity.put(serializable.getClass().getCanonicalName(), idSet);
  }
  if (idSet.contains(serializable.getId())) {
   return;
  }
  Set targets = getNextTarget(serializable.getClass().getCanonicalName());
  if (targets.isEmpty()) {
   return;
  }
  for (String target : targets) {
   List> relation = getParentMap(serializable.getClass().getCanonicalName(), target);
   List> foreginKeyValuMapList = new ArrayList>();
   for (Set set : relation) {
    Map hashMap = new HashMap();
    for (String key : set) {
     Object property = PropertyUtils.getProperty(serializable, key);
     hashMap.put(key, (Serializable) property);
    }
    foreginKeyValuMapList.add(hashMap);
   }

   List searched = searchTarget(target, foreginKeyValuMapList);
   Map> keysMap = getChildMap(serializable.getClass().getCanonicalName(),
     target);
   if (searched != null) {
    Map, Serializable> hashMap2 = new HashMap, Serializable>();
    seachResult.put(target, hashMap2);

    Map hashMap = new HashMap();
    for (Serializable serializable2 : searched) {
     for (Entry> e : keysMap.entrySet()) {
      Map keys = e.getValue();
      for (Entry e2 : keys.entrySet()) {
       Object property = PropertyUtils.getProperty(serializable2, e2.getValue());
       hashMap.put(e2.getKey(), (Serializable) property);
      }
      hashMap2.put(hashMap, serializable2);
     }
    }
   }

   Set keySet = keysMap.keySet();
   for (String key : keySet) {
    List keyList = new ArrayList();
    keyList.add(serializable.getClass().getCanonicalName());
    keyList.add(key);
    keyList.add(target);
    Map map2 = relationMap.get(keyList);
    Map, Serializable> searchResultMap = seachResult.get(target);
    Serializable serializable2 = searchResultMap != null ? searchResultMap.get(map2) : null;
    Field declaredField = serializable.getClass().getDeclaredField(key);
    declaredField.setAccessible(true);
    if (Set.class.equals(declaredField)) {
     Set set = (Set) PropertyUtils.getProperty(serializable, key);
     if (set == null) {
      set = new HashSet();
      PropertyUtils.setProperty(serializable, key, set);
     }
     if (serializable2 != null) {
      set.add(serializable2);
     }
    }
    else {
     PropertyUtils.setProperty(serializable, key, serializable2);
    }
   }

   for (Serializable serializable2 : searched) {
    loadRoleEntity(serializable2);
   }

  }
 }

 private static Map> getChildMap(String canonicalName, String target) {
  Map> result = new HashMap>();
  for (Entry, Map> e : relationMap.entrySet()) {
   List list = e.getKey();
   if (list.get(0).equals(canonicalName) &&
     list.get(2).equals(canonicalName)) {
    Map set = result.get(list.get(1));
    if (set == null) {
     set = new HashMap();
     result.put(list.get(1), e.getValue());
    }
   }
  }

  return result;
 }

 private static List searchTarget(String target, List> foreginKeyValuMapList) {
  return null;

 }

 private static Set getNextTarget(String canonicalName) {
  Set result = new HashSet();
  Set> keySet = relationMap.keySet();
  for (List list : keySet) {
   if (list.get(0).equals(canonicalName)) {
    result.add(list.get(2));
   }
  }
  return result;
 }

 private static List> getParentMap(String canonicalName, String target) {
  List> result = new ArrayList>();
  for (Entry, Map> e : relationMap.entrySet()) {
   List list = e.getKey();
   if (list.get(0).equals(canonicalName) &&
     list.get(2).equals(canonicalName)) {
    Set keySet = e.getValue().keySet();
    result.add(keySet);
   }
  }

  return result;
 }
}

2014年11月12日水曜日

VMwareにてandroidインストール時の解像度

Vmwareにてandroidをインストールして解像度を変更したいとき

デバッグモードにて起動
# mount -o remount,rw /mnt
# vi /mnt/grub/menu.lst
引数の最後にvga=794とつけると1280×1024になる
vga=askとつけると一覧で確認したうえで選択できる模様

2014年11月4日火曜日

Tera Termマクロ コマンドリスト(cmd.txt)を読み込んで実行

Tera Termマクロ コマンドリスト(cmd.txt)を読み込んで実行
コマンド実行 一回ごとに実行していか確認
;=========================================================== 
;; 接続報ホスト/ユーザ名設定 
HOSTADDR = '192.168.109.129' 
USERNAME = 'root' 
;=========================================================== 
;; ①接続先ホストのパスワードを入力 
MASSAGE = 'HOST : ' 
strconcat MASSAGE HOSTADDR 
strconcat MASSAGE ' / USER NAME : ' 
strconcat MASSAGE USERNAME 
passwordbox MASSAGE 'Please input a password.' 
PASSWORD = inputstr
 
;; ②入力確認(パスワードが入力されていない場合マクロ終了) 
strcompare PASSWORD '' 
if result=0 then 
    messagebox 'A password is not input.' 'Input error' 
    end 
endif
 
;; ③コマンド組立て 
COMMAND = HOSTADDR 
strconcat COMMAND ':22 /ssh /2 /auth=password /user=' 
strconcat COMMAND USERNAME 
strconcat COMMAND ' /passwd=' 
strconcat COMMAND PASSWORD
 
;; ④接続 
connect COMMAND
 
;; ⑤接続判定1(接続出来ない場合はメッセージを表示しマクロ終了) 
if result <> 2 then 
    messagebox 'It could not be connected.' 'Connection Error' 
    end 
endif
 
;; ⑥接続判定2(10秒以内にプロンプトが表示されない場合TeraTerm終了) 
timeout = 10 
wait '$' '#' 
if result=0 then 
    end 
endif
 
;; ⑦コマンド実行
; ファイルオープン
fileopen fhandle 'cmd.txt' 0

:loop
; 一行読み込み
filereadln fhandle line
if result goto fclose

yesnobox line 'Tera Term'  
if result=0 then
 end
endif

sendln line 
wait '$' '#'

; ファイル最後まで繰り返す
goto loop

:fclose
; ファイルクローズ
fileclose fhandle



;; ⑧マクロ終了 
end

2014年11月3日月曜日

winscpをバッチから使う

winscpにscriptという機能を使うとバッチ処理ができそう http://sourceforge.jp/projects/winscp/wiki/scripting

ganymed-ssh2を使ってコマンド実行

ganymed-ssh2を使ってコマンド実行 一回ごとに実行していか確認

引数 host port username password コマンドファイル
コマンドファイル1行を1コマンドとして実行

POM
 
  ch.ethz.ganymed
  ganymed-ssh2
  262
 
Java
package jp.tuyoyun.metatrader.sshclient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class App
{
 private static Scanner scan;

 public static void main(String[] args) throws Exception
 {
  Connection con = new Connection(args[0], Integer.parseInt(args[1]));
  con.connect();
  con.authenticateWithPassword(args[2], args[3]);
  File file = new File(args[4]);
  InputStream stream = new FileInputStream(file);
  BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF8"));
  String line = reader.readLine();
  while (line != null) {
   System.out.println("\ncommand----------------------------------------------------\n");
   System.out.println(line);
   System.out.println("-----------------------------------------------------------\n");
   boolean confirm = confirm();
   if (!confirm) {
    scan.close();
    reader.close();
    stream.close();
    con.close();
    return;
   }
   exec(con, line);
   line = reader.readLine();
  }
  scan.close();
  reader.close();
  stream.close();
  con.close();
 }

 private static boolean confirm() {
  System.out.println("execute command? y/n");
  scan = new Scanner(System.in);
  String confirm = scan.next();
  if ("y".equals(confirm)) {
   return true;
  }
  else if ("n".equals(confirm)) {
   return false;
  } else {
   return confirm();
  }
 }

 private static void exec(Connection con, String cmd) throws IOException, InterruptedException {
  Session session = con.openSession();
  session.execCommand(cmd);
  InputStream inputStream = session.getStdout();
  readResult(inputStream);
  inputStream = session.getStderr();
  readResult(inputStream);
  session.close();
 }

 private static void readResult(InputStream inputStream) throws UnsupportedEncodingException, IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF8"));
  String line = reader.readLine();
  while (line != null) {
   System.out.println(line);
   line = reader.readLine();
  }
  reader.close();
  inputStream.close();
 }
}

2013年7月14日日曜日

sping cash

Sping cash
http://d.hatena.ne.jp/daisuke-m/touch/20111126/1322292063



2013年7月13日土曜日

java スタックなど

java 問題解析に

jstack でスレッドダンプを取る
http://aoking.hatenablog.jp/entry/20120629/1340965676


サーバから応答がない!そんな時はスレッドダンプです
http://advpro.co.jp/Devlop/?p=365


あなたの知らないJDKの便利ツールたち
http://www.atmarkit.co.jp/fjava/column/andoh/andoh43.html


JavaVMのメモリ領域について
http://d.hatena.ne.jp/tanakakns/20120508/1336467306

2013年7月1日月曜日

GAE/J で非同期HTTPリクエスト

GAEにて非同期でHTTPリクエストを行う
複数のサイトにアクセスするのに有効


Google App Engine 非同期URLFetch、FetchAsync()の使い方
http://www.synaesthesia.jp/googleAppEngine/URLFetchAsync.php


Using Asynchronous URLFetch on Java App Engine(英語)
http://ikaisays.com/2010/06/29/using-asynchronous-urlfetch-on-java-app-engine/


GAE/Jで複数のHTTPリクエストを非同期で効率よく処理する
http://d.hatena.ne.jp/thrakt/20100529/1275139919

2013年6月25日火曜日

InstallCertでJREに証明書インポート

InstallCertの使い方がわかったのでちょっと書いておく

InstallCert.java

http://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java

<使い方>

java InstallCert [ホスト]:[ポート]


実行すると%JAVA_HOME%/lib/security/jssecacerts を読み込む
なければcacertsを読み込み 

ホストに接続して、必要な証明書を追加したものを実行ディレクトリにjssecacertsというファイル名で
出力してくれる

なので、jssecacertsを%JAVA_HOME%/lib/security/cacertsというファイルと置き換えるとよい

これは色々使えるかも?

2013年6月23日日曜日

ORA-12519 オラクルエラー

oracle XE でエラー ORA-12519, TNS:no appropriate service handler found
おそらくセッション数が足りてないとかだろう トランザクションを何個も使うことしてたので。
 根本的にはトランザクション減らすほうがよいけど めんどくさいのでオラクルのパラメータ変更にて対応
 sqlplus sys/pass as sysdba
SQL> ALTER SYSTEM SET PROCESSES=150 SCOPE=SPFILE
SQL> shutdown immediate
SQL> startup
 2008年の情報なので違うかもしれないけど下記が書かれていた processは 「Oracleに同時に接続できるオペレーティングシステムのユーザプロセスの最大数」 (開発してるWebアプリとかcseとかObjectBlowserとか) sessionsは 「Oracle に同時に接続できるセッションの最大数」 (process + Oracleが内部的に使用する接続数) デフォルトの初期値は sessions = 1.1 × process + 5
 ついでによく忘れる画面の表示文字数 set linesize 200

spring mvcで文字化け

文字化け対策  web.xmlにfilter追加(最初に)
tomcatのserver.xmlにURIEncoding="UTF-8" こんな感じ
jspに追加

2013年6月22日土曜日

openldapの証明書をjavaにimport

openldap(windows)には
もともとopenldapにはsecure\certs\server.pem
という証明書がついていたのでそれをjavaでインポートする

pemはjavaでは扱えないようなのでopensslで変換する

1.
openssl pkcs8 -topk8 -nocrypt -in server.pem -inform PEM -out key.der -outform DER
openssl x509 -in server.pem -inform PEM -out cert.der -outform DER

参考
http://www.agentbob.info/agentbob/79-AB.html

 2.
上記サイトのImportKey.javaを実行
java ImportKey key.der cert.der
keystore.ImportKey が作成される


3.
証明書作成
keytool -export -alias importkey -keystore keystore.ImportKey -storepass importkey -file tomcat.cer
参考
http://apis.jpn.ph/fswiki/wiki.cgi?page=Java%2Fkeytool#p7
4.
証明書をインポート

keytool -import -storepass changeit -keystore  "%JAVA_HOME%/jre/lib/security/cacerts"  -alias localhost -file tomcat.cer


こんな感じだけどaliasとパスワードは違うかも
これでjavaでSSL通信が可能に

これ以外にも下記のやつを引数をサーバアドレスにして
を実行すると自動でcertをインポートしてくれるらしいけど たぶんそれだけでは足りない

http://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java



opensslにてCA証明書作成

CA.sh -newcaでうまくいかないので以下で対応

# mkdir -p demoCA/private
# mkdir -p demoCA/newcerts
# touch demoCA/index.txt
# touch demoCA/serial
# echo 00 > demoCA/serial
# openssl req -new -x509 -newkey rsa:2048 -out cacert.pem -keyout private/cakey.pem

openssl.confにてpolicy_matchをすべてoptionalにすればfiledが一致してなくても
うまくいく

参考
http://d.hatena.ne.jp/marmotte/20100203


サーバ証明書への署名
openssl ca -keyfile cakey.pem -cert cacert.pem -in server.csr -out server.crt


参考
http://www.ksgmt.com/article/java/javassl_clientcert.html

2013年5月25日土曜日

JQuery php ajax

JQuery php ajax

http://firespeed.org/diary.php?diary=kenz-1314

インストールはファイルを解凍するだけ
app/Config/core.phpの
'Security.salt'
'Security.cipherSeed'
をセキュリティのため変える