利用例

サンプルプログラムと利用しているライブラリ(およびバージョン)は自己責任でご使用ください。サンプルプログラムを使用したことにより発生した損害に関して、弊社はそのいかなる責任も負わないものとします。

javascript

  • WebSocket API - javascript

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    <html>
    <head>
    </head>
    <body>
    <div id="output"></div>
    
    <script>
    (function() {
      // websocketサーバアドレスおよびポートを指定
      var ws = new WebSocket("wss://localhost:443");
    
      var output = document.getElementById('output');
    
      function logStr(eventStr, msg) {
        return '<div>' + eventStr + ':' + msg + '</div>';
      }
    
      // websoket接続確立イベント処理
      ws.onopen = function() {
        output.innerHTML += logStr('connect', 'success');
    
        // websocket認証メッセージ
        var auth_message = {
          version: {
            common_version:   "1",                                   // commonセクションバージョン
            details_version:  "1"                                    // detailsセクションバージョン
          },
          common: {
            datatype:     "authentication",                          // データタイプ:認証(authenticaion指定)
            msgid:        "*",                                       // *を設定(認証では利用しない)
            sendid:       "*",                                       // *を設定(認証では利用しない)
            senddatetime: "*"                                        // *を設定(認証では利用しない)
          },
          details:      {
            password:     "trialpass"                                // ユーザパスワードを設定(利用申請時に発行)
          },
          sender: {
            version:      "1",                                       // senderセクションバージョン
            userid:       "trialuser",                               // ユーザIDを設定(利用申請時に発行)
            termid:       "000000001"                                // 接続端末識別IDを設定(ユーザがユニークな値となるよう任意に採番)
          },
          receiver: {
            version:      "1",                                       // receiverセクションバージョン
            userid:       "*",                                       // *を設定(認証では利用しない)
            termid:       "*"                                        // *を設定(認証では利用しない)
          }
        };
        // JSON形式に変換し、websocketサーバに送信
        ws.send(JSON.stringify(auth_message));
      };
    
      // メッセージ受信イベント処理
      ws.onmessage = function(e) {
        // JSON形式からオブジェクトに変換
        var parse = JSON.parse(e.data);
    
        if( parse.common.datatype === 'authentication' ) {
          // 認証メッセージ受信処理
          output.innerHTML += logStr('recieved', 'authentication result');
          if( parse.details.resultcode === '200' ) {
            // 認証成功
            output.innerHTML += logStr('authentication', 'success');
          } else {
            // 認証失敗
            output.innerHTML += logStr('authentication', 'failed');
          }
        } else {
          // 各データタイプ処理
          output.innerHTML += logStr('message', parse.details.data1 + ' - ' + parse.details.data2 + '- ' + parse.details.data3);
        }
      };
    
      // 切断イベント処理
      ws.onclose = function (e) {
        output.innerHTML += logStr('disconnect', e.code + ' - ' + e.type);
      };
    }());
    
    </script>
    </body>
    </html>
    

python

  • REST API - RESTAPIへのリクエスト送信およびレスポンス受信

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    #
    # EqCare sample client for python3
    #
    # please execute
    #  $ python3 restapi_sample.py
    #
    # NOTICE
    #   This program tested with python3.5 and python3.6 .
    #
    import sys
    import json
    
    # pip install requests==2.21.0
    import requests
    
    
    """
    パラメータ
    """
    BASE_URL = 'https://api.example.com/info/1.0'
    API_USER = 'trialuser'
    API_PASS = 'trialpass'
    TARGET_DATATYPE = 'trialinfo'
    
    """
    定数
    """
    HEADERS = {
        'User-Agent': 'EqCare Sample Client for python3',
        'Content-Type': 'application/json',
    }
    
    
    def testcall(target_path):
        try:
            url = '%s%s' % (BASE_URL, target_path)
    
            param = {
                'system': {
                    'login_name': API_USER,           # 認証ユーザ名
                    'login_pass': API_PASS,           # 認証パスワード
                    'app_servername': '',             # APIの呼び出し元システムのサーバ名
                    'app_username': '',               # APIの呼び出し元システムのログイン名
                    'timezone': '',                   # タイムゾーン変換
                },
                'query': {
                    'datatypename': TARGET_DATATYPE,  # データタイプ名
                    'dataversion': '==1',             # データバージョン
                    'limit': 100,                     # 検索で応答する最大上限数
                    'sortorder': [                    # ソート順
                        {'key': 'update_date', 'is_asc': '0'},
                    ],
                    'matching': [                     # 検索パラメータ
                        {'key': 'trialcode', 'value': '110', 'pattern': 'cmp'},
                    ],
                }
            }
    
            # jsonに変換します
            data = json.dumps(param)
    
            HEADERS['Content-Length'] = str(len(data))
    
            print('')
            print('request:')
            print(url)
            print(HEADERS)
            print(data)
            print('')
    
            # サーバにリクエストします
            response = _request(url, data.encode('utf-8'), HEADERS)
            print('response:')
            print(response)
            print('')
    
            # 結果を表示します
            print('result:')
            print_response(response)
            print('')
        except:
            msg = 'except ; %s; %s' % (sys.exc_info()[0], sys.exc_info()[1])
            print(msg)
    
        return 0
    
    
    def _request(url, data, headers={}):
        result = requests.post(url, data=data, headers=headers, timeout=60)
        return result.text
    
    
    def print_response(response):
        """
        結果を見やすくします
        """
        response = json.loads(response)
    
        print('code = %s' % response['code'])
        print('message = %s' % response['message'])
    
        if 'datalist' in response:
            print('datalist = ')
            print('------------')
    
            for item in response['datalist']:
                for k, v in item.items():
                    print('%s : %s' % (k, v))
    
                print('------------')
    
    
    if __name__ == '__main__':
        print('=============================')
    
        testcall('/data/search.json')
    
        print('=============================')
    
  • WebSocket API - websocket接続/認証およびメッセージ受信

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    #
    # EqCare sample websocket client for python3
    #
    # please execute
    #  $ python3 websocket_sample.py
    #
    # NOTICE
    #   This program tested with python3.5 and python3.6 .
    #
    import os
    import sys
    import json
    import time
    
    # pip install ws4py==0.5.1
    from ws4py.client.threadedclient import WebSocketClient
    
    
    WS_SERVER_URI = "wss://ws.example.com:443"
    API_USER = "trialuser"
    API_PASS = "trialpass"
    
    CLIENT_TERMID = "0000000001"
    
    
    class EventPushClient(WebSocketClient):
        def opened(self):
            print('EVENT : opened')
    
            data = {
              "version": {
                "common_version": "1",
                "details_version": "1"
              },
              "common": {
                "datatype": "authentication",
                "msgid": "",
                "sendid": "",
                "senddatetime": ""
              },
              "details": {
                "password": API_PASS
              },
              "sender": {
                "version": "1",
                "userid": API_USER,
                "termid": CLIENT_TERMID
              },
              "receiver": {
                "version": "1",
                "userid": "*",
                "termid": "*"
              },
            }
    
            self.senddata(data)
            print('')
    
        def closed(self, code, reason):
            print('EVENT : Closed down, code=%s, reason=%s' % (code, reason))
            print('')
    
        def received_message(self, m):
            print('EVENT : receive')
    
            data_str = m.data.decode('utf-8')
            message = json.loads(data_str)
    
            print('datatypename: %s' % message["common"]["datatype"])
            print(message)
            print('')
    
        def senddata(self, data):
            message = json.dumps(data)
            self.send(message.encode('utf-8'))
    
            print('senddata:')
            print(message)
            print('')
    
    
    if __name__ == '__main__':
        try:
            ws = EventPushClient(WS_SERVER_URI,
                                 protocols=['http-only', 'chat'])
            ws.connect()
    
            ws.run_forever()
        except KeyboardInterrupt:
            print('INT Keyboard')
            ws.close()
    
            sys.exit(1)
        except:
            print('EXCEPT : %s' % sys.exc_info()[1])
            ws.close()
    
            sys.exit(1)
    
        print('success. exit.')
        sys.exit(0)
    

ruby

  • REST API - ruby

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    #!/usr/bin/env ruby
    # -*- coding: utf-8 -*-
    require "net/http"
    require "uri"
    require 'json'
    
    BASE_URL = "https://localhost/info/1.0";
    LOGIN_NAME = "trialuser";
    LOGIN_PASS = "trialpass";
    DATATYPENAME = "publiccommons1";
    
    SYSTEM_PARAM = {
        'system' => {
            'login_name' => LOGIN_NAME,    # 認証ユーザ名(必須)
            'login_pass' => LOGIN_PASS,    # 認証パスワード(必須)
            'app_servername' => '',        # APIの呼び出し元システムのサーバ名(任意)
            'app_username' => '',          # APIの呼び出し元システムのログイン名(任意)
            'timezone' => '',              # タイムゾーン変換(任意) ※現時点では"Asia/Tokyo"のみ対応
            'use_rawdata' => '',           # 生データ利用有無
        },
    }
    
    # 最新データ get
    DATA_GET_QUERY_PARAM = {
        'query' => {
            'idlist' => [],     # idの配列(必須)
            'datatypename' => DATATYPENAME, # データタイプ名(必須)
            'dataversion' => 1,             # データバージョン(必須)
        }
    }
    
    # 最新データ search
    DATA_SEARCH_QUERY_PARAM = {
        'query' => {
            'datatypename' => DATATYPENAME, # データタイプ名(必須)
            'dataversion' => '==1',         # データバージョン(必須)
            'limit' => 10,                  # 検索で応答する最大上限数(必須)
            'sortorder' => [],              # ソート順(任意)
            'matching' => []                # 検索パラメータ(任意)
        }
    }
    
    #
    # search
    #
    id = nil
    uri = URI.parse(BASE_URL + "/data/search.json")
    Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
      req_param = SYSTEM_PARAM.merge(DATA_SEARCH_QUERY_PARAM)
      
      encoded = JSON.generate(req_param)
      
      response = http.post(uri.path, encoded)
      parsed = JSON.parse(response.body)
      puts(parsed)
      
      if "200" == parsed["code"]
        if parsed["datalist"].length > 0
          id = parsed["datalist"][0]["id"]
        end
      end
    }
    
    #
    # get
    #
    if id
      uri = URI.parse(BASE_URL + "/data/get.json")
      Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
        # searchで取得したデータIDでgetしてみます
        get_param = Marshal.load(Marshal.dump(DATA_GET_QUERY_PARAM))
        get_param["query"]["idlist"].push(id)
        
        req_param = SYSTEM_PARAM.merge(get_param)
        
        encoded = JSON.generate(req_param)
        
        response = http.post(uri.path, encoded)
        
        parsed = JSON.parse(response.body)
        puts(parsed)
      }
    end
    
  • WebSocket API - ruby

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    #!/usr/bin/env ruby
    # -*- coding: utf-8 -*-
    require "rubygems"
    require "eventmachine"
    require "faye/websocket"  # gem install faye-websocket
    require "json"
    
    WSS_SERVER = "wss://localhost:443"
    USERID = "trialuser"
    PASSWD = "trialpass"
    TERMID = "0000000001"
    
    AUTH_MESSAGE = {
        "version" => {
            "common_version" =>   "1",
            "details_version" =>  "1"
        },
        "common" => {
            "datatype" =>     "authentication",
            "msgid" =>        "*",
            "sendid" =>       "*",
            "senddatetime" => ""
        },
        "details" =>      {
            "password" =>     PASSWD
        },
        "sender" => {
            "version" =>      "1",
            "userid" =>       USERID,
            "termid" =>       TERMID,
        },
        "receiver" => {
            "version" =>      "1",
            "userid" =>       "*",
            "termid" =>       "*"
        }
    }
    
    
    EM.run do
      conn = Faye::WebSocket::Client.new(WSS_SERVER)
    
      conn.on :open do |e|
        puts "connection success."
        puts "send auth message."
        conn.send(JSON::dump(AUTH_MESSAGE))
      end
    
      conn.on :error do |e|
        puts "error occured."
      end
    
      conn.on :close do |e|
        puts "connection close."
      end
    
      conn.on :message do |msg|
        now = Time.now.strftime("%Y-%m-%d %H:%M:%S")
        puts "#{now} message receive."
        result = JSON::parse(msg.data.to_s)
        puts result
      end
    end
    

Java

  • REST API - java

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    package jp.co.iij-engineering.ig;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import net.arnx.jsonic.JSON;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContextBuilder;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    public class WebApiSample {
        private static final String BASE_URL = "https://localhost/info/1.0";
        private static final String LOGIN_NAME = "trialuser";
        private static final String LOGIN_PASS = "trialpass";
        private static final String DATATYPENAME = "publiccommons1";
    
        private static class RequestParamDataSearch {
            public System system = new System();
            public Query query = new Query();
    
            class System {
                public String login_name = LOGIN_NAME;
                public String login_pass = LOGIN_PASS;
                public String app_servername;
                public String app_username;
                public String timezone;
                public String use_rawdata = "0";
            }
    
            class Query {
                public String datatypename = DATATYPENAME;
                public String dataversion = "==1";
                public int limit = 1;
                public List<?> sortorder = new ArrayList<>();
                public List<?> matching = new ArrayList<>();
            }
        }
    
        private static class RequestParamDataGet {
            public System system = new System();
            public Query query = new Query();
    
            class System {
                public String login_name = LOGIN_NAME;
                public String login_pass = LOGIN_PASS;
                public String app_servername;
                public String app_username;
                public String timezone;
                public String use_rawdata = "0";
            }
    
            class Query {
                public List<String> idlist = new ArrayList<String>();
                public String datatypename = DATATYPENAME;
                public int dataversion = 1;
            }
        }
    
        public class ResponsePublicCommons {
            public String code;
            public String message;
            public Datalist[] datalist;
    
            public class Datalist {
                public String id;
                public String datatypename;
                public String dataversion;
                public String create_date;
                public String update_date;
                public String expire_date;
    
                public String docid;
                public String revision;
                public String lang;
                public String countrycode;
                public String countryname;
                public String prefcode;
                public String prefname;
                public String citycode;
                public String cityname;
                public String send_at;
                public String status;
                public String category;
                public String subject;
                public String info_summary;
                public String info_detail;
                public String info_complement;
                public String incident_desc;
            }
        }
    
        public static void main(String[] args) {
            try {
                // search
                RequestParamDataSearch req_param_search = new RequestParamDataSearch();
                String request_body = JSON.encode(req_param_search);
                String response = httpPost(request_body, BASE_URL + "/data/search.json");
    
                ResponsePublicCommons decoded = JSON.decode(response, ResponsePublicCommons.class);
    
                System.out.println("res code : " + decoded.code);
                System.out.println("res mesasge : " + decoded.message);
    
                String id = null;
                if ("200".equals(decoded.code) && decoded.datalist.length > 0) {
                    id = decoded.datalist[0].id;
                }
    
                // get
                if (id != null) {
                    RequestParamDataGet req_param_get = new RequestParamDataGet();
                    // searchで取得したデータIDでgetしてみます
                    req_param_get.query.idlist.add(id);
    
                    request_body = JSON.encode(req_param_get);
                    response = httpPost(request_body, BASE_URL + "/data/get.json");
    
                    decoded = JSON.decode(response, ResponsePublicCommons.class);
    
                    System.out.println("res code : " + decoded.code);
                    System.out.println("res mesasge : " + decoded.message);
    
                    System.out.println("docid : " + decoded.datalist[0].docid);
                    System.out.println("prefname : " + decoded.datalist[0].prefname);
                    System.out.println("cityname : " + decoded.datalist[0].cityname);
                    System.out.println("subject : " + decoded.datalist[0].subject);
                    System.out.println("info_detail : " + decoded.datalist[0].info_summary);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static String httpPost(String request_body, String url) {
            int socketTimeout = 60000;
            int connectionTimeout = 60000;
    
            String ret = "";
    
            try {
                RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
    
                HttpPost request = new HttpPost(url);
                request.setEntity(new ByteArrayEntity(request_body.getBytes("UTF-8")));
    
                String res_body = "";
                if (url.startsWith("https")) {
                    // ssl
                    SSLContextBuilder builder = new SSLContextBuilder();
                    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                                                                              builder.build(),
                                                                              SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                                                                          );
                    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
                    CloseableHttpResponse response = httpclient.execute(request);
                    res_body = EntityUtils.toString(response.getEntity(), "UTF-8");
    
                    httpclient.close();
                    response.close();
                } else {
                    HttpClient httpclient = HttpClientBuilder.create()
                        .setDefaultRequestConfig(requestConfig)
                        .build();
                    HttpResponse response = httpclient.execute(request);
                    res_body = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
    
                ret = res_body;
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return ret;
        }
    }
    
  • WebSocket API - java

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    package jp.co.iij-engineering.ig;
    
    import java.net.URI;
    
    import javax.net.ssl.SSLContext;
    
    import net.arnx.jsonic.JSON;
    
    import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
    import org.java_websocket.client.WebSocketClient;
    import org.java_websocket.drafts.Draft_17;
    import org.java_websocket.handshake.ServerHandshake;
    
    public class WebSocketSample {
        private static final String WS_URL = "wss://localhost:443";
        private static final String USERID = "trialuser";
        private static final String PASSWORD = "trialpass";
        private static final String TERMID = "000000001";
        
        public static class AuthRequestParam {
            public Version version = new Version();
            public Common common = new Common();
            public Sender sender = new Sender();
            public Receiver receiver = new Receiver();
            public Details details = new Details();
            
            public class Version {
                public String common_version = "1";
                public String details_version = "1";
            }
            
            public class Common {
                public String datatype = "authentication";
                public String msgid = "*";
                public String sendid = "*";
                public String senddatetime = "*";
            }
            
            public class Sender {
                public String version = "1";
                public String userid = USERID;
                public String termid = TERMID;
            }
            
            public class Receiver {
                public String version = "1";
                public String userid = "*";
                public String termid = "*";
            }
            
            public class Details {
                public String password = PASSWORD;
            }
        }
        
        public static void main(String[] args) {
            try {
                WebSocketClient c = new WebSocketClient(new URI(WS_URL), new Draft_17()) {
                    @Override
                    public void onOpen(ServerHandshake handshakedata) {
                        System.out.println("onOpen");
                        this.send(JSON.encode(new AuthRequestParam()));
                    }
                    @Override
                    public void onMessage(String message) {
                        System.out.println("onMessage");
                        System.out.println(message);
                    }
                    @Override
                    public void onError(Exception ex) {
                        System.out.println("onError");
                        System.out.println(ex.toString());
                    }
                    @Override
                    public void onClose(int code, String reason, boolean remote) {
                        System.out.println("onClose");
                        System.out.println(code);
                        System.out.println(reason);
                    }
                };
                
                if (WS_URL.startsWith("wss")) {
                    SSLContext sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(null, null, null);
                    c.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
                }
                
                c.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

C

  • REST API - c

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    #################################################
    # Makefile
    #################################################
    # directorys
    SRCDIR=.
    
    # compiler
    CC=cc
    
    # compile and link option(both)
    DEBUG=-Wall -O0 -g
    BIN=a.out
    OBJS=$(SRCDIR)/webapimain.o
    
    # compile option
    LIBS=
    
    # link option
    CFLAGS=
    LDFLAGS=-lcurl -ljansson
    
    #################################################
    #
    ################################################
    .PHONY:all
    all:$(BIN)
    
    $(BIN):$(OBJS)
    	$(CC) $(DEBUG) $(LDFLAGS) -o $(BIN) $(LIBS) $(OBJS)
    
    .PHONY:clean
    clean:
    	rm -f $(BIN) $(OBJS) *~
    
    #################################################
    # suffixes
    #################################################
    .SUFFIXES: .c .o
    .c.o:
    	$(CC) $(DEBUG) $(CFLAGS) -c $< -o $@
    
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    /************
     webapi client program
    
     this program is required libcurl and jansson 2.3.1 .
       see https://curl.haxx.se/libcurl/
       see http://www.digip.org/jansson/
     ************/
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <curl/curl.h>
    #include <jansson.h>
    
    /* macro */
    // Memory Size
    #define BUFF_MAX_SIZE (1500)
    #define LONGSTR_MAX_LENGTH (256)
    #define SHORTSTR_MAX_LENGTH (30)
    #define MAX_CHILD_LIST (10)
    
    /* typedef */
    typedef enum query_type {
      QUERY_DATA_SEARCH,
      QUERY_DATA_GET,
      QUERY_DATA_SET,
      QUERY_DATA_DELETE,
      QUERY_HISTORY_SEARCH,
      QUERY_HISTORY_GET,
      QUERY_HISTORY_GET_CONTEXT,
      QUERY_ERROR,
    } QUERY_TYPES;
    
    struct system_conf {
      char login_name[LONGSTR_MAX_LENGTH];
      char login_pass[LONGSTR_MAX_LENGTH];
      char app_servername[LONGSTR_MAX_LENGTH];
      char app_username[LONGSTR_MAX_LENGTH];
      char timezone[SHORTSTR_MAX_LENGTH];
      char use_rawdata[SHORTSTR_MAX_LENGTH];
    };
    
    typedef struct api_map {
      QUERY_TYPES query_type;
      const char query_type_str[SHORTSTR_MAX_LENGTH];
      const char api_path[SHORTSTR_MAX_LENGTH];
    } API_MAP;
    
    typedef struct {
      char *data;   // response data from server
      size_t size;  // response size of data
    } MEMFILE;
    
    /* proto type */
    static char *post_api(const char *url, const char *postdata);
    static char *create_postdata(QUERY_TYPES query_type);
    static json_t *create_system_json();
    static json_t *create_query_json(QUERY_TYPES query_type);
    static API_MAP get_apimap(const char *query_type_str);
    static void print_api_res(const char *response);
    
    /* global variables */
    const char *base_url_g = "https://localhost/info/1.0";
    struct system_conf system_conf_g = {.login_name = "trialuser",
                                        .login_pass = "trialpass",
                                        .app_servername = "",
                                        .app_username = "",
                                        .timezone = "",
                                        .use_rawdata = "", };
    API_MAP api_map_g[] = {
        {.query_type = QUERY_DATA_SEARCH, .query_type_str = "data.search", .api_path = "/data/search.json"},
        {.query_type = QUERY_HISTORY_SEARCH,
         .query_type_str = "history.search",
         .api_path = "/history/search.json"},
        {.query_type = QUERY_ERROR, .query_type_str = "", .api_path = ""}, };
    
    /* MEM CONTROL Functions */
    MEMFILE *memfopen() {
      MEMFILE *mf = (MEMFILE *)malloc(sizeof(MEMFILE));
      if (mf) {
        mf->data = NULL;
        mf->size = 0;
      }
      return mf;
    }
    
    size_t memfwrite(char *ptr, size_t size, size_t nmemb, void *stream) {
      MEMFILE *mf = (MEMFILE *)stream;
      int block = size * nmemb;
      if (!mf) {
        return block;  // through
      }
      if (!mf->data) {
        mf->data = (char *)malloc(block);
      } else {
        mf->data = (char *)realloc(mf->data, mf->size + block);
      }
    
      if (mf->data) {
        memcpy(mf->data + mf->size, ptr, block);
        mf->size += block;
      }
      return block;
    }
    
    char *memfstrdup(MEMFILE *mf) {
      char *buf;
      if (mf->size == 0) {
        return NULL;
      }
      buf = (char *)malloc(mf->size + 1);
      memcpy(buf, mf->data, mf->size);
      buf[mf->size] = 0;
      return buf;
    }
    
    void memfclose(MEMFILE *mf) {
      if (mf->data) free(mf->data);
      free(mf);
    }
    
    /* POST DATA Functions */
    // create api data
    static char *create_postdata(QUERY_TYPES query_type) {
      char *postdata = NULL;
      json_t *root_dict = NULL;
      json_t *system_dict = NULL;
      json_t *query_dict = NULL;
    
      /* system   */
      system_dict = create_system_json();
      /* query   */
      query_dict = create_query_json(query_type);
    
      root_dict = json_object();
      json_object_set_new(root_dict, "system", system_dict);
      json_object_set_new(root_dict, "query", query_dict);
    
      /* result value must free() */
      postdata = json_dumps(root_dict, JSON_COMPACT);
    
      json_decref(root_dict);
      return postdata;
    }
    
    //  create system section
    static json_t *create_system_json() {
      json_t *system_dict = json_object();
      json_object_set_new(system_dict, "login_name", json_string(system_conf_g.login_name));
      json_object_set_new(system_dict, "login_pass", json_string(system_conf_g.login_pass));
      json_object_set_new(system_dict, "app_servername", json_string(system_conf_g.app_servername));
      json_object_set_new(system_dict, "app_username", json_string(system_conf_g.app_username));
      json_object_set_new(system_dict, "timezone", json_string(system_conf_g.timezone));
      json_object_set_new(system_dict, "use_rawdata", json_string(system_conf_g.use_rawdata));
      return system_dict;
    }
    
    //  create query section
    static json_t *create_query_json(QUERY_TYPES query_type) {
      json_t *query_dict = json_object();
      json_t *child_list_dict[MAX_CHILD_LIST];
      json_t *tmp_object = NULL;
    
      int obj_index = 0;
    
      switch (query_type) {
        case QUERY_DATA_SEARCH:
          // 最新データ search
          json_object_set_new(query_dict, "datatypename", json_string("trialinfo"));
          json_object_set_new(query_dict, "dataversion", json_string("==1"));
          json_object_set_new(query_dict, "limit", json_integer(1));
          child_list_dict[obj_index] = json_array();
          json_object_set_new(query_dict, "sortorder", child_list_dict[obj_index]);
          obj_index++;
          child_list_dict[obj_index] = json_array();
          json_object_set_new(query_dict, "matching", child_list_dict[obj_index]);
          obj_index++;
          break;
        case QUERY_HISTORY_SEARCH:
          // 履歴データ search
          json_object_set_new(query_dict, "datatypename", json_string("trialinfo"));
          json_object_set_new(query_dict, "dataversion", json_string("==1"));
          json_object_set_new(query_dict, "limit", json_integer(1));
          child_list_dict[obj_index] = json_array();
          tmp_object = json_object();
          json_object_set_new(tmp_object, "key", json_string("update_date"));
          json_object_set_new(tmp_object, "is_asc", json_string("0"));
          json_array_append_new(child_list_dict[obj_index], tmp_object);
          tmp_object = NULL;
          json_object_set_new(query_dict, "sortorder", child_list_dict[obj_index]);
          obj_index++;
    
          child_list_dict[obj_index] = json_array();
          tmp_object = json_object();
          json_object_set_new(tmp_object, "key", json_string("trialcode"));
          json_object_set_new(tmp_object, "value", json_string("110"));
          json_object_set_new(tmp_object, "pattern", json_string("cmp"));
          json_array_append_new(child_list_dict[obj_index], tmp_object);
          tmp_object = NULL;
          json_object_set_new(query_dict, "matching", child_list_dict[obj_index]);
          obj_index++;
          break;
        default:
          ;
      }
      return query_dict;
    }
    
    /* REST API Functions */
    // util string to API_MAP
    static API_MAP get_apimap(const char *query_type_str) {
      int i;
      for (i = 0; i < sizeof(api_map_g) / sizeof(API_MAP) - 1; i++) {
        if (strncmp(query_type_str, api_map_g[i].query_type_str, SHORTSTR_MAX_LENGTH) == 0) {
          return api_map_g[i];
        }
      }
      return api_map_g[i];
    }
    
    // REST API request
    static char *post_api(const char *url, const char *postdata) {
      CURL *curl;
      MEMFILE *mf = memfopen();
      char *js = NULL;
    
      struct curl_slist *headers = NULL;
    
      if (!postdata) {
        fprintf(stderr, "postdata is None.\n");
        return NULL;
      }
    
      // api post
      headers = curl_slist_append(headers, "Content-Type: application/json");
      curl = curl_easy_init();
      curl_easy_setopt(curl, CURLOPT_URL, url);
      curl_easy_setopt(curl, CURLOPT_POST, 1);
      curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
      curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postdata));
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite);
      curl_easy_perform(curl);
      curl_easy_cleanup(curl);
      js = (char *)memfstrdup(mf);
      memfclose(mf);
    
      return js;
    }
    
    // REST API REQUEST INFO print
    static void print_api_req(const char *url, const char *postdata) {
      // dump request information
      fprintf(stdout, "Request Info:\n");
      if (url) {
        fprintf(stdout, "url:\n");
        fprintf(stdout, "%s\n", url);
      }
      if (postdata) {
        fprintf(stdout, "parameter:\n");
        fprintf(stdout, "%s\n", postdata);
        fprintf(stdout, "\n");
      }
    }
    
    // REST API RESPONSE print
    static void print_api_res(const char *response) {
      int i;
    
      if (!response) {
        fprintf(stderr, "response is None.\n");
        return;
      }
    
      json_error_t error;
      json_t *res_json = json_loads(response, 0, &error);
      if (res_json == NULL) {
        fputs(error.text, stderr);
        return;
      }
    
      fprintf(stdout, "API Response:\n");
      fprintf(stdout, "%s\n", response);
      fprintf(stdout, "\n");
    
      fprintf(stdout, "API Result Info:\n");
      fprintf(stdout, "code: %s\n", json_string_value(json_object_get(res_json, "code")));
      fprintf(stdout, "message: %s\n", json_string_value(json_object_get(res_json, "message")));
    
      json_t *datalist = json_object_get(res_json, "datalist");
      json_t *data;
      const char *key;
      json_t *value;
      fprintf(stdout, "datalist:\n");
      fprintf(stdout, "------------\n");
      json_array_foreach(datalist, i, data) {
        json_object_foreach(data, key, value) { fprintf(stdout, "%s: %s\n", key, json_string_value(value)); }
        fprintf(stdout, "------------\n");
      }
      fprintf(stdout, "\n");
      json_decref(datalist);
    }
    
    int main(int argc, char *argv[]) {
      char *postdata = NULL;
      char *response = NULL;
      char *api_name = "data.search";
      char apiurl[LONGSTR_MAX_LENGTH];
    
      if (argc > 1) {
        api_name = argv[1];
      }
    
      fprintf(stdout, "hello webapimain.\n");
      fprintf(stdout, "\n");
    
      API_MAP api = get_apimap(api_name);
      if (api.query_type == QUERY_ERROR) {
        fprintf(stderr, "Unknown api.\n");
        return EXIT_FAILURE;
      }
      snprintf(apiurl, LONGSTR_MAX_LENGTH, "%s%s", base_url_g, api.api_path);
      postdata = create_postdata(api.query_type);
    
      print_api_req(apiurl, postdata);
    
      response = post_api(apiurl, postdata);
    
      print_api_res(response);
    
      free(postdata);
      free(response);
    
      fprintf(stdout, "process exit.\n");
      return EXIT_SUCCESS;
    }
    
  • WebSocket API - c

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    #################################################
    # Makefile
    #################################################
    # directorys
    SRCDIR=.
    
    # compiler
    CC=cc
    
    # compile and link option(both)
    DEBUG=-Wall -O0 -g
    BIN=a.out
    OBJS=$(SRCDIR)/wsmain.o
    
    # compile option
    LIBS=
    
    # link option
    CFLAGS=
    LDFLAGS=-lwebsockets -ljansson
    
    #################################################
    #
    ################################################
    .PHONY:all
    all:$(BIN)
    
    $(BIN):$(OBJS)
    	$(CC) $(DEBUG) $(LDFLAGS) -o $(BIN) $(LIBS) $(OBJS)
    
    .PHONY:clean
    clean:
    	rm -f $(BIN) $(OBJS) *~
    
    #################################################
    # suffixes
    #################################################
    .SUFFIXES: .c .o
    .c.o:
    	$(CC) $(DEBUG) $(CFLAGS) -c $< -o $@
    
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    /************
     websocket client program
    
     this program is required libwebsockets 1.3 and jansson 2.3.1 .
       see http://libwebsockets.org/trac/libwebsockets
       see http://www.digip.org/jansson/
     ************/
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <unistd.h>
    #include <signal.h>
    #include <fcntl.h>
    #include <assert.h>
    #include <stdarg.h>
    
    #include <libwebsockets.h>
    #include <jansson.h>
    
    /* macro */
    #define RX_BUFFERSIZE_ONE_CALLBACK  (1500)
    #define MY_DATATYPE_AUTH   "authentication"
    
    /* typedef */
    typedef enum  {
        WSPROTO_CHAT,
        WSPROTO_MAX,
    } MY_PROTOCALS;
    
    struct myconfig {
        char wsapi_user[256];
        char wsapi_pass[256];
        char wsapi_addr[256];
        char wsapi_termid[256];
        unsigned short wsapi_port;
        int wsapi_use_ssl;
        int wsapi_ietf_version;
    };
    
    /* proto type */
    void signal_handler(int);
    int callback_chat(struct libwebsocket_context *,
                      struct libwebsocket *,
                      enum libwebsocket_callback_reasons,
                      void *, void *, size_t);
    
    /* global variables */
    volatile sig_atomic_t g_sigint = 0;
    int g_use_verbose = 0;
    struct myconfig g_config;
    
    struct libwebsocket_protocols g_wsproto[] = {
        {
            "chat",
            callback_chat,
            /* per_session_data_size :
               no use BASIC or DIGEST auth. */
            0, 
            /* rx_buffer_size:
               limit "len" parameter for callback function.
               If too long data received, many call callback function. */
            RX_BUFFERSIZE_ONE_CALLBACK,
            /* no_buffer_all_partial_tx : 
               If set zero, partial send when big data send
               into libwebsockets library. */
            0, 
            NULL,
            0,
        },
        { /* end of list */
            NULL,
            NULL,
            0,
            0,
            0,
            NULL,
            0,
        }
    };
    
    
    void signal_handler(int sig){
        switch(sig){
        case SIGINT:
            g_sigint = 1;
            break;
        case SIGTERM:
            exit(1);
            break;
        case SIGKILL:
            exit(1);
            break;
        case SIGHUP:
            exit(1);
            break;
        case SIGPIPE:
            /* nothing */
            break;
        default:
            exit(1);
        }
    }
    
    
    int callback_chat(struct libwebsocket_context *this,
                      struct libwebsocket *wsi,
                      enum libwebsocket_callback_reasons reason,
                      void *user, void *in, size_t len)
    {
        int ret = 0;
        char *jsonmsg = NULL;
        json_t *root_dict = NULL;
        json_t *version_dict = NULL;
        json_t *common_dict = NULL;
        json_t *sender_dict = NULL;
        json_t *receiver_dict = NULL;
        json_t *details_dict = NULL;
    
        switch (reason) {
        case LWS_CALLBACK_CLIENT_ESTABLISHED:
            fprintf(stderr, "LWS_CALLBACK_CLIENT_ESTABLISHED\n");
    
            /* websocket application authentication. */
            {
                version_dict = json_object();
    
                json_object_set_new(version_dict, "common_version", json_string("1"));
                json_object_set_new(version_dict, "details_version", json_string("1"));
            }
    
            {
                common_dict = json_object();
    
                json_object_set_new(common_dict, "datatype", json_string(MY_DATATYPE_AUTH));
                json_object_set_new(common_dict, "msgid", json_string(""));
                json_object_set_new(common_dict, "sendid", json_string(""));
    
                json_object_set_new(common_dict, "senddatetime", json_string(""));
            }
    
            {
                sender_dict = json_object();
    
                json_object_set_new(sender_dict, "version", json_string("1"));
                json_object_set_new(sender_dict, "userid", json_string(g_config.wsapi_user));
                json_object_set_new(sender_dict, "termid", json_string(g_config.wsapi_termid));
            }
    
            {
                receiver_dict = json_object();
    
                json_object_set_new(receiver_dict, "version", json_string("1"));
                json_object_set_new(receiver_dict, "userid", json_string("*"));
                json_object_set_new(receiver_dict, "termid", json_string("*"));
            }
    
            {
                details_dict = json_object();
    
                json_object_set_new(details_dict, "password", json_string(g_config.wsapi_pass));
            }
    
            {
                root_dict = json_object();
    
                json_object_set_new(root_dict, "version", version_dict);
                json_object_set_new(root_dict, "common", common_dict);
                json_object_set_new(root_dict, "sender", sender_dict);
                json_object_set_new(root_dict, "receiver", receiver_dict);
                json_object_set_new(root_dict, "details", details_dict);
    
                /* result value must free() */
                jsonmsg = json_dumps(root_dict, JSON_COMPACT);
                if(NULL == jsonmsg){
                    fprintf(stderr, "fail malloc for jsonmsg.\n");
                    return 1;
                }
            }
    
            fprintf(stderr, "jsonmsg = %p\n", &(*jsonmsg));
            fprintf(stderr, "send message length : %ld\n", strlen(jsonmsg));
            fprintf(stderr, "send message:\n%s\n", jsonmsg);
    
            /* adjust websocket payload alignment */
            {
                unsigned char *sendmsg = NULL;
                size_t msglen = strlen(jsonmsg);
    
                sendmsg = (unsigned char*)malloc(
                    LWS_SEND_BUFFER_PRE_PADDING + msglen +
                    LWS_SEND_BUFFER_POST_PADDING);
                if(NULL == sendmsg){
                    fprintf(stderr, "fail malloc for sendmsg.\n");
                    return 1;
                }
    
                memcpy(sendmsg + LWS_SEND_BUFFER_PRE_PADDING, jsonmsg, msglen);
    
                ret = libwebsocket_write(wsi,
                                         sendmsg + LWS_SEND_BUFFER_PRE_PADDING,
                                         msglen,
                                         LWS_WRITE_TEXT);
    
                free(sendmsg);
            }
    
            free(jsonmsg);
    
            json_decref(root_dict);
    
            if(ret < 0){
                fprintf(stderr, "libwebsocket write message failed. (%d)\n", ret);
            }
            break;
        case LWS_CALLBACK_ESTABLISHED:
            fprintf(stderr, "LWS_CALLBACK_ESTABLISHED\n");
            break;
        case LWS_CALLBACK_RECEIVE:
            fprintf(stderr, "LWS_CALLBACK_RECEIVE\n");
            break;
        case LWS_CALLBACK_CLIENT_RECEIVE:
            ((char *)in)[len] = '\0';
            fprintf(stderr, "rx %d '%s'\n", (int)len, (char *)in);
            break;
        /* because we are protocols[0] ... */
        case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
            fprintf(stderr, "no support extension\n");
            return 1;
        case LWS_CALLBACK_CLOSED:
            fprintf(stderr, "LWS_CALLBACK_CLOSED\n");
            break;
        case LWS_CALLBACK_CLOSED_HTTP:
            fprintf(stderr, "LWS_CALLBACK_CLOSED_HTTP\n");
            break;
        case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
            fprintf(stderr, "LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
            break;
        default:
            if(g_use_verbose){
                fprintf(stderr, "LWS_CALLBACK_* = %d\n", reason);
            }
    
            break;
        }
    
        return 0;
    }
    
    
    int init_config()
    {
        strcpy(g_config.wsapi_user, "trialuser");
        strcpy(g_config.wsapi_pass, "trialpass");
        strcpy(g_config.wsapi_addr, "https://localhost");
        strcpy(g_config.wsapi_termid, "test-libwebsockets1");
        g_config.wsapi_port = 443;
        g_config.wsapi_use_ssl = 1;
        g_config.wsapi_ietf_version = -1;
    
        return 0;
    }
    
    
    int main(int argc, char *argv[])
    {
        struct libwebsocket_context *context = NULL;
        struct lws_context_creation_info wsinfo = {0};
        struct libwebsocket *wsi_chat = NULL;
        int ret = 0;
    
        fprintf(stderr, "hello wsmain.\n");
        fprintf(stderr, "libwebsockets version: %s\n", lws_get_library_version());
    
        ret = init_config();
        if(ret < 0){
            fprintf(stderr, "fail read config. abort.\n");
            return EXIT_FAILURE;
        }
    
        /* set signal handler. */
        signal(SIGINT, signal_handler);
        signal(SIGTERM, signal_handler);
        signal(SIGKILL, signal_handler);
        signal(SIGHUP, signal_handler);
        signal(SIGPIPE, signal_handler);
    
        wsinfo.port = CONTEXT_PORT_NO_LISTEN;
        wsinfo.iface = NULL;
        wsinfo.protocols = g_wsproto;
        /*wsinfo.protocols = NULL;*/
        wsinfo.extensions = libwebsocket_get_internal_extensions();
        wsinfo.token_limits = NULL;
        /*wsinfo.ssl_private_key_password = NULL;*/
        wsinfo.ssl_cert_filepath = NULL;
        wsinfo.ssl_private_key_filepath = NULL;
        wsinfo.ssl_ca_filepath = NULL;
        wsinfo.ssl_cipher_list = NULL;
        wsinfo.http_proxy_address = NULL;
        wsinfo.http_proxy_port = 0;
        wsinfo.gid = -1;
        wsinfo.uid = -1;
        wsinfo.options = 0;
        wsinfo.user = NULL;
        wsinfo.ka_time = 0;
        wsinfo.ka_probes = 0;
        wsinfo.ka_interval = 0;
    
        fprintf(stderr, "try libwebsocket_create_context.\n");
    
        context = libwebsocket_create_context(&wsinfo);
        if (context == NULL) {
            fprintf(stderr, "Creating libwebsocket context failed\n");
            return EXIT_FAILURE;
        }
    
        fprintf(stderr, "try libwebsocket_client_connect. (%s:%d)\n",
                g_config.wsapi_addr, g_config.wsapi_port);
    
        wsi_chat = libwebsocket_client_connect(
            context,
            g_config.wsapi_addr,
            g_config.wsapi_port,
            g_config.wsapi_use_ssl,
            "/",
            "example.com",
            "http://example.com",
            g_wsproto[WSPROTO_CHAT].name,
            g_config.wsapi_ietf_version);
        if (wsi_chat == NULL) {
            fprintf(stderr, "libwebsocket chat connect failed\n");
            return EXIT_FAILURE;
        }
    
        /* loop */
        for(;;){
            ret = libwebsocket_service(context, 1000);
            if(g_use_verbose){
                fprintf(stderr, "service : %d\n", ret);
            }
    
            if(0 < g_sigint){
                fprintf(stderr, "receive SIGINT\n");
                break;
            }
        }
    
        fprintf(stderr, "Exiting\n");
    
        sleep(2);
        libwebsocket_context_destroy(context);
    
        fprintf(stderr, "process exit.\n");
        return EXIT_SUCCESS;
    }
    

C-Sharp(C#)-DataContract

  • REST API - C-Sharp(C#)-DataContract

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    using System;
    using System.IO;
    using System.Text;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using Newtonsoft.Json;
    using System.Net;
    
    
    namespace webapisample1
    {
        class Program
        {
            static int Main(string[] args)
            {
                string APIURL_PREFIX = "/info/1.0";
    
                string APIURL_DATA_GET = "/data/get.json";
                string APIURL_DATA_SEARCH = "/data/search.json";
                string APIURL_DATA_SET = "/data/set.json";
                string APIURL_DATA_DELETE = "/data/delete.json";
                string APIURL_HISTORY_GET = "/history/get.json";
                string APIURL_HISTORY_GET_CONTEXT = "/history/get_context.json";
                string APIURL_HISTORY_SEARCH = "/history/search.json";
    
                string serverurl = "https://localhost";
                string apiuser = "trialuser";
                string apipass = "trialpass";
    
    
                // create api url (api: data.search)
                string requestUrl = String.Format("{0}/{1}/{2}", serverurl, APIURL_PREFIX, APIURL_DATA_SEARCH);
    
                WebRequest request = WebRequest.Create(requestUrl);
    
                try
                {
                    // create post data
                    string requestDatatype = "publiccommons1";
    
                    RequestPublicCommonsSearch1 reqdata = new RequestPublicCommonsSearch1(
                        new RequestSystem1(apiuser, apipass, "", "", "", "0"),
                        new RequestQuerySearch1(requestDatatype, "==1", 10,
                            new RequestQuerySortOrder1[] { new RequestQuerySortOrder1("update_date", "0") },
                            new RequestQueryMatching1[] { new RequestQueryMatching1("prefcode", "13", "cmp") }));
    
                    // serialize to post data.
                    string jsonString = null;
                    byte[] requestdata = null;
    
                    using (MemoryStream ms = new MemoryStream())
                    {
                        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(RequestPublicCommonsSearch1));
                        s.WriteObject(ms, reqdata);
    
                        jsonString = Encoding.UTF8.GetString(ms.ToArray());
                        requestdata = Encoding.UTF8.GetBytes(jsonString);
                    }
    
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = requestdata.Length;
    
                    //send request
                    using (Stream sr = request.GetRequestStream())
                    {
                        sr.Write(requestdata, 0, requestdata.Length);
                    }
    
                    //read response
                    string responseMessage = "";
    
                    using (WebResponse response = request.GetResponse())
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseMessage = sr.ReadToEnd();
                    }
    
                    // deserialize to response data.
                    ResponsePublicCommons1 responseObj = null;
    
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseMessage)))
                    {
                        DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(ResponsePublicCommons1));
                        responseObj = (ResponsePublicCommons1)ds.ReadObject(ms);
                    }
    
                    //check response code.
                    Console.WriteLine("code : {0}", responseObj.code);
                    Console.WriteLine("message : {0}", responseObj.message);
    
                    Console.WriteLine("response data:");
                    Console.WriteLine(responseMessage);
                    Console.WriteLine("");
    
                    for(int i = 0; i < responseObj.datalist.Length; i ++)
                    {
                        PublicCommons1 obj = responseObj.datalist[i];
    
                        Console.WriteLine("==== [{0}] ====", i);
                        Console.WriteLine("id : {0}", obj.id);
                        Console.WriteLine("datatypename : {0}", obj.datatypename);
                        Console.WriteLine("dataversion : {0}", obj.dataversion);
                        Console.WriteLine("create_date : {0}", obj.create_date);
                        Console.WriteLine("update_date : {0}", obj.update_date);
                        Console.WriteLine("expire_date: {0}", obj.expire_date);
                        Console.WriteLine("-------");
                        Console.WriteLine("docid : {0}", obj.docid);
                        Console.WriteLine("revision : {0}", obj.revision);
                        Console.WriteLine("lang : {0}", obj.lang);
                        Console.WriteLine("countrycode : {0}", obj.countrycode);
                        Console.WriteLine("countryname : {0}", obj.countryname);
                        Console.WriteLine("prefcode : {0}", obj.prefcode);
                        Console.WriteLine("prefname : {0}", obj.prefname);
                        Console.WriteLine("citycode : {0}", obj.citycode);
                        Console.WriteLine("cityname : {0}", obj.cityname);
                        Console.WriteLine("send_at : {0}", obj.send_at);
                        Console.WriteLine("status : {0}", obj.status);
                        Console.WriteLine("category : {0}", obj.category);
                        Console.WriteLine("subject : {0}", obj.subject);
                        Console.WriteLine("info_summary : {0}", obj.info_summary);
                        Console.WriteLine("info_detail : {0}", obj.info_detail);
                        Console.WriteLine("info_complement : {0}", obj.info_complement);
                        Console.WriteLine("incident_desc : {0}", obj.incident_desc);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception!! ({0})", e.Message);
                }
    
                Console.WriteLine("");
                Console.WriteLine("Finish.");
    
                return 0;
            }
        }
    
        [DataContract]
        public class RequestSystem1
        {
            public RequestSystem1(string _login_name, string _login_pass, string _app_servername, string _app_username,
                string _timezone, string _use_rawdata)
            {
                login_name = _login_name;
                login_pass = _login_pass;
                app_servername = _app_servername;
                app_username = _app_username;
                timezone = _timezone;
                use_rawdata = _use_rawdata;
            }
    
            [DataMember(Name = "login_name")]
            public string login_name { get; set; }
            [DataMember(Name = "login_pass")]
            public string login_pass { get; set; }
            [DataMember(Name = "app_servername")]
            public string app_servername { get; set; }
            [DataMember(Name = "app_username")]
            public string app_username { get; set; }
            [DataMember(Name = "timezone")]
            public string timezone { get; set; }
            [DataMember(Name = "use_rawdata")]
            public string use_rawdata { get; set; }
        }
    
        [DataContract]
        public class RequestQuerySearch1
        {
            public RequestQuerySearch1(string _datatypename, string _dataversion, int _limit,
                RequestQuerySortOrder1[] _sortorder, RequestQueryMatching1[] _matching)
            {
                datatypename = _datatypename;
                dataversion = _dataversion;
                limit = _limit;
                sortorder = _sortorder;
                matching = _matching;
            }
    
            [DataMember(Name = "datatypename")]
            public string datatypename { get; set; }
            [DataMember(Name = "dataversion")]
            public string dataversion { get; set; }
            [DataMember(Name = "limit")]
            public int limit { get; set; }
            [DataMember(Name = "sortorder")]
            public RequestQuerySortOrder1[] sortorder { get; set; }
            [DataMember(Name = "matching")]
            public RequestQueryMatching1[] matching { get; set; }
        }
    
        [DataContract]
        public class RequestQuerySortOrder1
        {
            public RequestQuerySortOrder1(string _key, string _is_asc)
            {
                key = _key;
                is_asc = _is_asc;
            }
    
            [DataMember(Name = "key")]
            public string key { get; set; }
            [DataMember(Name = "is_asc")]
            public string is_asc { get; set; }
        }
    
        [DataContract]
        public class RequestQueryMatching1
        {
            public RequestQueryMatching1(string _key, string _value, string _pattern)
            {
                key = _key;
                value = _value;
                pattern = _pattern;
            }
    
            [DataMember(Name = "key")]
            public string key { get; set; }
            [DataMember(Name = "value")]
            public string value { get; set; }
            [DataMember(Name = "pattern")]
            public string pattern { get; set; }
        }
    
    
        [DataContract]
        public class RequestPublicCommonsSearch1
        {
            public RequestPublicCommonsSearch1(RequestSystem1 _system, RequestQuerySearch1 _query)
            {
                system = _system;
                query = _query;
            }
    
            [DataMember(Name = "system")]
            public RequestSystem1 system { get; set; }
            [DataMember(Name = "query")]
            public RequestQuerySearch1 query { get; set; }
        }
    
        [DataContract]
        public class ResponsePublicCommons1
        {
            public ResponsePublicCommons1(string _code, string _message, PublicCommons1[] _datalist)
            {
                code = _code;
                message = _message;
                datalist = _datalist;
            }
    
            [DataMember(Name = "code")]
            public string code { get; set; }
            [DataMember(Name = "message")]
            public string message { get; set; }
            [DataMember(Name = "datalist")]
            public PublicCommons1[] datalist { get; set; }
        }
    
    
        [DataContract]
        public class PublicCommons1
        {
            public PublicCommons1(string _id, string _datatypename, int _dataversion,
                string _create_date, string _update_date, string _expire_date,
                string _docid, string _revision, string _lang, string _countrycode, string _countryname,
                string _prefcode, string _prefname, string _citycode, string _cityname,
                string _send_at, string _status, string _category, string _subject,
                string _info_summary, string _info_detail, string _info_complement, string _incident_desc)
    
            {
                id = _id;
                datatypename = _datatypename;
                dataversion = _dataversion;
                create_date = _create_date;
                update_date = _update_date;
                expire_date = _expire_date;
    
                docid = _docid;
                revision = _revision;
                lang = _lang;
                countrycode = _countrycode;
                countryname = _countryname;
                prefcode = _prefcode;
                prefname = _prefname;
                citycode = _citycode;
                cityname = _cityname;
                send_at = _send_at;
                status = _status;
                category = _category;
                subject = _subject;
                info_summary = _info_summary;
                info_detail = _info_detail;
                info_complement = _info_complement;
                incident_desc = _incident_desc;
            }
    
            [DataMember(Name = "id")]
            public string id { get; set; }
            [DataMember(Name = "datatypename")]
            public string datatypename { get; set; }
            [DataMember(Name = "dataversion")]
            public int dataversion { get; set; }
            [DataMember(Name = "create_date")]
            public string create_date { get; set; }
            [DataMember(Name = "update_date")]
            public string update_date { get; set; }
            [DataMember(Name = "expire_date")]
            public string expire_date { get; set; }
    
            [DataMember(Name = "docid")]
            public string docid { get; set; }
            [DataMember(Name = "revision")]
            public string revision { get; set; }
            [DataMember(Name = "lang")]
            public string lang { get; set; }
            [DataMember(Name = "countrycode")]
            public string countrycode { get; set; }
            [DataMember(Name = "countryname")]
            public string countryname { get; set; }
            [DataMember(Name = "prefcode")]
            public string prefcode { get; set; }
            [DataMember(Name = "prefname")]
            public string prefname { get; set; }
            [DataMember(Name = "citycode")]
            public string citycode { get; set; }
            [DataMember(Name = "cityname")]
            public string cityname { get; set; }
            [DataMember(Name = "send_at")]
            public string send_at { get; set; }
            [DataMember(Name = "status")]
            public string status { get; set; }
            [DataMember(Name = "category")]
            public string category { get; set; }
            [DataMember(Name = "subject")]
            public string subject { get; set; }
            [DataMember(Name = "info_summary")]
            public string info_summary { get; set; }
            [DataMember(Name = "info_detail")]
            public string info_detail { get; set; }
            [DataMember(Name = "info_complement")]
            public string info_complement { get; set; }
            [DataMember(Name = "incident_desc")]
            public string incident_desc { get; set; }
        }
    }
    
  • WebSocket API - C-Sharp(C#)-DataContract

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    using System;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Threading;
    using Newtonsoft.Json;
    // tested WebSocket4Net 0.15.2
    using WebSocket4Net;
    
    namespace wsapisample1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string url = "wss://127.0.0.1:443";
                string apiuser = "trialuser";
                string apipass = "00000000";
                string termid = "TERMID0001";
                MyWebSocketManager conn = new MyWebSocketManager(url, apiuser, apipass, termid);
    
                Console.WriteLine("start websocket sample program.");
                conn.Run();
    
                while (true)
                {
                    if (conn.IsClosed())
                    {
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
    
                Console.WriteLine("process finished.");
            }
        }
    
        class MyWebSocketManager
        {
            public static readonly string DATATYPE_AUTH = "authentication";
    
            WebSocket wsclient = null;
            string apiuser = "";
            string apipass = "";
            string termid = "";
    
            public MyWebSocketManager(string _url, string _apiuser, string _apipass, string _termid)
            {
                this.wsclient = new WebSocket(_url, sslProtocols: System.Security.Authentication.SslProtocols.Tls12);
                this.apiuser = _apiuser;
                this.apipass = _apipass;
                this.termid = _termid;
            }
    
            public void Run()
            {
                this.wsclient.Opened += new EventHandler(ws_opened);
                this.wsclient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(ws_message_received);
                this.wsclient.Closed += new EventHandler(ws_closed);
                this.wsclient.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(ws_error);
    
                this.wsclient.Open();
            }
    
            public bool IsClosed()
            {
                if (this.wsclient == null)
                {
                    return true;
                }
    
                if (this.wsclient.State == WebSocketState.Closed)
                {
                    return true;
                }
    
                return false;
            }
    
            private void ws_opened(Object o, EventArgs e)
            {
                Console.WriteLine("websocket connected.");
    
                // send auth message
                AuthMessageRequest1 authreq = new AuthMessageRequest1(
                    new Version1("1", "1"),
                    new Common1(DATATYPE_AUTH, "dummy", "dummy", DateTime.Now.ToString()),
                    new Sender1("1", this.apiuser, this.termid),
                    new Receiver1("1", "*", "*"),
                    new DetailsAuthRequest1(this.apipass));
    
                try
                {
                    DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(AuthMessageRequest1));
    
                    using (MemoryStream ms = new MemoryStream())
                    {
                        s.WriteObject(ms, authreq);
    
                        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                        this.wsclient.Send(jsonString);
                    }
                }
                catch (Exception ee)
                {
                    Console.WriteLine("erro send auth message.{0}", ee.Message);
                    Console.WriteLine("");
                }
            }
    
            private void ws_message_received(Object o, MessageReceivedEventArgs e)
            {
                Console.WriteLine("received websocket message.");
    
                // analyze datatype.
                PreParseMessageResponse1 resjson = JsonConvert.DeserializeObject<PreParseMessageResponse1>(e.Message);
    
                if (resjson.common.datatype == DATATYPE_AUTH)
                {
                    Console.WriteLine("  received auth message.");
                    Console.WriteLine("");
    
                    AuthMessageResponse1 authresjson = JsonConvert.DeserializeObject<AuthMessageResponse1>(e.Message);
    
                    if (true == authresjson.IsAuthSuccess())
                    {
                        Console.WriteLine("success auth.");
                        Console.WriteLine("");
                    }
                    else
                    {
                        Console.WriteLine("fail auth. disconnect.");
                        Console.WriteLine("");
                        this.wsclient.Close();
                    }
                }
                else
                {
                    Console.WriteLine("  receive other datatype message.");
                    Console.WriteLine(e.Message);
                    Console.WriteLine("");
                }
            }
    
            private void ws_error(Object o, SuperSocket.ClientEngine.ErrorEventArgs e)
            {
                Console.WriteLine("websocket connection error.");
                this.wsclient.Close();
            }
    
            private void ws_closed(Object o, EventArgs e)
            {
                Console.WriteLine("websocket connection error.");
            }
        }
    
        [DataContract]
        public class Version1
        {
            public Version1(string _common_ver, string _detail_ver)
            {
                common_version = _common_ver;
                details_version = _detail_ver;
            }
    
            [DataMember(Name = "common_version")]
            public string common_version { get; set; }
            [DataMember(Name = "details_version")]
            public string details_version { get; set; }
        }
    
        [DataContract]
        public class Common1
        {
            public Common1(string _datatype, string _msgid, string _sendid, string _senddatetime)
            {
                datatype = _datatype;
                msgid = _msgid;
                sendid = _sendid;
                senddatetime = _senddatetime;
            }
    
            [DataMember(Name = "datatype")]
            public string datatype { get; set; }
            [DataMember(Name = "msgid")]
            public string msgid { get; set; }
            [DataMember(Name = "sendid")]
            public string sendid { get; set; }
            [DataMember(Name = "senddatetime")]
            public string senddatetime { get; set; }
        }
    
        [DataContract]
        public class Sender1
        {
            public Sender1(string _version, string _userid, string _termid)
            {
                version = _version;
                userid = _userid;
                termid = _termid;
            }
    
            [DataMember(Name = "version")]
            public string version { get; set; }
            [DataMember(Name = "userid")]
            public string userid { get; set; }
            [DataMember(Name = "termid")]
            public string termid { get; set; }
        }
    
        [DataContract]
        public class Receiver1
        {
            public Receiver1(string _version, string _userid, string _termid)
            {
                version = _version;
                userid = _userid;
                termid = _termid;
            }
    
            [DataMember(Name = "version")]
            public string version { get; set; }
            [DataMember(Name = "userid")]
            public string userid { get; set; }
            [DataMember(Name = "termid")]
            public string termid { get; set; }
        }
    
        [DataContract]
        public class DetailsAuthRequest1
        {
            public DetailsAuthRequest1(string _password)
            {
                password = _password;
            }
    
            [DataMember(Name = "password")]
            public string password { get; set; }
        }
    
        [DataContract]
        public class DetailsAuthResponse1
        {
            public DetailsAuthResponse1(string _resultcode, string _message)
            {
                resultcode = _resultcode;
                message = _message;
            }
    
            [DataMember(Name = "resultcode")]
            public string resultcode { get; set; }
    
            [DataMember(Name = "message")]
            public string message { get; set; }
        }
    
        [DataContract]
        public class PreParseMessageResponse1
        {
            public PreParseMessageResponse1(Version1 _version, Common1 _common,
                Sender1 _sender, Receiver1 _receiver)
            {
                version = _version;
                common = _common;
                sender = _sender;
                receiver = _receiver;
            }
    
            [DataMember(Name = "version")]
            public Version1 version { get; set; }
    
            [DataMember(Name = "common")]
            public Common1 common { get; set; }
    
            [DataMember(Name = "sender")]
            public Sender1 sender { get; set; }
    
            [DataMember(Name = "receiver")]
            public Receiver1 receiver { get; set; }
        }
    
    
        [DataContract]
        public class AuthMessageRequest1
        {
            public AuthMessageRequest1(Version1 _version, Common1 _common,
                Sender1 _sender, Receiver1 _receiver, DetailsAuthRequest1 _details)
            {
                version = _version;
                common = _common;
                sender = _sender;
                receiver = _receiver;
                details = _details;
            }
    
            [DataMember(Name = "version")]
            public Version1 version { get; set; }
    
            [DataMember(Name = "common")]
            public Common1 common { get; set; }
    
            [DataMember(Name = "sender")]
            public Sender1 sender { get; set; }
    
            [DataMember(Name = "receiver")]
            public Receiver1 receiver { get; set; }
    
            [DataMember(Name = "details")]
            public DetailsAuthRequest1 details { get; set; }
        }
    
        [DataContract]
        public class AuthMessageResponse1
        {
            public AuthMessageResponse1(Version1 _version, Common1 _common,
                Sender1 _sender, Receiver1 _receiver, DetailsAuthResponse1 _details)
            {
                version = _version;
                common = _common;
                sender = _sender;
                receiver = _receiver;
                details = _details;
            }
    
            [DataMember(Name = "version")]
            public Version1 version { get; set; }
    
            [DataMember(Name = "common")]
            public Common1 common { get; set; }
    
            [DataMember(Name = "sender")]
            public Sender1 sender { get; set; }
    
            [DataMember(Name = "receiver")]
            public Receiver1 receiver { get; set; }
    
            [DataMember(Name = "details")]
            public DetailsAuthResponse1 details { get; set; }
    
            /// <summary>
            /// check auth result.
            /// </summary>
            /// <returns></returns>
            public bool IsAuthSuccess()
            {
                return ("200" == this.details.resultcode) ? true : false;
            }
        }
    }
    

C-Sharp(C#)-System.Json

  • REST API - C-Sharp(C#)-System.Json

  • WebSocket API - C-Sharp(C#)-System.Json

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    using System;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    using System.Collections.Generic;
    using System.Web.Script.Serialization;
    using System.Json;
    // tested WebSocket4Net 0.15.2
    using WebSocket4Net;
    
    namespace wsapisample2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string url = "wss://127.0.0.1:443";
                string apiuser = "trialuser";
                string apipass = "00000000";
                string termid = "TERMID0001";
                MyWebSocketManager conn = new MyWebSocketManager(url, apiuser, apipass, termid);
    
                Console.WriteLine("start websocket sample program.");
                conn.Run();
    
                while (true)
                {
                    if (conn.IsClosed())
                    {
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
    
                Console.WriteLine("process finished.");
            }
        }
    
        class MyWebSocketManager
        {
            public static readonly string DATATYPE_AUTH = "authentication";
    
            WebSocket wsclient = null;
            string apiuser = "";
            string apipass = "";
            string termid = "";
    
            public MyWebSocketManager(string _url, string _apiuser, string _apipass, string _termid)
            {
                this.wsclient = new WebSocket(_url, sslProtocols: System.Security.Authentication.SslProtocols.Tls12);
                this.apiuser = _apiuser;
                this.apipass = _apipass;
                this.termid = _termid;
            }
    
            public void Run()
            {
                this.wsclient.Opened += new EventHandler(ws_opened);
                this.wsclient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(ws_message_received);
                this.wsclient.Closed += new EventHandler(ws_closed);
                this.wsclient.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(ws_error);
    
                this.wsclient.Open();
            }
    
            public bool IsClosed()
            {
                if (this.wsclient == null)
                {
                    return true;
                }
    
                if (this.wsclient.State == WebSocketState.Closed)
                {
                    return true;
                }
    
                return false;
            }
    
            private void ws_opened(Object o, EventArgs e)
            {
                Console.WriteLine("websocket connected.");
    
                // send auth message
                try
                {
                    Dictionary<string, string> version = new Dictionary<string, string>();
                    version["common_version"] = "1";
                    version["details_version"] = "1";
    
                    Dictionary<string, string> commons = new Dictionary<string, string>();
                    commons["datatype"] = DATATYPE_AUTH;
                    commons["msgid"] = "dummy";
                    commons["sendid"] = "dummy";
                    commons["senddatetime"] = DateTime.Now.ToString();
    
                    Dictionary<string, string> sender = new Dictionary<string, string>();
                    sender["version"] = "1";
                    sender["userid"] = this.apiuser;
                    sender["termid"] = this.termid;
    
                    Dictionary<string, string> receiver = new Dictionary<string, string>();
                    receiver["version"] = "1";
                    receiver["userid"] = "*";
                    receiver["termid"] = "*";
    
                    Dictionary<string, string> details = new Dictionary<string, string>();
                    details["password"] = this.apipass;
    
                    JavaScriptSerializer sel = new JavaScriptSerializer();
    
                    string version_str = sel.Serialize(version);
                    string commons_str = sel.Serialize(commons);
                    string sender_str = sel.Serialize(sender);
                    string receiver_str = sel.Serialize(receiver);
                    string details_str = sel.Serialize(details);
    
    
                    StringBuilder jsonString = new StringBuilder();
                    jsonString.Append("{");
                    jsonString.Append(String.Format("\"version\": {0}", version_str));
                    jsonString.Append(",");
                    jsonString.Append(String.Format("\"common\": {0}", commons_str));
                    jsonString.Append(",");
                    jsonString.Append(String.Format("\"sender\": {0}", sender_str));
                    jsonString.Append(",");
                    jsonString.Append(String.Format("\"receiver\": {0}", receiver_str));
                    jsonString.Append(",");
                    jsonString.Append(String.Format("\"details\": {0}", details_str));
                    jsonString.Append("}");
    
                    this.wsclient.Send(jsonString.ToString());
                }
                catch (Exception ee)
                {
                    Console.WriteLine("erro send auth message.{0}", ee.Message);
                    Console.WriteLine("");
                }
            }
    
            private void ws_message_received(Object o, MessageReceivedEventArgs e)
            {
                Console.WriteLine("received websocket message.");
    
                // analyze datatype.
                dynamic resjson = JsonObject.Parse(e.Message).AsDynamic();
    
                if (resjson.common.datatype == DATATYPE_AUTH)
                {
                    Console.WriteLine("  received auth message.");
                    Console.WriteLine("");
    
                    if ("200" == resjson.details.resultcode.Value)
                    {
                        Console.WriteLine("success auth.");
                        Console.WriteLine("");
                    }
                    else
                    {
                        Console.WriteLine("fail auth. disconnect.");
                        Console.WriteLine("");
                        this.wsclient.Close();
                    }
                }
                else if (resjson.common.datatype == "earthquake")
                {
                    Console.WriteLine("  receive earthquake datatype message.");
                    Console.WriteLine(e.Message);
                    Console.WriteLine("");
    
                    string quakeid = resjson.details.eewid.Value;
                    string sequence = resjson.details.sequence.Value;
                    Console.WriteLine("eewid: {0}", quakeid);
                    Console.WriteLine("sequence: {0}", sequence);
    
                    try
                    {
                        foreach (var area in resjson.details.areainfo)
                        {
                            string meshcode = area.Key;
                            dynamic data = area.Value;
    
                            double intensity = (double)data.intensity.Value;
                            long s_time = (long)data.s_time.Value;
    
                            Console.WriteLine("  meshcode: {0}", meshcode);
                            Console.WriteLine("  intensity: {0}", intensity);
                            Console.WriteLine("  s_time: {0}", s_time);
                            Console.WriteLine("");
                        }
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.Message);
                        Console.WriteLine("");
                    }
                }
                else
                {
                    Console.WriteLine("  receive other datatype message.");
                    Console.WriteLine(e.Message);
                    Console.WriteLine("");
                }
            }
    
            private void ws_error(Object o, SuperSocket.ClientEngine.ErrorEventArgs e)
            {
                Console.WriteLine("websocket connection error.");
                this.wsclient.Close();
            }
    
            private void ws_closed(Object o, EventArgs e)
            {
                Console.WriteLine("websocket connection error.");
            }
        }
    }
    

PHP

  • REST API - PHP

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    #!/usr/bin/env php73
    <?php
    /*
        ※このサンプルプログラムはPHP7.3で動作確認しています。
    */
    
    $base_url = 'https://localhost/info/1.0';
    $endpoint = '/data/search.json';
    
    $system = [
        'login_name' => 'trialuser',  // 認証ユーザ名(必須)
        'login_pass' => 'trialpass',  // 認証パスワード(必須)
        'app_servername' => '',  // APIの呼び出し元システムのサーバ名(任意)
        'app_username ' => '', // APIの呼び出し元システムのログイン名(任意)
        'timezone' => '',  // タイムゾーン変換(任意)
        'use_rawdata' => '',  // 生データ利用有無
    ];
    
    $query = [
        'datatypename' => 'trialinfo',
        'dataversion' => '==1',
        'limit' => 10,
        'sortorder' => [
            ['key' => 'update_date', 'is_asc' => '0'],
        ],
        'matching' => [
            //['key' => 'trialcode', 'value' => '110', 'pattern' => 'cmp']
        ],
    ];
    
    function api_post($api_url, $data)
    {
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' =>  json_encode($data),
                'ignore_errors' => true
            ]
        ]);
    
        $response = file_get_contents(
            $api_url,
            false,
            $context
        );
    
        return json_decode($response, true);
    }
    
    $result = api_post($base_url . $endpoint, [
        'system' => $system,
        'query' => $query,
    ]);
    print_r($result);
    
  • WebSocket API - PHP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env php73
<?php
/*
    ※このサンプルプログラムはPHP7.3で動作確認しています。

    composerを使用し、以下のライブラリをインストールしてください。
    ratchet/pawl:v0.3.4

    詳細は以下をご覧ください。
    https://github.com/ratchetphp/Pawl
*/

require(__DIR__ . '/vendor/autoload.php');

// 接続先URL
const URL = 'wss://localhost:443';
// ユーザID
const USERID = 'trialuser';
// パスワード
const PASSWORD = 'trialpass';
// 端末ID
const TERMID = '000000001';

// 認証要求メッセージ
const AUTH_MESSAGE = [
    'version' => [
        'common_version' => '1',
        'details_version' => '1',
    ],
    'common' => [
        'datatype' => 'authentication',
        'msgid' => '*',
        'sendid' => '*',
        'senddatetime' => '',
    ],
    'details' => [
        'password' => PASSWORD,
    ],
    'sender' => [
        'version' => '1',
        'userid' => USERID,
        'termid' => TERMID,
    ],
    'receiver' => [
        'version' => '1',
        'userid' => '*',
        'termid' => '*',
    ],
];

\Ratchet\Client\connect(URL)->then(function ($conn) {
    $conn->on('message', function ($msg) use ($conn) {
        // 受信したメッセージを表示します。
        echo "{$msg}\n";
    });

    $conn->on('close', function ($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });

    // 認証要求メッセージをJSONに変換して送信します。
    $conn->send(json_encode(AUTH_MESSAGE));
}, function ($e) {
    exit($e->getMessage());
});

shell script(curl)

  • REST API - shell script(curl)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #!/bin/bash
    BASE_URL="https://localhost/info/1.0"
    METHOD="/data/search.json"
    _post(){
    	data=$(cat -)
    	curl=`cat <<-EOS
    	curl
    	-m 60
    	--request POST
    	$BASE_URL$METHOD
    	--header 'Content-Type: application/json'
    	--data '$data'
    	EOS`
    	eval ${curl}
    }
    
    if [ -p /dev/stdin ]; then
    	 cat -
    else
    	 echo $*
    fi | _post
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    {
      "query": {
          "datatypename": "trialinfo",
          "dataversion": "==1",
          "limit": 0,
          "matching": [
              {
                  "key": "trialcode",
                  "pattern": "cmp",
                  "value": "210"
              }
          ],
          "sortorder": []
      },
      "system": {
          "app_servername": "",
          "app_username": "",
          "login_name": "trialuser",
          "login_pass": "trialpass",
          "timezone": "",
          "use_rawdata": ""
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    # シェルスクリプト実行例
    # curl scriptの実行(要curl)
    $ cat sample.json | ./curl_sample.sh
    # API実行結果をjsonで整形する(要curl,jq)
    $ cat sample.json | ./curl_sample.sh | jq
    # 入力ファイルのJSONフォーマットが適切かを確認する(要jq)
    $ jq "" sample.json