View Javadoc

    1   /*
    2    *  Licensed to the Apache Software Foundation (ASF) under one
    3    *  or more contributor license agreements.  See the NOTICE file
    4    *  distributed with this work for additional information
    5    *  regarding copyright ownership.  The ASF licenses this file
    6    *  to you under the Apache License, Version 2.0 (the
    7    *  "License"); you may not use this file except in compliance
    8    *  with the License.  You may obtain a copy of the License at
    9    *
    10   *    http://www.apache.org/licenses/LICENSE-2.0
    11   *
    12   *  Unless required by applicable law or agreed to in writing,
    13   *  software distributed under the License is distributed on an
    14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    15   *  KIND, either express or implied.  See the License for the
    16   *  specific language governing permissions and limitations
    17   *  under the License.
    18   *
    19   */
    20  package org.apache.mina.examples.coap;
    21
    22  import java.net.InetSocketAddress;
    23  import java.nio.ByteBuffer;
    24
    25  import org.apache.mina.api.AbstractIoFutureListener;
    26  import org.apache.mina.api.AbstractIoHandler;
    27  import org.apache.mina.api.IoFuture;
    28  import org.apache.mina.api.IoSession;
    29  import org.apache.mina.coap.CoapCode;
    30  import org.apache.mina.coap.CoapMessage;
    31  import org.apache.mina.coap.codec.CoapDecoder;
    32  import org.apache.mina.coap.codec.CoapEncoder;
    33  import org.apache.mina.coap.resource.AbstractResourceHandler;
    34  import org.apache.mina.coap.resource.CoapResponse;
    35  import org.apache.mina.coap.resource.ResourceRegistry;
    36  import org.apache.mina.filter.codec.ProtocolCodecFilter;
    37  import org.apache.mina.filter.query.RequestFilter;
    38  import org.apache.mina.transport.nio.NioUdpClient;
    39
    40  /**
    41   *
    42   * A CoAP client, accepting "piggy-backed" request and behaving like a server too.
    43   */
    44  public class CoapClient {
    45
    46      static final ResourceRegistry reg = new ResourceRegistry();
    47
    48      public static void main(String[] args) {
    49
    50          final String status = "status message";
    51          System.err.println(status.length());
    52
    53          final RequestFilter<CoapMessage, CoapMessage> rq = new RequestFilter<>();
    54
    55          NioUdpClient client = new NioUdpClient();
    56          client.setFilters( //
    57                  new ProtocolCodecFilter<CoapMessage, ByteBuffer, Void, Void>( //
    58                          new CoapEncoder(), new CoapDecoder() //
    59                  ), rq);
    60
    61          client.setIoHandler(new Handler());
    62
    63          reg.register(new AbstractResourceHandler() {
    64
    65              @Override
    66              public CoapResponse handle(CoapMessage request, IoSession session) {
    67                  if (request.getCode() == CoapCode.GET.getCode()) {
    68                      return new CoapResponse(CoapCode.CONTENT.getCode(), status.getBytes());
    69                  } else {
    70                      return new CoapResponse(CoapCode.METHOD_NOT_ALLOWED.getCode(), null);
    71                  }
    72              }
    73
    74              @Override
    75              public String getTittle() {
    76                  return "Status report";
    77              }
    78
    79              @Override
    80              public String getPath() {
    81                  return "st";
    82              }
    83
    84          });
    85
    86          IoFuture<IoSession> cf = client.connect(new InetSocketAddress(args[0], Integer.parseInt(args[1])));
    87
    88          // register on connection
    89          cf.register(new AbstractIoFutureListener<IoSession>() {
    90
    91              @Override
    92              public void completed(IoSession session) {
    93                  IoFuture<CoapMessage> response = rq.request(session,
    94                          CoapMessage.post("register?id=1234567890ABCDEF", true, "true".getBytes()), 10000);
    95                  response.register(new AbstractIoFutureListener<CoapMessage>() {
    96                      @Override
    97                      public void completed(CoapMessage result) {
    98                          if (result.getCode() == CoapCode.CREATED.getCode()) {
    99                              System.err.println("registered !" + result);
    100                         } else {
    101                             System.err.println("registration error : " + result.getCode());
    102                         }
    103                     }
    104                 });
    105             }
    106         });
    107
    108         try {
    109             Thread.sleep(50000);
    110         } catch (InterruptedException e) {
    111             e.printStackTrace();
    112         }
    113
    114     }
    115
    116     private static class Handler extends AbstractIoHandler {
    117
    118         @Override
    119         public void messageReceived(IoSession session, Object message) {
    120
    121             System.err.println("rcvd : " + message);
    122             CoapMessage msg = (CoapMessage) message;
    123             if (msg.getCode() == CoapCode.GET.getCode() || msg.getCode() == CoapCode.POST.getCode()
    124                     || msg.getCode() == CoapCode.PUT.getCode() || msg.getCode() == CoapCode.DELETE.getCode()) {
    125                 CoapMessage resp = reg.respond(msg, session);
    126                 session.write(resp);
    127             }
    128         }
    129
    130         @Override
    131         public void messageSent(IoSession session, Object message) {
    132             System.err.println("sent : " + message);
    133         }
    134
    135         @Override
    136         public void exceptionCaught(IoSession session, Exception cause) {
    137             System.err.println("exception !");
    138             cause.printStackTrace();
    139
    140             try {
    141                 Thread.sleep(200);
    142             } catch (InterruptedException e) {
    143                 e.printStackTrace();
    144             }
    145             session.close(true);
    146         }
    147     }
    148 }