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();
 }
}