2017年8月29日 星期二

PKIX:unable to find valid certification path to requested target


/* 
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 *   - Redistributions of source code must retain the above copyright 
 *     notice, this list of conditions and the following disclaimer. 
 * 
 *   - Redistributions in binary form must reproduce the above copyright 
 *     notice, this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution. 
 * 
 *   - Neither the name of Sun Microsystems nor the names of its 
 *     contributors may be used to endorse or promote products derived 
 *     from this software without specific prior written permission. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert [:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}

2016年4月6日 星期三

ADBException: Any type element type has not been given

這陣子在做API改寫時,我用了Dynamic Proxy Pattern統一處理了Service層級的API Response與Exception Handler。
現在的團隊使用Apache Axis2建立WebService,雖然使用的是WSDL、SOAP,但回傳的格式不是XML,而是JSON String,所以Service層的回傳型態都是String。
代理將Service Return的東西做了Object to Json String與外層格式的統一處理,所以Proxy實際回傳的是JSON String,Servcie的Impl回傳的東西可能是各種形態。因為Proxy與Implement回傳的型態是不同的,所以Service Interface的回傳型態必須改為Object
問題來了,Axis2 Service不能回傳Object型別,因為Axis2 adb有bug,ADB handles anyType
在使用Axis2 Code Generator Tool做WSDL2Java產生stub後,會看到只要回傳型態為Object時,(WSDL XML Return type就會是type:anyType),產生出來的stub code就會在API回傳的時候,試著要在回傳的XML資料內找到type,並嘗試將回傳資料轉型(ConverterUtil.getAnyTypeObject(...)),但是記得嗎??最一開始我就提到了,回傳的格式不是XML,而是JSON String,所以根本不會有type,在找不到type屬性的情況下CnverterUtil索性就丟了一個ADBException(as my title)。
Workaround的解法有兩種:
解法一,override ConverterUtil getAnyTypeObject Method,替換掉丟出異常的那一行
returnObject = xmlStreamReader.getElementText();

Java Exception

http://villebez.logdown.com/posts/2016/04/01/java-exception
java exception hierarchy
Exception Hierarchy DiagramException Hierarchy Diagram
圖片來源:http://java5tutor.info/java/flowcontrol/exceptionover.html

checked exceptions and unchecked exceptions

Use checked exceptions for recoverable conditions and runtime (unchecked) exceptions for programming errors.

checked Exception

程式如果違反handle-or-declare rule,將被Java Compiler視為『語法錯誤』,程式無法編譯成功。
handle-or-declare rule
  • Handle the exception by using the try-catch-finally block.
  • Declare that the code causes an exception by using the throws clause.

unchecked Exception

不需要補抓的錯誤,例如:RuntimeException、NullPointerException...等等

JAVA異常處理中的原則和建議

原則:不要忽略checked Exception

忽略可能導致兩個結果:
由於這裡的異常導致在程序中別的地方拋出一個異常,這種情況會使工程師在除錯時感到迷惑,因為新的異常拋出的地方並不是程式真正發生問題的地方,也不是發生問題的真正原因。
程序繼續運行,並得出一個錯誤的輸出結果,這種問題更加難以捕捉,因為很可能把它當成一個正確的輸出。

建議:不要捕獲unchecked Exception

Error
RuntimeException
ex:NullPointException, IndexOutofBoundsException
例外情況:Daemon Thread (長時間運行的背景程式)

原則:不要直接 catch 最上層的 Exception

不同Exception需要不同的處裡與恢復機制
可能拋出RuntimeException

原則:使用finally釋放資源

檔案串流,DB、Socket、FTP Connection

原則:finally不能拋出異常

會導致真正的異常訊息遺失

原則:拋出自定義異常時帶上原始異常訊息

new MyException(key+“:”+e.getMessage);
new MyException(key, e);

原則:print Exception Stack, not just message

原則:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

怎麼做??

2015年12月30日 星期三

Message Queue Intro & Spring RabbitMQ Example

http://villebez.logdown.com/posts/2015/12/21/message-queue-intro-spring-rabbitmq-example
進入這次主題之前,先讓大家認識
什麼是 Message Queue, Wikipedia.
在電腦科學中,訊息佇列(英語:Message queue)是一種行程間通信或同一行程的不同執行緒間的通信方式,軟體的貯列用來處理一系列的輸入,通常是來自使用者。訊息佇列提供了非同步的通信協定,也就是說:訊息的傳送者和接收者不需要同時與訊息佇列互交。訊息會儲存在佇列中,直到接收者取回它。
訊息佇列(Message Queue,簡稱MQ),從字面意思上看,本質是個佇列,FIFO先入先出,只不過佇列中存放的內容是message而已。其主要用途:不同行程Process/執行緒Thread之間通信。
最初起源于金融系統,用於在分散式系統中存儲轉發消息,在易用性、擴展性、高可用性等方面表現不俗。
訊息中介軟體主要用於元件之間的解耦,訊息的發送者無需知道訊息使用者的存在,反之亦然。
接著要準備這次的環境,下載安裝server,RabbitMQ
RabbitMQ Server Commands,詳見手冊
基本上windows上安裝方式就是下一步、下一步就好了,
安裝完可以連看看RabbitMQ Management Page,輸入default user
Management Page就不詳述了,自己玩玩看吧。
http://localhost:15672/
default username/password:guest/guest
server安裝完後就可以進入這次的主題
其實Spring AMQP管網已經有兩個簡易範例了,一個是純Java,一個是使用Spring的方式
我是使用Spring的方式,做些微調整,並記錄下須注意的地方
首先New Gradle Project,設定dependencies
dependencies {
compile 'org.springframework.amqp:spring-rabbit:1.5.3.RELEASE'
}
Spring Context Config (applicationContext.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <rabbit:connection-factory id="connectionFactory"
        host="127.0.0.1" port="5672" username="guest" password="guest" />

    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
        exchange="myExchange" />
 
    <rabbit:admin connection-factory="connectionFactory" />

  <rabbit:queue name="myQueue" />

    <rabbit:fanout-exchange name="myExchange">
        <rabbit:bindings>
            <rabbit:binding queue="myQueue" />
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <rabbit:listener-container id="rabbitMQContainer"
        connection-factory="connectionFactory" auto-startup="false">
        <rabbit:listener ref="messageHandler" queue-names="myQueue" />
    </rabbit:listener-container>

    <bean id="messageHandler" class="MessageHandler"/>
</beans>


注意設定xmlns:rabbit以及xsi:schemaLocation (http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd)
auto-startup預設為true,也就是spring載入後consumer listener就會啟動並且keep alive
與官網做法不同rabbit:listener沒有設定method屬性,後面說明

Message Handler
public class MessageHandler implements MessageListener {
    public void onMessage(Message message) {
        System.out.println(message);
    }
}
這裡跟官網用法不同,是去實作org.springframework.amqp.core.MessageListener
所以Spring Content Config並沒有設定rabbit:listener的method屬性,
好處是可以拿到更多Message的資訊,不是只有Body的字串,
要用哪種方式沒有對錯,單看需求而定!!
Output Message Object
(Body:'Test'; ID:null; Content:text/plain; Headers:{}; Exchange:myExchange; RoutingKey:; Reply:null; DeliveryMode:PERSISTENT; DeliveryTag:1)
Main
public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        AmqpTemplate amqpTemplate = ctx.getBean("amqpTemplate", AmqpTemplate.class);
        amqpTemplate.convertAndSend("Test");
}