From bde916859859bc9ff6de96682a2989a373e28a0d Mon Sep 17 00:00:00 2001 From: hubiss Date: Wed, 22 Nov 2017 19:01:26 +0900 Subject: [PATCH] gitignore updated --- .gitignore | 12 +- .../server.xml | 132 -- si-modules/DM_Web_Server/.classpath | 32 - .../net/herit/business/api/ApiController.java | 1626 ++++++++--------- .../herit/business/api/service/ApiHdmDAO.java | 1130 ++++++------ .../herit/business/api/service/ApiHdpDAO.java | 656 +++---- .../business/api/service/LWM2MApiService.java | 476 ++--- .../business/api/service/TR069ApiService.java | 1224 ++++++------- .../herit/business/api/service/TR069Apis.java | 274 +-- .../net/herit/business/protocol/DmModel.java | 240 +-- .../net/herit/business/protocol/DmVO.java | 196 +- .../business/protocol/HttpConnector.java | 372 ++-- .../herit/business/protocol/HttpOperator.java | 822 ++++----- .../business/protocol/MessageHandler.java | 184 +- .../net/herit/business/protocol/Util.java | 328 ++-- .../business/protocol/constant/Errors.java | 50 +- .../business/protocol/constant/KeyName.java | 10 +- .../business/protocol/constant/Target.java | 14 +- .../business/protocol/constant/Type.java | 10 +- .../protocol/lwm2m/LWM2MController.java | 1240 ++++++------- .../protocol/lwm2m/LWM2MFormatter.java | 58 +- .../protocol/lwm2m/LWM2MKeyExtractor.java | 186 +- .../herit/business/protocol/lwm2m/Util.java | 222 +-- .../lwm2m/exception/JsonFormatException.java | 8 +- .../protocol/lwm2m/resource/ResourceVO.java | 256 +-- .../business/protocol/model/EtcProtocol.java | 26 +- .../protocol/tr069/CurlOperation.java | 532 +++--- .../protocol/tr069/TR069ConnectOperator.java | 518 +++--- .../protocol/tr069/TR069Controller.java | 736 ++++---- .../protocol/tr069/TR069Formatter.java | 86 +- .../protocol/tr069/TR069KeyExtractor.java | 256 +-- .../resources/herit/props/globals.properties | 444 ++--- .../device.status.single_num_bar_lwm2m_ip.js | 132 +- .../leshan-client-demo/.classpath | 31 - .../LWM2M_IPE_Server/META-INF/MANIFEST.MF | 14 +- .../LWM2M_IPE_Server/META-INF/MANIFEST.MF.bak | 14 +- .../leshan-client-cf/pom.properties | 10 +- .../leshan-client-cf/pom.xml | 160 +- .../leshan-client-core/pom.properties | 10 +- .../leshan-client-core/pom.xml | 144 +- .../leshan-client-demo/pom.properties | 14 +- .../leshan-client-demo/pom.xml | 160 +- .../leshan-core/pom.properties | 10 +- .../org.eclipse.leshan/leshan-core/pom.xml | 152 +- .../maven/org.slf4j/slf4j-api/pom.properties | 10 +- .../maven/org.slf4j/slf4j-api/pom.xml | 174 +- si-modules/LWM2M_IPE_Server/doc.txt | 140 +- .../leshan-server-core/.classpath | 26 - .../leshan-server-core/pom.xml | 166 +- .../eclipse/leshan/server/Destroyable.java | 46 +- .../eclipse/leshan/server/LwM2mServer.java | 206 +-- .../leshan/server/Lwm2mServerConfig.java | 400 ++-- .../org/eclipse/leshan/server/Startable.java | 44 +- .../org/eclipse/leshan/server/Stoppable.java | 44 +- .../org/eclipse/leshan/server/Version.java | 64 +- .../server/bootstrap/BootstrapConfig.java | 170 +- .../server/bootstrap/BootstrapHandler.java | 502 ++--- .../server/bootstrap/BootstrapSession.java | 138 +- .../bootstrap/BootstrapSessionManager.java | 110 +- .../server/bootstrap/BootstrapStore.java | 50 +- .../LwM2mBootstrapRequestSender.java | 82 +- .../bootstrap/LwM2mBootstrapServer.java | 84 +- .../leshan/server/bootstrap/SecurityMode.java | 58 +- .../server/bootstrap/SmsSecurityMode.java | 58 +- .../eclipse/leshan/server/client/Client.java | 774 ++++---- .../leshan/server/client/ClientRegistry.java | 178 +- .../server/client/ClientRegistryListener.java | 88 +- .../leshan/server/client/ClientUpdate.java | 238 +-- .../leshan/server/extension/Constants.java | 210 +-- .../leshan/server/extension/HttpOperator.java | 626 +++---- .../leshan/server/extension/Lwm2mVO.java | 78 +- .../leshan/server/extension/TaskTimer.java | 40 +- .../leshan/server/extension/Tokenization.java | 402 ++-- .../eclipse/leshan/server/extension/Util.java | 332 ++-- .../server/extension/dm/DmFormatter.java | 10 +- .../extension/dm/handler/DmConnector.java | 98 +- .../extension/dm/handler/DmOperator.java | 92 +- .../extension/onem2m/Onem2mHeaderMaker.java | 80 +- .../extension/onem2m/handler/Executor.java | 232 +-- .../onem2m/handler/Onem2mConnector.java | 82 +- .../onem2m/handler/Onem2mOperator.java | 806 ++++---- .../onem2m/handler/TDeviceControl.java | 110 +- .../extension/onem2m/handler/TReport.java | 122 +- .../extension/onem2m/handler/TSubscribe.java | 130 +- .../server/extension/onem2m/resources/AE.java | 220 +-- .../extension/onem2m/resources/Container.java | 120 +- .../onem2m/resources/ContentInstance.java | 118 +- .../onem2m/resources/PollingChannel.java | 102 +- .../extension/onem2m/resources/Resource.java | 414 ++--- .../onem2m/resources/ResourceHandler.java | 142 +- .../onem2m/resources/SemanticDescriptor.java | 218 +-- .../onem2m/resources/Subscription.java | 120 +- .../impl/BootstrapSessionManagerImpl.java | 128 +- .../server/impl/ClientRegistryImpl.java | 360 ++-- .../server/impl/LwM2mRequestSenderImpl.java | 194 +- .../server/impl/SecurityRegistryImpl.java | 550 +++--- .../server/model/LwM2mModelProvider.java | 88 +- .../server/model/StandardModelProvider.java | 64 +- .../server/model/StaticModelProvider.java | 86 +- .../observation/ObservationRegistry.java | 158 +- .../ObservationRegistryListener.java | 74 +- .../leshan/server/queue/ClientState.java | 60 +- .../leshan/server/queue/MessageStore.java | 140 +- .../leshan/server/queue/QueuedRequest.java | 88 +- .../queue/impl/ClientStatusTracker.java | 152 +- .../queue/impl/InMemoryMessageStore.java | 204 +-- .../queue/impl/QueuedRequestSender.java | 786 ++++---- .../server/queue/impl/RequestSendingTask.java | 178 +- .../registration/RegistrationHandler.java | 466 ++--- .../server/request/LwM2mRequestSender.java | 138 +- .../server/response/ResponseListener.java | 84 +- .../response/ResponseProcessingTask.java | 206 +-- .../security/BootstrapSecurityStore.java | 74 +- .../NonUniqueSecurityInfoException.java | 82 +- .../leshan/server/security/SecurityCheck.java | 324 ++-- .../leshan/server/security/SecurityInfo.java | 298 +-- .../server/security/SecurityRegistry.java | 142 +- .../leshan/server/security/SecurityStore.java | 78 +- .../bootstrap/BootstrapHandlerTest.java | 332 ++-- .../server/client/ClientSortObjectTest.java | 94 +- .../leshan/server/impl/BasicTestSupport.java | 78 +- .../server/impl/ClientRegistryImplTest.java | 186 +- .../queue/impl/ClientStatusTrackerTest.java | 142 +- .../lwm2m-server-dms/.classpath | 31 - .../lwm2m-server-dms/Californium.properties | 84 +- .../lwm2m-server-dms/config.xml | 104 +- .../herit/iot/lwm2m/dms/Lwm2mServerMain.java | 346 ++-- .../iot/lwm2m/dms/servlet/ApiServlet.java | 1018 +++++------ .../org/eclipse/leshan/LinkObject.java | 380 ++-- .../org/eclipse/leshan/LwM2mId.java | 100 +- .../org/eclipse/leshan/ObserveSpec.java | 364 ++-- .../org/eclipse/leshan/ResponseCode.java | 124 +- .../leshan/client/demo/MyDevice.java.bak.org | 306 ++-- .../client/demo/MyLocation.java.bak.org | 162 +- .../client/servers/BootstrapHandler.class | Bin 4742 -> 0 bytes .../client/servers/BootstrapListener.class | Bin 183 -> 0 bytes .../leshan/client/servers/DmServerInfo.class | Bin 863 -> 0 bytes .../client/servers/RegistrationEngine$1.class | Bin 273 -> 0 bytes .../RegistrationEngine$RegistrationTask.class | Bin 2129 -> 0 bytes ...trationEngine$UpdateRegistrationTask.class | Bin 1631 -> 0 bytes .../client/servers/RegistrationEngine.class | Bin 13227 -> 0 bytes .../leshan/client/servers/ServerInfo.class | Bin 2353 -> 0 bytes .../leshan/client/servers/ServersInfo.class | Bin 875 -> 0 bytes .../client/servers/ServersInfoExtractor.class | Bin 4674 -> 0 bytes .../leshan/core/model/DDFFileParser.java | 378 ++-- .../leshan/core/model/Ddf2JsonGenerator.java | 216 +-- .../eclipse/leshan/core/model/LwM2mModel.java | 174 +- .../leshan/core/model/ObjectLoader.java | 310 ++-- .../leshan/core/model/ObjectModel.java | 150 +- .../leshan/core/model/ResourceModel.java | 150 +- .../model/json/ObjectModelDeserializer.java | 106 +- .../model/json/ObjectModelSerializer.java | 116 +- .../model/json/ResourceModelDeserializer.java | 112 +- .../model/json/ResourceModelSerializer.java | 90 +- .../core/node/LwM2mMultipleResource.java | 510 +++--- .../eclipse/leshan/core/node/LwM2mNode.java | 66 +- .../leshan/core/node/LwM2mNodeVisitor.java | 58 +- .../eclipse/leshan/core/node/LwM2mObject.java | 242 +-- .../leshan/core/node/LwM2mObjectInstance.java | 260 +-- .../eclipse/leshan/core/node/LwM2mPath.java | 560 +++--- .../leshan/core/node/LwM2mResource.java | 176 +- .../leshan/core/node/LwM2mSingleResource.java | 384 ++-- .../core/node/TimestampedLwM2mNode.java | 86 +- .../node/codec/DefaultLwM2mNodeDecoder.java | 258 +-- .../node/codec/DefaultLwM2mNodeEncoder.java | 202 +- .../node/codec/InvalidValueException.java | 86 +- .../core/node/codec/LwM2mNodeDecoder.java | 152 +- .../core/node/codec/LwM2mNodeEncoder.java | 110 +- .../core/node/codec/Lwm2mNodeEncoderUtil.java | 300 +-- .../node/codec/json/LwM2mNodeJsonDecoder.java | 756 ++++---- .../node/codec/json/LwM2mNodeJsonEncoder.java | 418 ++--- .../codec/opaque/LwM2mNodeOpaqueDecoder.java | 80 +- .../codec/opaque/LwM2mNodeOpaqueEncoder.java | 156 +- .../node/codec/text/LwM2mNodeTextDecoder.java | 182 +- .../node/codec/text/LwM2mNodeTextEncoder.java | 200 +- .../node/codec/tlv/LwM2mNodeTlvDecoder.java | 434 ++--- .../node/codec/tlv/LwM2mNodeTlvEncoder.java | 376 ++-- .../leshan/core/observation/Observation.java | 124 +- .../core/request/AbstractDownlinkRequest.java | 100 +- .../leshan/core/request/BindingMode.java | 80 +- .../core/request/BootstrapDeleteRequest.java | 74 +- .../core/request/BootstrapFinishRequest.java | 74 +- .../leshan/core/request/BootstrapRequest.java | 82 +- .../core/request/BootstrapWriteRequest.java | 210 +-- .../leshan/core/request/ContentFormat.java | 260 +-- .../leshan/core/request/CreateRequest.java | 488 ++--- .../leshan/core/request/DeleteRequest.java | 122 +- .../core/request/DeregisterRequest.java | 92 +- .../leshan/core/request/DiscoverRequest.java | 160 +- .../leshan/core/request/DownlinkRequest.java | 78 +- .../core/request/DownlinkRequestVisitor.java | 86 +- .../leshan/core/request/ExecuteRequest.java | 186 +- .../eclipse/leshan/core/request/Identity.java | 192 +- .../leshan/core/request/LwM2mRequest.java | 48 +- .../leshan/core/request/ObserveRequest.java | 270 +-- .../leshan/core/request/ReadRequest.java | 274 +-- .../leshan/core/request/RegisterRequest.java | 182 +- .../leshan/core/request/UpdateRequest.java | 158 +- .../leshan/core/request/UplinkRequest.java | 60 +- .../core/request/UplinkRequestVisitor.java | 58 +- .../core/request/WriteAttributesRequest.java | 126 +- .../leshan/core/request/WriteRequest.java | 698 +++---- .../exception/RequestFailedException.java | 66 +- .../exception/ResourceAccessException.java | 128 +- .../request/exception/TimeoutException.java | 52 +- .../core/response/AbstractLwM2mResponse.java | 102 +- .../response/BootstrapDeleteResponse.java | 110 +- .../response/BootstrapFinishResponse.java | 110 +- .../core/response/BootstrapResponse.java | 110 +- .../core/response/BootstrapWriteResponse.java | 120 +- .../leshan/core/response/CreateResponse.java | 150 +- .../leshan/core/response/DeleteResponse.java | 128 +- .../core/response/DeregisterResponse.java | 112 +- .../core/response/DiscoverResponse.java | 170 +- .../leshan/core/response/ErrorCallback.java | 56 +- .../leshan/core/response/ExecuteResponse.java | 126 +- .../leshan/core/response/LwM2mResponse.java | 98 +- .../leshan/core/response/ObserveResponse.java | 154 +- .../leshan/core/response/ReadResponse.java | 240 +-- .../core/response/RegisterResponse.java | 132 +- .../core/response/ResponseCallback.java | 58 +- .../leshan/core/response/UpdateResponse.java | 112 +- .../response/WriteAttributesResponse.java | 128 +- .../leshan/core/response/WriteResponse.java | 136 +- .../eclipse/leshan/json/JsonArrayEntry.java | 340 ++-- .../eclipse/leshan/json/JsonRootObject.java | 210 +-- .../org/eclipse/leshan/json/LwM2mJson.java | 90 +- .../leshan/json/LwM2mJsonException.java | 68 +- .../org/eclipse/leshan/tlv/Tlv.java | 280 +-- .../org/eclipse/leshan/tlv/TlvDecoder.java | 436 ++--- .../org/eclipse/leshan/tlv/TlvEncoder.java | 454 ++--- .../org/eclipse/leshan/tlv/TlvException.java | 60 +- .../org/eclipse/leshan/util/Base64.java | 1568 ++++++++-------- .../org/eclipse/leshan/util/BaseNCodec.java | 1008 +++++----- .../org/eclipse/leshan/util/Charsets.java | 116 +- .../org/eclipse/leshan/util/Hex.java | 590 +++--- .../leshan/util/NamedThreadFactory.java | 94 +- .../leshan/util/RandomStringUtils.java | 698 +++---- .../org/eclipse/leshan/util/StringUtils.java | 708 +++---- .../org/eclipse/leshan/util/Validate.java | 1150 ++++++------ si-modules/LWM2M_IPE_Server/pom.xml | 28 +- si-modules/OIC-IPE/.classpath | 24 - si-onem2m-src/.classpath | 32 - si-onem2m-src/incse.xml | 230 +-- 244 files changed, 26812 insertions(+), 27120 deletions(-) delete mode 100644 Servers/Tomcat v7.0 Server at localhost-config/server.xml delete mode 100644 si-modules/DM_Web_Server/.classpath delete mode 100644 si-modules/LWM2M_IPE_Client/leshan-client-demo/.classpath delete mode 100644 si-modules/LWM2M_IPE_Server/leshan-server-core/.classpath delete mode 100644 si-modules/LWM2M_IPE_Server/lwm2m-server-dms/.classpath delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapHandler.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapListener.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/DmServerInfo.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine$1.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine$RegistrationTask.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine$UpdateRegistrationTask.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/ServerInfo.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/ServersInfo.class delete mode 100644 si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/ServersInfoExtractor.class delete mode 100644 si-modules/OIC-IPE/.classpath delete mode 100644 si-onem2m-src/.classpath diff --git a/.gitignore b/.gitignore index 2a40a2c..5373f51 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ -Servers -*/target/ -.project -.settings -.metadata -.recommenders +Servers +*/target/ +.project +.settings +.metadata +.recommenders .classpath \ No newline at end of file diff --git a/Servers/Tomcat v7.0 Server at localhost-config/server.xml b/Servers/Tomcat v7.0 Server at localhost-config/server.xml deleted file mode 100644 index 950c3e0..0000000 --- a/Servers/Tomcat v7.0 Server at localhost-config/server.xml +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/si-modules/DM_Web_Server/.classpath b/si-modules/DM_Web_Server/.classpath deleted file mode 100644 index 28e4a52..0000000 --- a/si-modules/DM_Web_Server/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/ApiController.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/ApiController.java index 5c78373..cd42f1f 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/ApiController.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/ApiController.java @@ -1,813 +1,813 @@ -package net.herit.business.api; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.LinkedBlockingDeque; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; - -import net.herit.business.api.service.ApiHdmDAO; -import net.herit.business.api.service.ApiHdpDAO; -import net.herit.business.api.service.DatabaseService; -import net.herit.business.api.service.FileUploadVO; -import net.herit.business.api.service.LWM2MApiService; -import net.herit.business.api.service.OneM2MApiService; -import net.herit.business.api.service.OpenApiService; -import net.herit.business.api.service.TR069ApiService; -import net.herit.business.device.service.DeviceModelVO; -import net.herit.business.device.service.DeviceVO; -import net.herit.business.device.service.ExtMoProfileVO; -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.device.service.ParameterVO; -import net.herit.business.firmware.service.FirmwareDAO; -import net.herit.business.firmware.service.FirmwareService; -import net.herit.business.protocol.HttpConnector; -import net.herit.business.protocol.lwm2m.Util; -import net.herit.business.protocol.tr069.CurlOperation; -import net.herit.common.conf.HeritProperties; -import net.herit.common.exception.UserSysException; -import net.herit.common.model.ErrorVO; -import net.herit.common.model.HeritFormBasedFileVO; -import net.herit.common.util.HeritFileUploadUtil; -import net.herit.common.util.PagingUtil; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.DefaultHttpClient; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartHttpServletRequest; - -import com.oreilly.servlet.MultipartRequest; - -@Controller -@RequestMapping(value = "/api") -public class ApiController { - - @Resource(name = "DatabaseService") - private DatabaseService databaseService; - @Resource(name = "OpenApiService") - private OpenApiService openApiService; - @Resource(name = "LWM2MApiService") - private LWM2MApiService lwm2mApiService; - @Resource(name = "TR069ApiService") - private TR069ApiService tr069ApiService; - @Resource(name = "ApiHdmDAO") - private ApiHdmDAO hdmDAO; - @Resource(name="ApiHdpDAO") - private ApiHdpDAO hdpDAO; - @Resource(name = "FirmwareService") - private FirmwareService firmwareService; - @Resource(name = "FirmwareDAO") - private FirmwareDAO fdao; - - /** 이미지경로를 위한 URL */ - private final String hostUrl = HeritProperties - .getProperty("Globals.hostUrl"); - /** 톰캣 위치 지정 */ - private final String tomcatDir = HeritProperties - .getProperty("Globals.tomcatDir"); - /** 첨부파일 위치 지정 */ - private final String uploadDir = HeritProperties - .getProperty("Globals.uploadDir"); - - private final String firmwareDir = HeritProperties - .getProperty("Globals.firmwareDir"); - - private final long maxFileSize = 1024 * 1024 * 100; - - public final static String INVALID_PARAM = "101"; - public final static String DUPLICATED_DEVICE_ID = "102"; - - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/{data}/{operation}") - public Map get(@PathVariable("system") String system, - @PathVariable("domain") String domain, - @PathVariable("data") String data, - @PathVariable("operation") String operation, - HttpServletRequest request) throws Exception { - - System.out.println("##### get in! "+system+"/"+domain+"/"+data+"/"+operation); - Map response = new HashMap(); - - HashMap param = new HashMap(); - - // URL Sample: /hdp/deviceModel/info/get - // URL Sample: /hdm/device/info/list - /* - * HttpSession session = request.getSession(false); if(session != null){ - * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization) - * session.getAttribute("requestAuth"); - * if(!requestAuth.getAuthorizationDBRead().equals("1")){ - * - * response.put("result", 505); response.put("errorCode", 505); - * response.put("content", "Permission denied"); - * response.put("parameter", param); return response; } } - */ - Enumeration names = request.getParameterNames(); - - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = request.getParameter(name); - param.put(name, value); - } - System.out.println(param); - - try { - - Map content = databaseService.execute(system, - domain, data, operation, param); - System.out.println(content); - - response.put("result", 0); - response.put("errorCode", 0); - response.put("content", content); - response.put("parameter", param); - - } catch (UserSysException ex) { - ex.printStackTrace(); - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", param); - - } catch (Exception ex) { - ex.printStackTrace(); - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("parameter", param); - } - - return response; - } - - @SuppressWarnings("unchecked") - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/{operation}") - public Map execute( - @RequestBody String bodyString, - @PathVariable("system") String system, - @PathVariable("domain") String domain, - @PathVariable("operation") String operation, - HttpServletRequest request) throws Exception { - - System.out.println("##### get in222! "+system+"/"+domain+"/"+operation); - - Map response = new HashMap(); - HashMap param = new HashMap(); - /* - * HttpSession session = request.getSession(false); if(session != null){ - * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization) - * session.getAttribute("requestAuth"); - * if(!requestAuth.getAuthorizationDBRead().equals("1")){ - * - * response.put("result", 505); response.put("errorCode", 505); - * response.put("content", "Permission denied"); - * response.put("parameter", param); return response; } } - */ - - Enumeration names = request.getParameterNames(); - - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = request.getParameter(name); - param.put(name, value); - } - - //TODO:body 안에 있는 정보를 가져와야 햄. - HashMap contentMap = new ObjectMapper().readValue(bodyString, HashMap.class); - - String deviceId = contentMap.containsKey("d") ? (String) contentMap.get("d") : null; - if (deviceId == null || "".equals(deviceId)) { - /** oneM2M 서버에서 검색 */ - if (operation.equals("discovery")) { - String sn = (String) contentMap.get("sn"); - - OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance(); - HashMap content = oneM2MSvc.discovery(operation, sn); - - ArrayList> eList = new ArrayList>(); - LinkedHashMap snContent = new LinkedHashMap(); - - snContent.put("o", "d"); - snContent.put("r", "200");//XXX - snContent.put("devId", content); - - response.put("result", 0); - response.put("content", snContent); - System.out.println("response (discovery) : " + response.toString()); - return response; - } - } - - System.out.println("deviceId:" + deviceId); - System.out.println("WHY"); - DeviceVO deviceInfo = hdmDAO.getDeviceInfo(deviceId); - - System.out.println("deviceInfo is null? : " + deviceInfo == null); - - int dmType = deviceInfo.getDmType(); - String extDeviceId = deviceInfo.getExtDeviceId(); - String modelName = deviceInfo.getModelName(); - DeviceModelVO deviceModelInfo = hdpDAO.getDeviceModelId(modelName); - String deviceModelId = deviceModelInfo.getId(); - System.out.println("dmType : " + dmType); - System.out.println("extDeviceId : " + extDeviceId); - System.out.println("modelName : " + modelName); - System.out.println("deviceModelId : " + deviceModelId); - - System.err.println("#########################################"); - System.err.println(" TEST :: dmType :: "+dmType); - System.err.println("#########################################"); - - String body = null; - if (dmType == 0) { - try { - - // body = getBody(request); - HashMap content = openApiService.execute(operation, bodyString); - - System.err.println(content.toString()); - if (content.get("exception") == null - && (Integer) content.get("status") == 200) { - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - } else if (content.get("exception") == null - && (Integer) content.get("status") != 200) { - response.put("result", 1); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - } else { - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("exception").toString()); - // response.put("exception", content.get("exception")); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - // response.put("json", content.get("json")); - } - - } catch (UserSysException ex) { - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", param); - - } catch (Exception ex) { - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("requestBody", body); - } - } else if (dmType == 1) {//oneM2M서버 - try { - //body data - ArrayList> resourceList = contentMap.containsKey("e") ? (ArrayList>) contentMap.get("e") : null; - if (resourceList == null || resourceList.isEmpty()) { - // 예외처리 - } - System.out.println("e:" + resourceList.toString()); - - ArrayList resUris = new ArrayList(); - String executeCont = null; - for (int i=0; i < resourceList.size(); i++) { - System.out.println("contentList:" + resourceList.get(i)); - - HashMap resUri = resourceList.get(i); - String resource = resUri.get("n"); - System.out.println("resource:" + resource); - - //execute 명령에 대한 웹 제어 데이터 - executeCont = resUri.get("sv"); - System.out.println("executeCont:" + executeCont); - - MoProfileVO moProfileInfo = hdpDAO.getMoProfileId(deviceModelId, resource); - String moProfileId = moProfileInfo.getId(); - System.out.println("moProfileId : " + moProfileId); - - ExtMoProfileVO extInfo = hdpDAO.getResUriNameInfo(moProfileId); - System.out.println("extInfo:" + extInfo.getExtResourceUri()); - - String resourceUri = extDeviceId +"/"+ extInfo.getExtResourceUri(); - System.out.println("resourceUri:" + resourceUri); - - resUris.add(resourceUri); - } - - System.out.println("resUris:" + resUris.toString()); - - //oneM2M 서버 - OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance(); - HashMap content = oneM2MSvc.execute(operation, resUris, extDeviceId, executeCont); - - //dm서버와 같은 데이터 형식으로 만들어서 구현 - ArrayList to = new ArrayList(); - ArrayList ct = new ArrayList(); - for(int j=0; j < resUris.size(); j++) { - to.add((String) content.get(resUris.get(j))); - ct.add((String) content.get(resUris.get(j)+"_"+j)); - System.out.println(resUris.get(j) + content.get(resUris.get(j))); - System.out.println(resUris.get(j)+"_"+j + content.get(resUris.get(j)+"_"+j)); - } - - ArrayList> eList = new ArrayList>(); - - LinkedHashMap resContent = new LinkedHashMap(); - HashMap resDatas = new HashMap(); - - resContent.put("o", (String)content.get("o")); - resContent.put("r", "200");//XXX - for(int k=0; k < resourceList.size(); k++) { - resDatas = resourceList.get(k); - String resData = resDatas.get("n"); - HashMap dataMap = new HashMap(); - dataMap.put("n", resData); - dataMap.put("sv", to.get(k)); - dataMap.put("ti", ct.get(k)); - eList.add(dataMap); - } - resContent.put("e", eList); - /*ObjectMapper mapper = new ObjectMapper(); - Object json = mapper.writeValueAsString(resContent);*/ - response.put("result", 0); - response.put("errorCode", "200"); - response.put("content", resContent); - - - //System.out.println("=================" + response.toString()); - - } catch (Exception ex) { - System.out.println("ex :" + ex); - } - } else if (dmType == 2) { // LWM2M Server - try { - - String op = "r"; - if(operation.equals("write")){ - op = "e"; - } else if(operation.equals("reboot")) { - op = "rb"; - } - contentMap.put("o", op); - HashMap content = lwm2mApiService.execute(operation, contentMap, deviceInfo.getAuthId()); - - - //* - if (content.get("exception") == null - && (Integer) content.get("status") == 200) { - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - } else if (content.get("exception") == null - && (Integer) content.get("status") != 200) { - response.put("result", 1); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - } else { - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("exception").toString()); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - }//*/ - - System.out.println("CONTENT : " + content.toString()); - System.out.println("RESPONSE : " + response); - - } catch (UserSysException ex) { - ex.printStackTrace(); - - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", param); - - } catch (Exception ex) { - ex.printStackTrace(); - - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("requestBody", body); - } - - } else if (dmType == 3) { // TR-069 Server - - System.out.println("##### operation : "+operation); - System.out.println("##### bodyString : "+bodyString); - System.out.println("##### contentMap : "+contentMap); - - HashMap content = null; - - try{ - content = tr069ApiService.execute2(operation, new JSONObject(bodyString)); - System.out.println("::::::::::::::::::::::::::::::::::"); - System.out.println(content); - if (content.get("exception") == null && (Integer) content.get("status") == 200) { - - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - } else if (content.get("exception") == null && (Integer) content.get("status") != 200) { - response.put("result", 1); - response.put("errorCode", content.get("status")); - response.put("content", content.get("json")); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - } else { - response.put("result", 0); - response.put("errorCode", content.get("status")); - response.put("content", content.get("exception").toString()); - response.put("requestBody", body); - response.put("responseBody", content.get("body")); - } - } /*catch (UserSysException ex) { - ex.printStackTrace(); - System.out.println(ex); - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", param); - - }*/ catch (Exception ex) { - ex.printStackTrace(); - System.out.println(ex); - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("requestBody", body); - } - - System.out.println("[ CONTENT_OUT ] : "+content); - System.out.println("[ RESPONSE_OUT ] : "+response); - - } - - return response; - } - - // HERE FIRMWARE VERSION INSERT, UPDATE - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/upload") - public String uploadFirmware( - @PathVariable("system") String system, - @PathVariable("domain") String domain, - HttpServletRequest request) { - //throws Exception { - - String returnMsg = "success"; - Map response = new HashMap(); - - try{ - System.out.println("##### get in444! "+system+"/"+domain); - - String savePath = ""; - System.out.println(firmwareDir); - System.out.println(tomcatDir+uploadDir); - System.out.println("ddddddddd3333"); - - MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; - String originalFileName = mptRequest.getFile("packageName").getOriginalFilename(); - System.out.println(originalFileName); - File dir = new File(originalFileName); - - if (!dir.exists()) { - dir.mkdir(); - } - - String directory = null; - int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); - if( fileType == 1 ){ - directory = firmwareDir; - } else { - directory = tomcatDir+uploadDir; - } - - System.out.println("middle test : " +dir); - List result = HeritFileUploadUtil.filesUpload(request, directory, maxFileSize); - System.out.println(result.size()); - - String res = null; - HttpConnector hc = new HttpConnector(); - res = hc.sendFile(mptRequest); - System.out.println("---- res : "+res); - /* - hc.sendFileWithCurl(); - - - if( result.size() > 0 ){ - - CurlOperation co = new CurlOperation(); - co.setHeader("fileType", mptRequest.getParameter("fileType")); - co.setHeader("oui", mptRequest.getParameter("oui")); - co.setHeader("productClass", mptRequest.getParameter("productClass")); - co.setHeader("version", mptRequest.getParameter("version")); - - Object[] params = new Object[3]; - params[0] = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort"); - params[1] = co.getHeader(); - params[2] = firmwareDir+dir.getName(); - - res = co.send("file upload", params); - System.out.println(res); - }*/ - - if(res != null && res.indexOf("201") > -1){ - int deviceModelId = Integer.parseInt(mptRequest.getParameter("deviceModel")); - //long fileSize = dir.length(); - long fileSize = result.get(0).getSize(); - System.out.println("######################## file size "); - System.out.println(fileSize); - int fwId = 0; - String fileName = originalFileName; - String version = mptRequest.getParameter("version"); - String description = mptRequest.getParameter("description"); - - fwId = fdao.getFirmwareId(deviceModelId, fileType); - int fvCount = 0; - if(fwId == 0){ - fwId = fdao.addFirmwareInfo(deviceModelId, fileName, fileType, description); - fdao.addFirmwareVersion(fwId, version, fileSize); - } else { - fvCount = fdao.getFirmwareVersionCount(fwId, mptRequest.getParameter("version")); - if(fvCount == 0){ - fdao.addFirmwareVersion(fwId, version, fileSize); - } - } - } - - } catch (Exception ex) { - ex.printStackTrace(); - returnMsg = ex.getMessage(); - } - - return returnMsg; - } - - // HERE FIRMWARE VERSION INSERT, UPDATE - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/{data}/upload") - public Map upload( - @PathVariable("system") String system, - @PathVariable("domain") String domain, - @PathVariable("data") String data, HttpServletRequest request) - throws Exception { - - System.out.println("##### get in333! "+system+"/"+domain+"/"+data); - - Map response = new HashMap(); - HashMap param = new HashMap(); - - Enumeration names = request.getParameterNames(); - - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = request.getParameter(name); - System.out.println("name value : " + name + " , " + value); - param.put(name, value); - } - - FileUploadVO fileUploadVO = new FileUploadVO(); - - List fileUploadList = new ArrayList(); - - // List list = - // HeritFileUploadUtil.filesUpload(request, fileDir, maxFileSize); - String fileUploadDir = ""; - - List list = null; - if (domain.equalsIgnoreCase("firmware")) { - - String dirPackageName = (String) param.get("packageName"); - System.out.println("dirPackageName : " + dirPackageName); - File dir = new File(dirPackageName); - - if (!dir.exists()) { - dir.mkdir(); - } - - String fileDir = firmwareDir + dir; - System.out.println("fileDir " + fileDir); - - fileUploadDir = firmwareDir; - list = HeritFileUploadUtil.filesUpload(request, fileDir, - maxFileSize); - } else { - fileUploadDir = tomcatDir + uploadDir; - list = HeritFileUploadUtil.uploadFiles(request, fileUploadDir, - maxFileSize); - } - - if (list.size() > 0) { - for (int i = 0; i < list.size(); i++) { - HeritFormBasedFileVO vo = list.get(i); - - fileUploadVO.setFileRealName(vo.getFileName()); - fileUploadVO.setFilePhysName(vo.getPhysicalName()); - fileUploadVO.setFileSize(String.valueOf(vo.getSize())); - fileUploadList.add(fileUploadVO); - } - } - // js에 보내질 url 경로 - // param.put("fileUploadDir", fileUploadDir); - param.put("hostUrl", hostUrl); - param.put("uploadDir", uploadDir); - - try { - - Map content = databaseService.upload(system, - domain, data, param, fileUploadList); - - response.put("result", 0); - response.put("errorCode", 0); - response.put("content", content); - response.put("parameter", param); - - } catch (UserSysException ex) { - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", param); - - } catch (Exception ex) { - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("parameter", param); - } - return response; - } - - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/{data}/{operation}/json") - public Map getJson( - @RequestBody Map paramMap, - @PathVariable("system") String system, - @PathVariable("domain") String domain, - @PathVariable("data") String data, - @PathVariable("operation") String operation, - HttpServletRequest request) throws Exception { - - Map response = new HashMap(); - HashMap param = new HashMap(); - - try { - - Map content = databaseService.execute(system, - domain, data, operation, paramMap); - - response.put("result", 0); - response.put("errorCode", 0); - response.put("content", content); - response.put("parameter", paramMap); - - } catch (UserSysException ex) { - ErrorVO err = ex.getErrorVO(); - response.put("result", 1); - response.put("errorCode", err.getErrorCode()); - response.put("content", err.getErrorMessage()); - response.put("parameter", paramMap); - - } catch (Exception ex) { - response.put("result", 1); - response.put("errorCode", -1); - response.put("content", ex.toString()); - response.put("exception", ex); - response.put("parameter", paramMap); - } - - return response; - } - - /*public static void main(String[] a) throws JsonGenerationException, JsonMappingException, IOException { - HashMap map = new HashMap(); - map.put("a", "aaa"); - map.put("b", "bbb"); - - ObjectMapper mapper = new ObjectMapper(); - Object json = mapper.writeValueAsString(map); - - System.out.println("json: " + json.toString()); - }*/ - - /* - @SuppressWarnings("unchecked") - @ResponseBody - @RequestMapping(value = "/{system}/{domain}/{operation}/json") - public Map dbHandler( - @RequestBody String bodyString, - @PathVariable("system") String system, - @PathVariable("domain") String domain, - @PathVariable("operation") String operation, - HttpServletRequest request) throws Exception { - - HashMap param = new HashMap(); - - Enumeration names = request.getParameterNames(); - - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = request.getParameter(name); - param.put(name, value); - } - - - return null; - } - */ - - @ResponseBody - @RequestMapping(value = "/firmware/list.do") - //public Map getFirmwareList(ParameterVO po, HttpServletRequest request) throws Exception { - public Map getFirmwareList(@RequestBody String bodyString, HttpServletRequest request) throws Exception { - System.out.println("값 체크"); - Map response = new HashMap(); - - - - //* - JSONObject param = new JSONObject(bodyString); - System.out.println(bodyString); - System.out.println(param); - System.out.println("@@@@@@@@@@@@@@@@@@@"); - ParameterVO po = new ParameterVO(); - try{ - po.setSn(param.getString("sn")); - po.setDeviceModel(String.valueOf(param.getInt("deviceModel"))); - po.setOui(param.getString("oui")); - po.setModelName(param.getString("modelName"));//*/ - - Method[] methods = po.getClass().getMethods(); - for(int i=0; i get(@PathVariable("system") String system, + @PathVariable("domain") String domain, + @PathVariable("data") String data, + @PathVariable("operation") String operation, + HttpServletRequest request) throws Exception { + + System.out.println("##### get in! "+system+"/"+domain+"/"+data+"/"+operation); + Map response = new HashMap(); + + HashMap param = new HashMap(); + + // URL Sample: /hdp/deviceModel/info/get + // URL Sample: /hdm/device/info/list + /* + * HttpSession session = request.getSession(false); if(session != null){ + * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization) + * session.getAttribute("requestAuth"); + * if(!requestAuth.getAuthorizationDBRead().equals("1")){ + * + * response.put("result", 505); response.put("errorCode", 505); + * response.put("content", "Permission denied"); + * response.put("parameter", param); return response; } } + */ + Enumeration names = request.getParameterNames(); + + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = request.getParameter(name); + param.put(name, value); + } + System.out.println(param); + + try { + + Map content = databaseService.execute(system, + domain, data, operation, param); + System.out.println(content); + + response.put("result", 0); + response.put("errorCode", 0); + response.put("content", content); + response.put("parameter", param); + + } catch (UserSysException ex) { + ex.printStackTrace(); + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", param); + + } catch (Exception ex) { + ex.printStackTrace(); + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("parameter", param); + } + + return response; + } + + @SuppressWarnings("unchecked") + @ResponseBody + @RequestMapping(value = "/{system}/{domain}/{operation}") + public Map execute( + @RequestBody String bodyString, + @PathVariable("system") String system, + @PathVariable("domain") String domain, + @PathVariable("operation") String operation, + HttpServletRequest request) throws Exception { + + System.out.println("##### get in222! "+system+"/"+domain+"/"+operation); + + Map response = new HashMap(); + HashMap param = new HashMap(); + /* + * HttpSession session = request.getSession(false); if(session != null){ + * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization) + * session.getAttribute("requestAuth"); + * if(!requestAuth.getAuthorizationDBRead().equals("1")){ + * + * response.put("result", 505); response.put("errorCode", 505); + * response.put("content", "Permission denied"); + * response.put("parameter", param); return response; } } + */ + + Enumeration names = request.getParameterNames(); + + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = request.getParameter(name); + param.put(name, value); + } + + //TODO:body 안에 있는 정보를 가져와야 햄. + HashMap contentMap = new ObjectMapper().readValue(bodyString, HashMap.class); + + String deviceId = contentMap.containsKey("d") ? (String) contentMap.get("d") : null; + if (deviceId == null || "".equals(deviceId)) { + /** oneM2M 서버에서 검색 */ + if (operation.equals("discovery")) { + String sn = (String) contentMap.get("sn"); + + OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance(); + HashMap content = oneM2MSvc.discovery(operation, sn); + + ArrayList> eList = new ArrayList>(); + LinkedHashMap snContent = new LinkedHashMap(); + + snContent.put("o", "d"); + snContent.put("r", "200");//XXX + snContent.put("devId", content); + + response.put("result", 0); + response.put("content", snContent); + System.out.println("response (discovery) : " + response.toString()); + return response; + } + } + + System.out.println("deviceId:" + deviceId); + System.out.println("WHY"); + DeviceVO deviceInfo = hdmDAO.getDeviceInfo(deviceId); + + System.out.println("deviceInfo is null? : " + deviceInfo == null); + + int dmType = deviceInfo.getDmType(); + String extDeviceId = deviceInfo.getExtDeviceId(); + String modelName = deviceInfo.getModelName(); + DeviceModelVO deviceModelInfo = hdpDAO.getDeviceModelId(modelName); + String deviceModelId = deviceModelInfo.getId(); + System.out.println("dmType : " + dmType); + System.out.println("extDeviceId : " + extDeviceId); + System.out.println("modelName : " + modelName); + System.out.println("deviceModelId : " + deviceModelId); + + System.err.println("#########################################"); + System.err.println(" TEST :: dmType :: "+dmType); + System.err.println("#########################################"); + + String body = null; + if (dmType == 0) { + try { + + // body = getBody(request); + HashMap content = openApiService.execute(operation, bodyString); + + System.err.println(content.toString()); + if (content.get("exception") == null + && (Integer) content.get("status") == 200) { + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + } else if (content.get("exception") == null + && (Integer) content.get("status") != 200) { + response.put("result", 1); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + } else { + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("exception").toString()); + // response.put("exception", content.get("exception")); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + // response.put("json", content.get("json")); + } + + } catch (UserSysException ex) { + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", param); + + } catch (Exception ex) { + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("requestBody", body); + } + } else if (dmType == 1) {//oneM2M서버 + try { + //body data + ArrayList> resourceList = contentMap.containsKey("e") ? (ArrayList>) contentMap.get("e") : null; + if (resourceList == null || resourceList.isEmpty()) { + // 예외처리 + } + System.out.println("e:" + resourceList.toString()); + + ArrayList resUris = new ArrayList(); + String executeCont = null; + for (int i=0; i < resourceList.size(); i++) { + System.out.println("contentList:" + resourceList.get(i)); + + HashMap resUri = resourceList.get(i); + String resource = resUri.get("n"); + System.out.println("resource:" + resource); + + //execute 명령에 대한 웹 제어 데이터 + executeCont = resUri.get("sv"); + System.out.println("executeCont:" + executeCont); + + MoProfileVO moProfileInfo = hdpDAO.getMoProfileId(deviceModelId, resource); + String moProfileId = moProfileInfo.getId(); + System.out.println("moProfileId : " + moProfileId); + + ExtMoProfileVO extInfo = hdpDAO.getResUriNameInfo(moProfileId); + System.out.println("extInfo:" + extInfo.getExtResourceUri()); + + String resourceUri = extDeviceId +"/"+ extInfo.getExtResourceUri(); + System.out.println("resourceUri:" + resourceUri); + + resUris.add(resourceUri); + } + + System.out.println("resUris:" + resUris.toString()); + + //oneM2M 서버 + OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance(); + HashMap content = oneM2MSvc.execute(operation, resUris, extDeviceId, executeCont); + + //dm서버와 같은 데이터 형식으로 만들어서 구현 + ArrayList to = new ArrayList(); + ArrayList ct = new ArrayList(); + for(int j=0; j < resUris.size(); j++) { + to.add((String) content.get(resUris.get(j))); + ct.add((String) content.get(resUris.get(j)+"_"+j)); + System.out.println(resUris.get(j) + content.get(resUris.get(j))); + System.out.println(resUris.get(j)+"_"+j + content.get(resUris.get(j)+"_"+j)); + } + + ArrayList> eList = new ArrayList>(); + + LinkedHashMap resContent = new LinkedHashMap(); + HashMap resDatas = new HashMap(); + + resContent.put("o", (String)content.get("o")); + resContent.put("r", "200");//XXX + for(int k=0; k < resourceList.size(); k++) { + resDatas = resourceList.get(k); + String resData = resDatas.get("n"); + HashMap dataMap = new HashMap(); + dataMap.put("n", resData); + dataMap.put("sv", to.get(k)); + dataMap.put("ti", ct.get(k)); + eList.add(dataMap); + } + resContent.put("e", eList); + /*ObjectMapper mapper = new ObjectMapper(); + Object json = mapper.writeValueAsString(resContent);*/ + response.put("result", 0); + response.put("errorCode", "200"); + response.put("content", resContent); + + + //System.out.println("=================" + response.toString()); + + } catch (Exception ex) { + System.out.println("ex :" + ex); + } + } else if (dmType == 2) { // LWM2M Server + try { + + String op = "r"; + if(operation.equals("write")){ + op = "e"; + } else if(operation.equals("reboot")) { + op = "rb"; + } + contentMap.put("o", op); + HashMap content = lwm2mApiService.execute(operation, contentMap, deviceInfo.getAuthId()); + + + //* + if (content.get("exception") == null + && (Integer) content.get("status") == 200) { + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + } else if (content.get("exception") == null + && (Integer) content.get("status") != 200) { + response.put("result", 1); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + } else { + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("exception").toString()); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + }//*/ + + System.out.println("CONTENT : " + content.toString()); + System.out.println("RESPONSE : " + response); + + } catch (UserSysException ex) { + ex.printStackTrace(); + + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", param); + + } catch (Exception ex) { + ex.printStackTrace(); + + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("requestBody", body); + } + + } else if (dmType == 3) { // TR-069 Server + + System.out.println("##### operation : "+operation); + System.out.println("##### bodyString : "+bodyString); + System.out.println("##### contentMap : "+contentMap); + + HashMap content = null; + + try{ + content = tr069ApiService.execute2(operation, new JSONObject(bodyString)); + System.out.println("::::::::::::::::::::::::::::::::::"); + System.out.println(content); + if (content.get("exception") == null && (Integer) content.get("status") == 200) { + + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + } else if (content.get("exception") == null && (Integer) content.get("status") != 200) { + response.put("result", 1); + response.put("errorCode", content.get("status")); + response.put("content", content.get("json")); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + } else { + response.put("result", 0); + response.put("errorCode", content.get("status")); + response.put("content", content.get("exception").toString()); + response.put("requestBody", body); + response.put("responseBody", content.get("body")); + } + } /*catch (UserSysException ex) { + ex.printStackTrace(); + System.out.println(ex); + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", param); + + }*/ catch (Exception ex) { + ex.printStackTrace(); + System.out.println(ex); + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("requestBody", body); + } + + System.out.println("[ CONTENT_OUT ] : "+content); + System.out.println("[ RESPONSE_OUT ] : "+response); + + } + + return response; + } + + // HERE FIRMWARE VERSION INSERT, UPDATE + @ResponseBody + @RequestMapping(value = "/{system}/{domain}/upload") + public String uploadFirmware( + @PathVariable("system") String system, + @PathVariable("domain") String domain, + HttpServletRequest request) { + //throws Exception { + + String returnMsg = "success"; + Map response = new HashMap(); + + try{ + System.out.println("##### get in444! "+system+"/"+domain); + + String savePath = ""; + System.out.println(firmwareDir); + System.out.println(tomcatDir+uploadDir); + System.out.println("ddddddddd3333"); + + MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; + String originalFileName = mptRequest.getFile("packageName").getOriginalFilename(); + System.out.println(originalFileName); + File dir = new File(originalFileName); + + if (!dir.exists()) { + dir.mkdir(); + } + + String directory = null; + int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); + if( fileType == 1 ){ + directory = firmwareDir; + } else { + directory = tomcatDir+uploadDir; + } + + System.out.println("middle test : " +dir); + List result = HeritFileUploadUtil.filesUpload(request, directory, maxFileSize); + System.out.println(result.size()); + + String res = null; + HttpConnector hc = new HttpConnector(); + res = hc.sendFile(mptRequest); + System.out.println("---- res : "+res); + /* + hc.sendFileWithCurl(); + + + if( result.size() > 0 ){ + + CurlOperation co = new CurlOperation(); + co.setHeader("fileType", mptRequest.getParameter("fileType")); + co.setHeader("oui", mptRequest.getParameter("oui")); + co.setHeader("productClass", mptRequest.getParameter("productClass")); + co.setHeader("version", mptRequest.getParameter("version")); + + Object[] params = new Object[3]; + params[0] = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort"); + params[1] = co.getHeader(); + params[2] = firmwareDir+dir.getName(); + + res = co.send("file upload", params); + System.out.println(res); + }*/ + + if(res != null && res.indexOf("201") > -1){ + int deviceModelId = Integer.parseInt(mptRequest.getParameter("deviceModel")); + //long fileSize = dir.length(); + long fileSize = result.get(0).getSize(); + System.out.println("######################## file size "); + System.out.println(fileSize); + int fwId = 0; + String fileName = originalFileName; + String version = mptRequest.getParameter("version"); + String description = mptRequest.getParameter("description"); + + fwId = fdao.getFirmwareId(deviceModelId, fileType); + int fvCount = 0; + if(fwId == 0){ + fwId = fdao.addFirmwareInfo(deviceModelId, fileName, fileType, description); + fdao.addFirmwareVersion(fwId, version, fileSize); + } else { + fvCount = fdao.getFirmwareVersionCount(fwId, mptRequest.getParameter("version")); + if(fvCount == 0){ + fdao.addFirmwareVersion(fwId, version, fileSize); + } + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + returnMsg = ex.getMessage(); + } + + return returnMsg; + } + + // HERE FIRMWARE VERSION INSERT, UPDATE + @ResponseBody + @RequestMapping(value = "/{system}/{domain}/{data}/upload") + public Map upload( + @PathVariable("system") String system, + @PathVariable("domain") String domain, + @PathVariable("data") String data, HttpServletRequest request) + throws Exception { + + System.out.println("##### get in333! "+system+"/"+domain+"/"+data); + + Map response = new HashMap(); + HashMap param = new HashMap(); + + Enumeration names = request.getParameterNames(); + + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = request.getParameter(name); + System.out.println("name value : " + name + " , " + value); + param.put(name, value); + } + + FileUploadVO fileUploadVO = new FileUploadVO(); + + List fileUploadList = new ArrayList(); + + // List list = + // HeritFileUploadUtil.filesUpload(request, fileDir, maxFileSize); + String fileUploadDir = ""; + + List list = null; + if (domain.equalsIgnoreCase("firmware")) { + + String dirPackageName = (String) param.get("packageName"); + System.out.println("dirPackageName : " + dirPackageName); + File dir = new File(dirPackageName); + + if (!dir.exists()) { + dir.mkdir(); + } + + String fileDir = firmwareDir + dir; + System.out.println("fileDir " + fileDir); + + fileUploadDir = firmwareDir; + list = HeritFileUploadUtil.filesUpload(request, fileDir, + maxFileSize); + } else { + fileUploadDir = tomcatDir + uploadDir; + list = HeritFileUploadUtil.uploadFiles(request, fileUploadDir, + maxFileSize); + } + + if (list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + HeritFormBasedFileVO vo = list.get(i); + + fileUploadVO.setFileRealName(vo.getFileName()); + fileUploadVO.setFilePhysName(vo.getPhysicalName()); + fileUploadVO.setFileSize(String.valueOf(vo.getSize())); + fileUploadList.add(fileUploadVO); + } + } + // js에 보내질 url 경로 + // param.put("fileUploadDir", fileUploadDir); + param.put("hostUrl", hostUrl); + param.put("uploadDir", uploadDir); + + try { + + Map content = databaseService.upload(system, + domain, data, param, fileUploadList); + + response.put("result", 0); + response.put("errorCode", 0); + response.put("content", content); + response.put("parameter", param); + + } catch (UserSysException ex) { + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", param); + + } catch (Exception ex) { + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("parameter", param); + } + return response; + } + + @ResponseBody + @RequestMapping(value = "/{system}/{domain}/{data}/{operation}/json") + public Map getJson( + @RequestBody Map paramMap, + @PathVariable("system") String system, + @PathVariable("domain") String domain, + @PathVariable("data") String data, + @PathVariable("operation") String operation, + HttpServletRequest request) throws Exception { + + Map response = new HashMap(); + HashMap param = new HashMap(); + + try { + + Map content = databaseService.execute(system, + domain, data, operation, paramMap); + + response.put("result", 0); + response.put("errorCode", 0); + response.put("content", content); + response.put("parameter", paramMap); + + } catch (UserSysException ex) { + ErrorVO err = ex.getErrorVO(); + response.put("result", 1); + response.put("errorCode", err.getErrorCode()); + response.put("content", err.getErrorMessage()); + response.put("parameter", paramMap); + + } catch (Exception ex) { + response.put("result", 1); + response.put("errorCode", -1); + response.put("content", ex.toString()); + response.put("exception", ex); + response.put("parameter", paramMap); + } + + return response; + } + + /*public static void main(String[] a) throws JsonGenerationException, JsonMappingException, IOException { + HashMap map = new HashMap(); + map.put("a", "aaa"); + map.put("b", "bbb"); + + ObjectMapper mapper = new ObjectMapper(); + Object json = mapper.writeValueAsString(map); + + System.out.println("json: " + json.toString()); + }*/ + + /* + @SuppressWarnings("unchecked") + @ResponseBody + @RequestMapping(value = "/{system}/{domain}/{operation}/json") + public Map dbHandler( + @RequestBody String bodyString, + @PathVariable("system") String system, + @PathVariable("domain") String domain, + @PathVariable("operation") String operation, + HttpServletRequest request) throws Exception { + + HashMap param = new HashMap(); + + Enumeration names = request.getParameterNames(); + + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = request.getParameter(name); + param.put(name, value); + } + + + return null; + } + */ + + @ResponseBody + @RequestMapping(value = "/firmware/list.do") + //public Map getFirmwareList(ParameterVO po, HttpServletRequest request) throws Exception { + public Map getFirmwareList(@RequestBody String bodyString, HttpServletRequest request) throws Exception { + System.out.println("값 체크"); + Map response = new HashMap(); + + + + //* + JSONObject param = new JSONObject(bodyString); + System.out.println(bodyString); + System.out.println(param); + System.out.println("@@@@@@@@@@@@@@@@@@@"); + ParameterVO po = new ParameterVO(); + try{ + po.setSn(param.getString("sn")); + po.setDeviceModel(String.valueOf(param.getInt("deviceModel"))); + po.setOui(param.getString("oui")); + po.setModelName(param.getString("modelName"));//*/ + + Method[] methods = po.getClass().getMethods(); + for(int i=0; i getList(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "getList"; - List resultList = null; - - try { - resultList = getSqlMapClientTemplate().queryForList( - "DeviceDAO.deviceList", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultList; - } - - public Object get(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "get"; - - HashMap result = null; - try { - result = (HashMap)getSqlMapClientTemplate().queryForObject( - "DeviceDAO.deviceCount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - - return result; - } - - //추가 - public DeviceVO getDeviceInfo(String deviceId) throws UserSysException { - METHOD_NAME = "getDeviceInfo"; - - DeviceVO resultVO = null; - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - - System.out.println("11111111111111"); - resultVO = (DeviceVO)getSqlMapClientTemplate().queryForObject("DeviceDAO.device", po); - System.out.println("22222222222222"); - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultVO; - } - - /*public HashMap getDeviceInfo(String deviceId) throws UserSysException { - METHOD_NAME = "getDeviceInfo"; - - HashMap resultMap = null; - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - - resultMap = (HashMap)getSqlMapClientTemplate().queryForObject( - "DeviceDAO.deviceInfo", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultMap; - }*/ - - - public ProcessResult update(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "update"; - - ProcessResult result = null; - - - return result; - } - - public ProcessResult insert(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "insert"; - - ProcessResult result = null; - - - return result; - } - - public ProcessResult delete(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "delete"; - - ProcessResult result = null; - - - return result; - } - - - /**************************************************** - * ETC Protocol - ****************************************************/ - - - - - /************************************************* - * lwm2m - *************************************************/ - public int getCountByAuthAccount(JSONObject token) throws UserSysException { - METHOD_NAME = "getCountByAuthAccount"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", token.getString("deviceId")); - po.put("authId", token.getString("authId")); - po.put("authPwd", token.getString("authPw")); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "device.get.count.by.authAccount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - // device Resource 갯수 파악 - public int getResourceCountByDeviceId(String deviceId) throws UserSysException { - METHOD_NAME = "getResourceCountByDeviceId"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "deviceResource.get.count.by.deviceId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - // device Resource 제거 - public boolean removeResourceByDeviceId(String deviceId) throws UserSysException { - METHOD_NAME = "removeResourceByDeviceId"; - - boolean result = false; - - try { - HashMap po = new HashMap(); - po.put("device_id", deviceId); - - int rCode = delete("deviceResource.remove.by.deviceId", po); - - if(rCode > 0){ - result = true; - } - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - // hdm_device_mo_data테이블에 데이터 추가 - public boolean insertDeviceResources(String deviceId, List unList) throws UserSysException { - METHOD_NAME = "insertDeviceResources"; - - boolean result = false; - - try { - - int rCode = 0; - for(int i=0; i po = new HashMap(); - po.put("device_id", deviceId); - po.put("resource_uri", unList.get(i).getResourceUri()); - po.put("resource_name", unList.get(i).getDisplayName()); - po.put("data", unList.get(i).getData()); - System.out.println(po.get("data")); - rCode += (Integer)insert("device.insert.resource", po); -/* if(unList.get(i).getData() != null){ - po.put("data", unList.get(i).getData()); - rCode += (Integer)insert("device.insert.resource.withData", po); - } else { - }*/ - } - - if(rCode == unList.size()){ - result = true; - } - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // hit_dev_inf_tbl테이블 deviceId로 조회한 갯수 - public int getDeviceConnStatusCount(String deviceId) throws UserSysException { - METHOD_NAME = "getDeviceConnStatusCount"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - result = (Integer)getSqlMapClientTemplate().queryForObject("device.get.count.by.deviceId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // hit_dev_inf_tbl테이블에 접속 데이터 추가 - public boolean insertDeviceConnStatus(String deviceId, String systemId) throws UserSysException { - METHOD_NAME = "insertDeviceConnStatus"; - - boolean result = false; - - try { - - HashMap po = new HashMap(); - po.put("deviceId",deviceId); - po.put("status","1"); - po.put("systemId", systemId); - - int rCode = (Integer)insert("device.insert.connStatus", po); - - if(rCode == 1){ - result = true; - } - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // hit_dev_inf_tbl테이블에 접속 상태 업데이트 - public boolean updateDeviceConnStatus(String deviceId, String status) throws UserSysException { - METHOD_NAME = "updateDeviceConnStatus"; - - boolean result = false; - - try { - - HashMap po = new HashMap(); - po.put("device_id",deviceId); - po.put("status",status); - - int rCode = (Integer)update("device.update.connStatus", po); - - if(rCode == 1){ - result = true; - } - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // hdm_device_mo_data 테이블에 데이터 update - public boolean updateDeviceResourcesData(String deviceId, HashMap map) throws UserSysException { - METHOD_NAME = "insertDeviceResources"; - - boolean result = false; - - try { - - int rCode = 0; - JSONArray arr = new JSONArray((String) map.get("body")); - for(int i=0; i resMap = new HashMap(); - - JSONObject body = arr.getJSONObject(i); - resMap.put("value", body.getJSONObject("content").getString("value")); - resMap.put("uri", body.getString("uri").replace("/0/", "/-/")); - resMap.put("device_id", deviceId); - rCode += (Integer)update("device.update.data", resMap); - - System.out.println(resMap.toString()); - } - - //rCode += (Integer)insert("device.insert.resource", po); - if(rCode == arr.length()){ - result = true; - } - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - - /********************************************* - * TR-069 - * ******************************************/ - - public boolean updateDeviceResourcesData(String deviceId, JSONObject param) throws UserSysException { - METHOD_NAME = "insertDeviceResources"; - - boolean result = false; - - try { - int rCode = 0; - - Iterator it = param.keys(); - while(it.hasNext()){ - - HashMap resMap = new HashMap(); - String uri = (String)it.next(); - String value = param.getString(uri); - - if(!uri.equals("command")){ - resMap.put("value", value); - resMap.put("uri", uri.replace(".", "/")); - resMap.put("device_id", deviceId); - update("device.update.data", resMap); - } - } - - - //rCode += (Integer)insert("device.insert.resource", po); - //if(rCode == ){ - // result = true; - //} - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - public ArrayList getResources(String deviceId, List paramList) throws UserSysException { - METHOD_NAME = "getDeviceInfo"; - - ArrayList result = null; - try { - StringBuffer listToString = new StringBuffer(); - for(int i=0; i)getSqlMapClientTemplate().queryForList("device.status.list.by.uris", po); - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - public String getHistoricalOption(String deviceId, String resourceUri, String operation) throws UserSysException { - METHOD_NAME = "getDeviceInfo"; - - String result = null; - try { - - HashMap po = new HashMap(); - po.put("operation", operation); - po.put("deviceId", deviceId); - po.put("resourceUri", resourceUri); - - result = (String)getSqlMapClientTemplate().queryForObject("get.historical.option", po); - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - public HashMap getResourceInfoByDeviceId(String deviceId, String resourceUri) throws UserSysException { - METHOD_NAME = "getDeviceInfo"; - - HashMap result = null; - try { - - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - po.put("resourceUri", resourceUri); - - result = (HashMap)getSqlMapClientTemplate().queryForObject("get.resource.info.by.id", po); - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - - - - - - - - - - - - - - /** - * using package : protocol - * made by : MSH - * date : 17.11.16 - * - */ - - // 디바이스 조회(계정별) - public int getCountByAuthAccount(DmVO vo) throws UserSysException { - METHOD_NAME = "getCountByAuthAccount"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", vo.getDeviceId()); - po.put("authId", vo.getAuthId()); - po.put("authPwd", vo.getAuthPwd()); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "device.get.count.by.authAccount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - - - public int getCountByAuthAccount(String deviceId, String authId, String authPwd) throws UserSysException { - METHOD_NAME = "getCountByAuthAccount"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - po.put("authId", authId); - po.put("authPwd", authPwd); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "device.get.count.by.authAccount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - public int getCountByAuthAccount(String deviceId, JSONObject token, Type type) throws UserSysException { - METHOD_NAME = "getCountByAuthAccount"; - - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("deviceId", deviceId); - switch(type){ - case LWM2M: - po.put("authId", token.getString("authId")); - po.put("authPwd", token.getString("authPw")); - break; - case TR_069: - po.put("authId", token.getString("Device.ManagementServer.Username")); - po.put("authPwd", token.getString("Device.ManagementServer.Password")); - break; - } - - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "device.get.count.by.authAccount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // 디바이스 리소스 업데이트 - public boolean updateDeviceResourcesData(DmVO vo) throws UserSysException { - METHOD_NAME = "insertDeviceResources"; - - boolean result = false; - - try { - String deviceId = TR069Formatter.getInstance().getDeviceId(vo.getDeviceId(), Target.DM); - JSONObject param = vo.getInform(); - - Iterator it = param.keys(); - while(it.hasNext()){ - - HashMap resMap = new HashMap(); - String uri = (String)it.next(); - String value = param.getString(uri); - - if(!uri.equals("command")){ - resMap.put("value", value); - resMap.put("uri", TR069Formatter.getInstance().getResourceUri(uri, Target.DM)); - resMap.put("device_id", deviceId); - update("device.update.data", resMap); - } - } - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - -} +package net.herit.business.api.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import net.herit.business.api.service.*; +import net.herit.business.device.service.DeviceModelVO; +import net.herit.business.device.service.DeviceVO; +import net.herit.business.device.service.MoProfileVO; +import net.herit.business.protocol.DmVO; +import net.herit.business.protocol.constant.Target; +import net.herit.business.protocol.constant.Type; +import net.herit.business.protocol.tr069.TR069Formatter; +import net.herit.common.dataaccess.*; +import net.herit.common.exception.UserSysException; +import net.herit.common.model.*; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.stereotype.Repository; + +import com.ibatis.sqlmap.client.SqlMapException; + +@Repository("ApiHdmDAO") +public class ApiHdmDAO extends HeritHdmAbstractDAO { + /** 클래스 명칭 */ + private final String CLASS_NAME = getClass().getName(); + /** 메소드명칭 */ + private String METHOD_NAME = ""; + + public List getList(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "getList"; + List resultList = null; + + try { + resultList = getSqlMapClientTemplate().queryForList( + "DeviceDAO.deviceList", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultList; + } + + public Object get(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "get"; + + HashMap result = null; + try { + result = (HashMap)getSqlMapClientTemplate().queryForObject( + "DeviceDAO.deviceCount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + + return result; + } + + //추가 + public DeviceVO getDeviceInfo(String deviceId) throws UserSysException { + METHOD_NAME = "getDeviceInfo"; + + DeviceVO resultVO = null; + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + + System.out.println("11111111111111"); + resultVO = (DeviceVO)getSqlMapClientTemplate().queryForObject("DeviceDAO.device", po); + System.out.println("22222222222222"); + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultVO; + } + + /*public HashMap getDeviceInfo(String deviceId) throws UserSysException { + METHOD_NAME = "getDeviceInfo"; + + HashMap resultMap = null; + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + + resultMap = (HashMap)getSqlMapClientTemplate().queryForObject( + "DeviceDAO.deviceInfo", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultMap; + }*/ + + + public ProcessResult update(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "update"; + + ProcessResult result = null; + + + return result; + } + + public ProcessResult insert(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "insert"; + + ProcessResult result = null; + + + return result; + } + + public ProcessResult delete(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "delete"; + + ProcessResult result = null; + + + return result; + } + + + /**************************************************** + * ETC Protocol + ****************************************************/ + + + + + /************************************************* + * lwm2m + *************************************************/ + public int getCountByAuthAccount(JSONObject token) throws UserSysException { + METHOD_NAME = "getCountByAuthAccount"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", token.getString("deviceId")); + po.put("authId", token.getString("authId")); + po.put("authPwd", token.getString("authPw")); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "device.get.count.by.authAccount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + // device Resource 갯수 파악 + public int getResourceCountByDeviceId(String deviceId) throws UserSysException { + METHOD_NAME = "getResourceCountByDeviceId"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "deviceResource.get.count.by.deviceId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + // device Resource 제거 + public boolean removeResourceByDeviceId(String deviceId) throws UserSysException { + METHOD_NAME = "removeResourceByDeviceId"; + + boolean result = false; + + try { + HashMap po = new HashMap(); + po.put("device_id", deviceId); + + int rCode = delete("deviceResource.remove.by.deviceId", po); + + if(rCode > 0){ + result = true; + } + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + // hdm_device_mo_data테이블에 데이터 추가 + public boolean insertDeviceResources(String deviceId, List unList) throws UserSysException { + METHOD_NAME = "insertDeviceResources"; + + boolean result = false; + + try { + + int rCode = 0; + for(int i=0; i po = new HashMap(); + po.put("device_id", deviceId); + po.put("resource_uri", unList.get(i).getResourceUri()); + po.put("resource_name", unList.get(i).getDisplayName()); + po.put("data", unList.get(i).getData()); + System.out.println(po.get("data")); + rCode += (Integer)insert("device.insert.resource", po); +/* if(unList.get(i).getData() != null){ + po.put("data", unList.get(i).getData()); + rCode += (Integer)insert("device.insert.resource.withData", po); + } else { + }*/ + } + + if(rCode == unList.size()){ + result = true; + } + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // hit_dev_inf_tbl테이블 deviceId로 조회한 갯수 + public int getDeviceConnStatusCount(String deviceId) throws UserSysException { + METHOD_NAME = "getDeviceConnStatusCount"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + result = (Integer)getSqlMapClientTemplate().queryForObject("device.get.count.by.deviceId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // hit_dev_inf_tbl테이블에 접속 데이터 추가 + public boolean insertDeviceConnStatus(String deviceId, String systemId) throws UserSysException { + METHOD_NAME = "insertDeviceConnStatus"; + + boolean result = false; + + try { + + HashMap po = new HashMap(); + po.put("deviceId",deviceId); + po.put("status","1"); + po.put("systemId", systemId); + + int rCode = (Integer)insert("device.insert.connStatus", po); + + if(rCode == 1){ + result = true; + } + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // hit_dev_inf_tbl테이블에 접속 상태 업데이트 + public boolean updateDeviceConnStatus(String deviceId, String status) throws UserSysException { + METHOD_NAME = "updateDeviceConnStatus"; + + boolean result = false; + + try { + + HashMap po = new HashMap(); + po.put("device_id",deviceId); + po.put("status",status); + + int rCode = (Integer)update("device.update.connStatus", po); + + if(rCode == 1){ + result = true; + } + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // hdm_device_mo_data 테이블에 데이터 update + public boolean updateDeviceResourcesData(String deviceId, HashMap map) throws UserSysException { + METHOD_NAME = "insertDeviceResources"; + + boolean result = false; + + try { + + int rCode = 0; + JSONArray arr = new JSONArray((String) map.get("body")); + for(int i=0; i resMap = new HashMap(); + + JSONObject body = arr.getJSONObject(i); + resMap.put("value", body.getJSONObject("content").getString("value")); + resMap.put("uri", body.getString("uri").replace("/0/", "/-/")); + resMap.put("device_id", deviceId); + rCode += (Integer)update("device.update.data", resMap); + + System.out.println(resMap.toString()); + } + + //rCode += (Integer)insert("device.insert.resource", po); + if(rCode == arr.length()){ + result = true; + } + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + + /********************************************* + * TR-069 + * ******************************************/ + + public boolean updateDeviceResourcesData(String deviceId, JSONObject param) throws UserSysException { + METHOD_NAME = "insertDeviceResources"; + + boolean result = false; + + try { + int rCode = 0; + + Iterator it = param.keys(); + while(it.hasNext()){ + + HashMap resMap = new HashMap(); + String uri = (String)it.next(); + String value = param.getString(uri); + + if(!uri.equals("command")){ + resMap.put("value", value); + resMap.put("uri", uri.replace(".", "/")); + resMap.put("device_id", deviceId); + update("device.update.data", resMap); + } + } + + + //rCode += (Integer)insert("device.insert.resource", po); + //if(rCode == ){ + // result = true; + //} + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + public ArrayList getResources(String deviceId, List paramList) throws UserSysException { + METHOD_NAME = "getDeviceInfo"; + + ArrayList result = null; + try { + StringBuffer listToString = new StringBuffer(); + for(int i=0; i)getSqlMapClientTemplate().queryForList("device.status.list.by.uris", po); + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + public String getHistoricalOption(String deviceId, String resourceUri, String operation) throws UserSysException { + METHOD_NAME = "getDeviceInfo"; + + String result = null; + try { + + HashMap po = new HashMap(); + po.put("operation", operation); + po.put("deviceId", deviceId); + po.put("resourceUri", resourceUri); + + result = (String)getSqlMapClientTemplate().queryForObject("get.historical.option", po); + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + public HashMap getResourceInfoByDeviceId(String deviceId, String resourceUri) throws UserSysException { + METHOD_NAME = "getDeviceInfo"; + + HashMap result = null; + try { + + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + po.put("resourceUri", resourceUri); + + result = (HashMap)getSqlMapClientTemplate().queryForObject("get.resource.info.by.id", po); + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + + + + + + + + + + + + + + /** + * using package : protocol + * made by : MSH + * date : 17.11.16 + * + */ + + // 디바이스 조회(계정별) + public int getCountByAuthAccount(DmVO vo) throws UserSysException { + METHOD_NAME = "getCountByAuthAccount"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", vo.getDeviceId()); + po.put("authId", vo.getAuthId()); + po.put("authPwd", vo.getAuthPwd()); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "device.get.count.by.authAccount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + + + public int getCountByAuthAccount(String deviceId, String authId, String authPwd) throws UserSysException { + METHOD_NAME = "getCountByAuthAccount"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + po.put("authId", authId); + po.put("authPwd", authPwd); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "device.get.count.by.authAccount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + public int getCountByAuthAccount(String deviceId, JSONObject token, Type type) throws UserSysException { + METHOD_NAME = "getCountByAuthAccount"; + + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("deviceId", deviceId); + switch(type){ + case LWM2M: + po.put("authId", token.getString("authId")); + po.put("authPwd", token.getString("authPw")); + break; + case TR_069: + po.put("authId", token.getString("Device.ManagementServer.Username")); + po.put("authPwd", token.getString("Device.ManagementServer.Password")); + break; + } + + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "device.get.count.by.authAccount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // 디바이스 리소스 업데이트 + public boolean updateDeviceResourcesData(DmVO vo) throws UserSysException { + METHOD_NAME = "insertDeviceResources"; + + boolean result = false; + + try { + String deviceId = TR069Formatter.getInstance().getDeviceId(vo.getDeviceId(), Target.DM); + JSONObject param = vo.getInform(); + + Iterator it = param.keys(); + while(it.hasNext()){ + + HashMap resMap = new HashMap(); + String uri = (String)it.next(); + String value = param.getString(uri); + + if(!uri.equals("command")){ + resMap.put("value", value); + resMap.put("uri", TR069Formatter.getInstance().getResourceUri(uri, Target.DM)); + resMap.put("device_id", deviceId); + update("device.update.data", resMap); + } + } + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/ApiHdpDAO.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/ApiHdpDAO.java index 63abd20..bded570 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/ApiHdpDAO.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/ApiHdpDAO.java @@ -1,328 +1,328 @@ -package net.herit.business.api.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import net.herit.business.api.service.*; -import net.herit.business.device.service.DeviceModelVO; -import net.herit.business.device.service.DeviceVO; -import net.herit.business.device.service.ExtMoProfileVO; -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.protocol.lwm2m.resource.ResourceVO; -import net.herit.common.dataaccess.*; -import net.herit.common.exception.UserSysException; -import net.herit.common.model.*; - -import org.springframework.stereotype.Repository; - -import com.ibatis.sqlmap.client.SqlMapException; - -@Repository("ApiHdpDAO") -public class ApiHdpDAO extends HeritHdpAbstractDAO { - /** 클래스 명칭 */ - private final String CLASS_NAME = getClass().getName(); - /** 메소드명칭 */ - private String METHOD_NAME = ""; - - public List getList(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "getList"; - List resultList = null; - - try { - resultList = getSqlMapClientTemplate().queryForList( - "DeviceDAO.deviceList", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultList; - } - - public Object get(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "get"; - - HashMap result = null; - try { - result = (HashMap)getSqlMapClientTemplate().queryForObject( - "DeviceDAO.deviceCount", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - - return result; - } - - - /*public HashMap getResUriNameInfo(String resourceUri) throws UserSysException { - METHOD_NAME = "getResUriNameInfo"; - - HashMap resultMap = null; - try { - HashMap po = new HashMap(); - po.put("resourceUri", resourceUri); - - resultMap = (HashMap)getSqlMapClientTemplate().queryForObject( - "deviceModel.moProfile.extDisplayName", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return null; - }*/ - -/* public List getResUriNameList(String resourceUri) throws UserSysException { - METHOD_NAME = "getResUriNameList"; - List resultList = null; - - try { - HashMap po = new HashMap(); - po.put("resourceUri", resourceUri); - resultList = getSqlMapClientTemplate().queryForList( - "deviceModel.moProfile.extDisplayName", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultList; - }*/ - - //수정(2016.02.03 onem2m연동 관련) - public ExtMoProfileVO getResUriNameInfo(String moProfileId) throws UserSysException { - METHOD_NAME = "getResUriNameInfo"; - - ExtMoProfileVO resultVO = null; - - try { - HashMap po = new HashMap(); - po.put("moProfileId", moProfileId); - - resultVO = (ExtMoProfileVO)getSqlMapClientTemplate().queryForObject( - "deviceModel.moProfile.extDisplayName", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultVO; - } - - //추가(2016.02.03 onem2m연동 관련) - public DeviceModelVO getDeviceModelId(String modelName) throws UserSysException { - METHOD_NAME = "getDeviceModelId"; - - DeviceModelVO resultVO = null; - - try { - HashMap po = new HashMap(); - po.put("modelName", modelName); - - resultVO = (DeviceModelVO)getSqlMapClientTemplate().queryForObject( - "DeviceModelVO.deviceModel.getId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultVO; - } - - //추가(2016.02.03 onem2m연동 관련) - public MoProfileVO getMoProfileId(String deviceModelId, String resourceUri) throws UserSysException { - METHOD_NAME = "getMoProfileId"; - - MoProfileVO resultVO = null; - - try { - HashMap po = new HashMap(); - po.put("deviceModelId", deviceModelId); - po.put("resourceUri", resourceUri); - - resultVO = (MoProfileVO)getSqlMapClientTemplate().queryForObject( - "MoProfileVO.moProfile.getId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return resultVO; - } - - public ProcessResult update(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "update"; - - ProcessResult result = null; - - - return result; - } - - public ProcessResult insert(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "insert"; - - ProcessResult result = null; - - - return result; - } - - public ProcessResult delete(String queryId, HashMap po) throws UserSysException { - METHOD_NAME = "delete"; - - ProcessResult result = null; - - - return result; - } - - - /************************************************* - * lwm2m - *************************************************/ - - // profile 갯수 확인 - public List getResourceUriByDeviceModelId(String dmId) throws UserSysException { - METHOD_NAME = "getMoProfileCountByDeviceModelId"; - - List result = null; - int deviceModelId = Integer.parseInt(dmId); - - try { - HashMap po = new HashMap(); - po.put("deviceModelId", deviceModelId); - - result = (List)getSqlMapClientTemplate().queryForList( - "MoProfileVO.get.resourceUri.by.deviceModelId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - - // device model 갯수 확인 - public int getDeviceModelCountByModelName(String modelName) throws UserSysException { - METHOD_NAME = "getDeviceModelCountByModelName"; - System.out.println(modelName); - int result = 0; - - try { - HashMap po = new HashMap(); - po.put("modelName", modelName); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "deviceModel.get.count.by.modelName", po); - System.out.println(result); - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // profile 갯수 확인 - public int getMoProfileCountByDeviceModelId(String dmId) throws UserSysException { - METHOD_NAME = "getMoProfileCountByDeviceModelId"; - - int result = 0; - int deviceModelId = Integer.parseInt(dmId); - - try { - HashMap po = new HashMap(); - po.put("deviceModelId", deviceModelId); - - result = (Integer)getSqlMapClientTemplate().queryForObject( - "MoProfileVO.get.count.by.deviceModelId", po); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - - - /************************************************* - * temp - * @return - *************************************************/ - - - - // profile - public int insertsProfile(List list) throws UserSysException { - METHOD_NAME = "insertsProfile"; - int result = 0; - try{ - for(int i=0; i po = new HashMap(); - po.put("resource_uri", vo.getResource_uri()); - po.put("profile_ver", vo.getProfile_ver()); - po.put("data_type", vo.getData_type()); - po.put("unit", vo.getUnit()); - po.put("noti_type", new String().valueOf(vo.getNoti_type())); - po.put("operation", vo.getOperation()); - po.put("device_model_id", new String().valueOf(vo.getDevice_model_id())); - po.put("is_diagnostic", vo.getIs_diagnostic()); - po.put("is_mandatory", vo.getIs_mandatory()); - po.put("display_name", vo.getDisplay_name()); - po.put("is_multiple", vo.getIs_multiple()); - po.put("is_historical", vo.getIs_historical()); - po.put("is_error", vo.getIs_error()); - po.put("default_value", vo.getDefault_value()); - po.put("description", vo.getDescription()); - po.put("is_display", vo.getIs_display()); - po.put("display_type", vo.getDisplay_type()); - - - result = (Integer) insert("MoProfile.insert", vo); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } - - // 상태 이력 남기기 위한 resoure uri 불러오기 - // profile 갯수 확인 - public List getStatusUris(HashMap map) throws UserSysException { - METHOD_NAME = "getMoProfileCountByDeviceModelId"; - - List result = null; - - try { - result = (List)getSqlMapClientTemplate().queryForList( - "get.status.uris", map); - - } catch (SqlMapException ex) { - throw new UserSysException(CLASS_NAME, METHOD_NAME, - "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); - } - return result; - } -} +package net.herit.business.api.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import net.herit.business.api.service.*; +import net.herit.business.device.service.DeviceModelVO; +import net.herit.business.device.service.DeviceVO; +import net.herit.business.device.service.ExtMoProfileVO; +import net.herit.business.device.service.MoProfileVO; +import net.herit.business.protocol.lwm2m.resource.ResourceVO; +import net.herit.common.dataaccess.*; +import net.herit.common.exception.UserSysException; +import net.herit.common.model.*; + +import org.springframework.stereotype.Repository; + +import com.ibatis.sqlmap.client.SqlMapException; + +@Repository("ApiHdpDAO") +public class ApiHdpDAO extends HeritHdpAbstractDAO { + /** 클래스 명칭 */ + private final String CLASS_NAME = getClass().getName(); + /** 메소드명칭 */ + private String METHOD_NAME = ""; + + public List getList(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "getList"; + List resultList = null; + + try { + resultList = getSqlMapClientTemplate().queryForList( + "DeviceDAO.deviceList", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultList; + } + + public Object get(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "get"; + + HashMap result = null; + try { + result = (HashMap)getSqlMapClientTemplate().queryForObject( + "DeviceDAO.deviceCount", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + + return result; + } + + + /*public HashMap getResUriNameInfo(String resourceUri) throws UserSysException { + METHOD_NAME = "getResUriNameInfo"; + + HashMap resultMap = null; + try { + HashMap po = new HashMap(); + po.put("resourceUri", resourceUri); + + resultMap = (HashMap)getSqlMapClientTemplate().queryForObject( + "deviceModel.moProfile.extDisplayName", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return null; + }*/ + +/* public List getResUriNameList(String resourceUri) throws UserSysException { + METHOD_NAME = "getResUriNameList"; + List resultList = null; + + try { + HashMap po = new HashMap(); + po.put("resourceUri", resourceUri); + resultList = getSqlMapClientTemplate().queryForList( + "deviceModel.moProfile.extDisplayName", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultList; + }*/ + + //수정(2016.02.03 onem2m연동 관련) + public ExtMoProfileVO getResUriNameInfo(String moProfileId) throws UserSysException { + METHOD_NAME = "getResUriNameInfo"; + + ExtMoProfileVO resultVO = null; + + try { + HashMap po = new HashMap(); + po.put("moProfileId", moProfileId); + + resultVO = (ExtMoProfileVO)getSqlMapClientTemplate().queryForObject( + "deviceModel.moProfile.extDisplayName", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultVO; + } + + //추가(2016.02.03 onem2m연동 관련) + public DeviceModelVO getDeviceModelId(String modelName) throws UserSysException { + METHOD_NAME = "getDeviceModelId"; + + DeviceModelVO resultVO = null; + + try { + HashMap po = new HashMap(); + po.put("modelName", modelName); + + resultVO = (DeviceModelVO)getSqlMapClientTemplate().queryForObject( + "DeviceModelVO.deviceModel.getId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultVO; + } + + //추가(2016.02.03 onem2m연동 관련) + public MoProfileVO getMoProfileId(String deviceModelId, String resourceUri) throws UserSysException { + METHOD_NAME = "getMoProfileId"; + + MoProfileVO resultVO = null; + + try { + HashMap po = new HashMap(); + po.put("deviceModelId", deviceModelId); + po.put("resourceUri", resourceUri); + + resultVO = (MoProfileVO)getSqlMapClientTemplate().queryForObject( + "MoProfileVO.moProfile.getId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return resultVO; + } + + public ProcessResult update(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "update"; + + ProcessResult result = null; + + + return result; + } + + public ProcessResult insert(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "insert"; + + ProcessResult result = null; + + + return result; + } + + public ProcessResult delete(String queryId, HashMap po) throws UserSysException { + METHOD_NAME = "delete"; + + ProcessResult result = null; + + + return result; + } + + + /************************************************* + * lwm2m + *************************************************/ + + // profile 갯수 확인 + public List getResourceUriByDeviceModelId(String dmId) throws UserSysException { + METHOD_NAME = "getMoProfileCountByDeviceModelId"; + + List result = null; + int deviceModelId = Integer.parseInt(dmId); + + try { + HashMap po = new HashMap(); + po.put("deviceModelId", deviceModelId); + + result = (List)getSqlMapClientTemplate().queryForList( + "MoProfileVO.get.resourceUri.by.deviceModelId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + + // device model 갯수 확인 + public int getDeviceModelCountByModelName(String modelName) throws UserSysException { + METHOD_NAME = "getDeviceModelCountByModelName"; + System.out.println(modelName); + int result = 0; + + try { + HashMap po = new HashMap(); + po.put("modelName", modelName); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "deviceModel.get.count.by.modelName", po); + System.out.println(result); + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // profile 갯수 확인 + public int getMoProfileCountByDeviceModelId(String dmId) throws UserSysException { + METHOD_NAME = "getMoProfileCountByDeviceModelId"; + + int result = 0; + int deviceModelId = Integer.parseInt(dmId); + + try { + HashMap po = new HashMap(); + po.put("deviceModelId", deviceModelId); + + result = (Integer)getSqlMapClientTemplate().queryForObject( + "MoProfileVO.get.count.by.deviceModelId", po); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + + + /************************************************* + * temp + * @return + *************************************************/ + + + + // profile + public int insertsProfile(List list) throws UserSysException { + METHOD_NAME = "insertsProfile"; + int result = 0; + try{ + for(int i=0; i po = new HashMap(); + po.put("resource_uri", vo.getResource_uri()); + po.put("profile_ver", vo.getProfile_ver()); + po.put("data_type", vo.getData_type()); + po.put("unit", vo.getUnit()); + po.put("noti_type", new String().valueOf(vo.getNoti_type())); + po.put("operation", vo.getOperation()); + po.put("device_model_id", new String().valueOf(vo.getDevice_model_id())); + po.put("is_diagnostic", vo.getIs_diagnostic()); + po.put("is_mandatory", vo.getIs_mandatory()); + po.put("display_name", vo.getDisplay_name()); + po.put("is_multiple", vo.getIs_multiple()); + po.put("is_historical", vo.getIs_historical()); + po.put("is_error", vo.getIs_error()); + po.put("default_value", vo.getDefault_value()); + po.put("description", vo.getDescription()); + po.put("is_display", vo.getIs_display()); + po.put("display_type", vo.getDisplay_type()); + + + result = (Integer) insert("MoProfile.insert", vo); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } + + // 상태 이력 남기기 위한 resoure uri 불러오기 + // profile 갯수 확인 + public List getStatusUris(HashMap map) throws UserSysException { + METHOD_NAME = "getMoProfileCountByDeviceModelId"; + + List result = null; + + try { + result = (List)getSqlMapClientTemplate().queryForList( + "get.status.uris", map); + + } catch (SqlMapException ex) { + throw new UserSysException(CLASS_NAME, METHOD_NAME, + "사용자관리 데이터 취득 처리에서 에러가 발생했습니다.", ex); + } + return result; + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/LWM2MApiService.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/LWM2MApiService.java index e89bb4b..fc19bb1 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/LWM2MApiService.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/LWM2MApiService.java @@ -1,238 +1,238 @@ -package net.herit.business.api.service; - -import java.util.HashMap; -import java.util.List; -import javax.annotation.Resource; - -import java.io.*; -import java.net.*; -import java.sql.Timestamp; - -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.protocol.lwm2m.Util; -import net.herit.common.conf.HeritProperties; -import net.herit.common.exception.UserSysException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.stereotype.Repository; - - -@Repository("LWM2MApiService") -public class LWM2MApiService { - @Resource(name="ApiHdhDAO") - private ApiHdhDAO hdhDAO; - @Resource(name="ApiHdpDAO") - private ApiHdpDAO hdpDAO; - - /** 클래스 명칭 **/ - private final String CLASS_NAME = getClass().getName(); - /** 메소드 명칭 **/ - private String METHOD_NAME = ""; - private long curTime = 0; - - private String dmHost = ""; - private int dmPort = 8085; - - public LWM2MApiService() { - dmHost = HeritProperties.getProperty("Globals.lwm2mServerHost"); - dmPort = Integer.parseInt(HeritProperties.getProperty("Globals.lwm2mServerPort")); - } - - - public HashMap execute(String operation, HashMap contentMap, String endPoint) - throws JsonGenerationException, JsonMappingException, IOException, UserSysException, JSONException - { - HashMap res = callOpenAPI(operation, endPoint, contentMap); - - HashMap uriList = new HashMap(); - if( !Util.isNOE(res.toString()) ){ - JSONArray body = new JSONArray(res.get("body").toString()); - for(int i=0; i info = new HashMap(); - - info.put("oui", vals[0]); - info.put("model_name", vals[1]); - - - List statusUriList = hdpDAO.getStatusUris(info); - HashMap baseInfo = new HashMap(); - baseInfo.put("device_id", deviceId); - baseInfo.put("model_name", vals[1]); - baseInfo.put("sn", vals[2]); - baseInfo.put("trigger_type", "N"); - baseInfo.put("data_time", new Timestamp(curTime).toString()); - - int r = 0; - for(int i=0; i res){ - /********************************************* - * body rebuild - ********************************************/ - JSONObject e_o = new JSONObject(); - try{ - e_o.put("n", "/3/-/4"); - e_o.put("sv", "CHANGED"); - e_o.put("ti", curTime); - } catch(Exception err) { - - } - - JSONObject content = new JSONObject(); - content.put("r", res.get("status")); - content.put("e", e_o); - - /********************************************/ - return content; - } - - public JSONObject getBaseForm(HashMap res){ - /********************************************* - * body rebuild - ********************************************/ - JSONArray e = new JSONArray(); - JSONObject content = new JSONObject(); - try{ - JSONArray body = new JSONArray((String)res.get("body")); - for (int i = 0; i < body.length(); i++) { - try{ - JSONObject o = body.getJSONObject(i); - JSONObject e_o = new JSONObject(); - e_o.put("n", o.getString("uri").replace("/0/", "/-/")); - if(e_o.getString("n").equals("/3/-/10")){ - e_o.put("sv", (Integer)o.getJSONObject("content").get("value")/ (1024*1024)); - } else { - e_o.put("sv", o.getJSONObject("content").get("value")); - } - e_o.put("ti", System.currentTimeMillis()); - e.put(e_o); - } catch(Exception err) { - - } - } - content.put("r", res.get("status")); - content.put("e", e); - - } catch(Exception ew){ - ew.printStackTrace(); - } - /********************************************/ - return content; - } - - - - public HashMap callOpenAPI(String operation, String endPoint, HashMap contentMap) - throws IOException - { - - METHOD_NAME = "callOpenAPI"; - - HashMap res = new HashMap(); - - URL url = new URL(getUrl(endPoint)); - - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - - String uri = null; - try{ - uri = (String) contentMap.get("n"); - }catch(Exception e){e.printStackTrace();} - - if(operation.equals("read") || operation.equals("reboot")){ - conn.setRequestMethod("POST"); - } else if(operation.equals("write") ){ - if(!Util.isNOE(uri) && uri.equals("/7/-/6")){ - conn.setRequestMethod("POST"); - } else { - conn.setRequestMethod("PUT"); - } - } - conn.setRequestProperty("Content-Type", "application/json"); - conn.setRequestProperty("Content-Length", String.valueOf(contentMap.size())); - - conn.setDoOutput(true); - conn.setDoInput(true); - - JSONObject rr = new JSONObject(contentMap); - OutputStream wr = conn.getOutputStream(); - wr.write(rr.toString().getBytes()); - wr.flush(); - wr.close(); - - int resCode = conn.getResponseCode(); - - if (resCode == 200) { - - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - StringBuffer resBody = new StringBuffer(); - - while ((line = in.readLine()) != null) { - resBody.append(line); - } - in.close(); - - res.put("status", resCode); - res.put("body", resBody.toString()); - curTime = System.currentTimeMillis(); - } else { - - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream())); - String line; - StringBuffer resBody = new StringBuffer(); - - while ((line = in.readLine()) != null) { - resBody.append(line); - } - in.close(); - - res.put("status", resCode); - res.put("body", resBody.toString()); - - } - - return res; - } - - private String getUrl(String endPoint) { - System.err.println("http://"+ dmHost +":"+ dmPort +"/api/hdm/"+endPoint); - return "http://"+ dmHost +":"+ dmPort +"/api/hdm/"+endPoint; - } - -} +package net.herit.business.api.service; + +import java.util.HashMap; +import java.util.List; +import javax.annotation.Resource; + +import java.io.*; +import java.net.*; +import java.sql.Timestamp; + +import net.herit.business.device.service.MoProfileVO; +import net.herit.business.protocol.lwm2m.Util; +import net.herit.common.conf.HeritProperties; +import net.herit.common.exception.UserSysException; + +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.stereotype.Repository; + + +@Repository("LWM2MApiService") +public class LWM2MApiService { + @Resource(name="ApiHdhDAO") + private ApiHdhDAO hdhDAO; + @Resource(name="ApiHdpDAO") + private ApiHdpDAO hdpDAO; + + /** 클래스 명칭 **/ + private final String CLASS_NAME = getClass().getName(); + /** 메소드 명칭 **/ + private String METHOD_NAME = ""; + private long curTime = 0; + + private String dmHost = ""; + private int dmPort = 8085; + + public LWM2MApiService() { + dmHost = HeritProperties.getProperty("Globals.lwm2mServerHost"); + dmPort = Integer.parseInt(HeritProperties.getProperty("Globals.lwm2mServerPort")); + } + + + public HashMap execute(String operation, HashMap contentMap, String endPoint) + throws JsonGenerationException, JsonMappingException, IOException, UserSysException, JSONException + { + HashMap res = callOpenAPI(operation, endPoint, contentMap); + + HashMap uriList = new HashMap(); + if( !Util.isNOE(res.toString()) ){ + JSONArray body = new JSONArray(res.get("body").toString()); + for(int i=0; i info = new HashMap(); + + info.put("oui", vals[0]); + info.put("model_name", vals[1]); + + + List statusUriList = hdpDAO.getStatusUris(info); + HashMap baseInfo = new HashMap(); + baseInfo.put("device_id", deviceId); + baseInfo.put("model_name", vals[1]); + baseInfo.put("sn", vals[2]); + baseInfo.put("trigger_type", "N"); + baseInfo.put("data_time", new Timestamp(curTime).toString()); + + int r = 0; + for(int i=0; i res){ + /********************************************* + * body rebuild + ********************************************/ + JSONObject e_o = new JSONObject(); + try{ + e_o.put("n", "/3/-/4"); + e_o.put("sv", "CHANGED"); + e_o.put("ti", curTime); + } catch(Exception err) { + + } + + JSONObject content = new JSONObject(); + content.put("r", res.get("status")); + content.put("e", e_o); + + /********************************************/ + return content; + } + + public JSONObject getBaseForm(HashMap res){ + /********************************************* + * body rebuild + ********************************************/ + JSONArray e = new JSONArray(); + JSONObject content = new JSONObject(); + try{ + JSONArray body = new JSONArray((String)res.get("body")); + for (int i = 0; i < body.length(); i++) { + try{ + JSONObject o = body.getJSONObject(i); + JSONObject e_o = new JSONObject(); + e_o.put("n", o.getString("uri").replace("/0/", "/-/")); + if(e_o.getString("n").equals("/3/-/10")){ + e_o.put("sv", (Integer)o.getJSONObject("content").get("value")/ (1024*1024)); + } else { + e_o.put("sv", o.getJSONObject("content").get("value")); + } + e_o.put("ti", System.currentTimeMillis()); + e.put(e_o); + } catch(Exception err) { + + } + } + content.put("r", res.get("status")); + content.put("e", e); + + } catch(Exception ew){ + ew.printStackTrace(); + } + /********************************************/ + return content; + } + + + + public HashMap callOpenAPI(String operation, String endPoint, HashMap contentMap) + throws IOException + { + + METHOD_NAME = "callOpenAPI"; + + HashMap res = new HashMap(); + + URL url = new URL(getUrl(endPoint)); + + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + + String uri = null; + try{ + uri = (String) contentMap.get("n"); + }catch(Exception e){e.printStackTrace();} + + if(operation.equals("read") || operation.equals("reboot")){ + conn.setRequestMethod("POST"); + } else if(operation.equals("write") ){ + if(!Util.isNOE(uri) && uri.equals("/7/-/6")){ + conn.setRequestMethod("POST"); + } else { + conn.setRequestMethod("PUT"); + } + } + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Content-Length", String.valueOf(contentMap.size())); + + conn.setDoOutput(true); + conn.setDoInput(true); + + JSONObject rr = new JSONObject(contentMap); + OutputStream wr = conn.getOutputStream(); + wr.write(rr.toString().getBytes()); + wr.flush(); + wr.close(); + + int resCode = conn.getResponseCode(); + + if (resCode == 200) { + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + StringBuffer resBody = new StringBuffer(); + + while ((line = in.readLine()) != null) { + resBody.append(line); + } + in.close(); + + res.put("status", resCode); + res.put("body", resBody.toString()); + curTime = System.currentTimeMillis(); + } else { + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream())); + String line; + StringBuffer resBody = new StringBuffer(); + + while ((line = in.readLine()) != null) { + resBody.append(line); + } + in.close(); + + res.put("status", resCode); + res.put("body", resBody.toString()); + + } + + return res; + } + + private String getUrl(String endPoint) { + System.err.println("http://"+ dmHost +":"+ dmPort +"/api/hdm/"+endPoint); + return "http://"+ dmHost +":"+ dmPort +"/api/hdm/"+endPoint; + } + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/TR069ApiService.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/TR069ApiService.java index 8da7de3..1431475 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/TR069ApiService.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/api/service/TR069ApiService.java @@ -1,612 +1,612 @@ -package net.herit.business.api.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import javax.annotation.Resource; - -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.*; -import java.sql.Timestamp; - -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.protocol.HttpConnector; -import net.herit.business.protocol.Util; -import net.herit.business.protocol.tr069.CurlOperation; -import net.herit.common.conf.HeritProperties; -import net.herit.common.exception.UserSysException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.stereotype.Repository; - - -@Repository("TR069ApiService") -public class TR069ApiService { - @Resource(name="ApiHdhDAO") - private ApiHdhDAO hdhDAO; - @Resource(name="ApiHdmDAO") - private ApiHdmDAO hdmDAO; - @Resource(name="ApiHdpDAO") - private ApiHdpDAO hdpDAO; - - private String deviceId; - private long curTime; - private String acsHost = ""; - private int acsPort = 7557; - - - private String ip; - private String port; - - // init variable - /* - private JSONObject msg = null; - private HashMap res = null; - private URL url = null; - private HttpURLConnection conn = null; - private StringBuffer baseUrlString = new StringBuffer("http://").append(acsHost).append(":").append(acsPort); - private StringBuffer urlString = null; - private List urlList = null; - private int maxSeconds = 2; - public TR069ApiService() { - acsHost = HeritProperties.getProperty("Globals.tr069ServerHost"); - acsPort = Integer.parseInt(HeritProperties.getProperty("Globals.tr069ServerPort")); - } - */ - - @SuppressWarnings("unchecked") - public HashMap execute2(String operation, JSONObject parameters) throws JSONException, UserSysException { - - - - HashMap res = null; - HashMap param = null; - - ip = HeritProperties.getProperty("Globals.tr069ServerHost"); - port = HeritProperties.getProperty("Globals.tr069ServerPort"); - - if(operation.equals("read")){ - res = read(parameters); - - } else if(operation.equals("write")){ - res = write(parameters); - } else if(operation.equals("firmware_update")){ - res = firmware_update(parameters); - } else if(operation.equals("reboot")){ - res = reboot(parameters); - } - - return res; - } - - // DB에서 업데이트 된 값 조회 - public HashMap read(JSONObject parameters){ - HashMap res = null; - String deviceId = parameters.getString("d"); - try{ - List paramList = getParamList(parameters); - ArrayList resources = hdmDAO.getResources(parameters.getString("d"), paramList); - - HashMap param = null; - for(int i=0; i write(JSONObject parameters){ - HashMap res = null; - HttpURLConnection conn = null; - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - String url = "http://"+ip+":"+port+"/devices/"+deviceId+"/tasks?timeout=3000&connection_request"; - conn = HttpConnector.getInstance().getConnection(url); - JSONObject msg = new JSONObject(); - msg.put("name", "setParameterValues"); - - Object[][] parameterValues = new Object[1][2]; - parameterValues[0][0] = parameters.getJSONArray("e").getJSONObject(0).get("n"); - parameterValues[0][1] = parameters.getJSONArray("e").getJSONObject(0).get("sv"); - msg.put("parameterValues", parameterValues); - - String convertedMsg = Formatter.getInstance().getTR069ResourceUriFromDm(msg.toString()); - JSONObject result = new JSONObject(HttpConnector.getInstance().sendMsg(conn, convertedMsg)); - - JSONArray resp = result.getJSONArray("parameterValues").getJSONArray(0); - HashMap param = null; - String resourceUri = resp.getString(0).replace(".", "/"); - if("Y".equals(hdmDAO.getHistoricalOption(parameters.getString("d"), resourceUri,"RW"))){ - param = hdmDAO.getResourceInfoByDeviceId(parameters.getString("d"), resourceUri); - param.put("ctl_type", "C"); - param.put("ctl_data", resp.getString(1)); - param.put("ctl_result", parameterValues[0][1].equals(resp.getString(1)) ? "OK" : "NO"); - param.put("error_code", "0"); - hdhDAO.insertControlHistory(param); - } - - System.out.println(result); - res = Formatter.getInstance().writeToDmFormat(result, conn); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(conn != null){ - conn.disconnect(); - conn = null; - } - } - return res; - } - - public HashMap firmware_update(JSONObject parameters){ - String operation = "file download"; - HashMap res = new HashMap(); - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - - CurlOperation co = new CurlOperation(); - String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); - JSONObject msg = new JSONObject(); - msg.put("name", "download"); - msg.put("file", parameters.getString("fn")); - msg.put("filename", parameters.getString("fn")); - - Object[] params = new Object[2]; - params[0] = url; - params[1] = msg; - - String response = co.send(operation, params); - System.out.println(response); - - res.put("status", 200); - } catch(Exception e) { - e.printStackTrace(); - } - - return res; - } - - public HashMap reboot(JSONObject parameters){ - String operation = "reboot"; - HashMap res = null; - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - - CurlOperation co = new CurlOperation(); - String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); - JSONObject msg = new JSONObject(); - msg.put("name", "reboot"); - - Object[] params = new Object[2]; - params[0] = url; - params[1] = msg; - - String response = co.send(operation, params); - System.out.println(response); - } catch(Exception e) { - e.printStackTrace(); - } - - return res; - } - - public ArrayList getParamList(JSONObject parameters){ - ArrayList paramList = new ArrayList(); - for(int i=0; i execute(String operation, JSONObject inform) throws IOException - { - // init deviceId - initDeviceId(inform); - - // set url from parameters - urlList = new ArrayList(); - for(int i=0; i execute(String operation, JSONObject parameters) - throws JsonGenerationException, JsonMappingException, IOException, UserSysException, JSONException, InterruptedException - { - deviceId = parameters.getString("d").replace("_", "-"); - HashMap res = null; - - // refresh - boolean result = refreshObjects(deviceId, parameters); - //boolean result = refreshObject(deviceId, "InternetGatewayDevice"); - - if(operation.equals("read")){ - int sec = 0; - while(true){ - if(result){ - res = callOpenAPI(operation, parameters); - sec = 0; - break; - } else { - try { - System.out.println("[refreshObject2] - sec : " + (++sec)); - Thread.sleep(200); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } else { - res = callOpenAPI(operation, parameters); - } - return res; - } - - public HashMap callOpenAPI(String operation, JSONObject inform) - throws IOException - { - HashMap res = new HashMap(); - HttpURLConnection conn = openConnection(operation, inform); - - BufferedReader in = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - String inputLine; - StringBuffer response = new StringBuffer(); - - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - in.close(); - - //print result - System.out.println("[ RESPONSE to STRING ] : "+response.toString()); - - int resCode = conn.getResponseCode(); - - JSONObject result = null; - JSONObject body = new JSONObject(); - JSONArray e = new JSONArray(); - - if(operation.equals("read")){ - result = new JSONObject(response.toString().substring(1,response.toString().length()-1)); - - for(int i=0; i res = null; + private URL url = null; + private HttpURLConnection conn = null; + private StringBuffer baseUrlString = new StringBuffer("http://").append(acsHost).append(":").append(acsPort); + private StringBuffer urlString = null; + private List urlList = null; + private int maxSeconds = 2; + public TR069ApiService() { + acsHost = HeritProperties.getProperty("Globals.tr069ServerHost"); + acsPort = Integer.parseInt(HeritProperties.getProperty("Globals.tr069ServerPort")); + } + */ + + @SuppressWarnings("unchecked") + public HashMap execute2(String operation, JSONObject parameters) throws JSONException, UserSysException { + + + + HashMap res = null; + HashMap param = null; + + ip = HeritProperties.getProperty("Globals.tr069ServerHost"); + port = HeritProperties.getProperty("Globals.tr069ServerPort"); + + if(operation.equals("read")){ + res = read(parameters); + + } else if(operation.equals("write")){ + res = write(parameters); + } else if(operation.equals("firmware_update")){ + res = firmware_update(parameters); + } else if(operation.equals("reboot")){ + res = reboot(parameters); + } + + return res; + } + + // DB에서 업데이트 된 값 조회 + public HashMap read(JSONObject parameters){ + HashMap res = null; + String deviceId = parameters.getString("d"); + try{ + List paramList = getParamList(parameters); + ArrayList resources = hdmDAO.getResources(parameters.getString("d"), paramList); + + HashMap param = null; + for(int i=0; i write(JSONObject parameters){ + HashMap res = null; + HttpURLConnection conn = null; + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + String url = "http://"+ip+":"+port+"/devices/"+deviceId+"/tasks?timeout=3000&connection_request"; + conn = HttpConnector.getInstance().getConnection(url); + JSONObject msg = new JSONObject(); + msg.put("name", "setParameterValues"); + + Object[][] parameterValues = new Object[1][2]; + parameterValues[0][0] = parameters.getJSONArray("e").getJSONObject(0).get("n"); + parameterValues[0][1] = parameters.getJSONArray("e").getJSONObject(0).get("sv"); + msg.put("parameterValues", parameterValues); + + String convertedMsg = Formatter.getInstance().getTR069ResourceUriFromDm(msg.toString()); + JSONObject result = new JSONObject(HttpConnector.getInstance().sendMsg(conn, convertedMsg)); + + JSONArray resp = result.getJSONArray("parameterValues").getJSONArray(0); + HashMap param = null; + String resourceUri = resp.getString(0).replace(".", "/"); + if("Y".equals(hdmDAO.getHistoricalOption(parameters.getString("d"), resourceUri,"RW"))){ + param = hdmDAO.getResourceInfoByDeviceId(parameters.getString("d"), resourceUri); + param.put("ctl_type", "C"); + param.put("ctl_data", resp.getString(1)); + param.put("ctl_result", parameterValues[0][1].equals(resp.getString(1)) ? "OK" : "NO"); + param.put("error_code", "0"); + hdhDAO.insertControlHistory(param); + } + + System.out.println(result); + res = Formatter.getInstance().writeToDmFormat(result, conn); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(conn != null){ + conn.disconnect(); + conn = null; + } + } + return res; + } + + public HashMap firmware_update(JSONObject parameters){ + String operation = "file download"; + HashMap res = new HashMap(); + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + + CurlOperation co = new CurlOperation(); + String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); + JSONObject msg = new JSONObject(); + msg.put("name", "download"); + msg.put("file", parameters.getString("fn")); + msg.put("filename", parameters.getString("fn")); + + Object[] params = new Object[2]; + params[0] = url; + params[1] = msg; + + String response = co.send(operation, params); + System.out.println(response); + + res.put("status", 200); + } catch(Exception e) { + e.printStackTrace(); + } + + return res; + } + + public HashMap reboot(JSONObject parameters){ + String operation = "reboot"; + HashMap res = null; + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + + CurlOperation co = new CurlOperation(); + String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); + JSONObject msg = new JSONObject(); + msg.put("name", "reboot"); + + Object[] params = new Object[2]; + params[0] = url; + params[1] = msg; + + String response = co.send(operation, params); + System.out.println(response); + } catch(Exception e) { + e.printStackTrace(); + } + + return res; + } + + public ArrayList getParamList(JSONObject parameters){ + ArrayList paramList = new ArrayList(); + for(int i=0; i execute(String operation, JSONObject inform) throws IOException + { + // init deviceId + initDeviceId(inform); + + // set url from parameters + urlList = new ArrayList(); + for(int i=0; i execute(String operation, JSONObject parameters) + throws JsonGenerationException, JsonMappingException, IOException, UserSysException, JSONException, InterruptedException + { + deviceId = parameters.getString("d").replace("_", "-"); + HashMap res = null; + + // refresh + boolean result = refreshObjects(deviceId, parameters); + //boolean result = refreshObject(deviceId, "InternetGatewayDevice"); + + if(operation.equals("read")){ + int sec = 0; + while(true){ + if(result){ + res = callOpenAPI(operation, parameters); + sec = 0; + break; + } else { + try { + System.out.println("[refreshObject2] - sec : " + (++sec)); + Thread.sleep(200); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } else { + res = callOpenAPI(operation, parameters); + } + return res; + } + + public HashMap callOpenAPI(String operation, JSONObject inform) + throws IOException + { + HashMap res = new HashMap(); + HttpURLConnection conn = openConnection(operation, inform); + + BufferedReader in = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + + //print result + System.out.println("[ RESPONSE to STRING ] : "+response.toString()); + + int resCode = conn.getResponseCode(); + + JSONObject result = null; + JSONObject body = new JSONObject(); + JSONArray e = new JSONArray(); + + if(operation.equals("read")){ + result = new JSONObject(response.toString().substring(1,response.toString().length()-1)); + + for(int i=0; i getParamList(JSONObject parameters){ - ArrayList paramList = new ArrayList(); - for(int i=0; i read(JSONObject parameters){ - HashMap res = null; - try{ - List paramList = getParamList(parameters); - ArrayList resources = hdmDAO.getResources(parameters.getString("d"), paramList); - res = Formatter.getInstance().readToDmFormat(resources); - } catch(Exception e) { - e.printStackTrace(); - } - return res; - } - - public HashMap write(JSONObject parameters){ - HashMap res = null; - HttpURLConnection conn = null; - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - String url = "http://"+ip+":"+port+"/devices/"+deviceId+"/tasks?timeout=3000&connection_request"; - conn = HttpConnector.getInstance().getConnection(url); - JSONObject msg = new JSONObject(); - msg.put("name", "setParameterValues"); - - Object[][] parameterValues = new Object[1][2]; - parameterValues[0][0] = parameters.getJSONArray("e").getJSONObject(0).get("n"); - parameterValues[0][1] = parameters.getJSONArray("e").getJSONObject(0).get("sv"); - msg.put("parameterValues", parameterValues); - - String convertedMsg = Formatter.getInstance().getTR069ResourceUriFromDm(msg.toString()); - JSONObject result = new JSONObject(HttpConnector.getInstance().sendMsg(conn, convertedMsg)); - - System.out.println(result); - res = Formatter.getInstance().writeToDmFormat(result, conn); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(conn != null){ - conn.disconnect(); - conn = null; - } - } - return res; - } - - public HashMap firmware_update(JSONObject parameters){ - String operation = "file download"; - HashMap res = null; - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - - CurlOperation co = new CurlOperation(); - String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); - JSONObject msg = new JSONObject(); - msg.put("name", "download"); - msg.put("file", parameters.getString("fn")); - msg.put("filename", parameters.getString("fn")); - - Object[] params = new Object[2]; - params[0] = url; - params[1] = msg; - - String response = co.send(operation, params); - System.out.println(response); - } catch(Exception e) { - e.printStackTrace(); - } - - return res; - } - - public HashMap reboot(JSONObject parameters){ - String operation = "reboot"; - HashMap res = null; - - try{ - String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); - - CurlOperation co = new CurlOperation(); - String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); - JSONObject msg = new JSONObject(); - msg.put("name", "reboot"); - - Object[] params = new Object[2]; - params[0] = url; - params[1] = msg; - - String response = co.send(operation, params); - System.out.println(response); - } catch(Exception e) { - e.printStackTrace(); - } - - return res; - } - - -} +package net.herit.business.api.service; + +import java.net.HttpURLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.annotation.Resource; + +import org.json.JSONObject; + +import net.herit.business.device.service.MoProfileVO; +import net.herit.business.protocol.HttpConnector; +import net.herit.business.protocol.tr069.CurlOperation; + + +public class TR069Apis { + + @Resource(name="ApiHdmDAO") + private ApiHdmDAO hdmDAO; + + private String ip; + private String port; + + public TR069Apis(String ip, String port){ + this.ip = ip; + this.port = port; + } + + public ArrayList getParamList(JSONObject parameters){ + ArrayList paramList = new ArrayList(); + for(int i=0; i read(JSONObject parameters){ + HashMap res = null; + try{ + List paramList = getParamList(parameters); + ArrayList resources = hdmDAO.getResources(parameters.getString("d"), paramList); + res = Formatter.getInstance().readToDmFormat(resources); + } catch(Exception e) { + e.printStackTrace(); + } + return res; + } + + public HashMap write(JSONObject parameters){ + HashMap res = null; + HttpURLConnection conn = null; + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + String url = "http://"+ip+":"+port+"/devices/"+deviceId+"/tasks?timeout=3000&connection_request"; + conn = HttpConnector.getInstance().getConnection(url); + JSONObject msg = new JSONObject(); + msg.put("name", "setParameterValues"); + + Object[][] parameterValues = new Object[1][2]; + parameterValues[0][0] = parameters.getJSONArray("e").getJSONObject(0).get("n"); + parameterValues[0][1] = parameters.getJSONArray("e").getJSONObject(0).get("sv"); + msg.put("parameterValues", parameterValues); + + String convertedMsg = Formatter.getInstance().getTR069ResourceUriFromDm(msg.toString()); + JSONObject result = new JSONObject(HttpConnector.getInstance().sendMsg(conn, convertedMsg)); + + System.out.println(result); + res = Formatter.getInstance().writeToDmFormat(result, conn); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(conn != null){ + conn.disconnect(); + conn = null; + } + } + return res; + } + + public HashMap firmware_update(JSONObject parameters){ + String operation = "file download"; + HashMap res = null; + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + + CurlOperation co = new CurlOperation(); + String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); + JSONObject msg = new JSONObject(); + msg.put("name", "download"); + msg.put("file", parameters.getString("fn")); + msg.put("filename", parameters.getString("fn")); + + Object[] params = new Object[2]; + params[0] = url; + params[1] = msg; + + String response = co.send(operation, params); + System.out.println(response); + } catch(Exception e) { + e.printStackTrace(); + } + + return res; + } + + public HashMap reboot(JSONObject parameters){ + String operation = "reboot"; + HashMap res = null; + + try{ + String deviceId = Formatter.getInstance().getTR069DeviceIdFromDm(parameters.getString("d")); + + CurlOperation co = new CurlOperation(); + String url = co.getUriByHttpMethod(co.getCmdList().get(operation), ip, port, deviceId); + JSONObject msg = new JSONObject(); + msg.put("name", "reboot"); + + Object[] params = new Object[2]; + params[0] = url; + params[1] = msg; + + String response = co.send(operation, params); + System.out.println(response); + } catch(Exception e) { + e.printStackTrace(); + } + + return res; + } + + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/DmModel.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/DmModel.java index d047a69..751cfe4 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/DmModel.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/DmModel.java @@ -1,120 +1,120 @@ -package net.herit.business.protocol; - -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathFactory; - -import org.json.JSONObject; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -import net.herit.business.protocol.constant.Type; - -public class DmModel { - private JSONObject inform; - private String deviceId; - private String oui; - private String modelName; - private String serialNumber; - private String authId; - private String authPw; - - public String getDeviceId() { - return deviceId; - } - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - public String getOui() { - return oui; - } - public String getModelName() { - return modelName; - } - public String getSerialNumber() { - return serialNumber; - } - public String getAuthId() { - return authId; - } - public String getAuthPw() { - return authPw; - } - public void initDeviceInfo(JSONObject token){ - initDeviceInfo(token, Type.LWM2M); - } - public JSONObject getInform() { - return inform; - } - - - public JSONObject getXml(String xml){ - JSONObject result = new JSONObject(); - - try{ - InputSource is = new InputSource(new StringReader(xml)); - Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); - XPath xpath = XPathFactory.newInstance().newXPath(); - String expression = "//*/ParameterValueStruct"; - NodeList cols = (NodeList) xpath.compile(expression).evaluate(document, XPathConstants.NODESET); - - expression = "//*/EventCode"; - String command = xpath.compile(expression).evaluate(document); - //System.out.println("Command................"+command); - - result.put("command", command); - - for( int idx=0; idx uriList = null; - private JSONObject inform = null; - - // LWM2M - private JSONArray objectModels = null; - private List objModels = null; - - - public String getDeviceId() { - return deviceId; - } - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - public String getOui() { - return oui; - } - public void setOui(String oui) { - this.oui = oui; - } - public String getModelName() { - return modelName; - } - public void setModelName(String modelName) { - this.modelName = modelName; - } - public String getSerialNumber() { - return serialNumber; - } - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } - public JSONObject getInform() { - return inform; - } - public void setInform(JSONObject inform) { - this.inform = inform; - } - public String getAuthId() { - return authId; - } - public void setAuthId(String authId) { - this.authId = authId; - } - public String getAuthPwd() { - return authPwd; - } - public void setAuthPwd(String authPwd) { - this.authPwd = authPwd; - } - public String getUriString() { - return uriString; - } - public void setUriString(String uriString) { - this.uriString = uriString; - } - public JSONArray getObjectModels() { - return objectModels; - } - public void setObjectModels(JSONArray objectModels) { - this.objectModels = objectModels; - } - public List getObjModels() { - return objModels; - } - public void setObjModels(List objModels) { - this.objModels = objModels; - } - public List getUriList() { - return uriList; - } - public void setUriList(List uriList) { - this.uriList = uriList; - } - - -} +package net.herit.business.protocol; + +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONObject; + +import net.herit.business.device.service.MoProfileVO; + +public class DmVO { + + // DM Base + private String deviceId = null; + private String oui = null; + private String modelName = null; + private String serialNumber = null; + private String authId = null; + private String authPwd = null; + + // TR-069 + private String uriString = null; + private List uriList = null; + private JSONObject inform = null; + + // LWM2M + private JSONArray objectModels = null; + private List objModels = null; + + + public String getDeviceId() { + return deviceId; + } + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + public String getOui() { + return oui; + } + public void setOui(String oui) { + this.oui = oui; + } + public String getModelName() { + return modelName; + } + public void setModelName(String modelName) { + this.modelName = modelName; + } + public String getSerialNumber() { + return serialNumber; + } + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } + public JSONObject getInform() { + return inform; + } + public void setInform(JSONObject inform) { + this.inform = inform; + } + public String getAuthId() { + return authId; + } + public void setAuthId(String authId) { + this.authId = authId; + } + public String getAuthPwd() { + return authPwd; + } + public void setAuthPwd(String authPwd) { + this.authPwd = authPwd; + } + public String getUriString() { + return uriString; + } + public void setUriString(String uriString) { + this.uriString = uriString; + } + public JSONArray getObjectModels() { + return objectModels; + } + public void setObjectModels(JSONArray objectModels) { + this.objectModels = objectModels; + } + public List getObjModels() { + return objModels; + } + public void setObjModels(List objModels) { + this.objModels = objModels; + } + public List getUriList() { + return uriList; + } + public void setUriList(List uriList) { + this.uriList = uriList; + } + + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpConnector.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpConnector.java index 8d7c90e..c54b248 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpConnector.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpConnector.java @@ -1,186 +1,186 @@ -package net.herit.business.protocol; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; - -import org.springframework.web.multipart.MultipartHttpServletRequest; - -import net.herit.common.conf.HeritProperties; - -public class HttpConnector { - - private static HttpConnector instance = null; - public static HttpConnector getInstance(){ - if(instance == null){ - instance = new HttpConnector(); - } - return instance; - } - - private HttpURLConnection conn = null; - public HttpURLConnection getConnection(String target){ - URL url = null; - try{ - url = new URL(target); - conn = (HttpURLConnection)url.openConnection(); - } catch(Exception e){ - e.printStackTrace(); - } - return conn; - } - - public String sendMsg(HttpURLConnection conn, String msg){ - - OutputStream wr = null; - BufferedReader in = null; - String line = null; - StringBuffer resBody = null; - - try{ - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setRequestProperty("Content-Length", String.valueOf(msg.length())); - - conn.setDoOutput(true); - conn.setDoInput(true); - - wr = conn.getOutputStream(); - wr.write(msg.getBytes()); - wr.flush(); - - in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - resBody = new StringBuffer(); - - while ((line = in.readLine()) != null) { - resBody.append(line); - } - } catch(Exception e) { - e.printStackTrace(); - } finally { - try{ - if(in != null){ in.close(); } - if(wr != null){ wr.close(); } - } catch(Exception e) {} - - } - - String resultStr; - if(resBody == null || resBody.length() < 1) { - resBody.append(""); - resultStr = resBody.toString(); - } else { - resultStr = resBody.toString(); - } - return resultStr; - } - - public String sendMsg(String target, String msg){ - return sendMsg(getConnection(target), msg); - } - - public String sendFile(MultipartHttpServletRequest mptRequest) { - - int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); - StringBuffer result = new StringBuffer(); - String fileName = mptRequest.getFile("packageName").getOriginalFilename(); - String uploadFile = null; - if(fileType == 1){ - uploadFile = HeritProperties.getProperty("Globals.firmwareDir") + fileName; - } else { - uploadFile = HeritProperties.getProperty("Globals.tomcatDir") + HeritProperties.getProperty("Globals.uploadDir") + fileName; - } - String actionUrl = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort")+"/files/"+mptRequest.getFile("packageName").getOriginalFilename(); - String end = "\r\n"; - String boundary = Long.toHexString(System.currentTimeMillis()); - - URL url = null; - HttpURLConnection conn = null; - DataOutputStream dos = null; - FileInputStream fis = null; - - try{ - url = new URL(actionUrl); - conn = (HttpURLConnection)url.openConnection(); - - // set option - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setUseCaches(false); - conn.setRequestMethod("PUT"); - - // set header - conn.setRequestProperty("fileType", mptRequest.getParameter("fileType")); - conn.setRequestProperty("oui", mptRequest.getParameter("oui")); - conn.setRequestProperty("productClass", mptRequest.getParameter("productClass")); - conn.setRequestProperty("version", mptRequest.getParameter("version")); - conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary); - - //set I/O - dos = new DataOutputStream(conn.getOutputStream()); - fis = new FileInputStream(uploadFile); - - // set buffer - int bufferSize = 1024; - byte[] buffer = new byte[bufferSize]; - int length = -1; - - // write - while((length = fis.read(buffer)) != -1) { - dos.write(buffer, 0, length); - } - dos.writeBytes(end); - dos.flush(); - dos.close(); - - // log - System.out.println(" ::::::::::::::::::: "+conn.getResponseCode()); - - // get result - InputStream is = conn.getInputStream(); - byte[] data = new byte[bufferSize]; - int leng = -1; - while((leng = is.read(data)) != -1) { - result.append(new String(data, 0, leng)); - } - result.append("resultCode : "); - result.append(conn.getResponseCode()); - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(fis != null){ - try { - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if(conn != null){ - conn.disconnect(); - } - } - - return result.toString(); - } - - public void sendFileWithCurl(){ - String cmd = "curl -i 'http://10.10.0.82:7557/files/firmware.tar.gz' -X PUT --data-binary @\"C:/uploads/firmware/firmware.tar.gz\" --header \"fileType: 1 Firmware Upgrade Image\" --header \"oui: 625009\" --header \"productClass: TTB2706\" --header \"version: asdf\""; - try{ - Process p = Runtime.getRuntime().exec(cmd); - BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line = null; - - while((line = br.readLine()) != null){ - System.out.println(line); - } - } catch(Exception e) { - System.out.println(e); - } - } -} +package net.herit.business.protocol; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import net.herit.common.conf.HeritProperties; + +public class HttpConnector { + + private static HttpConnector instance = null; + public static HttpConnector getInstance(){ + if(instance == null){ + instance = new HttpConnector(); + } + return instance; + } + + private HttpURLConnection conn = null; + public HttpURLConnection getConnection(String target){ + URL url = null; + try{ + url = new URL(target); + conn = (HttpURLConnection)url.openConnection(); + } catch(Exception e){ + e.printStackTrace(); + } + return conn; + } + + public String sendMsg(HttpURLConnection conn, String msg){ + + OutputStream wr = null; + BufferedReader in = null; + String line = null; + StringBuffer resBody = null; + + try{ + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Content-Length", String.valueOf(msg.length())); + + conn.setDoOutput(true); + conn.setDoInput(true); + + wr = conn.getOutputStream(); + wr.write(msg.getBytes()); + wr.flush(); + + in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + resBody = new StringBuffer(); + + while ((line = in.readLine()) != null) { + resBody.append(line); + } + } catch(Exception e) { + e.printStackTrace(); + } finally { + try{ + if(in != null){ in.close(); } + if(wr != null){ wr.close(); } + } catch(Exception e) {} + + } + + String resultStr; + if(resBody == null || resBody.length() < 1) { + resBody.append(""); + resultStr = resBody.toString(); + } else { + resultStr = resBody.toString(); + } + return resultStr; + } + + public String sendMsg(String target, String msg){ + return sendMsg(getConnection(target), msg); + } + + public String sendFile(MultipartHttpServletRequest mptRequest) { + + int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); + StringBuffer result = new StringBuffer(); + String fileName = mptRequest.getFile("packageName").getOriginalFilename(); + String uploadFile = null; + if(fileType == 1){ + uploadFile = HeritProperties.getProperty("Globals.firmwareDir") + fileName; + } else { + uploadFile = HeritProperties.getProperty("Globals.tomcatDir") + HeritProperties.getProperty("Globals.uploadDir") + fileName; + } + String actionUrl = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort")+"/files/"+mptRequest.getFile("packageName").getOriginalFilename(); + String end = "\r\n"; + String boundary = Long.toHexString(System.currentTimeMillis()); + + URL url = null; + HttpURLConnection conn = null; + DataOutputStream dos = null; + FileInputStream fis = null; + + try{ + url = new URL(actionUrl); + conn = (HttpURLConnection)url.openConnection(); + + // set option + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + conn.setRequestMethod("PUT"); + + // set header + conn.setRequestProperty("fileType", mptRequest.getParameter("fileType")); + conn.setRequestProperty("oui", mptRequest.getParameter("oui")); + conn.setRequestProperty("productClass", mptRequest.getParameter("productClass")); + conn.setRequestProperty("version", mptRequest.getParameter("version")); + conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary); + + //set I/O + dos = new DataOutputStream(conn.getOutputStream()); + fis = new FileInputStream(uploadFile); + + // set buffer + int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + int length = -1; + + // write + while((length = fis.read(buffer)) != -1) { + dos.write(buffer, 0, length); + } + dos.writeBytes(end); + dos.flush(); + dos.close(); + + // log + System.out.println(" ::::::::::::::::::: "+conn.getResponseCode()); + + // get result + InputStream is = conn.getInputStream(); + byte[] data = new byte[bufferSize]; + int leng = -1; + while((leng = is.read(data)) != -1) { + result.append(new String(data, 0, leng)); + } + result.append("resultCode : "); + result.append(conn.getResponseCode()); + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(fis != null){ + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if(conn != null){ + conn.disconnect(); + } + } + + return result.toString(); + } + + public void sendFileWithCurl(){ + String cmd = "curl -i 'http://10.10.0.82:7557/files/firmware.tar.gz' -X PUT --data-binary @\"C:/uploads/firmware/firmware.tar.gz\" --header \"fileType: 1 Firmware Upgrade Image\" --header \"oui: 625009\" --header \"productClass: TTB2706\" --header \"version: asdf\""; + try{ + Process p = Runtime.getRuntime().exec(cmd); + BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line = null; + + while((line = br.readLine()) != null){ + System.out.println(line); + } + } catch(Exception e) { + System.out.println(e); + } + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpOperator.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpOperator.java index 74e82fe..ad7bab0 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpOperator.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/HttpOperator.java @@ -1,411 +1,411 @@ -package net.herit.business.protocol; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; - -import javax.servlet.http.HttpServletRequest; - -import org.json.JSONObject; -import org.springframework.web.multipart.MultipartHttpServletRequest; - -import net.herit.business.protocol.lwm2m.exception.JsonFormatException; -import net.herit.common.conf.HeritProperties; - -public class HttpOperator { - - // send get with base header - public HttpURLConnection sendGet(String strUri){ - - URL url = null; - HttpURLConnection conn = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("GET"); - conn.setDoInput(true); - - } catch (IOException e) { - e.printStackTrace(); - } - - return conn; - } - - // send get with oneM2M header - public HttpURLConnection sendGet(String strUri, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("GET"); - conn.setDoInput(true); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - - } catch (IOException e) { - e.printStackTrace(); - } - - return conn; - } - - // send post with base header - public HttpURLConnection sendPost(String strUri, JSONObject data){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setDoOutput(true); - conn.setDoInput(true); - - os = conn.getOutputStream(); - os.write(data.toString().getBytes()); - os.flush(); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return conn; - } - - // send post with onem2m header - public HttpURLConnection sendPost(String strUri, JSONObject data, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setDoOutput(true); - conn.setDoInput(true); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - - os = conn.getOutputStream(); - os.write(data.toString().getBytes()); - os.flush(); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return conn; - } - - // send delete with onem2m header - public HttpURLConnection sendLongPolling(String strUri, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("DELETE"); - conn.setDoInput(true); - conn.setDoOutput(false); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return conn; - } - - // send file - public String sendFile(MultipartHttpServletRequest mptRequest) { - - int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); - StringBuffer result = new StringBuffer(); - String fileName = mptRequest.getFile("packageName").getOriginalFilename(); - String uploadFile = null; - if(fileType == 1){ - uploadFile = HeritProperties.getProperty("Globals.firmwareDir") + fileName; - } else { - uploadFile = HeritProperties.getProperty("Globals.tomcatDir") + HeritProperties.getProperty("Globals.uploadDir") + fileName; - } - String actionUrl = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort")+"/files/"+mptRequest.getFile("packageName").getOriginalFilename(); - String end = "\r\n"; - String boundary = Long.toHexString(System.currentTimeMillis()); - - URL url = null; - HttpURLConnection conn = null; - DataOutputStream dos = null; - FileInputStream fis = null; - - try{ - url = new URL(actionUrl); - conn = (HttpURLConnection)url.openConnection(); - - // set option - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setUseCaches(false); - conn.setRequestMethod("PUT"); - - // set header - conn.setRequestProperty("fileType", mptRequest.getParameter("fileType")); - conn.setRequestProperty("oui", mptRequest.getParameter("oui")); - conn.setRequestProperty("productClass", mptRequest.getParameter("productClass")); - conn.setRequestProperty("version", mptRequest.getParameter("version")); - conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary); - - //set I/O - dos = new DataOutputStream(conn.getOutputStream()); - fis = new FileInputStream(uploadFile); - - // set buffer - int bufferSize = 1024; - byte[] buffer = new byte[bufferSize]; - int length = -1; - - // write - while((length = fis.read(buffer)) != -1) { - dos.write(buffer, 0, length); - } - dos.writeBytes(end); - dos.flush(); - dos.close(); - - // log - System.out.println(" ::::::::::::::::::: "+conn.getResponseCode()); - - // get result - InputStream is = conn.getInputStream(); - byte[] data = new byte[bufferSize]; - int leng = -1; - while((leng = is.read(data)) != -1) { - result.append(new String(data, 0, leng)); - } - result.append("resultCode : "); - result.append(conn.getResponseCode()); - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(fis != null){ - try { - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if(conn != null){ - conn.disconnect(); - } - } - - return result.toString(); - } - - - - // get response from the server - public JSONObject getResponse(HttpURLConnection conn){ - - JSONObject result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - int responseCode = conn.getResponseCode(); - - if (responseCode == HttpURLConnection.HTTP_OK) { - is = conn.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - byte[] byteData = null; - int nLength = 0; - while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { - baos.write(byteBuffer, 0, nLength); - } - byteData = baos.toByteArray(); - result = new JSONObject(new String(byteData)); - } else { - result = new JSONObject(); - result.put("RESPONSE-CODE", String.valueOf(responseCode)); - } - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(baos != null){ - baos.close(); - } - if(is != null){ - is.close(); - } - if(conn != null){ - conn.disconnect(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return result; - } - - - public String getResponseString(HttpURLConnection conn){ - - String result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - int responseCode = conn.getResponseCode(); - - if (responseCode >= HttpURLConnection.HTTP_OK && responseCode <= 202) { - is = conn.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - int nLength = 0; - while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { - baos.write(byteBuffer, 0, nLength); - } - result = new String(baos.toByteArray()); - } else { - JSONObject job = new JSONObject(); - job.put("RESPONSE-CODE", String.valueOf(responseCode)); - - result = job.toString(); - } - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(is != null){ - is.close(); - } - if(baos != null){ - baos.close(); - } - if(conn != null){ - conn.disconnect(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return result; - } - - - // get request by json from the http request - public JSONObject getParamFromRequest(HttpServletRequest request) throws JsonFormatException{ - - JSONObject result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - is = request.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - byte[] byteData; - int nLength = 0; - - while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ - baos.write(byteBuffer,0,nLength); - } - byteData = baos.toByteArray(); - result = new JSONObject(new String(byteData)); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(baos != null){ - baos.close(); - } - if(is != null){ - is.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - System.out.println(result); - return result; - } -} +package net.herit.business.protocol; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; + +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import net.herit.business.protocol.lwm2m.exception.JsonFormatException; +import net.herit.common.conf.HeritProperties; + +public class HttpOperator { + + // send get with base header + public HttpURLConnection sendGet(String strUri){ + + URL url = null; + HttpURLConnection conn = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("GET"); + conn.setDoInput(true); + + } catch (IOException e) { + e.printStackTrace(); + } + + return conn; + } + + // send get with oneM2M header + public HttpURLConnection sendGet(String strUri, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("GET"); + conn.setDoInput(true); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + + } catch (IOException e) { + e.printStackTrace(); + } + + return conn; + } + + // send post with base header + public HttpURLConnection sendPost(String strUri, JSONObject data){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + conn.setDoInput(true); + + os = conn.getOutputStream(); + os.write(data.toString().getBytes()); + os.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return conn; + } + + // send post with onem2m header + public HttpURLConnection sendPost(String strUri, JSONObject data, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + conn.setDoInput(true); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + + os = conn.getOutputStream(); + os.write(data.toString().getBytes()); + os.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return conn; + } + + // send delete with onem2m header + public HttpURLConnection sendLongPolling(String strUri, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("DELETE"); + conn.setDoInput(true); + conn.setDoOutput(false); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return conn; + } + + // send file + public String sendFile(MultipartHttpServletRequest mptRequest) { + + int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" "))); + StringBuffer result = new StringBuffer(); + String fileName = mptRequest.getFile("packageName").getOriginalFilename(); + String uploadFile = null; + if(fileType == 1){ + uploadFile = HeritProperties.getProperty("Globals.firmwareDir") + fileName; + } else { + uploadFile = HeritProperties.getProperty("Globals.tomcatDir") + HeritProperties.getProperty("Globals.uploadDir") + fileName; + } + String actionUrl = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort")+"/files/"+mptRequest.getFile("packageName").getOriginalFilename(); + String end = "\r\n"; + String boundary = Long.toHexString(System.currentTimeMillis()); + + URL url = null; + HttpURLConnection conn = null; + DataOutputStream dos = null; + FileInputStream fis = null; + + try{ + url = new URL(actionUrl); + conn = (HttpURLConnection)url.openConnection(); + + // set option + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + conn.setRequestMethod("PUT"); + + // set header + conn.setRequestProperty("fileType", mptRequest.getParameter("fileType")); + conn.setRequestProperty("oui", mptRequest.getParameter("oui")); + conn.setRequestProperty("productClass", mptRequest.getParameter("productClass")); + conn.setRequestProperty("version", mptRequest.getParameter("version")); + conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary); + + //set I/O + dos = new DataOutputStream(conn.getOutputStream()); + fis = new FileInputStream(uploadFile); + + // set buffer + int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + int length = -1; + + // write + while((length = fis.read(buffer)) != -1) { + dos.write(buffer, 0, length); + } + dos.writeBytes(end); + dos.flush(); + dos.close(); + + // log + System.out.println(" ::::::::::::::::::: "+conn.getResponseCode()); + + // get result + InputStream is = conn.getInputStream(); + byte[] data = new byte[bufferSize]; + int leng = -1; + while((leng = is.read(data)) != -1) { + result.append(new String(data, 0, leng)); + } + result.append("resultCode : "); + result.append(conn.getResponseCode()); + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(fis != null){ + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if(conn != null){ + conn.disconnect(); + } + } + + return result.toString(); + } + + + + // get response from the server + public JSONObject getResponse(HttpURLConnection conn){ + + JSONObject result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + int responseCode = conn.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + is = conn.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + byte[] byteData = null; + int nLength = 0; + while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { + baos.write(byteBuffer, 0, nLength); + } + byteData = baos.toByteArray(); + result = new JSONObject(new String(byteData)); + } else { + result = new JSONObject(); + result.put("RESPONSE-CODE", String.valueOf(responseCode)); + } + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(baos != null){ + baos.close(); + } + if(is != null){ + is.close(); + } + if(conn != null){ + conn.disconnect(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return result; + } + + + public String getResponseString(HttpURLConnection conn){ + + String result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + int responseCode = conn.getResponseCode(); + + if (responseCode >= HttpURLConnection.HTTP_OK && responseCode <= 202) { + is = conn.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + int nLength = 0; + while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { + baos.write(byteBuffer, 0, nLength); + } + result = new String(baos.toByteArray()); + } else { + JSONObject job = new JSONObject(); + job.put("RESPONSE-CODE", String.valueOf(responseCode)); + + result = job.toString(); + } + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(is != null){ + is.close(); + } + if(baos != null){ + baos.close(); + } + if(conn != null){ + conn.disconnect(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return result; + } + + + // get request by json from the http request + public JSONObject getParamFromRequest(HttpServletRequest request) throws JsonFormatException{ + + JSONObject result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + is = request.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + byte[] byteData; + int nLength = 0; + + while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ + baos.write(byteBuffer,0,nLength); + } + byteData = baos.toByteArray(); + result = new JSONObject(new String(byteData)); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(baos != null){ + baos.close(); + } + if(is != null){ + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + System.out.println(result); + return result; + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/MessageHandler.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/MessageHandler.java index e593c18..711b99b 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/MessageHandler.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/MessageHandler.java @@ -1,92 +1,92 @@ -package net.herit.business.protocol; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import javax.servlet.http.HttpServletRequest; - -import org.json.JSONObject; - -import net.herit.business.protocol.constant.Errors; -import net.herit.business.protocol.lwm2m.exception.JsonFormatException; - -public class MessageHandler { - - //singleton - private static MessageHandler instance = null; - public static MessageHandler getInstance(){ - if(instance == null){ - instance = new MessageHandler(); - } - return instance; - } - - // getByJSON - public JSONObject jsonReceiver(HttpServletRequest request) throws JsonFormatException{ - - JSONObject result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - is = request.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - byte[] byteData; - int nLength = 0; - while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ - baos.write(byteBuffer,0,nLength); - } - byteData = baos.toByteArray(); - result = new JSONObject(new String(byteData)); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(baos != null){ - baos.close(); - } - if(is != null){ - is.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - System.out.println(result); - return result; - } - - - /** set response **/ - public JSONObject setResponse(Errors caseOfResult, String msg) { - JSONObject response = new JSONObject(); - try{ - response.put("RESPONSE-CODE", caseOfResult.name()); - - switch(caseOfResult){ - // error - case ERR_500: - response.put("result", "Failed"); - break; - // success - case ERR_001: - response.put("result", "Connected"); - break; - case ERR_000: - response.put("result", "Disconnected"); - break; - } - response.put("reason", caseOfResult.getMsg()); - if(!Util.getInstance().isNOE(msg)){ - response.put("msg", msg); - } - } catch(Exception e) { - e.printStackTrace(); - } - return response; - } -} +package net.herit.business.protocol; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; + +import net.herit.business.protocol.constant.Errors; +import net.herit.business.protocol.lwm2m.exception.JsonFormatException; + +public class MessageHandler { + + //singleton + private static MessageHandler instance = null; + public static MessageHandler getInstance(){ + if(instance == null){ + instance = new MessageHandler(); + } + return instance; + } + + // getByJSON + public JSONObject jsonReceiver(HttpServletRequest request) throws JsonFormatException{ + + JSONObject result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + is = request.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + byte[] byteData; + int nLength = 0; + while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ + baos.write(byteBuffer,0,nLength); + } + byteData = baos.toByteArray(); + result = new JSONObject(new String(byteData)); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(baos != null){ + baos.close(); + } + if(is != null){ + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + System.out.println(result); + return result; + } + + + /** set response **/ + public JSONObject setResponse(Errors caseOfResult, String msg) { + JSONObject response = new JSONObject(); + try{ + response.put("RESPONSE-CODE", caseOfResult.name()); + + switch(caseOfResult){ + // error + case ERR_500: + response.put("result", "Failed"); + break; + // success + case ERR_001: + response.put("result", "Connected"); + break; + case ERR_000: + response.put("result", "Disconnected"); + break; + } + response.put("reason", caseOfResult.getMsg()); + if(!Util.getInstance().isNOE(msg)){ + response.put("msg", msg); + } + } catch(Exception e) { + e.printStackTrace(); + } + return response; + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/Util.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/Util.java index 3584a26..cda6dcd 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/Util.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/Util.java @@ -1,164 +1,164 @@ -package net.herit.business.protocol; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class Util { - - private static Util instance = null; - public static Util getInstance(){ - if(instance == null){ - instance = new Util(); - } - return instance; - } - - // is Null Or Empty - public boolean isNOE(String txt){ - boolean result = false; - if(txt == null || txt.replaceAll(" ", "").equals("")){ - result = true; - } - return result; - } - - // JSONObject 내용 전부 출력 - public void printJSONObject(JSONObject obj){ - System.out.println(":::: JSONObject contains.."); - Iterator it = obj.keys(); - while(it.hasNext()){ - try{ - String key = it.next(); - Object value = obj.get(key); - System.out.println("["+key+"]-["+value+"]"); - } catch(JSONException e){ - e.printStackTrace(); - } - } - } - - // HashMap 내용 전부 출력 - public void printMap(HashMap map){ - System.out.println(":::: HashMap contains.."); - Iterator it = map.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - Object value = map.get(key); - System.out.println("["+key+"]-["+value+"]"); - } - } - - - - - - - - - - - - - - - - - - - - - public static String makeDeviceId(JSONObject token){ - - StringBuffer deviceId = new StringBuffer(); - - try { - deviceId.append(token.get("oui")).append("_"); - deviceId.append(token.get("modelName")).append("_"); - deviceId.append(token.get("sn")); - } catch (JSONException e) { - e.printStackTrace(); - } - - - return deviceId.toString(); - } - - - - public static List getUriAndName(JSONObject token){ - - List list = new ArrayList(); - - try { - JSONArray objModels = token.getJSONArray("objectModels"); - for (int i = 0; i < objModels.length(); i++) { - StringBuffer uriBase = new StringBuffer("/"); - uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); - JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); - for (int j = 0; j < resources.length(); j++) { - StringBuffer uri = new StringBuffer(uriBase); - uri.append(resources.getJSONObject(j).get("id")); - - String[] vo = new String[2]; - vo[0] = uri.toString(); - vo[1] = resources.getJSONObject(j).get("name").toString(); - list.add(vo); - } - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return list; - } - - public HashMap jsonToMap(JSONObject token){ - HashMap map = new HashMap(); - Iterator keys = token.keySet().iterator(); - while(keys.hasNext()){ - String key = keys.next(); - map.put(key, token.getString(key)); - } - return map; - } - - - - - public String getDataType(String txt){ - String result = ""; - String elseTxt = ""; - - if("integer".equals(txt)){ - result = "I"; - } else if("string".equals(txt)){ - result = "S"; - } else if("boolean".equals(txt)){ - result = "B"; - } else if("float".equals(txt)){ - result = "F"; - } else if("long".equals(txt)){ - result = "L"; - } else if("double".equals(txt)){ - result = "D"; - } else if("time".equals(txt)){ - result = "T"; - } else if("opaque".equals(txt)){ - elseTxt = txt; - } else { - elseTxt = txt; - } - System.out.println(result); - System.out.println(elseTxt); - - return result; - } - -} +package net.herit.business.protocol; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Util { + + private static Util instance = null; + public static Util getInstance(){ + if(instance == null){ + instance = new Util(); + } + return instance; + } + + // is Null Or Empty + public boolean isNOE(String txt){ + boolean result = false; + if(txt == null || txt.replaceAll(" ", "").equals("")){ + result = true; + } + return result; + } + + // JSONObject 내용 전부 출력 + public void printJSONObject(JSONObject obj){ + System.out.println(":::: JSONObject contains.."); + Iterator it = obj.keys(); + while(it.hasNext()){ + try{ + String key = it.next(); + Object value = obj.get(key); + System.out.println("["+key+"]-["+value+"]"); + } catch(JSONException e){ + e.printStackTrace(); + } + } + } + + // HashMap 내용 전부 출력 + public void printMap(HashMap map){ + System.out.println(":::: HashMap contains.."); + Iterator it = map.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + Object value = map.get(key); + System.out.println("["+key+"]-["+value+"]"); + } + } + + + + + + + + + + + + + + + + + + + + + public static String makeDeviceId(JSONObject token){ + + StringBuffer deviceId = new StringBuffer(); + + try { + deviceId.append(token.get("oui")).append("_"); + deviceId.append(token.get("modelName")).append("_"); + deviceId.append(token.get("sn")); + } catch (JSONException e) { + e.printStackTrace(); + } + + + return deviceId.toString(); + } + + + + public static List getUriAndName(JSONObject token){ + + List list = new ArrayList(); + + try { + JSONArray objModels = token.getJSONArray("objectModels"); + for (int i = 0; i < objModels.length(); i++) { + StringBuffer uriBase = new StringBuffer("/"); + uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); + JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); + for (int j = 0; j < resources.length(); j++) { + StringBuffer uri = new StringBuffer(uriBase); + uri.append(resources.getJSONObject(j).get("id")); + + String[] vo = new String[2]; + vo[0] = uri.toString(); + vo[1] = resources.getJSONObject(j).get("name").toString(); + list.add(vo); + } + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return list; + } + + public HashMap jsonToMap(JSONObject token){ + HashMap map = new HashMap(); + Iterator keys = token.keySet().iterator(); + while(keys.hasNext()){ + String key = keys.next(); + map.put(key, token.getString(key)); + } + return map; + } + + + + + public String getDataType(String txt){ + String result = ""; + String elseTxt = ""; + + if("integer".equals(txt)){ + result = "I"; + } else if("string".equals(txt)){ + result = "S"; + } else if("boolean".equals(txt)){ + result = "B"; + } else if("float".equals(txt)){ + result = "F"; + } else if("long".equals(txt)){ + result = "L"; + } else if("double".equals(txt)){ + result = "D"; + } else if("time".equals(txt)){ + result = "T"; + } else if("opaque".equals(txt)){ + elseTxt = txt; + } else { + elseTxt = txt; + } + System.out.println(result); + System.out.println(elseTxt); + + return result; + } + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Errors.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Errors.java index 9aef498..f6b1929 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Errors.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Errors.java @@ -1,25 +1,25 @@ -package net.herit.business.protocol.constant; - -public enum Errors { - // Success - ERR_000("The device has disconnected without any of error."), - ERR_001("The device has connected without any of error."), - - // Error - Format Error - - // Error - DM Error - ERR_500("A value not expected has returned."); - - - - - - - private String msg; - Errors(String msg){ - this.msg = msg; - } - public String getMsg(){ - return this.msg; - } -} +package net.herit.business.protocol.constant; + +public enum Errors { + // Success + ERR_000("The device has disconnected without any of error."), + ERR_001("The device has connected without any of error."), + + // Error - Format Error + + // Error - DM Error + ERR_500("A value not expected has returned."); + + + + + + + private String msg; + Errors(String msg){ + this.msg = msg; + } + public String getMsg(){ + return this.msg; + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/KeyName.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/KeyName.java index 94ebd9e..e95f110 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/KeyName.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/KeyName.java @@ -1,5 +1,5 @@ -package net.herit.business.protocol.constant; - -public enum KeyName { - MODEL_NAME, MANUFACTURER_OUI, SERIAL_NUMBER -} +package net.herit.business.protocol.constant; + +public enum KeyName { + MODEL_NAME, MANUFACTURER_OUI, SERIAL_NUMBER +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Target.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Target.java index 638b764..05a4311 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Target.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Target.java @@ -1,7 +1,7 @@ -package net.herit.business.protocol.constant; - -public enum Target { - DM // self - , ACS // TR-069 Server - , IPE // LWM2M Server -} +package net.herit.business.protocol.constant; + +public enum Target { + DM // self + , ACS // TR-069 Server + , IPE // LWM2M Server +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Type.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Type.java index f5b0964..62e3954 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Type.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/constant/Type.java @@ -1,5 +1,5 @@ -package net.herit.business.protocol.constant; - -public enum Type { - LWM2M, TR_069 -} +package net.herit.business.protocol.constant; + +public enum Type { + LWM2M, TR_069 +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MController.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MController.java index 219776e..b8620ec 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MController.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MController.java @@ -1,620 +1,620 @@ -package net.herit.business.protocol.lwm2m; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; - -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import net.herit.business.api.service.ApiHdhDAO; -import net.herit.business.api.service.ApiHdmDAO; -import net.herit.business.api.service.ApiHdpDAO; -import net.herit.business.api.service.Formatter; -import net.herit.business.api.service.LWM2MApiService; -import net.herit.business.device.service.DeviceModelVO; -import net.herit.business.device.service.DeviceService; -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.protocol.DmVO; -import net.herit.business.protocol.HttpOperator; -import net.herit.business.protocol.constant.Errors; -import net.herit.business.protocol.constant.KeyName; -import net.herit.business.protocol.constant.Target; -import net.herit.business.protocol.lwm2m.exception.JsonFormatException; -import net.herit.business.protocol.lwm2m.resource.ResourceVO; -import net.herit.common.exception.UserSysException; -import net.herit.iot.message.onem2m.OneM2mRequest; -import net.herit.iot.message.onem2m.OneM2mResponse; -import net.herit.iot.message.onem2m.OneM2mRequest.OPERATION; -import net.herit.iot.message.onem2m.OneM2mRequest.RESOURCE_TYPE; -import net.herit.iot.message.onem2m.format.Enums.CONTENT_TYPE; -import net.herit.iot.onem2m.bind.http.client.HttpClient; - -@Controller -@RequestMapping("/lwm2m") -public class LWM2MController { - - @Resource(name = "DeviceService") - private DeviceService deviceService; - - @Resource(name="ApiHdhDAO") - private ApiHdhDAO hdhDAO; - @Resource(name="ApiHdmDAO") - private ApiHdmDAO hdmDAO; - @Resource(name="ApiHdpDAO") - private ApiHdpDAO hdpDAO; - - - private HttpOperator httpOperator = new HttpOperator(); - private LWM2MKeyExtractor keyExtractor = new LWM2MKeyExtractor(); - - private DmVO initialize(JSONObject token){ - DmVO vo = new DmVO(); - vo.setDeviceId(keyExtractor.getDeviceId(token)); - vo.setModelName(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.MODEL_NAME)); - vo.setOui(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.MANUFACTURER_OUI)); - vo.setSerialNumber(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.SERIAL_NUMBER)); - vo.setAuthId(keyExtractor.getAuthId(token)); - vo.setAuthPwd(keyExtractor.getAuthPwd(token)); - return vo; - } - - - // CONNECT - @ResponseBody - @RequestMapping(value="/connect.do", produces="application/json; charset=utf8") - public String connect(HttpServletRequest request){ - String response = null; - try{ - System.out.println("----------------------------------- LWM2M Connect Start!!"); - JSONObject token = httpOperator.getParamFromRequest(request); - - // 초기화 - DmVO vo = initialize(token); - - // 등록 조회 - DeviceModelVO deviceModel = checkDeviceModelRegist(vo.getModelName()); // 등록 조회 : hdp_device_model - checkDeviceModelProfileRegist(deviceModel); // 등록 조회 : hdp_mo_profile - checkDeviceRegist(vo); // 등록 조회 : hdm_device - System.out.println("----------------------------------- LWM2M Device has connected."); - response = "200 OK"; - - } catch(Exception e) { - response = e.getMessage(); - e.printStackTrace(); - } - return response; - } - - // REPORT - @ResponseBody - @RequestMapping(value="/report.do", produces="application/json; charset=utf8") - public String report(HttpServletRequest request){ - String response = null; - try{ - System.out.println("----------------------------------- LWM2M Report Start!!"); - JSONObject token = httpOperator.getParamFromRequest(request); - System.out.println(token); - response = "200 OK"; - - // DB에 데이터 업데이트 - hdmDAO.updateDeviceResourcesData(Formatter.getInstance().getTR069DeviceIdToDm(token.getString("deviceId")), token.getJSONObject("param")); - - } catch(Exception e) { - response = e.getMessage(); - e.printStackTrace(); - } - return response; - } - - - - - - - - - - - - - - - - /** 등록 조회 : hdp_device_model - * @throws Exception **/ - public DeviceModelVO checkDeviceModelRegist(String modelName) throws Exception{ - DeviceModelVO deviceModel = null; - - System.out.println(hdpDAO==null); - int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(modelName); - if(deviceModelCount != 1){ - throw new Exception(Response.ERR101.getMsg()); - } else { - deviceModel = hdpDAO.getDeviceModelId(modelName); - } - return deviceModel; - } - - /** 등록 조회 : hdp_mo_profile - * @throws Exception **/ - public void checkDeviceModelProfileRegist(DeviceModelVO deviceModel) throws Exception{ - int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); - if(profileCount < 1){ - // 최소 1개 이상의 resource가 등록되어야 함 - throw new Exception(Response.ERR102.getMsg()); - } - } - - /** 등록 조회 : hdm_device - * @throws Exception **/ - public void checkDeviceRegist(DmVO vo) throws Exception{ - int deviceCount = hdmDAO.getCountByAuthAccount(vo); - if(deviceCount == 0){ - throw new Exception(Errors.ERR_500.getMsg()); - } else if (deviceCount == 1) { - registResourceModel(vo); - } else { - throw new Exception(Errors.ERR_500.getMsg()); - } - } - - /** 리소스 등록 - * @throws UserSysException - */ - public void registResources(DmVO vo) throws UserSysException{ - // resource 개수 파악 - int resourceCount = hdmDAO.getResourceCountByDeviceId(vo.getDeviceId()); - if(resourceCount == 0){ - // resource 등록 : hdm_device_mo_data : resource 추출 - List profileList = hdpDAO.getResourceUriByDeviceModelId(vo.getDeviceId()); - List uri_list = new ArrayList(); - - JSONArray om = vo.getObjectModels(); - for(int i=0; i -1){ - uri_list.add(profileList.get(j)); - } - } - } - hdmDAO.insertDeviceResources(vo.getDeviceId(), uri_list); - System.out.println("Resources have registered."); - } - } - - /** resource 등록 : hdm_device_mo_data : resource 추출 - * @throws Exception **/ - public void registResourceModel(DmVO vo) throws Exception{ - registResources(vo); - - boolean isConnected = false; - int connCount = hdmDAO.getDeviceConnStatusCount(vo.getDeviceId()); - switch(connCount){ - case 0: - // 연결 정보가 없기 때문에 추가 - isConnected = hdmDAO.insertDeviceConnStatus(vo.getDeviceId(), "DGP2"); - break; - case 1: - // 연결 정보가 있기 때문에 상태값만 업데이트 - isConnected = hdmDAO.updateDeviceConnStatus(vo.getDeviceId(), "1"); - break; - default : - // 기대값 아니므로 exception 발생 - throw new Exception(Errors.ERR_500.getMsg()); - } - - if(isConnected){ - System.out.println("----------------------------------- Process done"); - } else { - throw new Exception(Errors.ERR_500.getMsg()); - } - } - - - - - - - - - - - - - - - - - - - - - - - // key value - private JSONObject token; - private String deviceId; - - // response msg - public enum Response{ - - // ERROR - ERR000("The error has occured."), - - ERR101("Data Error"), // =1 - ERR102("At least a resource or more than must be registered."), // >=1 - ERR103("The device hasn't registered or incorrect information call."), // =1 - ERR104("Data Error"), - - ERR900("The server doesn't support completely this device."), - ERR901("JSON Format Exception"), - - // SUCCESS - SUC_CONN("Connected"), - SUC_DISC("Disconnected "); - - private String msg; - Response(String msg){ - this.msg = msg; - } - public String getMsg(){ - return this.msg; - } - } - - // handler - @RequestMapping(value="/conn.do", produces="application/json; charset=utf8") - @ResponseBody - public String connectHandler(HttpServletRequest request){ - - JSONObject response = null; - - try{ - token = requestMessageFromLwmw2mServer(request); - deviceId = Util.makeDeviceId(token); - - System.out.println(token); - - String connectMethod = token.get("conn").toString(); - if(connectMethod.equals("connect")){ - response = connect2(); - } else if(connectMethod.equals("disconnect")){ - response = disconnect(); - } else if(connectMethod.equals("controlHistory")){ - hdhDAO.insertControlHistory(Util.jsonToMap(token)); - } - /* - else if(connectMethod.equals("res")){ - resourceDataToDatabase(token); - } else if(connectMethod.equals("oneM2M_write")){ - //write(token); - } else if(connectMethod.equals("oneM2M_read")){ - //read(token); - } else if(connectMethod.equals("setStatus")){ - // history 등록 process - } - //*/ - } catch(JsonFormatException e) { - response = setResponse(Response.ERR901,e.getMessage()); - e.printStackTrace(); - } catch(Exception e) { - response = setResponse(Response.ERR900,e.getMessage()); - e.printStackTrace(); - } - - return response.toString(); - } - - // handler - @RequestMapping(value="/test.do", produces="application/json; charset=utf8") - @ResponseBody - public String test(HttpServletRequest request){ - - OneM2mRequest req = new OneM2mRequest(); - req.setRequestIdentifier("req"); - req.setFrom("S"); - req.setTo("/herit-cse"); - req.setContentType(CONTENT_TYPE.JSON); - req.setOperation(OPERATION.RETRIEVE); - req.setResourceType(RESOURCE_TYPE.CSE_BASE); - - OneM2mResponse res = HttpClient.getInstance().sendRequest("http://10.10.224.240:8080/herit-in/herit-cse", req); - return res.toString(); - } - - // set response - public JSONObject setResponse(Response caseOfResult, String msg) { - JSONObject response = new JSONObject(); - - try{ - response.put("RESPONSE-CODE", caseOfResult.name()); - - switch(caseOfResult){ - // error - case ERR101: case ERR102: case ERR103: - response.put("result", "Failed"); - break; - case ERR900: - response.put("result", "Failed"); - break; - - // success - case SUC_CONN: - response.put("result", "Connected"); - break; - case SUC_DISC: - response.put("result", "Disconnected"); - break; - - // default - default : - response.put("result", "Failed"); - break; - } - - response.put("reason", caseOfResult.getMsg()); - - if(!Util.isNOE(msg)){ - response.put("msg", msg); - } - - } catch(Exception e) { - e.printStackTrace(); - } - - return response; - } - - - // 메시지 받기 - public JSONObject requestMessageFromLwmw2mServer(HttpServletRequest request) throws JsonFormatException{ - - InputStream is; - String token; - JSONObject result = null; - - try{ - is = request.getInputStream(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - byte[] byteData; - int nLength = 0; - while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ - baos.write(byteBuffer,0,nLength); - } - byteData = baos.toByteArray(); - token = new String(byteData); - result = new JSONObject(token); - - } catch(Exception e) { - result = setResponse(Response.ERR901, null); - throw new JsonFormatException(); - } - - return result; - } - - - - public JSONObject connect2(){ - - JSONObject result = null; - boolean hasConnected = false; - - //* - try{ - // 등록 조회 : hdp_device_model, hdp_mo_profile, hdm_device - // hdp_device_model - int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(token.get("modelName").toString()); - DeviceModelVO deviceModel; - if(deviceModelCount != 1){ - // 기대값이 아니므로 exception 발생 - result = setResponse(Response.ERR101, null); - throw new Exception(Response.ERR101.getMsg()); - } else { - deviceModel = hdpDAO.getDeviceModelId(token.get("modelName").toString()); - } - - // hdp_mo_profile - int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); - if(profileCount < 1){ - // 최소 1개 이상의 resource가 등록되어야 함 - result = setResponse(Response.ERR102, null); - throw new Exception(Response.ERR102.getMsg()); - } - - // hdm_device - int deviceCount = hdmDAO.getCountByAuthAccount(deviceId, token.getString("authId"), token.getString("authPwd")); - switch(deviceCount){ - case 0: - // 정보 불일치 혹은 등록되지 않았으므로 exception 발생 - result = setResponse(Response.ERR103, null); - throw new Exception(Response.ERR103.getMsg()); - case 1: - // 조건 통과 - // resource 등록 : hdm_device_mo_data : resource 추출 - List profileList = hdpDAO.getResourceUriByDeviceModelId(deviceModel.getId()); - List uri_list = new ArrayList(); - - JSONArray om = token.getJSONArray("objectModels"); - for(int i=0; i -1){ - uri_list.add(profileList.get(j)); - } - } - } - - // resource 개수 파악 - int resourceCount = hdmDAO.getResourceCountByDeviceId(deviceId); - if(resourceCount != uri_list.size()){ - // db에서의 resource 개수와 client에서 보내온 resource 개수가 다를 경우 - /* - if(resourceCount != 0){ - // 기존 resource가 0개가 아닐 때, 기존 resource 삭제 후 재등록 - System.out.println("delete old resource"); - hdmDAO.removeResourceByDeviceId(deviceId); - } - */ - // resource 등록 - hdmDAO.insertDeviceResources(deviceId, uri_list); - System.out.println("Resources have registered."); - } - - // 연결 성공 - int connCount = hdmDAO.getDeviceConnStatusCount(deviceId); - switch(connCount){ - case 0: - // 연결 정보가 없기 때문에 추가 - hasConnected = hdmDAO.insertDeviceConnStatus(deviceId, "DGP2"); - result = setResponse(Response.SUC_CONN, null); - break; - case 1: - // 연결 정보가 있기 때문에 상태값만 업데이트 - hasConnected = hdmDAO.updateDeviceConnStatus(deviceId, "1"); - result = setResponse(Response.SUC_CONN, null); - break; - default : - // 기대값 아니므로 exception 발생 - result = setResponse(Response.ERR000, null); - throw new Exception(Response.ERR000.getMsg()); - } - - - break; - default : - // 기대값이 아니므로 exception 발생 - result = setResponse(Response.ERR104, null); - throw new Exception(Response.ERR104.getMsg()); - } - - } catch(Exception e){ - // 예외 발생시 client에 통보 - e.printStackTrace(); - result = setResponse(Response.ERR900,e.getMessage()); - } finally { - System.out.println("connected : "+hasConnected); - - //* - Timer timer = new Timer(); - timer.schedule(new TimerTask(){ - public void run() { - try{ - - // rx, tx start - LWM2MApiService ls = new LWM2MApiService(); - - String order = "{\"d\":\""+deviceId+"\", \"e\":[{\"n\":\"/7/-/6\",\"sv\":\"ON\"}]}"; - HashMap contentMap = new ObjectMapper().readValue(order, HashMap.class); - contentMap.put("o", "e"); - - ls.execute("write", contentMap, token.getString("authId")); - - order = "{\"d\":\""+deviceId+"\",\"e\":[{\"n\":\"/6/-/0\"},{\"n\":\"/6/-/1\"}]}"; - contentMap = new ObjectMapper().readValue(order, HashMap.class); - contentMap.put("o", "r"); - HashMap content = ls.execute("read", contentMap, token.getString("authId")); - - hdmDAO.updateDeviceResourcesData(deviceId, content); - } catch(Exception e){ - e.printStackTrace(); - } - } - }, 5000); - //*/ - } - - //*/ - return result ; - } - - public JSONObject disconnect(){ - - boolean hasDisconnected = false; - JSONObject result = null; - - try { - hasDisconnected = hdmDAO.updateDeviceConnStatus(deviceId, "0"); - result = setResponse(Response.SUC_DISC, null); - } catch (Exception e) { - e.printStackTrace(); - result = setResponse(Response.ERR900,e.getMessage()); - // TODO: handle exception - } finally { - System.out.println("disconnected : " + hasDisconnected); - } - return result; - } - - - ////////////////////////////////////////////////////////// - - // resource json 파일 일괄 db에 저장하기 - public void resourceDataToDatabase(JSONObject token) throws JSONException{ - - List list = new ArrayList(); - - JSONArray wrap = token.getJSONArray("contents"); - for (int i = 0; i < wrap.length(); i++) { - StringBuffer uri_base = new StringBuffer("/"); - JSONObject obj = wrap.getJSONObject(i); - uri_base.append(obj.get("id")).append("/-/"); - - JSONArray resourcedefs = obj.getJSONArray("resourcedefs"); - for (int j = 0; j < resourcedefs.length(); j++) { - ResourceVO res = new ResourceVO(); - StringBuffer uri = new StringBuffer(uri_base); - - JSONObject resourcedef = resourcedefs.getJSONObject(j); - uri.append(resourcedef.get("id")); - res.setResource_uri(uri.toString()); - res.setData_type(Util.getDataType(resourcedef.getString("type"))); - res.setUnit(resourcedef.getString("units").length()>3?"ref":resourcedef.getString("units")); - res.setOperation(resourcedef.getString("operations").equals("NONE")?"":resourcedef.getString("operations")); - res.setIs_mandatory(resourcedef.getBoolean("mandatory")?"Y":"N"); - res.setDisplay_name(resourcedef.getString("name")); - res.setIs_multiple(resourcedef.getString("instancetype").equals("single")?"N":"Y"); - res.setDescription(resourcedef.getString("description")); - - list.add(res); - } - } - - try { - int result = hdpDAO.insertsProfile(list); - } catch (UserSysException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - /* - public void write(JSONObject token){ - LWM2MApiService ls = new LWM2MApiService(); - String order = "{\"d\":\""+deviceId+"\" , \"n\":\""+token.getString("resourceUri")+"\", \"o\":\"e\", \"sv\":\""+token.getInt("sv")+"\"}"; - HashMap result = ls.startObserveRxTxData("write", order, token.getString("authId")); - System.out.println(result.toString()); - } - public void read(JSONObject token){ - LWM2MApiService ls = new LWM2MApiService(); - String order = "{\"d\":\""+deviceId+"\" , \"n\":\""+token.getString("resourceUri")+"\", \"o\":\"o\"}"; - HashMap result = ls.startObserveRxTxData("read", order, token.getString("authId")); - System.out.println(result.toString()); - } - //*/ -} +package net.herit.business.protocol.lwm2m; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +import org.codehaus.jackson.map.ObjectMapper; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import net.herit.business.api.service.ApiHdhDAO; +import net.herit.business.api.service.ApiHdmDAO; +import net.herit.business.api.service.ApiHdpDAO; +import net.herit.business.api.service.Formatter; +import net.herit.business.api.service.LWM2MApiService; +import net.herit.business.device.service.DeviceModelVO; +import net.herit.business.device.service.DeviceService; +import net.herit.business.device.service.MoProfileVO; +import net.herit.business.protocol.DmVO; +import net.herit.business.protocol.HttpOperator; +import net.herit.business.protocol.constant.Errors; +import net.herit.business.protocol.constant.KeyName; +import net.herit.business.protocol.constant.Target; +import net.herit.business.protocol.lwm2m.exception.JsonFormatException; +import net.herit.business.protocol.lwm2m.resource.ResourceVO; +import net.herit.common.exception.UserSysException; +import net.herit.iot.message.onem2m.OneM2mRequest; +import net.herit.iot.message.onem2m.OneM2mResponse; +import net.herit.iot.message.onem2m.OneM2mRequest.OPERATION; +import net.herit.iot.message.onem2m.OneM2mRequest.RESOURCE_TYPE; +import net.herit.iot.message.onem2m.format.Enums.CONTENT_TYPE; +import net.herit.iot.onem2m.bind.http.client.HttpClient; + +@Controller +@RequestMapping("/lwm2m") +public class LWM2MController { + + @Resource(name = "DeviceService") + private DeviceService deviceService; + + @Resource(name="ApiHdhDAO") + private ApiHdhDAO hdhDAO; + @Resource(name="ApiHdmDAO") + private ApiHdmDAO hdmDAO; + @Resource(name="ApiHdpDAO") + private ApiHdpDAO hdpDAO; + + + private HttpOperator httpOperator = new HttpOperator(); + private LWM2MKeyExtractor keyExtractor = new LWM2MKeyExtractor(); + + private DmVO initialize(JSONObject token){ + DmVO vo = new DmVO(); + vo.setDeviceId(keyExtractor.getDeviceId(token)); + vo.setModelName(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.MODEL_NAME)); + vo.setOui(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.MANUFACTURER_OUI)); + vo.setSerialNumber(keyExtractor.getKeyFromId(vo.getDeviceId(), KeyName.SERIAL_NUMBER)); + vo.setAuthId(keyExtractor.getAuthId(token)); + vo.setAuthPwd(keyExtractor.getAuthPwd(token)); + return vo; + } + + + // CONNECT + @ResponseBody + @RequestMapping(value="/connect.do", produces="application/json; charset=utf8") + public String connect(HttpServletRequest request){ + String response = null; + try{ + System.out.println("----------------------------------- LWM2M Connect Start!!"); + JSONObject token = httpOperator.getParamFromRequest(request); + + // 초기화 + DmVO vo = initialize(token); + + // 등록 조회 + DeviceModelVO deviceModel = checkDeviceModelRegist(vo.getModelName()); // 등록 조회 : hdp_device_model + checkDeviceModelProfileRegist(deviceModel); // 등록 조회 : hdp_mo_profile + checkDeviceRegist(vo); // 등록 조회 : hdm_device + System.out.println("----------------------------------- LWM2M Device has connected."); + response = "200 OK"; + + } catch(Exception e) { + response = e.getMessage(); + e.printStackTrace(); + } + return response; + } + + // REPORT + @ResponseBody + @RequestMapping(value="/report.do", produces="application/json; charset=utf8") + public String report(HttpServletRequest request){ + String response = null; + try{ + System.out.println("----------------------------------- LWM2M Report Start!!"); + JSONObject token = httpOperator.getParamFromRequest(request); + System.out.println(token); + response = "200 OK"; + + // DB에 데이터 업데이트 + hdmDAO.updateDeviceResourcesData(Formatter.getInstance().getTR069DeviceIdToDm(token.getString("deviceId")), token.getJSONObject("param")); + + } catch(Exception e) { + response = e.getMessage(); + e.printStackTrace(); + } + return response; + } + + + + + + + + + + + + + + + + /** 등록 조회 : hdp_device_model + * @throws Exception **/ + public DeviceModelVO checkDeviceModelRegist(String modelName) throws Exception{ + DeviceModelVO deviceModel = null; + + System.out.println(hdpDAO==null); + int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(modelName); + if(deviceModelCount != 1){ + throw new Exception(Response.ERR101.getMsg()); + } else { + deviceModel = hdpDAO.getDeviceModelId(modelName); + } + return deviceModel; + } + + /** 등록 조회 : hdp_mo_profile + * @throws Exception **/ + public void checkDeviceModelProfileRegist(DeviceModelVO deviceModel) throws Exception{ + int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); + if(profileCount < 1){ + // 최소 1개 이상의 resource가 등록되어야 함 + throw new Exception(Response.ERR102.getMsg()); + } + } + + /** 등록 조회 : hdm_device + * @throws Exception **/ + public void checkDeviceRegist(DmVO vo) throws Exception{ + int deviceCount = hdmDAO.getCountByAuthAccount(vo); + if(deviceCount == 0){ + throw new Exception(Errors.ERR_500.getMsg()); + } else if (deviceCount == 1) { + registResourceModel(vo); + } else { + throw new Exception(Errors.ERR_500.getMsg()); + } + } + + /** 리소스 등록 + * @throws UserSysException + */ + public void registResources(DmVO vo) throws UserSysException{ + // resource 개수 파악 + int resourceCount = hdmDAO.getResourceCountByDeviceId(vo.getDeviceId()); + if(resourceCount == 0){ + // resource 등록 : hdm_device_mo_data : resource 추출 + List profileList = hdpDAO.getResourceUriByDeviceModelId(vo.getDeviceId()); + List uri_list = new ArrayList(); + + JSONArray om = vo.getObjectModels(); + for(int i=0; i -1){ + uri_list.add(profileList.get(j)); + } + } + } + hdmDAO.insertDeviceResources(vo.getDeviceId(), uri_list); + System.out.println("Resources have registered."); + } + } + + /** resource 등록 : hdm_device_mo_data : resource 추출 + * @throws Exception **/ + public void registResourceModel(DmVO vo) throws Exception{ + registResources(vo); + + boolean isConnected = false; + int connCount = hdmDAO.getDeviceConnStatusCount(vo.getDeviceId()); + switch(connCount){ + case 0: + // 연결 정보가 없기 때문에 추가 + isConnected = hdmDAO.insertDeviceConnStatus(vo.getDeviceId(), "DGP2"); + break; + case 1: + // 연결 정보가 있기 때문에 상태값만 업데이트 + isConnected = hdmDAO.updateDeviceConnStatus(vo.getDeviceId(), "1"); + break; + default : + // 기대값 아니므로 exception 발생 + throw new Exception(Errors.ERR_500.getMsg()); + } + + if(isConnected){ + System.out.println("----------------------------------- Process done"); + } else { + throw new Exception(Errors.ERR_500.getMsg()); + } + } + + + + + + + + + + + + + + + + + + + + + + + // key value + private JSONObject token; + private String deviceId; + + // response msg + public enum Response{ + + // ERROR + ERR000("The error has occured."), + + ERR101("Data Error"), // =1 + ERR102("At least a resource or more than must be registered."), // >=1 + ERR103("The device hasn't registered or incorrect information call."), // =1 + ERR104("Data Error"), + + ERR900("The server doesn't support completely this device."), + ERR901("JSON Format Exception"), + + // SUCCESS + SUC_CONN("Connected"), + SUC_DISC("Disconnected "); + + private String msg; + Response(String msg){ + this.msg = msg; + } + public String getMsg(){ + return this.msg; + } + } + + // handler + @RequestMapping(value="/conn.do", produces="application/json; charset=utf8") + @ResponseBody + public String connectHandler(HttpServletRequest request){ + + JSONObject response = null; + + try{ + token = requestMessageFromLwmw2mServer(request); + deviceId = Util.makeDeviceId(token); + + System.out.println(token); + + String connectMethod = token.get("conn").toString(); + if(connectMethod.equals("connect")){ + response = connect2(); + } else if(connectMethod.equals("disconnect")){ + response = disconnect(); + } else if(connectMethod.equals("controlHistory")){ + hdhDAO.insertControlHistory(Util.jsonToMap(token)); + } + /* + else if(connectMethod.equals("res")){ + resourceDataToDatabase(token); + } else if(connectMethod.equals("oneM2M_write")){ + //write(token); + } else if(connectMethod.equals("oneM2M_read")){ + //read(token); + } else if(connectMethod.equals("setStatus")){ + // history 등록 process + } + //*/ + } catch(JsonFormatException e) { + response = setResponse(Response.ERR901,e.getMessage()); + e.printStackTrace(); + } catch(Exception e) { + response = setResponse(Response.ERR900,e.getMessage()); + e.printStackTrace(); + } + + return response.toString(); + } + + // handler + @RequestMapping(value="/test.do", produces="application/json; charset=utf8") + @ResponseBody + public String test(HttpServletRequest request){ + + OneM2mRequest req = new OneM2mRequest(); + req.setRequestIdentifier("req"); + req.setFrom("S"); + req.setTo("/herit-cse"); + req.setContentType(CONTENT_TYPE.JSON); + req.setOperation(OPERATION.RETRIEVE); + req.setResourceType(RESOURCE_TYPE.CSE_BASE); + + OneM2mResponse res = HttpClient.getInstance().sendRequest("http://10.10.224.240:8080/herit-in/herit-cse", req); + return res.toString(); + } + + // set response + public JSONObject setResponse(Response caseOfResult, String msg) { + JSONObject response = new JSONObject(); + + try{ + response.put("RESPONSE-CODE", caseOfResult.name()); + + switch(caseOfResult){ + // error + case ERR101: case ERR102: case ERR103: + response.put("result", "Failed"); + break; + case ERR900: + response.put("result", "Failed"); + break; + + // success + case SUC_CONN: + response.put("result", "Connected"); + break; + case SUC_DISC: + response.put("result", "Disconnected"); + break; + + // default + default : + response.put("result", "Failed"); + break; + } + + response.put("reason", caseOfResult.getMsg()); + + if(!Util.isNOE(msg)){ + response.put("msg", msg); + } + + } catch(Exception e) { + e.printStackTrace(); + } + + return response; + } + + + // 메시지 받기 + public JSONObject requestMessageFromLwmw2mServer(HttpServletRequest request) throws JsonFormatException{ + + InputStream is; + String token; + JSONObject result = null; + + try{ + is = request.getInputStream(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + byte[] byteData; + int nLength = 0; + while((nLength=is.read(byteBuffer,0,byteBuffer.length)) != -1){ + baos.write(byteBuffer,0,nLength); + } + byteData = baos.toByteArray(); + token = new String(byteData); + result = new JSONObject(token); + + } catch(Exception e) { + result = setResponse(Response.ERR901, null); + throw new JsonFormatException(); + } + + return result; + } + + + + public JSONObject connect2(){ + + JSONObject result = null; + boolean hasConnected = false; + + //* + try{ + // 등록 조회 : hdp_device_model, hdp_mo_profile, hdm_device + // hdp_device_model + int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(token.get("modelName").toString()); + DeviceModelVO deviceModel; + if(deviceModelCount != 1){ + // 기대값이 아니므로 exception 발생 + result = setResponse(Response.ERR101, null); + throw new Exception(Response.ERR101.getMsg()); + } else { + deviceModel = hdpDAO.getDeviceModelId(token.get("modelName").toString()); + } + + // hdp_mo_profile + int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); + if(profileCount < 1){ + // 최소 1개 이상의 resource가 등록되어야 함 + result = setResponse(Response.ERR102, null); + throw new Exception(Response.ERR102.getMsg()); + } + + // hdm_device + int deviceCount = hdmDAO.getCountByAuthAccount(deviceId, token.getString("authId"), token.getString("authPwd")); + switch(deviceCount){ + case 0: + // 정보 불일치 혹은 등록되지 않았으므로 exception 발생 + result = setResponse(Response.ERR103, null); + throw new Exception(Response.ERR103.getMsg()); + case 1: + // 조건 통과 + // resource 등록 : hdm_device_mo_data : resource 추출 + List profileList = hdpDAO.getResourceUriByDeviceModelId(deviceModel.getId()); + List uri_list = new ArrayList(); + + JSONArray om = token.getJSONArray("objectModels"); + for(int i=0; i -1){ + uri_list.add(profileList.get(j)); + } + } + } + + // resource 개수 파악 + int resourceCount = hdmDAO.getResourceCountByDeviceId(deviceId); + if(resourceCount != uri_list.size()){ + // db에서의 resource 개수와 client에서 보내온 resource 개수가 다를 경우 + /* + if(resourceCount != 0){ + // 기존 resource가 0개가 아닐 때, 기존 resource 삭제 후 재등록 + System.out.println("delete old resource"); + hdmDAO.removeResourceByDeviceId(deviceId); + } + */ + // resource 등록 + hdmDAO.insertDeviceResources(deviceId, uri_list); + System.out.println("Resources have registered."); + } + + // 연결 성공 + int connCount = hdmDAO.getDeviceConnStatusCount(deviceId); + switch(connCount){ + case 0: + // 연결 정보가 없기 때문에 추가 + hasConnected = hdmDAO.insertDeviceConnStatus(deviceId, "DGP2"); + result = setResponse(Response.SUC_CONN, null); + break; + case 1: + // 연결 정보가 있기 때문에 상태값만 업데이트 + hasConnected = hdmDAO.updateDeviceConnStatus(deviceId, "1"); + result = setResponse(Response.SUC_CONN, null); + break; + default : + // 기대값 아니므로 exception 발생 + result = setResponse(Response.ERR000, null); + throw new Exception(Response.ERR000.getMsg()); + } + + + break; + default : + // 기대값이 아니므로 exception 발생 + result = setResponse(Response.ERR104, null); + throw new Exception(Response.ERR104.getMsg()); + } + + } catch(Exception e){ + // 예외 발생시 client에 통보 + e.printStackTrace(); + result = setResponse(Response.ERR900,e.getMessage()); + } finally { + System.out.println("connected : "+hasConnected); + + //* + Timer timer = new Timer(); + timer.schedule(new TimerTask(){ + public void run() { + try{ + + // rx, tx start + LWM2MApiService ls = new LWM2MApiService(); + + String order = "{\"d\":\""+deviceId+"\", \"e\":[{\"n\":\"/7/-/6\",\"sv\":\"ON\"}]}"; + HashMap contentMap = new ObjectMapper().readValue(order, HashMap.class); + contentMap.put("o", "e"); + + ls.execute("write", contentMap, token.getString("authId")); + + order = "{\"d\":\""+deviceId+"\",\"e\":[{\"n\":\"/6/-/0\"},{\"n\":\"/6/-/1\"}]}"; + contentMap = new ObjectMapper().readValue(order, HashMap.class); + contentMap.put("o", "r"); + HashMap content = ls.execute("read", contentMap, token.getString("authId")); + + hdmDAO.updateDeviceResourcesData(deviceId, content); + } catch(Exception e){ + e.printStackTrace(); + } + } + }, 5000); + //*/ + } + + //*/ + return result ; + } + + public JSONObject disconnect(){ + + boolean hasDisconnected = false; + JSONObject result = null; + + try { + hasDisconnected = hdmDAO.updateDeviceConnStatus(deviceId, "0"); + result = setResponse(Response.SUC_DISC, null); + } catch (Exception e) { + e.printStackTrace(); + result = setResponse(Response.ERR900,e.getMessage()); + // TODO: handle exception + } finally { + System.out.println("disconnected : " + hasDisconnected); + } + return result; + } + + + ////////////////////////////////////////////////////////// + + // resource json 파일 일괄 db에 저장하기 + public void resourceDataToDatabase(JSONObject token) throws JSONException{ + + List list = new ArrayList(); + + JSONArray wrap = token.getJSONArray("contents"); + for (int i = 0; i < wrap.length(); i++) { + StringBuffer uri_base = new StringBuffer("/"); + JSONObject obj = wrap.getJSONObject(i); + uri_base.append(obj.get("id")).append("/-/"); + + JSONArray resourcedefs = obj.getJSONArray("resourcedefs"); + for (int j = 0; j < resourcedefs.length(); j++) { + ResourceVO res = new ResourceVO(); + StringBuffer uri = new StringBuffer(uri_base); + + JSONObject resourcedef = resourcedefs.getJSONObject(j); + uri.append(resourcedef.get("id")); + res.setResource_uri(uri.toString()); + res.setData_type(Util.getDataType(resourcedef.getString("type"))); + res.setUnit(resourcedef.getString("units").length()>3?"ref":resourcedef.getString("units")); + res.setOperation(resourcedef.getString("operations").equals("NONE")?"":resourcedef.getString("operations")); + res.setIs_mandatory(resourcedef.getBoolean("mandatory")?"Y":"N"); + res.setDisplay_name(resourcedef.getString("name")); + res.setIs_multiple(resourcedef.getString("instancetype").equals("single")?"N":"Y"); + res.setDescription(resourcedef.getString("description")); + + list.add(res); + } + } + + try { + int result = hdpDAO.insertsProfile(list); + } catch (UserSysException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /* + public void write(JSONObject token){ + LWM2MApiService ls = new LWM2MApiService(); + String order = "{\"d\":\""+deviceId+"\" , \"n\":\""+token.getString("resourceUri")+"\", \"o\":\"e\", \"sv\":\""+token.getInt("sv")+"\"}"; + HashMap result = ls.startObserveRxTxData("write", order, token.getString("authId")); + System.out.println(result.toString()); + } + public void read(JSONObject token){ + LWM2MApiService ls = new LWM2MApiService(); + String order = "{\"d\":\""+deviceId+"\" , \"n\":\""+token.getString("resourceUri")+"\", \"o\":\"o\"}"; + HashMap result = ls.startObserveRxTxData("read", order, token.getString("authId")); + System.out.println(result.toString()); + } + //*/ +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MFormatter.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MFormatter.java index d4b981a..febcc8a 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MFormatter.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MFormatter.java @@ -1,29 +1,29 @@ -package net.herit.business.protocol.lwm2m; - -import net.herit.business.protocol.constant.Target; - -public class LWM2MFormatter { - // singleton - private static LWM2MFormatter instance = null; - public static LWM2MFormatter getInstance(){ - if(instance == null){ - instance = new LWM2MFormatter(); - } - return instance; - } - - // resource uri - public String getResourceUri(String resourceUri, Target to){ - String result = null; - switch(to){ - case DM: - result = resourceUri.replace("-", "0"); - break; - case IPE: - result = resourceUri.replace("0", "-"); - break; - } - return result; - } - -} +package net.herit.business.protocol.lwm2m; + +import net.herit.business.protocol.constant.Target; + +public class LWM2MFormatter { + // singleton + private static LWM2MFormatter instance = null; + public static LWM2MFormatter getInstance(){ + if(instance == null){ + instance = new LWM2MFormatter(); + } + return instance; + } + + // resource uri + public String getResourceUri(String resourceUri, Target to){ + String result = null; + switch(to){ + case DM: + result = resourceUri.replace("-", "0"); + break; + case IPE: + result = resourceUri.replace("0", "-"); + break; + } + return result; + } + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MKeyExtractor.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MKeyExtractor.java index 1449e7c..4d7e4a6 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MKeyExtractor.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/LWM2MKeyExtractor.java @@ -1,93 +1,93 @@ -package net.herit.business.protocol.lwm2m; - -import java.util.ArrayList; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import net.herit.business.protocol.constant.KeyName; -import net.herit.business.protocol.constant.Target; - -public class LWM2MKeyExtractor { - - // deviceId - public String getDeviceId(JSONObject token){ - return getDeviceId(token, Target.DM); - } - public String getDeviceId(JSONObject token, Target to){ - StringBuffer deviceId = new StringBuffer(); - - try { - if(to == Target.DM){ - deviceId.append(token.get("oui")).append("_"); - deviceId.append(token.get("modelName")).append("_"); - deviceId.append(token.get("sn")); - } else if(to == Target.IPE) { - deviceId.append(token.get("authId")); - } - } catch (JSONException e) { - e.printStackTrace(); - } - - return deviceId.toString(); - } - - // DM authId, authPwd 불러오기 - public String getAuthId(JSONObject token){ - return token.getString("authId"); - } - public String getAuthPwd(JSONObject token){ - return token.getString("authPwd"); - } - - // 필수 항목 불러오기 - public String getKeyFromId(String deviceId, KeyName keyName){ - String result = null; - String[] idSplit = deviceId.split("_"); - if(idSplit.length == 0){ - idSplit = deviceId.split("_"); - } - switch(keyName){ - case MODEL_NAME: - result = idSplit[1]; - break; - case MANUFACTURER_OUI: - result = idSplit[0]; - break; - case SERIAL_NUMBER: - result = idSplit[2]; - break; - } - return result; - } - - // lwm2m resource uri 불러오기 - public List getUriAndName(JSONObject token){ - - List list = new ArrayList(); - - try { - JSONArray objModels = token.getJSONArray("objectModels"); - for (int i = 0; i < objModels.length(); i++) { - StringBuffer uriBase = new StringBuffer("/"); - uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); - JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); - for (int j = 0; j < resources.length(); j++) { - StringBuffer uri = new StringBuffer(uriBase); - uri.append(resources.getJSONObject(j).get("id")); - - String[] vo = new String[2]; - vo[0] = uri.toString(); - vo[1] = resources.getJSONObject(j).get("name").toString(); - list.add(vo); - } - } - } catch (JSONException e) { - e.printStackTrace(); - } - - return list; - } -} +package net.herit.business.protocol.lwm2m; + +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import net.herit.business.protocol.constant.KeyName; +import net.herit.business.protocol.constant.Target; + +public class LWM2MKeyExtractor { + + // deviceId + public String getDeviceId(JSONObject token){ + return getDeviceId(token, Target.DM); + } + public String getDeviceId(JSONObject token, Target to){ + StringBuffer deviceId = new StringBuffer(); + + try { + if(to == Target.DM){ + deviceId.append(token.get("oui")).append("_"); + deviceId.append(token.get("modelName")).append("_"); + deviceId.append(token.get("sn")); + } else if(to == Target.IPE) { + deviceId.append(token.get("authId")); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + return deviceId.toString(); + } + + // DM authId, authPwd 불러오기 + public String getAuthId(JSONObject token){ + return token.getString("authId"); + } + public String getAuthPwd(JSONObject token){ + return token.getString("authPwd"); + } + + // 필수 항목 불러오기 + public String getKeyFromId(String deviceId, KeyName keyName){ + String result = null; + String[] idSplit = deviceId.split("_"); + if(idSplit.length == 0){ + idSplit = deviceId.split("_"); + } + switch(keyName){ + case MODEL_NAME: + result = idSplit[1]; + break; + case MANUFACTURER_OUI: + result = idSplit[0]; + break; + case SERIAL_NUMBER: + result = idSplit[2]; + break; + } + return result; + } + + // lwm2m resource uri 불러오기 + public List getUriAndName(JSONObject token){ + + List list = new ArrayList(); + + try { + JSONArray objModels = token.getJSONArray("objectModels"); + for (int i = 0; i < objModels.length(); i++) { + StringBuffer uriBase = new StringBuffer("/"); + uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); + JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); + for (int j = 0; j < resources.length(); j++) { + StringBuffer uri = new StringBuffer(uriBase); + uri.append(resources.getJSONObject(j).get("id")); + + String[] vo = new String[2]; + vo[0] = uri.toString(); + vo[1] = resources.getJSONObject(j).get("name").toString(); + list.add(vo); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + + return list; + } +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/Util.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/Util.java index da5fab6..9faeb8b 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/Util.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/Util.java @@ -1,111 +1,111 @@ -package net.herit.business.protocol.lwm2m; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import net.herit.business.protocol.lwm2m.resource.ResourceVO; - -public class Util { - - // is Null Or Empty - public static boolean isNOE(String txt){ - boolean result = false; - if(txt == null || txt.replaceAll(" ", "").equals("")){ - result = true; - } - return result; - } - - public static String makeDeviceId(JSONObject token){ - - StringBuffer deviceId = new StringBuffer(); - - try { - deviceId.append(token.get("oui")).append("_"); - deviceId.append(token.get("modelName")).append("_"); - deviceId.append(token.get("sn")); - } catch (JSONException e) { - e.printStackTrace(); - } - - - return deviceId.toString(); - } - - public static List getUriAndName(JSONObject token){ - - List list = new ArrayList(); - - try { - JSONArray objModels = token.getJSONArray("objectModels"); - for (int i = 0; i < objModels.length(); i++) { - StringBuffer uriBase = new StringBuffer("/"); - uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); - JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); - for (int j = 0; j < resources.length(); j++) { - StringBuffer uri = new StringBuffer(uriBase); - uri.append(resources.getJSONObject(j).get("id")); - - String[] vo = new String[2]; - vo[0] = uri.toString(); - vo[1] = resources.getJSONObject(j).get("name").toString(); - list.add(vo); - } - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return list; - } - - public static HashMap jsonToMap(JSONObject token){ - HashMap map = new HashMap(); - Iterator keys = token.keySet().iterator(); - while(keys.hasNext()){ - String key = keys.next(); - map.put(key, token.getString(key)); - } - return map; - } - - - - - public static String getDataType(String txt){ - String result = ""; - String elseTxt = ""; - - if("integer".equals(txt)){ - result = "I"; - } else if("string".equals(txt)){ - result = "S"; - } else if("boolean".equals(txt)){ - result = "B"; - } else if("float".equals(txt)){ - result = "F"; - } else if("long".equals(txt)){ - result = "L"; - } else if("double".equals(txt)){ - result = "D"; - } else if("time".equals(txt)){ - result = "T"; - } else if("opaque".equals(txt)){ - elseTxt = txt; - } else { - elseTxt = txt; - } - System.out.println(result); - System.out.println(elseTxt); - - return result; - } - -} +package net.herit.business.protocol.lwm2m; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import net.herit.business.protocol.lwm2m.resource.ResourceVO; + +public class Util { + + // is Null Or Empty + public static boolean isNOE(String txt){ + boolean result = false; + if(txt == null || txt.replaceAll(" ", "").equals("")){ + result = true; + } + return result; + } + + public static String makeDeviceId(JSONObject token){ + + StringBuffer deviceId = new StringBuffer(); + + try { + deviceId.append(token.get("oui")).append("_"); + deviceId.append(token.get("modelName")).append("_"); + deviceId.append(token.get("sn")); + } catch (JSONException e) { + e.printStackTrace(); + } + + + return deviceId.toString(); + } + + public static List getUriAndName(JSONObject token){ + + List list = new ArrayList(); + + try { + JSONArray objModels = token.getJSONArray("objectModels"); + for (int i = 0; i < objModels.length(); i++) { + StringBuffer uriBase = new StringBuffer("/"); + uriBase.append(objModels.getJSONObject(i).get("id")).append("/-/"); + JSONArray resources = objModels.getJSONObject(i).getJSONArray("resources"); + for (int j = 0; j < resources.length(); j++) { + StringBuffer uri = new StringBuffer(uriBase); + uri.append(resources.getJSONObject(j).get("id")); + + String[] vo = new String[2]; + vo[0] = uri.toString(); + vo[1] = resources.getJSONObject(j).get("name").toString(); + list.add(vo); + } + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return list; + } + + public static HashMap jsonToMap(JSONObject token){ + HashMap map = new HashMap(); + Iterator keys = token.keySet().iterator(); + while(keys.hasNext()){ + String key = keys.next(); + map.put(key, token.getString(key)); + } + return map; + } + + + + + public static String getDataType(String txt){ + String result = ""; + String elseTxt = ""; + + if("integer".equals(txt)){ + result = "I"; + } else if("string".equals(txt)){ + result = "S"; + } else if("boolean".equals(txt)){ + result = "B"; + } else if("float".equals(txt)){ + result = "F"; + } else if("long".equals(txt)){ + result = "L"; + } else if("double".equals(txt)){ + result = "D"; + } else if("time".equals(txt)){ + result = "T"; + } else if("opaque".equals(txt)){ + elseTxt = txt; + } else { + elseTxt = txt; + } + System.out.println(result); + System.out.println(elseTxt); + + return result; + } + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/exception/JsonFormatException.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/exception/JsonFormatException.java index 3e54074..8217c39 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/exception/JsonFormatException.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/exception/JsonFormatException.java @@ -1,4 +1,4 @@ -package net.herit.business.protocol.lwm2m.exception; - -public class JsonFormatException extends Exception{ -} +package net.herit.business.protocol.lwm2m.exception; + +public class JsonFormatException extends Exception{ +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/resource/ResourceVO.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/resource/ResourceVO.java index 7b6bb5b..1aae8fb 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/resource/ResourceVO.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/lwm2m/resource/ResourceVO.java @@ -1,128 +1,128 @@ -package net.herit.business.protocol.lwm2m.resource; - -import java.sql.Timestamp; - -public class ResourceVO { - private String resource_uri; - private String profile_ver = "1.0"; - private String data_type; - private String unit; - private int noti_type = 0; - private String operation; - private int device_model_id = 97; - private String is_diagnostic = "N"; - private String is_mandatory; - private String display_name; - private String is_multiple; - private String is_historical = "N"; - private String is_error = "N"; - private String default_value; - private String description; - private String is_display = "Y"; - private String display_type; - public String getResource_uri() { - return resource_uri; - } - public void setResource_uri(String resource_uri) { - this.resource_uri = resource_uri; - } - public String getProfile_ver() { - return profile_ver; - } - public void setProfile_ver(String profile_ver) { - this.profile_ver = profile_ver; - } - public String getData_type() { - return data_type; - } - public void setData_type(String data_type) { - this.data_type = data_type; - } - public String getUnit() { - return unit; - } - public void setUnit(String unit) { - this.unit = unit; - } - public int getNoti_type() { - return noti_type; - } - public void setNoti_type(int noti_type) { - this.noti_type = noti_type; - } - public String getOperation() { - return operation; - } - public void setOperation(String operation) { - this.operation = operation; - } - public int getDevice_model_id() { - return device_model_id; - } - public void setDevice_model_id(int device_model_id) { - this.device_model_id = device_model_id; - } - public String getIs_diagnostic() { - return is_diagnostic; - } - public void setIs_diagnostic(String is_diagnostic) { - this.is_diagnostic = is_diagnostic; - } - public String getIs_mandatory() { - return is_mandatory; - } - public void setIs_mandatory(String is_mandatory) { - this.is_mandatory = is_mandatory; - } - public String getDisplay_name() { - return display_name; - } - public void setDisplay_name(String display_name) { - this.display_name = display_name; - } - public String getIs_multiple() { - return is_multiple; - } - public void setIs_multiple(String is_multiple) { - this.is_multiple = is_multiple; - } - public String getIs_historical() { - return is_historical; - } - public void setIs_historical(String is_historical) { - this.is_historical = is_historical; - } - public String getIs_error() { - return is_error; - } - public void setIs_error(String is_error) { - this.is_error = is_error; - } - public String getDefault_value() { - return default_value; - } - public void setDefault_value(String default_value) { - this.default_value = default_value; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getIs_display() { - return is_display; - } - public void setIs_display(String is_display) { - this.is_display = is_display; - } - public String getDisplay_type() { - return display_type; - } - public void setDisplay_type(String display_type) { - this.display_type = display_type; - } - - - -} +package net.herit.business.protocol.lwm2m.resource; + +import java.sql.Timestamp; + +public class ResourceVO { + private String resource_uri; + private String profile_ver = "1.0"; + private String data_type; + private String unit; + private int noti_type = 0; + private String operation; + private int device_model_id = 97; + private String is_diagnostic = "N"; + private String is_mandatory; + private String display_name; + private String is_multiple; + private String is_historical = "N"; + private String is_error = "N"; + private String default_value; + private String description; + private String is_display = "Y"; + private String display_type; + public String getResource_uri() { + return resource_uri; + } + public void setResource_uri(String resource_uri) { + this.resource_uri = resource_uri; + } + public String getProfile_ver() { + return profile_ver; + } + public void setProfile_ver(String profile_ver) { + this.profile_ver = profile_ver; + } + public String getData_type() { + return data_type; + } + public void setData_type(String data_type) { + this.data_type = data_type; + } + public String getUnit() { + return unit; + } + public void setUnit(String unit) { + this.unit = unit; + } + public int getNoti_type() { + return noti_type; + } + public void setNoti_type(int noti_type) { + this.noti_type = noti_type; + } + public String getOperation() { + return operation; + } + public void setOperation(String operation) { + this.operation = operation; + } + public int getDevice_model_id() { + return device_model_id; + } + public void setDevice_model_id(int device_model_id) { + this.device_model_id = device_model_id; + } + public String getIs_diagnostic() { + return is_diagnostic; + } + public void setIs_diagnostic(String is_diagnostic) { + this.is_diagnostic = is_diagnostic; + } + public String getIs_mandatory() { + return is_mandatory; + } + public void setIs_mandatory(String is_mandatory) { + this.is_mandatory = is_mandatory; + } + public String getDisplay_name() { + return display_name; + } + public void setDisplay_name(String display_name) { + this.display_name = display_name; + } + public String getIs_multiple() { + return is_multiple; + } + public void setIs_multiple(String is_multiple) { + this.is_multiple = is_multiple; + } + public String getIs_historical() { + return is_historical; + } + public void setIs_historical(String is_historical) { + this.is_historical = is_historical; + } + public String getIs_error() { + return is_error; + } + public void setIs_error(String is_error) { + this.is_error = is_error; + } + public String getDefault_value() { + return default_value; + } + public void setDefault_value(String default_value) { + this.default_value = default_value; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getIs_display() { + return is_display; + } + public void setIs_display(String is_display) { + this.is_display = is_display; + } + public String getDisplay_type() { + return display_type; + } + public void setDisplay_type(String display_type) { + this.display_type = display_type; + } + + + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/model/EtcProtocol.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/model/EtcProtocol.java index 33f7a2d..ec7ac44 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/model/EtcProtocol.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/model/EtcProtocol.java @@ -1,13 +1,13 @@ -package net.herit.business.protocol.model; - -import org.json.JSONObject; -import org.springframework.web.bind.annotation.RequestMapping; - -public interface EtcProtocol { - - public JSONObject connect(); - - public JSONObject disconnect(); - - -} +package net.herit.business.protocol.model; + +import org.json.JSONObject; +import org.springframework.web.bind.annotation.RequestMapping; + +public interface EtcProtocol { + + public JSONObject connect(); + + public JSONObject disconnect(); + + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/CurlOperation.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/CurlOperation.java index 93eb1fe..9da2a3f 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/CurlOperation.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/CurlOperation.java @@ -1,266 +1,266 @@ -package net.herit.business.protocol.tr069; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.eclipse.persistence.sessions.Session; -import org.json.JSONObject; - -import com.mashape.unirest.http.Headers; - -import net.herit.business.protocol.Util; - -public class CurlOperation { - - // HTTP Objects - private HttpClient httpClient = null; - private HttpEntity entity = null; - private HttpResponse httpResponse = null; - - // Initialize - public CurlOperation(){ - headers = new HashMap(); - - cmdList = new HashMap(); - numberList = new HashMap(); - - setCmdList(); - setNumberList(); - httpClient = new DefaultHttpClient(); - } - - // Command list - private HashMap cmdList = null; - public HashMap getCmdList(){ - return cmdList; - } - public void setCmdList(){ - cmdList.put("get file","get"); - cmdList.put("file upload","put"); - cmdList.put("getParameterValues","post"); - cmdList.put("setParameterValues","post"); - cmdList.put("refresh","post"); - cmdList.put("reboot","post"); - cmdList.put("file download","post"); - cmdList.put("delete task","delete"); - cmdList.put("delete file","delete"); - } - - // The number of Parameter by operation - private HashMap numberList = null; - public HashMap getNumberList(){ - return numberList; - } - public void setNumberList(){ - numberList.put("get",1); - numberList.put("put",3); - numberList.put("post",2); - numberList.put("delete",1); - } - - // Get,Set HTTP Header - private HashMap headers = null; - public HashMap getHeader(){ - return headers; - } - public void setHeader(String key, String value){ - headers.put(key, value); - } - - - // Send msg - public String send(String operation, Object ...params) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{ - // 입력값, 개수 확인 - String httpMethod = cmdList.get(operation); - int tnop = numberList.get(httpMethod); - if(params == null || params.length < 1 || tnop != params.length){ - throw new ArrayIndexOutOfBoundsException(operation+" 은/는 "+tnop+"개의 parameter가 필요합니다."); - } - - // ACS서버 확인 - String acsUri = (String)params[0]; - if(Util.getInstance().isNOE(acsUri)){ - throw new NullPointerException("ACS address정보가 필요합니다."); - } - - System.out.println("DDDDDDDDDDDDDD555555555555DDDDDDDDDDD"); - // Method별 호출 - /*CurlOperation co = new CurlOperation(); - Method mtd = co.getClass().getMethod(httpMethod, new Class[]{Object.class}); - String response = (String)mtd.invoke(co, params);*/ - - String response = null; - if(httpMethod.equals("put")){ - response = put(params); - } else if(httpMethod.equals("post")) { - response = post(params); - } - return response; - } - - // PUT API - public String put(Object[] params){ - // params 초기화 - String uri = (String)params[0]; - HashMap headers = (HashMap)params[1]; - String path = (String)params[2]; - HttpEntity httpEntity = null; - - HttpPut httpPut = null; - try{ - httpClient = HttpClientBuilder.create().build(); - httpPut = new HttpPut(uri+"/files/"+path.substring(path.lastIndexOf("/")+1)); - Iterator keys = headers.keySet().iterator(); - while(keys.hasNext()){ - String name = keys.next(); - String value = headers.get(name); - System.out.println("…………… "+name+" : "+value); - httpPut.setHeader(name, value); - } - - File file = new File(path); - httpEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) - .addBinaryBody("file", file, ContentType.create("application/json"), path.substring(0, path.lastIndexOf("/"))).build(); - httpPut.setEntity(httpEntity); - - httpResponse = httpClient.execute(httpPut); - entity = httpResponse.getEntity(); - - // 응답 결과 - System.out.println("----------------------------------------"); - System.out.println(httpResponse.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); - - String line = ""; - while ((line = rd.readLine()) != null) { - System.out.println(line); - } - } - httpPut.abort(); - System.out.println("----------------------------------------"); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(httpClient != null){ - httpClient.getConnectionManager().shutdown(); - } - } - - return httpResponse.toString(); - } - - // POST API - public String post(Object[] params){ - // params 초기화 - String uri = (String)params[0]; - JSONObject param = (JSONObject)params[1]; - - HttpPost httpPost = null; - try{ - httpClient = HttpClientBuilder.create().build(); - httpPost = new HttpPost(uri); - - - StringEntity stringEntity = new StringEntity(param.toString()); - httpPost.addHeader("content-type", "application/json"); - httpPost.setEntity(stringEntity); - - httpResponse = httpClient.execute(httpPost); - - // 응답 결과 - System.out.println("----------------------------------------"); - System.out.println(httpResponse.getStatusLine()); - if (httpResponse != null) { - BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); - - String line = ""; - while ((line = rd.readLine()) != null) { - System.out.println(line); - } - } - httpPost.abort(); - System.out.println("----------------------------------------"); - - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(httpClient != null){ - httpClient.getConnectionManager().shutdown(); - } - } - - return httpResponse.toString(); - } - - // GET API - public String get(Object[] params){ - HttpGet httpGet = null; - try{ - - } catch(Exception e) { - - } finally { - - } - return null; - } - - // DELETE API - public String delete(Object[] params){ - HttpDelete httpDelete = null; - try{ - - } catch(Exception e) { - - } finally { - - } - return null; - } - - public String getUriByHttpMethod(String httpMethod, String ip, String port, String deviceId){ - StringBuffer sb = new StringBuffer("http://"); - sb.append(ip).append(":").append(port); - - if(httpMethod.equals("put")){ - - } else if(httpMethod.equals("post")){ - sb.append("/devices/").append(deviceId).append("/tasks?timeout=3000&connection_request"); - } else if(httpMethod.equals("get")){ - - } else if(httpMethod.equals("delete")){ - - } - - return sb.toString(); - } - - - - -} +package net.herit.business.protocol.tr069; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.eclipse.persistence.sessions.Session; +import org.json.JSONObject; + +import com.mashape.unirest.http.Headers; + +import net.herit.business.protocol.Util; + +public class CurlOperation { + + // HTTP Objects + private HttpClient httpClient = null; + private HttpEntity entity = null; + private HttpResponse httpResponse = null; + + // Initialize + public CurlOperation(){ + headers = new HashMap(); + + cmdList = new HashMap(); + numberList = new HashMap(); + + setCmdList(); + setNumberList(); + httpClient = new DefaultHttpClient(); + } + + // Command list + private HashMap cmdList = null; + public HashMap getCmdList(){ + return cmdList; + } + public void setCmdList(){ + cmdList.put("get file","get"); + cmdList.put("file upload","put"); + cmdList.put("getParameterValues","post"); + cmdList.put("setParameterValues","post"); + cmdList.put("refresh","post"); + cmdList.put("reboot","post"); + cmdList.put("file download","post"); + cmdList.put("delete task","delete"); + cmdList.put("delete file","delete"); + } + + // The number of Parameter by operation + private HashMap numberList = null; + public HashMap getNumberList(){ + return numberList; + } + public void setNumberList(){ + numberList.put("get",1); + numberList.put("put",3); + numberList.put("post",2); + numberList.put("delete",1); + } + + // Get,Set HTTP Header + private HashMap headers = null; + public HashMap getHeader(){ + return headers; + } + public void setHeader(String key, String value){ + headers.put(key, value); + } + + + // Send msg + public String send(String operation, Object ...params) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{ + // 입력값, 개수 확인 + String httpMethod = cmdList.get(operation); + int tnop = numberList.get(httpMethod); + if(params == null || params.length < 1 || tnop != params.length){ + throw new ArrayIndexOutOfBoundsException(operation+" 은/는 "+tnop+"개의 parameter가 필요합니다."); + } + + // ACS서버 확인 + String acsUri = (String)params[0]; + if(Util.getInstance().isNOE(acsUri)){ + throw new NullPointerException("ACS address정보가 필요합니다."); + } + + System.out.println("DDDDDDDDDDDDDD555555555555DDDDDDDDDDD"); + // Method별 호출 + /*CurlOperation co = new CurlOperation(); + Method mtd = co.getClass().getMethod(httpMethod, new Class[]{Object.class}); + String response = (String)mtd.invoke(co, params);*/ + + String response = null; + if(httpMethod.equals("put")){ + response = put(params); + } else if(httpMethod.equals("post")) { + response = post(params); + } + return response; + } + + // PUT API + public String put(Object[] params){ + // params 초기화 + String uri = (String)params[0]; + HashMap headers = (HashMap)params[1]; + String path = (String)params[2]; + HttpEntity httpEntity = null; + + HttpPut httpPut = null; + try{ + httpClient = HttpClientBuilder.create().build(); + httpPut = new HttpPut(uri+"/files/"+path.substring(path.lastIndexOf("/")+1)); + Iterator keys = headers.keySet().iterator(); + while(keys.hasNext()){ + String name = keys.next(); + String value = headers.get(name); + System.out.println("…………… "+name+" : "+value); + httpPut.setHeader(name, value); + } + + File file = new File(path); + httpEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) + .addBinaryBody("file", file, ContentType.create("application/json"), path.substring(0, path.lastIndexOf("/"))).build(); + httpPut.setEntity(httpEntity); + + httpResponse = httpClient.execute(httpPut); + entity = httpResponse.getEntity(); + + // 응답 결과 + System.out.println("----------------------------------------"); + System.out.println(httpResponse.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); + + String line = ""; + while ((line = rd.readLine()) != null) { + System.out.println(line); + } + } + httpPut.abort(); + System.out.println("----------------------------------------"); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(httpClient != null){ + httpClient.getConnectionManager().shutdown(); + } + } + + return httpResponse.toString(); + } + + // POST API + public String post(Object[] params){ + // params 초기화 + String uri = (String)params[0]; + JSONObject param = (JSONObject)params[1]; + + HttpPost httpPost = null; + try{ + httpClient = HttpClientBuilder.create().build(); + httpPost = new HttpPost(uri); + + + StringEntity stringEntity = new StringEntity(param.toString()); + httpPost.addHeader("content-type", "application/json"); + httpPost.setEntity(stringEntity); + + httpResponse = httpClient.execute(httpPost); + + // 응답 결과 + System.out.println("----------------------------------------"); + System.out.println(httpResponse.getStatusLine()); + if (httpResponse != null) { + BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); + + String line = ""; + while ((line = rd.readLine()) != null) { + System.out.println(line); + } + } + httpPost.abort(); + System.out.println("----------------------------------------"); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(httpClient != null){ + httpClient.getConnectionManager().shutdown(); + } + } + + return httpResponse.toString(); + } + + // GET API + public String get(Object[] params){ + HttpGet httpGet = null; + try{ + + } catch(Exception e) { + + } finally { + + } + return null; + } + + // DELETE API + public String delete(Object[] params){ + HttpDelete httpDelete = null; + try{ + + } catch(Exception e) { + + } finally { + + } + return null; + } + + public String getUriByHttpMethod(String httpMethod, String ip, String port, String deviceId){ + StringBuffer sb = new StringBuffer("http://"); + sb.append(ip).append(":").append(port); + + if(httpMethod.equals("put")){ + + } else if(httpMethod.equals("post")){ + sb.append("/devices/").append(deviceId).append("/tasks?timeout=3000&connection_request"); + } else if(httpMethod.equals("get")){ + + } else if(httpMethod.equals("delete")){ + + } + + return sb.toString(); + } + + + + +} diff --git a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/TR069ConnectOperator.java b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/TR069ConnectOperator.java index 47c6e6b..d94165a 100644 --- a/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/TR069ConnectOperator.java +++ b/si-modules/DM_Web_Server/src/main/java/net/herit/business/protocol/tr069/TR069ConnectOperator.java @@ -1,259 +1,259 @@ -package net.herit.business.protocol.tr069; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Resource; - -import org.json.JSONObject; -import org.springframework.stereotype.Service; - -import net.herit.business.api.service.ApiHdhDAO; -import net.herit.business.api.service.ApiHdmDAO; -import net.herit.business.api.service.ApiHdpDAO; -import net.herit.business.device.service.DeviceModelVO; -import net.herit.business.device.service.DeviceService; -import net.herit.business.device.service.MoProfileVO; -import net.herit.business.protocol.DmVO; -import net.herit.business.protocol.constant.Errors; -import net.herit.business.protocol.constant.Target; -import net.herit.business.protocol.constant.Type; -import net.herit.common.exception.UserSysException; - -@Service("Connector") -public class TR069ConnectOperator { - - @Resource(name = "DeviceService") - private DeviceService deviceService; - - @Resource(name="ApiHdhDAO") - private ApiHdhDAO hdhDAO; - @Resource(name="ApiHdmDAO") - private ApiHdmDAO hdmDAO; - @Resource(name="ApiHdpDAO") - private ApiHdpDAO hdpDAO; - - private String acsIp = null; - private int acsPort = 0; - - private static TR069ConnectOperator instance; - public static TR069ConnectOperator getInstance(){ - if(instance == null){ - instance = new TR069ConnectOperator(); - } - return instance; - } - - private DeviceModelVO deviceModel; - public DeviceModelVO getDeviceModelVO(){ - return deviceModel; - } - - private JSONObject token; - public JSONObject getToken(){ - return token; - } - private JSONObject inform; - public JSONObject getInform(){ - return inform; - } - private String deviceId; - public String getDeivceId(){ - return deviceId; - } - - /** 최초 token과 deviceId 저장 **/ - public void regist(JSONObject token, JSONObject inform, String deviceId){ - this.token = token; - this.inform = inform; - this.deviceId = deviceId; - } - - /** 등록 조회 : hdp_device_model - * @throws Exception **/ - public void checkDeviceModelRegistered(String modelName) throws Exception{ - System.out.println(modelName); - int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(modelName); - if(deviceModelCount != 1){ - // 기대값이 아니므로 exception 발생 - throw new Exception(Errors.ERR_500.getMsg()); - } else { - deviceModel = hdpDAO.getDeviceModelId(modelName); - } - } - public DeviceModelVO checkDeviceModelRegist(String modelName) throws Exception{ - DeviceModelVO deviceModel = null; - int deviceModelCount = hdpDAO.getDeviceModelCountByModelName(modelName); - if(deviceModelCount != 1){ - // 기대값이 아니므로 exception 발생 - throw new Exception(Errors.ERR_500.getMsg()); - } else { - deviceModel = hdpDAO.getDeviceModelId(modelName); - } - return deviceModel; - } - - /** 등록 조회 : hdp_mo_profile - * @throws Exception **/ - public void checkDeviceModelProfileRegistered() throws Exception{ - int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); - if(profileCount < 1){ - // 최소 1개 이상의 resource가 등록되어야 함 - throw new Exception(Errors.ERR_500.getMsg()); - } - } - public void checkDeviceModelProfileRegist(DeviceModelVO deviceModel) throws Exception{ - int profileCount = hdpDAO.getMoProfileCountByDeviceModelId(deviceModel.getId()); - if(profileCount < 1){ - // 최소 1개 이상의 resource가 등록되어야 함 - throw new Exception(Errors.ERR_500.getMsg()); - } - } - - /** 등록 조회 : hdm_device - * @throws Exception **/ - public void checkDeviceRegistered(Type protocol) throws Exception{ - int deviceCount = hdmDAO.getCountByAuthAccount(deviceId, inform, protocol); - if(deviceCount == 0){ - throw new Exception(Errors.ERR_500.getMsg()); - } else if (deviceCount == 1) { - registResourceModel(protocol); - } else { - throw new Exception(Errors.ERR_500.getMsg()); - } - } - public void checkDeviceRegist(DmVO vo) throws Exception{ - int deviceCount = hdmDAO.getCountByAuthAccount(TR069Formatter.getInstance().getDeviceId(vo.getDeviceId(), Target.DM), vo.getInform(), Type.TR_069); - if(deviceCount == 0){ - throw new Exception(Errors.ERR_500.getMsg()); - } else if (deviceCount == 1) { - registResourceModel(vo); - } else { - throw new Exception(Errors.ERR_500.getMsg()); - } - } - - /** 리소스 등록 - * @throws UserSysException - */ - public void registResources() throws UserSysException{ - // resource 개수 파악 - int resourceCount = hdmDAO.getResourceCountByDeviceId(deviceId); - - List uriList = new ArrayList(); - String uriString = token.getString("uriString"); - uriString = uriString.replace(",", "/"); - String[] uriSplit = uriString.split("@@"); - for(int i=0; i uriList = new ArrayList(); - String uriString = vo.getUriString().replace(",", "/"); - String[] uriSplit = uriString.split("@@"); - for(int i=0; i uriList = new ArrayList(); + String uriString = token.getString("uriString"); + uriString = uriString.replace(",", "/"); + String[] uriSplit = uriString.split("@@"); + for(int i=0; i uriList = new ArrayList(); + String uriString = vo.getUriString().replace(",", "/"); + String[] uriSplit = uriString.split("@@"); + for(int i=0; i getUriList(DmVO vo){ - List uriList = new ArrayList(); - String uriString = vo.getUriString().replace(",", "/"); - String[] uriSplit = uriString.split("@@"); - for(int i=0; i getUriList(DmVO vo){ + List uriList = new ArrayList(); + String uriString = vo.getUriString().replace(",", "/"); + String[] uriSplit = uriString.split("@@"); + for(int i=0; i index -# 2. views/herit/business/common/common.jsp -> herit/business/common/common -#------------------------------------------------------------------------------- - -# Globals.IndexPage = /v2/monitor/index -Globals.LoginPage = /v2/login - -#mobile용 로그인 페이지 -Globals.mLoginPage = /mobile/mLogin - -# 읽기 권한 없을때 돌아가는 페이지 -#Globals.MainPage = /home/main.do -Globals.MainPage = /v2/monitor/index - -#mobile용 메인 페이지 -Globals.mMainPage = /mobile/index -Globals.mFirstPage = /mdevice/detail - - -#----------------------------------------------- -# 로그인 실패 횟수 지정 -#----------------------------------------------- -# 로그인 실패 횟수 지정 -Globals.LoginFailCount = 5 - -#----------------------------------------------- -# List Paging Setting -#----------------------------------------------- -# 페이지 size -Globals.PageSize = 10 -# 페이지셋 size -Globals.PagesetSize = 10 - -#----------------------------------------------- -# Error Log Setting -#----------------------------------------------- -# 오류 로그 ON/OFF -Globals.ErrorFileOnOff = OFF -# 오류 로그 경로 설정 -Globals.ErrorFilePath = C:\\logs\\ -#Globals.ErrorFilePath = /usr/local/chs/tomcat/logs/ -#Globals.ErrorFilePath = /usr/local/hit/tomcat/logs/ -#Globals.ErrorFilePath = /svc/chs/was/tomcat/pttSvr11/logs/ - -#----------------------------------------------- -# 파일 업로드 경로(경로 설정은 반드시 절대경로를 사용해야함, 경로 뒤에 /를 붙여 주어야함.) -#----------------------------------------------- -#Globals.hostUrl = http://127.0.0.1:8080 -#Globals.tomcatDir = D://hdm/webapps -#Globals.uploadDir = /files/ - -#Globals.hostUrl = http://10.10.224.240:8089 -#Globals.tomcatDir = /usr/local/hdm/tomcat/webapps -#Globals.uploadDir = /files/ -#Globals.firmwareDir = /usr/local/hdm/nodejs/work/firmware/ - -Globals.hostUrl = http://10.10.0.23:8089 -Globals.tomcatDir = C:/uploads -Globals.uploadDir = /files/ -Globals.firmwareDir = C:/uploads/firmware/ - - -#----------------------------------------------- -# LWM2M 서버 정보 -#----------------------------------------------- -Globals.lwm2mServerHost = 10.10.0.23 -Globals.lwm2mServerPort = 8085 - -#----------------------------------------------- -# TR069 서버 정보(ACS) -#----------------------------------------------- -Globals.tr069ServerHost = 10.10.0.82 -Globals.tr069ServerPort = 7557 - -#----------------------------------------------- -# DM 서버 정보 -#----------------------------------------------- -Globals.dmServerHost = 10.101.101.177 -Globals.dmServerPort = 8888 - -#----------------------------------------------- -# 파일서버 정보 -#----------------------------------------------- -Globals.fileServerHost = 10.101.101.177 -Globals.fileServerPort = 8000 - -#----------------------------------------------- -# 서비스 MO 정보 -#----------------------------------------------- - -Globals.ServiceMoId = 99 -Globals.ServiceMoIdMax = 101 - -#----------------------------------------------- -# v2 GUI JS ROOT PATH -#----------------------------------------------- -Globals.v2JSRootPath = /hdm/v2/js/ - - -#----------------------------------------------- -# OneM2M 정보 -#----------------------------------------------- -Globals.UseOneM2M = true -Globals.aeTimeout = 2500 -Globals.aeId = CAE_HUBISS_ADMIN -Globals.aeName = hubiss_admin -Globals.appId = HUBISS -Globals.appName = HUBISS_ADMIN -Globals.cseAddr = http://10.10.0.23:8080 -#Globals.csebase = /herit-cse -Globals.csebase = /herit-in/herit-cse -#Globals.csebase = /mobius-yt -Globals.csebaseName = herit-cse -Globals.cseId = herit-in -Globals.ip = 10.10.0.23 -Globals.port = 8080 -Globals.poa = http://10.10.0.23:8080 -Globals.oneM2MHostUrl = http://10.10.0.23:8080 - -#----------------------------------------------- -# Fi-Ware 서버 정보 -#----------------------------------------------- -Globals.fiwareServerHost = 10.10.0.23 -Globals.fiwareServerPort = 1026 -Globals.fiwareService = myHome -Globals.fiwareServicePath = /environment -Globals.fiwareAgentUrl = http://10.10.224.240:7896/iot/d/commands +#----------------------------------------------- +# Server OS Type (window, linux, unix) +#----------------------------------------------- +Globals.OSType = window +#Globals.OSType = linux +#Globals.OSType = unix + +#----------------------------------------------- +# Server DB Type (oracle, mysql, altibase) +#----------------------------------------------- +#Globals.DBType = oracle +Globals.DBType = mysql +#Globals.DBType = altibase + +#----------------------------------------------- +# DB Driver Setting +#----------------------------------------------- +# MySQL +Globals.DriverClassName = com.mysql.jdbc.Driver +#Globals.URL = jdbc:mysql://10.101.101.107:3306/hdp + +# Oracle +#Globals.DriverClassName=oracle.jdbc.driver.OracleDriver +#Globals.URL=jdbc:oracle:thin:@127.0.0.1:1521:M2MWEB +# Altibase +#Globals.DriverClassName=Altibase.jdbc.driver.AltibaseDriver +#Globals.URL=jdbc:Altibase://10.101.101.146:20300/mydb + + +#----------------------------------------------- +# DB Account Info Setting +#----------------------------------------------- +# Remote +#Globals.UserName = chs +#Globals.Password = lgchspwd12#$ +# Local +#Globals.UserName = ini +#Globals.Password = ini + +Globals.contextPath = /hdm + +#----------------------------------------------- +# hdh db setting +#----------------------------------------------- +Globals.HDH.Database.URL = jdbc:mysql://10.10.0.39:3306/hdh +#Globals.HDH.Database.URL = jdbc:mysql://10.10.222.139:3306/hdh +Globals.HDH.Database.Account.UserName = ini +Globals.HDH.Database.Account.Password = ini + + +#----------------------------------------------- +# hdp db setting +#----------------------------------------------- +Globals.HDP.Database.URL = jdbc:mysql://10.10.0.39:3306/hdp +#Globals.HDP.Database.URL = jdbc:mysql://10.10.222.139:3306/hdp +Globals.HDP.Database.Account.UserName = ini +Globals.HDP.Database.Account.Password = ini + + +#----------------------------------------------- +# hdm db setting +#----------------------------------------------- +Globals.HDM.Database.URL = jdbc:mysql://10.10.0.39:3306/hdm +#Globals.HDM.Database.URL = jdbc:mysql://10.10.222.139:3306/hdm +Globals.HDM.Database.Account.UserName = ini +Globals.HDM.Database.Account.Password = ini + + +#----------------------------------------------- +# mongodb setting +#----------------------------------------------- +Globals.MongoDB.Host = 10.10.0.23 +Globals.MongoDB.Port = 27017 +Globals.MongoDB.User = herit +Globals.MongoDB.Password = qrwe1423 +Globals.MongoDB.DBName = IITP-IOT +Globals.MongoDB.Collection = resource + + +#----------------------------------------------- +# Portal Type Setting +#----------------------------------------------- +# For Admin +#Globals.PortalType = admin +# For User +Globals.PortalType = user + +#----------------------------------------------- +# WEB Account SUPER ADMIN Setting +#----------------------------------------------- +# Super Admin Login Id +Globals.SuperAdminUserId = smart + +#------------------------------------------------------------------------------- +# Welcome Page(First Page or Main Page) Setting +# ex) 1. views/index.jsp -> index +# 2. views/herit/business/common/common.jsp -> herit/business/common/common +#------------------------------------------------------------------------------- + +# Globals.IndexPage = /v2/monitor/index +Globals.LoginPage = /v2/login + +#mobile용 로그인 페이지 +Globals.mLoginPage = /mobile/mLogin + +# 읽기 권한 없을때 돌아가는 페이지 +#Globals.MainPage = /home/main.do +Globals.MainPage = /v2/monitor/index + +#mobile용 메인 페이지 +Globals.mMainPage = /mobile/index +Globals.mFirstPage = /mdevice/detail + + +#----------------------------------------------- +# 로그인 실패 횟수 지정 +#----------------------------------------------- +# 로그인 실패 횟수 지정 +Globals.LoginFailCount = 5 + +#----------------------------------------------- +# List Paging Setting +#----------------------------------------------- +# 페이지 size +Globals.PageSize = 10 +# 페이지셋 size +Globals.PagesetSize = 10 + +#----------------------------------------------- +# Error Log Setting +#----------------------------------------------- +# 오류 로그 ON/OFF +Globals.ErrorFileOnOff = OFF +# 오류 로그 경로 설정 +Globals.ErrorFilePath = C:\\logs\\ +#Globals.ErrorFilePath = /usr/local/chs/tomcat/logs/ +#Globals.ErrorFilePath = /usr/local/hit/tomcat/logs/ +#Globals.ErrorFilePath = /svc/chs/was/tomcat/pttSvr11/logs/ + +#----------------------------------------------- +# 파일 업로드 경로(경로 설정은 반드시 절대경로를 사용해야함, 경로 뒤에 /를 붙여 주어야함.) +#----------------------------------------------- +#Globals.hostUrl = http://127.0.0.1:8080 +#Globals.tomcatDir = D://hdm/webapps +#Globals.uploadDir = /files/ + +#Globals.hostUrl = http://10.10.224.240:8089 +#Globals.tomcatDir = /usr/local/hdm/tomcat/webapps +#Globals.uploadDir = /files/ +#Globals.firmwareDir = /usr/local/hdm/nodejs/work/firmware/ + +Globals.hostUrl = http://10.10.0.23:8089 +Globals.tomcatDir = C:/uploads +Globals.uploadDir = /files/ +Globals.firmwareDir = C:/uploads/firmware/ + + +#----------------------------------------------- +# LWM2M 서버 정보 +#----------------------------------------------- +Globals.lwm2mServerHost = 10.10.0.23 +Globals.lwm2mServerPort = 8085 + +#----------------------------------------------- +# TR069 서버 정보(ACS) +#----------------------------------------------- +Globals.tr069ServerHost = 10.10.0.82 +Globals.tr069ServerPort = 7557 + +#----------------------------------------------- +# DM 서버 정보 +#----------------------------------------------- +Globals.dmServerHost = 10.101.101.177 +Globals.dmServerPort = 8888 + +#----------------------------------------------- +# 파일서버 정보 +#----------------------------------------------- +Globals.fileServerHost = 10.101.101.177 +Globals.fileServerPort = 8000 + +#----------------------------------------------- +# 서비스 MO 정보 +#----------------------------------------------- + +Globals.ServiceMoId = 99 +Globals.ServiceMoIdMax = 101 + +#----------------------------------------------- +# v2 GUI JS ROOT PATH +#----------------------------------------------- +Globals.v2JSRootPath = /hdm/v2/js/ + + +#----------------------------------------------- +# OneM2M 정보 +#----------------------------------------------- +Globals.UseOneM2M = true +Globals.aeTimeout = 2500 +Globals.aeId = CAE_HUBISS_ADMIN +Globals.aeName = hubiss_admin +Globals.appId = HUBISS +Globals.appName = HUBISS_ADMIN +Globals.cseAddr = http://10.10.0.23:8080 +#Globals.csebase = /herit-cse +Globals.csebase = /herit-in/herit-cse +#Globals.csebase = /mobius-yt +Globals.csebaseName = herit-cse +Globals.cseId = herit-in +Globals.ip = 10.10.0.23 +Globals.port = 8080 +Globals.poa = http://10.10.0.23:8080 +Globals.oneM2MHostUrl = http://10.10.0.23:8080 + +#----------------------------------------------- +# Fi-Ware 서버 정보 +#----------------------------------------------- +Globals.fiwareServerHost = 10.10.0.23 +Globals.fiwareServerPort = 1026 +Globals.fiwareService = myHome +Globals.fiwareServicePath = /environment +Globals.fiwareAgentUrl = http://10.10.224.240:7896/iot/d/commands Globals.fiwareAgentAccessKey = AAFF9977 \ No newline at end of file diff --git a/si-modules/DM_Web_Server/src/main/webapp/v2/js/herit/component/device.status.single_num_bar_lwm2m_ip.js b/si-modules/DM_Web_Server/src/main/webapp/v2/js/herit/component/device.status.single_num_bar_lwm2m_ip.js index 833eb3b..0ac21c3 100644 --- a/si-modules/DM_Web_Server/src/main/webapp/v2/js/herit/component/device.status.single_num_bar_lwm2m_ip.js +++ b/si-modules/DM_Web_Server/src/main/webapp/v2/js/herit/component/device.status.single_num_bar_lwm2m_ip.js @@ -1,66 +1,66 @@ -// Custom scripts -$(document).ready(function () { - - dssnb_lwm2m_ip.init(); - - console.log("device.status.single_num_bar js initialized"); - - $(".dssnb_lwm2m_ip-bar-graph").peity("bar", { - fill: ["#1ab394", "#d7d7d7"] - }) -}); - -var dssnb_lwm2m_ip = { - divs: null, - resources: null, - init: function() { - dssnb_lwm2m_ip.divs = $(".hit-component-dssnb_lwm2m_ip"); - dssnb_lwm2m_ip.resources = []; - $.each(dssnb_lwm2m_ip.divs, function(idx, div) { - $.each(_ucc.getResListWithComponentDiv(div), function(idx, val) { - dssnb_lwm2m_ip.resources.push(val); - }); - //dssnb_lwm2m_ip.resources.push(_ucc.getResListWithComponentDiv(div)); - //dssnb_lwm2m_ip.resources = _ucc.getResListWithComponentDiv(div); - }); - - _ucc.setResourceHandler("dssnb_lwm2m_ip", dssnb_lwm2m_ip.resources, dssnb_lwm2m_ip.refresh); - dssnb_lwm2m_ip.refresh(); - }, - refresh: function(type) { - console.log("dssnb_lwm2m_ip.refresh("+type+") called"); - - $.each(dssnb_lwm2m_ip.divs, function(idx, div) { - dssnb_lwm2m_ip.refreshComponent(div); - }); - }, - refreshComponent: function(div) { - var resources = _ucc.getResListWithComponentDiv(div); - - var moData = _ucc.getMoData(resources[0]); - var unit = _ucc.getUnitString(resources[0]); - - - if (moData == null || typeof moData == "undefined") { - console.error("디바이스에 대해서 MO데이터가 정의되지 않았습니다. (dssnb_lwm2m_ip:"+resources[0]+")"); - //alert("디바이스에 대해서 MO데이터가 정의되지 않았습니다. (dssnb_lwm2m_ip:"+resources[0]+")"); - $(div).find(".dssnb_lwm2m_ip-value").text("-"); - $(div).find(".dssnb_lwm2m_ip-unit").text("-"); - return; - } - - - var value = moData.data; - var realIp = value; - /* - if(value != null && value != undefined && value.indexOf("\n")){ - var valArray = value.split("\n"); - realIp = valArray[1]; - } - */ - $(div).find(".dssnb_lwm2m_ip-value").text(realIp); - $(div).find(".dssnb_lwm2m_ip-unit").text(unit); - - } -} - +// Custom scripts +$(document).ready(function () { + + dssnb_lwm2m_ip.init(); + + console.log("device.status.single_num_bar js initialized"); + + $(".dssnb_lwm2m_ip-bar-graph").peity("bar", { + fill: ["#1ab394", "#d7d7d7"] + }) +}); + +var dssnb_lwm2m_ip = { + divs: null, + resources: null, + init: function() { + dssnb_lwm2m_ip.divs = $(".hit-component-dssnb_lwm2m_ip"); + dssnb_lwm2m_ip.resources = []; + $.each(dssnb_lwm2m_ip.divs, function(idx, div) { + $.each(_ucc.getResListWithComponentDiv(div), function(idx, val) { + dssnb_lwm2m_ip.resources.push(val); + }); + //dssnb_lwm2m_ip.resources.push(_ucc.getResListWithComponentDiv(div)); + //dssnb_lwm2m_ip.resources = _ucc.getResListWithComponentDiv(div); + }); + + _ucc.setResourceHandler("dssnb_lwm2m_ip", dssnb_lwm2m_ip.resources, dssnb_lwm2m_ip.refresh); + dssnb_lwm2m_ip.refresh(); + }, + refresh: function(type) { + console.log("dssnb_lwm2m_ip.refresh("+type+") called"); + + $.each(dssnb_lwm2m_ip.divs, function(idx, div) { + dssnb_lwm2m_ip.refreshComponent(div); + }); + }, + refreshComponent: function(div) { + var resources = _ucc.getResListWithComponentDiv(div); + + var moData = _ucc.getMoData(resources[0]); + var unit = _ucc.getUnitString(resources[0]); + + + if (moData == null || typeof moData == "undefined") { + console.error("디바이스에 대해서 MO데이터가 정의되지 않았습니다. (dssnb_lwm2m_ip:"+resources[0]+")"); + //alert("디바이스에 대해서 MO데이터가 정의되지 않았습니다. (dssnb_lwm2m_ip:"+resources[0]+")"); + $(div).find(".dssnb_lwm2m_ip-value").text("-"); + $(div).find(".dssnb_lwm2m_ip-unit").text("-"); + return; + } + + + var value = moData.data; + var realIp = value; + /* + if(value != null && value != undefined && value.indexOf("\n")){ + var valArray = value.split("\n"); + realIp = valArray[1]; + } + */ + $(div).find(".dssnb_lwm2m_ip-value").text(realIp); + $(div).find(".dssnb_lwm2m_ip-unit").text(unit); + + } +} + diff --git a/si-modules/LWM2M_IPE_Client/leshan-client-demo/.classpath b/si-modules/LWM2M_IPE_Client/leshan-client-demo/.classpath deleted file mode 100644 index 698778f..0000000 --- a/si-modules/LWM2M_IPE_Client/leshan-client-demo/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF b/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF index d1b092f..97a6a41 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF +++ b/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF @@ -1,7 +1,7 @@ -Manifest-Version: 1.0 -Built-By: MSH -Build-Jdk: 1.7.0_79 -Created-By: Apache Maven 3.3.3 -Main-Class: org.eclipse.leshan.client.demo.LeshanClientDemo -Archiver-Version: Plexus Archiver - +Manifest-Version: 1.0 +Built-By: MSH +Build-Jdk: 1.7.0_79 +Created-By: Apache Maven 3.3.3 +Main-Class: org.eclipse.leshan.client.demo.LeshanClientDemo +Archiver-Version: Plexus Archiver + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF.bak b/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF.bak index 3c9e740..35e083b 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF.bak +++ b/si-modules/LWM2M_IPE_Server/META-INF/MANIFEST.MF.bak @@ -1,7 +1,7 @@ -Manifest-Version: 1.0 -Built-By: 문선호 -Build-Jdk: 1.7.0_79 -Created-By: Apache Maven 3.3.3 -Main-Class: org.eclipse.leshan.client.demo.LeshanClientDemo -Archiver-Version: Plexus Archiver - +Manifest-Version: 1.0 +Built-By: 문선호 +Build-Jdk: 1.7.0_79 +Created-By: Apache Maven 3.3.3 +Main-Class: org.eclipse.leshan.client.demo.LeshanClientDemo +Archiver-Version: Plexus Archiver + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.properties b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.properties index e56bec6..9ff5af7 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.properties +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.properties @@ -1,5 +1,5 @@ -#Generated by org.apache.felix.bundleplugin -#Wed Mar 08 17:49:47 KST 2017 -version=0.1.11-M13-SNAPSHOT -groupId=org.eclipse.leshan -artifactId=leshan-client-cf +#Generated by org.apache.felix.bundleplugin +#Wed Mar 08 17:49:47 KST 2017 +version=0.1.11-M13-SNAPSHOT +groupId=org.eclipse.leshan +artifactId=leshan-client-cf diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.xml b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.xml index 9f14446..e19eb10 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.xml +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-cf/pom.xml @@ -1,80 +1,80 @@ - - - 4.0.0 - - org.eclipse.leshan - leshan - 0.1.11-M13-SNAPSHOT - - leshan-client-cf - bundle - leshan - client californium - A transport implementation for leshan client based on CoAP Californium - - - - org.eclipse.leshan - leshan-client-core - - - org.eclipse.californium - californium-core - - - org.eclipse.californium - scandium - - - - - org.apache.logging.log4j - log4j-core - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - junit - junit - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - <_exportcontents>!*.impl.*, !*.internal.*, * - * - ${project.artifactId} - - - - - - + + + 4.0.0 + + org.eclipse.leshan + leshan + 0.1.11-M13-SNAPSHOT + + leshan-client-cf + bundle + leshan - client californium + A transport implementation for leshan client based on CoAP Californium + + + + org.eclipse.leshan + leshan-client-core + + + org.eclipse.californium + californium-core + + + org.eclipse.californium + scandium + + + + + org.apache.logging.log4j + log4j-core + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + junit + junit + test + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + <_exportcontents>!*.impl.*, !*.internal.*, * + * + ${project.artifactId} + + + + + + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.properties b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.properties index 8061311..92913d7 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.properties +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.properties @@ -1,5 +1,5 @@ -#Generated by org.apache.felix.bundleplugin -#Wed Mar 08 17:49:47 KST 2017 -version=0.1.11-M13-SNAPSHOT -groupId=org.eclipse.leshan -artifactId=leshan-client-core +#Generated by org.apache.felix.bundleplugin +#Wed Mar 08 17:49:47 KST 2017 +version=0.1.11-M13-SNAPSHOT +groupId=org.eclipse.leshan +artifactId=leshan-client-core diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.xml b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.xml index 5a36455..0684c8b 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.xml +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-core/pom.xml @@ -1,72 +1,72 @@ - - - 4.0.0 - - org.eclipse.leshan - leshan - 0.1.11-M13-SNAPSHOT - - leshan-client-core - bundle - leshan - client core - A LWM2M client implementation which abstracts transport layer. A transport implementation like "leshan-client-cf" is needed. - - - - org.eclipse.leshan - leshan-core - - - - - org.apache.logging.log4j - log4j-core - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - junit - junit - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - <_exportcontents>!*.impl.*, !*.internal.*, * - * - ${project.artifactId} - - - - - - + + + 4.0.0 + + org.eclipse.leshan + leshan + 0.1.11-M13-SNAPSHOT + + leshan-client-core + bundle + leshan - client core + A LWM2M client implementation which abstracts transport layer. A transport implementation like "leshan-client-cf" is needed. + + + + org.eclipse.leshan + leshan-core + + + + + org.apache.logging.log4j + log4j-core + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + junit + junit + test + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + <_exportcontents>!*.impl.*, !*.internal.*, * + * + ${project.artifactId} + + + + + + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.properties b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.properties index e7c3573..6025e2d 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.properties +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.properties @@ -1,7 +1,7 @@ -#Generated by Maven Integration for Eclipse -#Wed Mar 08 17:40:12 KST 2017 -version=0.1.11-M13-SNAPSHOT -groupId=org.eclipse.leshan -m2e.projectName=leshan-client-demo -m2e.projectLocation=E\:\\src_workspace\\leshan\\leshan\\leshan-client-demo -artifactId=leshan-client-demo +#Generated by Maven Integration for Eclipse +#Wed Mar 08 17:40:12 KST 2017 +version=0.1.11-M13-SNAPSHOT +groupId=org.eclipse.leshan +m2e.projectName=leshan-client-demo +m2e.projectLocation=E\:\\src_workspace\\leshan\\leshan\\leshan-client-demo +artifactId=leshan-client-demo diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.xml b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.xml index ffe0825..9ddc2c5 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.xml +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-client-demo/pom.xml @@ -1,80 +1,80 @@ - - - 4.0.0 - - org.eclipse.leshan - leshan - 0.1.11-M13-SNAPSHOT - - leshan-client-demo - leshan - client demo - A demonstration client built upon the Leshan client. - - - - org.eclipse.leshan - leshan-client-cf - - - commons-cli - commons-cli - - - - - org.apache.logging.log4j - log4j-core - runtime - - - org.apache.logging.log4j - log4j-slf4j-impl - runtime - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.4 - - - - org.eclipse.leshan.client.demo.LeshanClientDemo - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - - + + + 4.0.0 + + org.eclipse.leshan + leshan + 0.1.11-M13-SNAPSHOT + + leshan-client-demo + leshan - client demo + A demonstration client built upon the Leshan client. + + + + org.eclipse.leshan + leshan-client-cf + + + commons-cli + commons-cli + + + + + org.apache.logging.log4j + log4j-core + runtime + + + org.apache.logging.log4j + log4j-slf4j-impl + runtime + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.4 + + + + org.eclipse.leshan.client.demo.LeshanClientDemo + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.properties b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.properties index db8596f..a8dfbf7 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.properties +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.properties @@ -1,5 +1,5 @@ -#Generated by org.apache.felix.bundleplugin -#Wed Mar 08 17:49:43 KST 2017 -version=0.1.11-M13-SNAPSHOT -groupId=org.eclipse.leshan -artifactId=leshan-core +#Generated by org.apache.felix.bundleplugin +#Wed Mar 08 17:49:43 KST 2017 +version=0.1.11-M13-SNAPSHOT +groupId=org.eclipse.leshan +artifactId=leshan-core diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.xml b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.xml index f0d0985..5346c2e 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.xml +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.eclipse.leshan/leshan-core/pom.xml @@ -1,76 +1,76 @@ - - - 4.0.0 - - org.eclipse.leshan - leshan - 0.1.11-M13-SNAPSHOT - - leshan-core - bundle - leshan - core - Core classes for implementing Lightweight M2M - - - - org.slf4j - slf4j-api - - - com.google.code.gson - gson - - - - - junit - junit - test - - - org.apache.logging.log4j - log4j-core - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - <_exportcontents>!oma-objects-spec.json, !*.impl.*, !*.internal.*, * - * - ${project.artifactId} - - - - - - + + + 4.0.0 + + org.eclipse.leshan + leshan + 0.1.11-M13-SNAPSHOT + + leshan-core + bundle + leshan - core + Core classes for implementing Lightweight M2M + + + + org.slf4j + slf4j-api + + + com.google.code.gson + gson + + + + + junit + junit + test + + + org.apache.logging.log4j + log4j-core + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + <_exportcontents>!oma-objects-spec.json, !*.impl.*, !*.internal.*, * + * + ${project.artifactId} + + + + + + diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.properties b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.properties index 19b44dd..0272479 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.properties +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.properties @@ -1,5 +1,5 @@ -#Generated by Maven -#Tue Jan 06 21:12:12 CET 2015 -version=1.7.10 -groupId=org.slf4j -artifactId=slf4j-api +#Generated by Maven +#Tue Jan 06 21:12:12 CET 2015 +version=1.7.10 +groupId=org.slf4j +artifactId=slf4j-api diff --git a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.xml b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.xml index 191a36b..3542565 100644 --- a/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.xml +++ b/si-modules/LWM2M_IPE_Server/META-INF/maven/org.slf4j/slf4j-api/pom.xml @@ -1,88 +1,88 @@ - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.10 - - - slf4j-api - - jar - SLF4J API Module - The slf4j API - - http://www.slf4j.org - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - bundle-test-jar - package - - jar - test-jar - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - process-classes - - run - - - - - - Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder - - - - - - - - - + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.10 + + + slf4j-api + + jar + SLF4J API Module + The slf4j API + + http://www.slf4j.org + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + bundle-test-jar + package + + jar + test-jar + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + process-classes + + run + + + + + + Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder + + + + + + + + + \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/doc.txt b/si-modules/LWM2M_IPE_Server/doc.txt index b69c28c..9dbdd52 100644 --- a/si-modules/LWM2M_IPE_Server/doc.txt +++ b/si-modules/LWM2M_IPE_Server/doc.txt @@ -1,71 +1,71 @@ -## method 별 명령 -- doGet : humidity, temperature 등 read -- doPost : humidity, temperature 등 observe / reboot -- doPut : led, sound 등 write(text/plain만) -- doDelete : humidity, temperature 등 observe 취소 - --- 여러개를 read 하기 위해서 post로 보내서 get의 방식대로 반복문 처리 --- 기존 폼과 연동이 되는가?? : yes - - - -## Direct - -# connect -{ - "conn":"connect", - "oui":"unidtf", - "manufacturer":"", - "modelName":"", - "sn":"", - "authId":"", - "authPwd":"", - "objectModels":[ - {"uri":"/1/0"}, - {"uri":"/3/0"}, - ... - ] -} - -# disconnect -{ - "conn":"disconnect", - "oui":"unidtf", - "manufacturer":"", - "modelName":"", - "sn":"", - "authId":"", - "authPwd":"", - "objectModels":[ - {"uri":"/1/0"}, - {"uri":"/3/0"}, - ... - ] -} - -# conn -- connect -- disconnect -- oneM2M_write -- oneM2M_read -- controlHistory - - - -# IPE -> 외부 -{ - -} - - - -## oneM2M -# 외부 -> IPE -{ - -} - -## IPE -> 외부 -{ - +## method 별 명령 +- doGet : humidity, temperature 등 read +- doPost : humidity, temperature 등 observe / reboot +- doPut : led, sound 등 write(text/plain만) +- doDelete : humidity, temperature 등 observe 취소 + +-- 여러개를 read 하기 위해서 post로 보내서 get의 방식대로 반복문 처리 +-- 기존 폼과 연동이 되는가?? : yes + + + +## Direct + +# connect +{ + "conn":"connect", + "oui":"unidtf", + "manufacturer":"", + "modelName":"", + "sn":"", + "authId":"", + "authPwd":"", + "objectModels":[ + {"uri":"/1/0"}, + {"uri":"/3/0"}, + ... + ] +} + +# disconnect +{ + "conn":"disconnect", + "oui":"unidtf", + "manufacturer":"", + "modelName":"", + "sn":"", + "authId":"", + "authPwd":"", + "objectModels":[ + {"uri":"/1/0"}, + {"uri":"/3/0"}, + ... + ] +} + +# conn +- connect +- disconnect +- oneM2M_write +- oneM2M_read +- controlHistory + + + +# IPE -> 외부 +{ + +} + + + +## oneM2M +# 외부 -> IPE +{ + +} + +## IPE -> 외부 +{ + } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/.classpath b/si-modules/LWM2M_IPE_Server/leshan-server-core/.classpath deleted file mode 100644 index bb4ae14..0000000 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/pom.xml b/si-modules/LWM2M_IPE_Server/leshan-server-core/pom.xml index ac8a96f..224c95a 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/pom.xml +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/pom.xml @@ -1,83 +1,83 @@ - - - 4.0.0 - - org.eclipse.leshan - leshan - 0.1.11-M13-SNAPSHOT - - leshan-server-core - bundle - leshan - server core - A LWM2M server implementation which abstracts transport layer. A transport implementation like "leshan-server-cf" is needed. - - - - - org.eclipse.leshan - leshan-core - - - - - commons-configuration - commons-configuration - 1.6 - - - junit - junit - test - - - org.apache.logging.log4j - log4j-core - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.json - json - 20090211 - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - <_exportcontents>* - * - ${project.artifactId} - - - - - - + + + 4.0.0 + + org.eclipse.leshan + leshan + 0.1.11-M13-SNAPSHOT + + leshan-server-core + bundle + leshan - server core + A LWM2M server implementation which abstracts transport layer. A transport implementation like "leshan-server-cf" is needed. + + + + + org.eclipse.leshan + leshan-core + + + + + commons-configuration + commons-configuration + 1.6 + + + junit + junit + test + + + org.apache.logging.log4j + log4j-core + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + org.json + json + 20090211 + + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + <_exportcontents>* + * + ${project.artifactId} + + + + + + diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Destroyable.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Destroyable.java index b83a213..deb6fd6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Destroyable.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Destroyable.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server; - -public interface Destroyable { - - /** Destroy the instances and frees all system resources. */ - void destroy(); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server; + +public interface Destroyable { + + /** Destroy the instances and frees all system resources. */ + void destroy(); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/LwM2mServer.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/LwM2mServer.java index 2978b89..640f510 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/LwM2mServer.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/LwM2mServer.java @@ -1,103 +1,103 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.model.LwM2mModelProvider; -import org.eclipse.leshan.server.observation.ObservationRegistry; -import org.eclipse.leshan.server.security.SecurityRegistry; - -/** - * An OMA Lightweight M2M device management server. - * - * Will receive client registration through the "/rd" resource. Is able to send requests (Read, Write, Create, Delete, - * Execute, Discover, Observer) to specified clients. - * - * It's your main entry point for using the Leshan-core API. - */ -public interface LwM2mServer { - - /** - * Starts the server (bind port, start to listen CoAP messages). - */ - void start(); - - /** - * Stops the server, i.e. unbinds it from all ports. Frees as much system resources as possible to still be able to - * be started. - */ - void stop(); - - /** - * Destroys the server, i.e. unbinds from all ports and frees all system resources. - */ - void destroy(); - - /** - * Sends a Lightweight M2M request synchronously. Will block until a response is received from the remote client. - * - * @param destination the remote client - * @param request the request to the client - * @return the response or null if the CoAP timeout expires ( see - * http://tools.ietf.org/html/rfc7252#section-4.2 ). - */ - T send(Client destination, DownlinkRequest request) throws InterruptedException; - - /** - * Sends a Lightweight M2M request synchronously. Will block until a response is received from the remote client. - * - * @param destination the remote client - * @param request the request to the client - * @param timeout the request timeout in millisecond - * @return the response or null if the timeout expires (given parameter or CoAP timeout). - */ - T send(Client destination, DownlinkRequest request, long timeout) - throws InterruptedException; - - /** - * Sends a Lightweight M2M request asynchronously. - */ - void send(Client destination, DownlinkRequest request, - ResponseCallback responseCallback, ErrorCallback errorCallback); - - /** - * Get the client registry containing the list of connected clients. You can use this object for listening client - * registration/deregistration. - */ - ClientRegistry getClientRegistry(); - - /** - * Get the Observation registry containing of current observation. You can use this object for listening resource - * observation or cancel it. - */ - ObservationRegistry getObservationRegistry(); - - /** - * Get the SecurityRegistry containing of security information. - */ - SecurityRegistry getSecurityRegistry(); - - /** - * Get the provider in charge of retrieving the object definitions for each client. - */ - LwM2mModelProvider getModelProvider(); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.model.LwM2mModelProvider; +import org.eclipse.leshan.server.observation.ObservationRegistry; +import org.eclipse.leshan.server.security.SecurityRegistry; + +/** + * An OMA Lightweight M2M device management server. + * + * Will receive client registration through the "/rd" resource. Is able to send requests (Read, Write, Create, Delete, + * Execute, Discover, Observer) to specified clients. + * + * It's your main entry point for using the Leshan-core API. + */ +public interface LwM2mServer { + + /** + * Starts the server (bind port, start to listen CoAP messages). + */ + void start(); + + /** + * Stops the server, i.e. unbinds it from all ports. Frees as much system resources as possible to still be able to + * be started. + */ + void stop(); + + /** + * Destroys the server, i.e. unbinds from all ports and frees all system resources. + */ + void destroy(); + + /** + * Sends a Lightweight M2M request synchronously. Will block until a response is received from the remote client. + * + * @param destination the remote client + * @param request the request to the client + * @return the response or null if the CoAP timeout expires ( see + * http://tools.ietf.org/html/rfc7252#section-4.2 ). + */ + T send(Client destination, DownlinkRequest request) throws InterruptedException; + + /** + * Sends a Lightweight M2M request synchronously. Will block until a response is received from the remote client. + * + * @param destination the remote client + * @param request the request to the client + * @param timeout the request timeout in millisecond + * @return the response or null if the timeout expires (given parameter or CoAP timeout). + */ + T send(Client destination, DownlinkRequest request, long timeout) + throws InterruptedException; + + /** + * Sends a Lightweight M2M request asynchronously. + */ + void send(Client destination, DownlinkRequest request, + ResponseCallback responseCallback, ErrorCallback errorCallback); + + /** + * Get the client registry containing the list of connected clients. You can use this object for listening client + * registration/deregistration. + */ + ClientRegistry getClientRegistry(); + + /** + * Get the Observation registry containing of current observation. You can use this object for listening resource + * observation or cancel it. + */ + ObservationRegistry getObservationRegistry(); + + /** + * Get the SecurityRegistry containing of security information. + */ + SecurityRegistry getSecurityRegistry(); + + /** + * Get the provider in charge of retrieving the object definitions for each client. + */ + LwM2mModelProvider getModelProvider(); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Lwm2mServerConfig.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Lwm2mServerConfig.java index b4efcbd..a679bb9 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Lwm2mServerConfig.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Lwm2mServerConfig.java @@ -1,200 +1,200 @@ -package org.eclipse.leshan.server; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.apache.commons.configuration.XMLConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Lwm2mServerConfig { - private static final String CONFIG_FILENAME = "config.xml"; - - private final static XMLConfiguration xmlConfig = new XMLConfiguration(); - private Logger log = LoggerFactory.getLogger(Lwm2mServerConfig.class); - - private static Lwm2mServerConfig instance = null; - - // si_server - private String siIp = "[siIp]"; - private int siPortNormal = 0; - private int siPortAuth = 0; - private boolean siAuthUse = false; - private String siUri = "[siUri]"; - private String siUriAuth = "[siUriAuth]"; - private String siResourceId = "[siResourceId]"; - private String siResourceName = "[siResourceName]"; - private int retryInterval = 10; - - // dm_server - private boolean dmUsing = false; - private String dmIp = "[dmIp]"; - private int dmPort = 0; - - // lwm2m_ipe - private boolean ipeUsing = false; - private String ipeIp = "[ipeIp]"; - private int ipePortNormal = 0; - private int ipePortSecure = 0; - private int ipePortWeb = 0; - private int reportInterval = 30; - - // debug log - private boolean debug = false; - - - public static Lwm2mServerConfig getInstance(){ - if(instance == null){ - try { - instance = new Lwm2mServerConfig(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return instance; - } - - public Lwm2mServerConfig() throws Exception { - loadConfig(); - } - - private void loadConfig() throws Exception { - - try { - log.info("Configuration loading started!!!"); - xmlConfig.load(CONFIG_FILENAME); - - // si_server - siIp = xmlConfig.getString("si.ip"); - siPortNormal = xmlConfig.getInt("si.port.normal"); - siPortAuth = xmlConfig.getInt("si.port.auth"); - siAuthUse = xmlConfig.getString("si.auth").equals("yes"); - siResourceId = xmlConfig.getString("si.resourceId"); - siResourceName = xmlConfig.getString("si.resourceName"); - siUri = "http://"+siIp+":"+siPortNormal+"/"+siResourceId+"/"+siResourceName; - siUriAuth = "http://"+siIp+":"+siPortAuth+"/si/dev_inf"; - retryInterval = xmlConfig.getInt("si.retryInterval") * 1000; - - // dm_server - dmUsing = xmlConfig.getString("dm.use").equals("yes"); - dmIp = xmlConfig.getString("dm.web.ip"); - dmPort = xmlConfig.getInt("dm.web.port"); - - // lwm2m_ipe - ipeUsing = xmlConfig.getString("ipe.use").equals("yes"); - ipeIp = xmlConfig.getString("ipe.ip"); - ipePortNormal = xmlConfig.getInt("ipe.port.normal"); - ipePortSecure = xmlConfig.getInt("ipe.port.secure"); - ipePortWeb = xmlConfig.getInt("ipe.port.web"); - reportInterval = xmlConfig.getInt("ipe.report.interval") * 1000; - - // debug log - debug = xmlConfig.getString("log.debug").equals("yes"); - - log.info("*= Configuration loading succeeded!!!"); - - } catch (Exception e) { - log.error("Exception during Configuration loading: ", e); - throw e; - } - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - /* - Method[] methods = this.getClass().getMethods(); - for(Method method : methods){ - try{ - Object result = method.invoke(new Object()); - - - } catch(Exception e) { - e.printStackTrace(); - } - try { - sb.append("[").append(method.getName()).append("] : "); - } catch (Exception e) {} - }*/ - return null; - } - - public String getSiIp() { - return siIp; - } - - public int getSiPortNormal() { - return siPortNormal; - } - - public int getSiPortAuth() { - return siPortAuth; - } - - public String getSiUri() { - return siUri; - } - - public String getSiUriAuth() { - return siUriAuth; - } - - public String getSiResourceId() { - return siResourceId; - } - - public String getSiResourceName() { - return siResourceName; - } - - public int getRetryInterval() { - return retryInterval; - } - - public boolean isDmUsing() { - return dmUsing; - } - - public String getDmIp() { - return dmIp; - } - - public int getDmPort() { - return dmPort; - } - - public boolean isIpeUsing() { - return ipeUsing; - } - - public String getIpeIp() { - return ipeIp; - } - - public int getIpePortNormal() { - return ipePortNormal; - } - - public int getIpePortSecure() { - return ipePortSecure; - } - - public int getIpePortWeb() { - return ipePortWeb; - } - - public boolean isDebug() { - return debug; - } - - public int getReportInterval() { - return reportInterval; - } - - public boolean isSiAuthUse() { - return siAuthUse; - } - - -} +package org.eclipse.leshan.server; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.commons.configuration.XMLConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Lwm2mServerConfig { + private static final String CONFIG_FILENAME = "config.xml"; + + private final static XMLConfiguration xmlConfig = new XMLConfiguration(); + private Logger log = LoggerFactory.getLogger(Lwm2mServerConfig.class); + + private static Lwm2mServerConfig instance = null; + + // si_server + private String siIp = "[siIp]"; + private int siPortNormal = 0; + private int siPortAuth = 0; + private boolean siAuthUse = false; + private String siUri = "[siUri]"; + private String siUriAuth = "[siUriAuth]"; + private String siResourceId = "[siResourceId]"; + private String siResourceName = "[siResourceName]"; + private int retryInterval = 10; + + // dm_server + private boolean dmUsing = false; + private String dmIp = "[dmIp]"; + private int dmPort = 0; + + // lwm2m_ipe + private boolean ipeUsing = false; + private String ipeIp = "[ipeIp]"; + private int ipePortNormal = 0; + private int ipePortSecure = 0; + private int ipePortWeb = 0; + private int reportInterval = 30; + + // debug log + private boolean debug = false; + + + public static Lwm2mServerConfig getInstance(){ + if(instance == null){ + try { + instance = new Lwm2mServerConfig(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return instance; + } + + public Lwm2mServerConfig() throws Exception { + loadConfig(); + } + + private void loadConfig() throws Exception { + + try { + log.info("Configuration loading started!!!"); + xmlConfig.load(CONFIG_FILENAME); + + // si_server + siIp = xmlConfig.getString("si.ip"); + siPortNormal = xmlConfig.getInt("si.port.normal"); + siPortAuth = xmlConfig.getInt("si.port.auth"); + siAuthUse = xmlConfig.getString("si.auth").equals("yes"); + siResourceId = xmlConfig.getString("si.resourceId"); + siResourceName = xmlConfig.getString("si.resourceName"); + siUri = "http://"+siIp+":"+siPortNormal+"/"+siResourceId+"/"+siResourceName; + siUriAuth = "http://"+siIp+":"+siPortAuth+"/si/dev_inf"; + retryInterval = xmlConfig.getInt("si.retryInterval") * 1000; + + // dm_server + dmUsing = xmlConfig.getString("dm.use").equals("yes"); + dmIp = xmlConfig.getString("dm.web.ip"); + dmPort = xmlConfig.getInt("dm.web.port"); + + // lwm2m_ipe + ipeUsing = xmlConfig.getString("ipe.use").equals("yes"); + ipeIp = xmlConfig.getString("ipe.ip"); + ipePortNormal = xmlConfig.getInt("ipe.port.normal"); + ipePortSecure = xmlConfig.getInt("ipe.port.secure"); + ipePortWeb = xmlConfig.getInt("ipe.port.web"); + reportInterval = xmlConfig.getInt("ipe.report.interval") * 1000; + + // debug log + debug = xmlConfig.getString("log.debug").equals("yes"); + + log.info("*= Configuration loading succeeded!!!"); + + } catch (Exception e) { + log.error("Exception during Configuration loading: ", e); + throw e; + } + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + /* + Method[] methods = this.getClass().getMethods(); + for(Method method : methods){ + try{ + Object result = method.invoke(new Object()); + + + } catch(Exception e) { + e.printStackTrace(); + } + try { + sb.append("[").append(method.getName()).append("] : "); + } catch (Exception e) {} + }*/ + return null; + } + + public String getSiIp() { + return siIp; + } + + public int getSiPortNormal() { + return siPortNormal; + } + + public int getSiPortAuth() { + return siPortAuth; + } + + public String getSiUri() { + return siUri; + } + + public String getSiUriAuth() { + return siUriAuth; + } + + public String getSiResourceId() { + return siResourceId; + } + + public String getSiResourceName() { + return siResourceName; + } + + public int getRetryInterval() { + return retryInterval; + } + + public boolean isDmUsing() { + return dmUsing; + } + + public String getDmIp() { + return dmIp; + } + + public int getDmPort() { + return dmPort; + } + + public boolean isIpeUsing() { + return ipeUsing; + } + + public String getIpeIp() { + return ipeIp; + } + + public int getIpePortNormal() { + return ipePortNormal; + } + + public int getIpePortSecure() { + return ipePortSecure; + } + + public int getIpePortWeb() { + return ipePortWeb; + } + + public boolean isDebug() { + return debug; + } + + public int getReportInterval() { + return reportInterval; + } + + public boolean isSiAuthUse() { + return siAuthUse; + } + + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Startable.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Startable.java index 74b0a5b..b9155de 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Startable.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Startable.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server; - -public interface Startable { - - void start(); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server; + +public interface Startable { + + void start(); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Stoppable.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Stoppable.java index 47f3926..d4a8827 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Stoppable.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Stoppable.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server; - -public interface Stoppable { - - void stop(); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server; + +public interface Stoppable { + + void stop(); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Version.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Version.java index 3cb66be..2777f62 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Version.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Version.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server; - -public class Version { - public static String value; - - public final static String getValue() { - if (value == null) { - Package p = Version.class.getPackage(); - String version = p.getImplementationVersion(); - if (version != null) - value = version; - else - value = "unknown"; - } - return value; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server; + +public class Version { + public static String value; + + public final static String getValue() { + if (value == null) { + Package p = Version.class.getPackage(); + String version = p.getImplementationVersion(); + if (version != null) + value = version; + else + value = "unknown"; + } + return value; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapConfig.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapConfig.java index 8e90290..3360f73 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapConfig.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapConfig.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.leshan.core.request.BindingMode; - -/** - * A client configuration to be pushed by a bootstrap operation - */ -@SuppressWarnings("serial") -public class BootstrapConfig implements Serializable { - - public Map servers = new HashMap<>(); - - public Map security = new HashMap<>(); - - /** server configuration (object 1) */ - static public class ServerConfig implements Serializable { - public int shortId; - public int lifetime = 86400; - public int defaultMinPeriod = 1; - public Integer defaultMaxPeriod = null; - public Integer disableTimeout = null; - public boolean notifIfDisabled = true; - public BindingMode binding = BindingMode.U; - - @Override - public String toString() { - return String - .format("ServerConfig [shortId=%s, lifetime=%s, defaultMinPeriod=%s, defaultMaxPeriod=%s, disableTimeout=%s, notifIfDisabled=%s, binding=%s]", - shortId, lifetime, defaultMinPeriod, defaultMaxPeriod, disableTimeout, notifIfDisabled, - binding); - } - } - - /** security configuration (object 0) */ - static public class ServerSecurity implements Serializable { - public String uri; - public boolean bootstrapServer = false; - public SecurityMode securityMode; - public byte[] publicKeyOrId = new byte[] {}; - public byte[] serverPublicKeyOrId = new byte[] {}; - public byte[] secretKey = new byte[] {}; - public SmsSecurityMode smsSecurityMode = SmsSecurityMode.NO_SEC; - public byte[] smsBindingKeyParam = new byte[] {}; - public byte[] smsBindingKeySecret = new byte[] {}; - public String serverSmsNumber = ""; // spec says integer WTF? - public Integer serverId; - public int clientOldOffTime = 1; - - @Override - public String toString() { - return String - .format("ServerSecurity [uri=%s, bootstrapServer=%s, securityMode=%s, publicKeyOrId=%s, serverPublicKeyOrId=%s, secretKey=%s, smsSecurityMode=%s, smsBindingKeyParam=%s, smsBindingKeySecret=%s, serverSmsNumber=%s, serverId=%s, clientOldOffTime=%s]", - uri, bootstrapServer, securityMode, Arrays.toString(publicKeyOrId), - Arrays.toString(serverPublicKeyOrId), Arrays.toString(secretKey), smsSecurityMode, - Arrays.toString(smsBindingKeyParam), Arrays.toString(smsBindingKeySecret), serverSmsNumber, - serverId, clientOldOffTime); - } - } - - @Override - public String toString() { - return String.format("BootstrapConfig [servers=%s, security=%s]", servers, security); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.leshan.core.request.BindingMode; + +/** + * A client configuration to be pushed by a bootstrap operation + */ +@SuppressWarnings("serial") +public class BootstrapConfig implements Serializable { + + public Map servers = new HashMap<>(); + + public Map security = new HashMap<>(); + + /** server configuration (object 1) */ + static public class ServerConfig implements Serializable { + public int shortId; + public int lifetime = 86400; + public int defaultMinPeriod = 1; + public Integer defaultMaxPeriod = null; + public Integer disableTimeout = null; + public boolean notifIfDisabled = true; + public BindingMode binding = BindingMode.U; + + @Override + public String toString() { + return String + .format("ServerConfig [shortId=%s, lifetime=%s, defaultMinPeriod=%s, defaultMaxPeriod=%s, disableTimeout=%s, notifIfDisabled=%s, binding=%s]", + shortId, lifetime, defaultMinPeriod, defaultMaxPeriod, disableTimeout, notifIfDisabled, + binding); + } + } + + /** security configuration (object 0) */ + static public class ServerSecurity implements Serializable { + public String uri; + public boolean bootstrapServer = false; + public SecurityMode securityMode; + public byte[] publicKeyOrId = new byte[] {}; + public byte[] serverPublicKeyOrId = new byte[] {}; + public byte[] secretKey = new byte[] {}; + public SmsSecurityMode smsSecurityMode = SmsSecurityMode.NO_SEC; + public byte[] smsBindingKeyParam = new byte[] {}; + public byte[] smsBindingKeySecret = new byte[] {}; + public String serverSmsNumber = ""; // spec says integer WTF? + public Integer serverId; + public int clientOldOffTime = 1; + + @Override + public String toString() { + return String + .format("ServerSecurity [uri=%s, bootstrapServer=%s, securityMode=%s, publicKeyOrId=%s, serverPublicKeyOrId=%s, secretKey=%s, smsSecurityMode=%s, smsBindingKeyParam=%s, smsBindingKeySecret=%s, serverSmsNumber=%s, serverId=%s, clientOldOffTime=%s]", + uri, bootstrapServer, securityMode, Arrays.toString(publicKeyOrId), + Arrays.toString(serverPublicKeyOrId), Arrays.toString(secretKey), smsSecurityMode, + Arrays.toString(smsBindingKeyParam), Arrays.toString(smsBindingKeySecret), serverSmsNumber, + serverId, clientOldOffTime); + } + } + + @Override + public String toString() { + return String.format("BootstrapConfig [servers=%s, security=%s]", servers, security); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapHandler.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapHandler.java index ca69edf..40abada 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapHandler.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapHandler.java @@ -1,251 +1,251 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.request.BootstrapDeleteRequest; -import org.eclipse.leshan.core.request.BootstrapFinishRequest; -import org.eclipse.leshan.core.request.BootstrapRequest; -import org.eclipse.leshan.core.request.BootstrapWriteRequest; -import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.core.response.BootstrapDeleteResponse; -import org.eclipse.leshan.core.response.BootstrapFinishResponse; -import org.eclipse.leshan.core.response.BootstrapResponse; -import org.eclipse.leshan.core.response.BootstrapWriteResponse; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.server.bootstrap.BootstrapConfig.ServerConfig; -import org.eclipse.leshan.server.bootstrap.BootstrapConfig.ServerSecurity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Handle the bootstrap logic at Server side. Check if the client is allowed to bootstrap, with the wanted security - * scheme. Then send delete and write request to bootstrap the client, then close the bootstrap session by sending a - * bootstrap finished request. - */ -public class BootstrapHandler { - - private static final Logger LOG = LoggerFactory.getLogger(BootstrapHandler.class); - - private final Executor e; - - private final BootstrapStore bsStore; - private final LwM2mBootstrapRequestSender requestSender; - private final BootstrapSessionManager bsSessionManager; - - public BootstrapHandler(BootstrapStore store, LwM2mBootstrapRequestSender requestSender, - BootstrapSessionManager bsSessionManager) { - this.bsStore = store; - this.requestSender = requestSender; - this.bsSessionManager = bsSessionManager; - this.e = Executors.newFixedThreadPool(5); - } - - protected BootstrapHandler(BootstrapStore store, LwM2mBootstrapRequestSender requestSender, - BootstrapSessionManager bsSessionManager, Executor executor) { - this.bsStore = store; - this.requestSender = requestSender; - this.bsSessionManager = bsSessionManager; - this.e = executor; - } - - public BootstrapResponse bootstrap(final Identity sender, final BootstrapRequest request) { - final String endpoint = request.getEndpointName(); - - // Start session, checking the BS credentials - final BootstrapSession bsSession = this.bsSessionManager.begin(endpoint, sender); - - if (!bsSession.isAuthorized()) { - return BootstrapResponse.badRequest("Unauthorized"); - } - - // Get the desired bootstrap config for the endpoint - final BootstrapConfig cfg = bsStore.getBootstrap(endpoint); - if (cfg == null) { - LOG.error("No bootstrap config for {}", endpoint); - return BootstrapResponse.badRequest("no bootstrap config"); - } - - // Start the boostrap session - e.execute(new Runnable() { - @Override - public void run() { - sendDelete(bsSession, cfg); - } - }); - - return BootstrapResponse.success(); - } - - private void sendDelete(final BootstrapSession bsSession, final BootstrapConfig cfg) { - - final BootstrapDeleteRequest writeDeleteRequest = new BootstrapDeleteRequest(); - send(bsSession, writeDeleteRequest, new ResponseCallback() { - @Override - public void onResponse(BootstrapDeleteResponse response) { - LOG.debug("Bootstrap delete {} return code {}", bsSession.getEndpoint(), response.getCode()); - List toSend = new ArrayList<>(cfg.security.keySet()); - sendBootstrap(bsSession, cfg, toSend); - } - }, new ErrorCallback() { - @Override - public void onError(Exception e) { - LOG.warn(String.format("Error pending bootstrap delete '/' on %s", bsSession.getEndpoint()), e); - bsSessionManager.failed(bsSession, writeDeleteRequest, e); - } - }); - } - - private void sendBootstrap(final BootstrapSession bsSession, final BootstrapConfig cfg, - final List toSend) { - if (!toSend.isEmpty()) { - // 1st encode them into a juicy TLV binary - Integer key = toSend.remove(0); - ServerSecurity securityConfig = cfg.security.get(key); - - // extract write request parameters - LwM2mPath path = new LwM2mPath(0, key); - final LwM2mNode securityInstance = convertToSecurityInstance(key, securityConfig); - - final BootstrapWriteRequest writeBootstrapRequest = new BootstrapWriteRequest(path, securityInstance, - ContentFormat.TLV); - send(bsSession, writeBootstrapRequest, new ResponseCallback() { - @Override - public void onResponse(BootstrapWriteResponse response) { - LOG.debug("Bootstrap write {} return code {}", bsSession.getEndpoint(), response.getCode()); - // recursive call until toSend is empty - sendBootstrap(bsSession, cfg, toSend); - } - }, new ErrorCallback() { - @Override - public void onError(Exception e) { - LOG.warn(String.format("Error pending bootstrap write of security instance %s on %s", - securityInstance, bsSession.getEndpoint()), e); - bsSessionManager.failed(bsSession, writeBootstrapRequest, e); - } - }); - } else { - // we are done, send the servers - List serversToSend = new ArrayList<>(cfg.servers.keySet()); - sendServers(bsSession, cfg, serversToSend); - } - } - - private void sendServers(final BootstrapSession bsSession, final BootstrapConfig cfg, final List toSend) { - if (!toSend.isEmpty()) { - // get next config - Integer key = toSend.remove(0); - ServerConfig serverConfig = cfg.servers.get(key); - - // extract write request parameters - LwM2mPath path = new LwM2mPath(1, key); - final LwM2mNode serverInstance = convertToServerInstance(key, serverConfig); - - final BootstrapWriteRequest writeServerRequest = new BootstrapWriteRequest(path, serverInstance, - ContentFormat.TLV); - send(bsSession, writeServerRequest, new ResponseCallback() { - @Override - public void onResponse(BootstrapWriteResponse response) { - LOG.debug("Bootstrap write {} return code {}", bsSession.getEndpoint(), response.getCode()); - // recursive call until toSend is empty - sendServers(bsSession, cfg, toSend); - } - }, new ErrorCallback() { - @Override - public void onError(Exception e) { - LOG.warn(String.format("Error pending bootstrap write of server instance %s on %s", serverInstance, - bsSession.getEndpoint()), e); - bsSessionManager.failed(bsSession, writeServerRequest, e); - } - }); - } else { - final BootstrapFinishRequest finishBootstrapRequest = new BootstrapFinishRequest(); - send(bsSession, finishBootstrapRequest, new ResponseCallback() { - @Override - public void onResponse(BootstrapFinishResponse response) { - LOG.debug("Bootstrap Finished {} return code {}", bsSession.getEndpoint(), response.getCode()); - if (response.isSuccess()) { - bsSessionManager.end(bsSession); - } else { - bsSessionManager.failed(bsSession, finishBootstrapRequest, new RuntimeException( - String.format("Bootstrap finished with response code : %s", response))); - } - } - }, new ErrorCallback() { - @Override - public void onError(Exception e) { - LOG.warn(String.format("Error pending bootstrap finished on %s", bsSession.getEndpoint()), e); - bsSessionManager.failed(bsSession, finishBootstrapRequest, e); - } - }); - } - } - - private void send(final BootstrapSession bsSession, final DownlinkRequest request, - final ResponseCallback responseCallback, final ErrorCallback errorCallback) { - requestSender.send(bsSession.getEndpoint(), bsSession.getClientIdentity().getPeerAddress(), - bsSession.getClientIdentity().isSecure(), request, responseCallback, errorCallback); - } - - private LwM2mObjectInstance convertToSecurityInstance(int instanceId, ServerSecurity securityConfig) { - Collection resources = new ArrayList<>(); - - resources.add(LwM2mSingleResource.newStringResource(0, securityConfig.uri)); - resources.add(LwM2mSingleResource.newBooleanResource(1, securityConfig.bootstrapServer)); - resources.add(LwM2mSingleResource.newIntegerResource(2, securityConfig.securityMode.code)); - resources.add(LwM2mSingleResource.newBinaryResource(3, securityConfig.publicKeyOrId)); - resources.add(LwM2mSingleResource.newBinaryResource(4, securityConfig.serverPublicKeyOrId)); - resources.add(LwM2mSingleResource.newBinaryResource(5, securityConfig.secretKey)); - resources.add(LwM2mSingleResource.newIntegerResource(6, securityConfig.smsSecurityMode.code)); - resources.add(LwM2mSingleResource.newBinaryResource(7, securityConfig.smsBindingKeyParam)); - resources.add(LwM2mSingleResource.newBinaryResource(8, securityConfig.smsBindingKeySecret)); - resources.add(LwM2mSingleResource.newStringResource(9, securityConfig.serverSmsNumber)); - resources.add(LwM2mSingleResource.newIntegerResource(10, securityConfig.serverId)); - resources.add(LwM2mSingleResource.newIntegerResource(11, securityConfig.clientOldOffTime)); - - return new LwM2mObjectInstance(instanceId, resources); - } - - private LwM2mObjectInstance convertToServerInstance(int instanceId, ServerConfig serverConfig) { - Collection resources = new ArrayList<>(); - - resources.add(LwM2mSingleResource.newIntegerResource(0, serverConfig.shortId)); - resources.add(LwM2mSingleResource.newIntegerResource(1, serverConfig.lifetime)); - resources.add(LwM2mSingleResource.newIntegerResource(2, serverConfig.defaultMinPeriod)); - if (serverConfig.defaultMaxPeriod != null) - resources.add(LwM2mSingleResource.newIntegerResource(3, serverConfig.defaultMaxPeriod)); - if (serverConfig.disableTimeout != null) - resources.add(LwM2mSingleResource.newIntegerResource(5, serverConfig.disableTimeout)); - resources.add(LwM2mSingleResource.newBooleanResource(6, serverConfig.notifIfDisabled)); - resources.add(LwM2mSingleResource.newStringResource(7, serverConfig.binding.name())); - - return new LwM2mObjectInstance(instanceId, resources); - } -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.request.BootstrapDeleteRequest; +import org.eclipse.leshan.core.request.BootstrapFinishRequest; +import org.eclipse.leshan.core.request.BootstrapRequest; +import org.eclipse.leshan.core.request.BootstrapWriteRequest; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.core.response.BootstrapDeleteResponse; +import org.eclipse.leshan.core.response.BootstrapFinishResponse; +import org.eclipse.leshan.core.response.BootstrapResponse; +import org.eclipse.leshan.core.response.BootstrapWriteResponse; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.eclipse.leshan.server.bootstrap.BootstrapConfig.ServerConfig; +import org.eclipse.leshan.server.bootstrap.BootstrapConfig.ServerSecurity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Handle the bootstrap logic at Server side. Check if the client is allowed to bootstrap, with the wanted security + * scheme. Then send delete and write request to bootstrap the client, then close the bootstrap session by sending a + * bootstrap finished request. + */ +public class BootstrapHandler { + + private static final Logger LOG = LoggerFactory.getLogger(BootstrapHandler.class); + + private final Executor e; + + private final BootstrapStore bsStore; + private final LwM2mBootstrapRequestSender requestSender; + private final BootstrapSessionManager bsSessionManager; + + public BootstrapHandler(BootstrapStore store, LwM2mBootstrapRequestSender requestSender, + BootstrapSessionManager bsSessionManager) { + this.bsStore = store; + this.requestSender = requestSender; + this.bsSessionManager = bsSessionManager; + this.e = Executors.newFixedThreadPool(5); + } + + protected BootstrapHandler(BootstrapStore store, LwM2mBootstrapRequestSender requestSender, + BootstrapSessionManager bsSessionManager, Executor executor) { + this.bsStore = store; + this.requestSender = requestSender; + this.bsSessionManager = bsSessionManager; + this.e = executor; + } + + public BootstrapResponse bootstrap(final Identity sender, final BootstrapRequest request) { + final String endpoint = request.getEndpointName(); + + // Start session, checking the BS credentials + final BootstrapSession bsSession = this.bsSessionManager.begin(endpoint, sender); + + if (!bsSession.isAuthorized()) { + return BootstrapResponse.badRequest("Unauthorized"); + } + + // Get the desired bootstrap config for the endpoint + final BootstrapConfig cfg = bsStore.getBootstrap(endpoint); + if (cfg == null) { + LOG.error("No bootstrap config for {}", endpoint); + return BootstrapResponse.badRequest("no bootstrap config"); + } + + // Start the boostrap session + e.execute(new Runnable() { + @Override + public void run() { + sendDelete(bsSession, cfg); + } + }); + + return BootstrapResponse.success(); + } + + private void sendDelete(final BootstrapSession bsSession, final BootstrapConfig cfg) { + + final BootstrapDeleteRequest writeDeleteRequest = new BootstrapDeleteRequest(); + send(bsSession, writeDeleteRequest, new ResponseCallback() { + @Override + public void onResponse(BootstrapDeleteResponse response) { + LOG.debug("Bootstrap delete {} return code {}", bsSession.getEndpoint(), response.getCode()); + List toSend = new ArrayList<>(cfg.security.keySet()); + sendBootstrap(bsSession, cfg, toSend); + } + }, new ErrorCallback() { + @Override + public void onError(Exception e) { + LOG.warn(String.format("Error pending bootstrap delete '/' on %s", bsSession.getEndpoint()), e); + bsSessionManager.failed(bsSession, writeDeleteRequest, e); + } + }); + } + + private void sendBootstrap(final BootstrapSession bsSession, final BootstrapConfig cfg, + final List toSend) { + if (!toSend.isEmpty()) { + // 1st encode them into a juicy TLV binary + Integer key = toSend.remove(0); + ServerSecurity securityConfig = cfg.security.get(key); + + // extract write request parameters + LwM2mPath path = new LwM2mPath(0, key); + final LwM2mNode securityInstance = convertToSecurityInstance(key, securityConfig); + + final BootstrapWriteRequest writeBootstrapRequest = new BootstrapWriteRequest(path, securityInstance, + ContentFormat.TLV); + send(bsSession, writeBootstrapRequest, new ResponseCallback() { + @Override + public void onResponse(BootstrapWriteResponse response) { + LOG.debug("Bootstrap write {} return code {}", bsSession.getEndpoint(), response.getCode()); + // recursive call until toSend is empty + sendBootstrap(bsSession, cfg, toSend); + } + }, new ErrorCallback() { + @Override + public void onError(Exception e) { + LOG.warn(String.format("Error pending bootstrap write of security instance %s on %s", + securityInstance, bsSession.getEndpoint()), e); + bsSessionManager.failed(bsSession, writeBootstrapRequest, e); + } + }); + } else { + // we are done, send the servers + List serversToSend = new ArrayList<>(cfg.servers.keySet()); + sendServers(bsSession, cfg, serversToSend); + } + } + + private void sendServers(final BootstrapSession bsSession, final BootstrapConfig cfg, final List toSend) { + if (!toSend.isEmpty()) { + // get next config + Integer key = toSend.remove(0); + ServerConfig serverConfig = cfg.servers.get(key); + + // extract write request parameters + LwM2mPath path = new LwM2mPath(1, key); + final LwM2mNode serverInstance = convertToServerInstance(key, serverConfig); + + final BootstrapWriteRequest writeServerRequest = new BootstrapWriteRequest(path, serverInstance, + ContentFormat.TLV); + send(bsSession, writeServerRequest, new ResponseCallback() { + @Override + public void onResponse(BootstrapWriteResponse response) { + LOG.debug("Bootstrap write {} return code {}", bsSession.getEndpoint(), response.getCode()); + // recursive call until toSend is empty + sendServers(bsSession, cfg, toSend); + } + }, new ErrorCallback() { + @Override + public void onError(Exception e) { + LOG.warn(String.format("Error pending bootstrap write of server instance %s on %s", serverInstance, + bsSession.getEndpoint()), e); + bsSessionManager.failed(bsSession, writeServerRequest, e); + } + }); + } else { + final BootstrapFinishRequest finishBootstrapRequest = new BootstrapFinishRequest(); + send(bsSession, finishBootstrapRequest, new ResponseCallback() { + @Override + public void onResponse(BootstrapFinishResponse response) { + LOG.debug("Bootstrap Finished {} return code {}", bsSession.getEndpoint(), response.getCode()); + if (response.isSuccess()) { + bsSessionManager.end(bsSession); + } else { + bsSessionManager.failed(bsSession, finishBootstrapRequest, new RuntimeException( + String.format("Bootstrap finished with response code : %s", response))); + } + } + }, new ErrorCallback() { + @Override + public void onError(Exception e) { + LOG.warn(String.format("Error pending bootstrap finished on %s", bsSession.getEndpoint()), e); + bsSessionManager.failed(bsSession, finishBootstrapRequest, e); + } + }); + } + } + + private void send(final BootstrapSession bsSession, final DownlinkRequest request, + final ResponseCallback responseCallback, final ErrorCallback errorCallback) { + requestSender.send(bsSession.getEndpoint(), bsSession.getClientIdentity().getPeerAddress(), + bsSession.getClientIdentity().isSecure(), request, responseCallback, errorCallback); + } + + private LwM2mObjectInstance convertToSecurityInstance(int instanceId, ServerSecurity securityConfig) { + Collection resources = new ArrayList<>(); + + resources.add(LwM2mSingleResource.newStringResource(0, securityConfig.uri)); + resources.add(LwM2mSingleResource.newBooleanResource(1, securityConfig.bootstrapServer)); + resources.add(LwM2mSingleResource.newIntegerResource(2, securityConfig.securityMode.code)); + resources.add(LwM2mSingleResource.newBinaryResource(3, securityConfig.publicKeyOrId)); + resources.add(LwM2mSingleResource.newBinaryResource(4, securityConfig.serverPublicKeyOrId)); + resources.add(LwM2mSingleResource.newBinaryResource(5, securityConfig.secretKey)); + resources.add(LwM2mSingleResource.newIntegerResource(6, securityConfig.smsSecurityMode.code)); + resources.add(LwM2mSingleResource.newBinaryResource(7, securityConfig.smsBindingKeyParam)); + resources.add(LwM2mSingleResource.newBinaryResource(8, securityConfig.smsBindingKeySecret)); + resources.add(LwM2mSingleResource.newStringResource(9, securityConfig.serverSmsNumber)); + resources.add(LwM2mSingleResource.newIntegerResource(10, securityConfig.serverId)); + resources.add(LwM2mSingleResource.newIntegerResource(11, securityConfig.clientOldOffTime)); + + return new LwM2mObjectInstance(instanceId, resources); + } + + private LwM2mObjectInstance convertToServerInstance(int instanceId, ServerConfig serverConfig) { + Collection resources = new ArrayList<>(); + + resources.add(LwM2mSingleResource.newIntegerResource(0, serverConfig.shortId)); + resources.add(LwM2mSingleResource.newIntegerResource(1, serverConfig.lifetime)); + resources.add(LwM2mSingleResource.newIntegerResource(2, serverConfig.defaultMinPeriod)); + if (serverConfig.defaultMaxPeriod != null) + resources.add(LwM2mSingleResource.newIntegerResource(3, serverConfig.defaultMaxPeriod)); + if (serverConfig.disableTimeout != null) + resources.add(LwM2mSingleResource.newIntegerResource(5, serverConfig.disableTimeout)); + resources.add(LwM2mSingleResource.newBooleanResource(6, serverConfig.notifIfDisabled)); + resources.add(LwM2mSingleResource.newStringResource(7, serverConfig.binding.name())); + + return new LwM2mObjectInstance(instanceId, resources); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSession.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSession.java index 6d683a6..51e7965 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSession.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSession.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import org.eclipse.leshan.core.request.Identity; - -/** - * Represent a single Bootstraping session. - * - * Should be created by {@link BootstrapSessionManager} implementations in {@link BootstrapSessionManager.begin}. - */ -public class BootstrapSession { - - private final String endpoint; - private final Identity clientIdentity; - private final boolean authorized; - - protected BootstrapSession(String endpoint, Identity clientIdentity, boolean authorized) { - this.endpoint = endpoint; - this.clientIdentity = clientIdentity; - this.authorized = authorized; - } - - public String getEndpoint() { - return endpoint; - } - - public Identity getClientIdentity() { - return clientIdentity; - } - - public boolean isAuthorized() { - return authorized; - } - - /** - * A Bootstrapping session where the client was not authorized. - */ - public static BootstrapSession unauthorized() { - return new BootstrapSession(null, null, false); - } - - /** - * A Bootstrapping session where the client was properly authorized. - */ - public static BootstrapSession authorized(String endpoint, Identity clientIdentity) { - return new BootstrapSession(endpoint, clientIdentity, true); - } - - @Override - public String toString() { - return String.format("BootstrapSession [endpoint=%s, clientIdentity=%s, authorized=%s]", endpoint, - clientIdentity, authorized); - } - -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import org.eclipse.leshan.core.request.Identity; + +/** + * Represent a single Bootstraping session. + * + * Should be created by {@link BootstrapSessionManager} implementations in {@link BootstrapSessionManager.begin}. + */ +public class BootstrapSession { + + private final String endpoint; + private final Identity clientIdentity; + private final boolean authorized; + + protected BootstrapSession(String endpoint, Identity clientIdentity, boolean authorized) { + this.endpoint = endpoint; + this.clientIdentity = clientIdentity; + this.authorized = authorized; + } + + public String getEndpoint() { + return endpoint; + } + + public Identity getClientIdentity() { + return clientIdentity; + } + + public boolean isAuthorized() { + return authorized; + } + + /** + * A Bootstrapping session where the client was not authorized. + */ + public static BootstrapSession unauthorized() { + return new BootstrapSession(null, null, false); + } + + /** + * A Bootstrapping session where the client was properly authorized. + */ + public static BootstrapSession authorized(String endpoint, Identity clientIdentity) { + return new BootstrapSession(endpoint, clientIdentity, true); + } + + @Override + public String toString() { + return String.format("BootstrapSession [endpoint=%s, clientIdentity=%s, authorized=%s]", endpoint, + clientIdentity, authorized); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSessionManager.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSessionManager.java index c3d2bd8..395395f 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSessionManager.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapSessionManager.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * Manages boundaries of bootstrap process. - */ -public interface BootstrapSessionManager { - - /** - * Starts a bootstrapping session for an endpoint. In particular, this is responsible for authorizing the endpoint - * if applicable. - * - * @param endpoint - * @param clientIdentity - * - * @return a BootstrapSession, possibly authorized. - */ - public BootstrapSession begin(String endpoint, Identity clientIdentity); - - /** - * Performs any housekeeping related to the successful ending of a Boostraping session. - * - * @param bsSession - */ - public void end(BootstrapSession bsSession); - - /** - * Performs any housekeeping related to the failure of a Boostraping session. - * - * @param bsSession - * @param request - * @param exception - */ - public void failed(BootstrapSession bsSession, DownlinkRequest request, - Exception exception); - -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * Manages boundaries of bootstrap process. + */ +public interface BootstrapSessionManager { + + /** + * Starts a bootstrapping session for an endpoint. In particular, this is responsible for authorizing the endpoint + * if applicable. + * + * @param endpoint + * @param clientIdentity + * + * @return a BootstrapSession, possibly authorized. + */ + public BootstrapSession begin(String endpoint, Identity clientIdentity); + + /** + * Performs any housekeeping related to the successful ending of a Boostraping session. + * + * @param bsSession + */ + public void end(BootstrapSession bsSession); + + /** + * Performs any housekeeping related to the failure of a Boostraping session. + * + * @param bsSession + * @param request + * @param exception + */ + public void failed(BootstrapSession bsSession, DownlinkRequest request, + Exception exception); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapStore.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapStore.java index 78f1488..d79fde1 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapStore.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/BootstrapStore.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -/** - * A store containing the bootstrap information to be sent to the devices. - */ -public interface BootstrapStore { - - BootstrapConfig getBootstrap(String endpoint); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +/** + * A store containing the bootstrap information to be sent to the devices. + */ +public interface BootstrapStore { + + BootstrapConfig getBootstrap(String endpoint); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapRequestSender.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapRequestSender.java index 69497bd..a460b6a 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapRequestSender.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapRequestSender.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import java.net.InetSocketAddress; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; - -public interface LwM2mBootstrapRequestSender { - /** - * Send a Lightweight M2M request synchronously. Will block until a response is received from the remote server. - * - * @return the LWM2M response. The response can be null if the timeout (given parameter or CoAP - * timeout) expires. - */ - T send(final String clientEndpoint, final InetSocketAddress client, final boolean secure, - final DownlinkRequest request, Long timeout) throws InterruptedException; - - /** - * Send a Lightweight M2M request asynchronously. - */ - void send(final String clientEndpoint, final InetSocketAddress client, - final boolean secure, final DownlinkRequest request, final ResponseCallback responseCallback, - final ErrorCallback errorCallback); -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import java.net.InetSocketAddress; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; + +public interface LwM2mBootstrapRequestSender { + /** + * Send a Lightweight M2M request synchronously. Will block until a response is received from the remote server. + * + * @return the LWM2M response. The response can be null if the timeout (given parameter or CoAP + * timeout) expires. + */ + T send(final String clientEndpoint, final InetSocketAddress client, final boolean secure, + final DownlinkRequest request, Long timeout) throws InterruptedException; + + /** + * Send a Lightweight M2M request asynchronously. + */ + void send(final String clientEndpoint, final InetSocketAddress client, + final boolean secure, final DownlinkRequest request, final ResponseCallback responseCallback, + final ErrorCallback errorCallback); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapServer.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapServer.java index eb43d25..d56fdc7 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapServer.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/LwM2mBootstrapServer.java @@ -1,42 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import org.eclipse.leshan.server.security.BootstrapSecurityStore; - -/** - * - * A Lightweight M2M server in charge of handling device bootstrap on the /bs resource. - * - */ -public interface LwM2mBootstrapServer { - - /** - * Access to the bootstrap configuration store. It's used for sending configuration to the devices initiating a - * bootstrap. - */ - BootstrapStore getBoostrapStore(); - - /** - * security store used for DTLS authentication on the bootstrap ressource. - */ - BootstrapSecurityStore getBootstrapSecurityStore(); - - void start(); - - void stop(); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import org.eclipse.leshan.server.security.BootstrapSecurityStore; + +/** + * + * A Lightweight M2M server in charge of handling device bootstrap on the /bs resource. + * + */ +public interface LwM2mBootstrapServer { + + /** + * Access to the bootstrap configuration store. It's used for sending configuration to the devices initiating a + * bootstrap. + */ + BootstrapStore getBoostrapStore(); + + /** + * security store used for DTLS authentication on the bootstrap ressource. + */ + BootstrapSecurityStore getBootstrapSecurityStore(); + + void start(); + + void stop(); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SecurityMode.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SecurityMode.java index 367bbc1..07dd458 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SecurityMode.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SecurityMode.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -/** - * The different DTLS security modes - */ -public enum SecurityMode { - PSK(0), RPK(1), X509(2), NO_SEC(3); - - public final int code; - - private SecurityMode(int code) { - this.code = code; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +/** + * The different DTLS security modes + */ +public enum SecurityMode { + PSK(0), RPK(1), X509(2), NO_SEC(3); + + public final int code; + + private SecurityMode(int code) { + this.code = code; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SmsSecurityMode.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SmsSecurityMode.java index 271d29e..7829c1e 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SmsSecurityMode.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/bootstrap/SmsSecurityMode.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -/** - * The different SMS security modes - */ -public enum SmsSecurityMode { - RESERVED(0), SPS_DEVICE(1), SPS_SMARTCARD(2), NO_SEC(3), PROPRIETARY(255); - - public final int code; - - private SmsSecurityMode(int code) { - this.code = code; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +/** + * The different SMS security modes + */ +public enum SmsSecurityMode { + RESERVED(0), SPS_DEVICE(1), SPS_SMARTCARD(2), NO_SEC(3), PROPRIETARY(255); + + public final int code; + + private SmsSecurityMode(int code) { + this.code = code; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/Client.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/Client.java index 6c6f224..f17a1ea 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/Client.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/Client.java @@ -1,387 +1,387 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.client; - -import java.io.Serializable; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.core.request.BindingMode; -import org.eclipse.leshan.util.Validate; - -/** - * An immutable structure which represent a LW-M2M client registered on the server - */ -public class Client implements Serializable { - - private static final long serialVersionUID = 1L; - - private static final long DEFAULT_LIFETIME_IN_SEC = 86400L; - - private static final String DEFAULT_LWM2M_VERSION = "1.0"; - - private final Date registrationDate; - - private final InetAddress address; - - private final int port; - - /* - * The address of the LWM2M Server's CoAP end point the client used to register. - */ - private final InetSocketAddress registrationEndpointAddress; - - private final long lifeTimeInSec; - - private final String smsNumber; - - private final String lwM2mVersion; - - private final BindingMode bindingMode; - - /** - * The LWM2M Client's unique end point name. - */ - private final String endpoint; - - private final String registrationId; - - private final LinkObject[] objectLinks; - - private final Map additionalRegistrationAttributes; - - /** The location where LWM2M objects are hosted on the device */ - private final String rootPath; - - private final Date lastUpdate; - - protected Client(String registrationId, String endpoint, InetAddress address, int port, String lwM2mVersion, - Long lifetimeInSec, String smsNumber, BindingMode bindingMode, LinkObject[] objectLinks, - InetSocketAddress registrationEndpointAddress, - - Date registrationDate, Date lastUpdate, Map additionalRegistrationAttributes) { - - Validate.notNull(registrationId); - Validate.notEmpty(endpoint); - Validate.notNull(address); - Validate.notNull(port); - Validate.notNull(registrationEndpointAddress); - - this.registrationId = registrationId; - this.endpoint = endpoint; - this.address = address; - this.port = port; - this.smsNumber = smsNumber; - this.registrationEndpointAddress = registrationEndpointAddress; - - this.objectLinks = objectLinks; - // extract the root objects path from the object links - String rootPath = "/"; - if (objectLinks != null) { - for (LinkObject link : objectLinks) { - if (link != null && "oma.lwm2m".equals(link.getAttributes().get("rt"))) { - rootPath = link.getUrl(); - break; - } - } - } - this.rootPath = rootPath; - - this.lifeTimeInSec = lifetimeInSec == null ? DEFAULT_LIFETIME_IN_SEC : lifetimeInSec; - this.lwM2mVersion = lwM2mVersion == null ? DEFAULT_LWM2M_VERSION : lwM2mVersion; - this.bindingMode = bindingMode == null ? BindingMode.U : bindingMode; - this.registrationDate = registrationDate == null ? new Date() : registrationDate; - this.lastUpdate = lastUpdate == null ? new Date() : lastUpdate; - this.additionalRegistrationAttributes = additionalRegistrationAttributes == null - ? Collections.unmodifiableMap(new HashMap()) - : Collections.unmodifiableMap(additionalRegistrationAttributes); - - } - - public String getRegistrationId() { - return registrationId; - } - - public Date getRegistrationDate() { - return registrationDate; - } - - /** - * Gets the client's network address. - * - * @return the source address from the client's most recent CoAP message. - */ - public InetAddress getAddress() { - return address; - } - - /** - * Gets the client's network port number. - * - * @return the source port from the client's most recent CoAP message. - */ - public int getPort() { - return port; - } - - /** - * Gets the network address and port number of LWM2M Server's CoAP endpoint the client originally registered at. - * - * A LWM2M Server may listen on multiple CoAP end points, e.g. a non-secure and a secure one. Clients are often - * behind a firewall which will only let incoming UDP packets pass if they originate from the same address:port that - * the client has initiated communication with, e.g. by means of registering with the LWM2M Server. It is therefore - * important to know, which of the server's CoAP end points the client contacted for registration. - * - * This information can be used to uniquely identify the CoAP endpoint that should be used to access resources on - * the client. - * - * @return the network address and port number - */ - public InetSocketAddress getRegistrationEndpointAddress() { - return registrationEndpointAddress; - } - - public LinkObject[] getObjectLinks() { - return objectLinks; - } - - public LinkObject[] getSortedObjectLinks() { - // sort the list of objects - if (objectLinks == null) { - return null; - } - - LinkObject[] res = Arrays.copyOf(objectLinks, objectLinks.length); - - Arrays.sort(res, new Comparator() { - - /* sort by path */ - @Override - public int compare(LinkObject o1, LinkObject o2) { - if (o1 == null && o2 == null) - return 0; - if (o1 == null) - return -1; - if (o2 == null) - return 1; - // by URL - String[] url1 = o1.getUrl().split("/"); - String[] url2 = o2.getUrl().split("/"); - - for (int i = 0; i < url1.length && i < url2.length; i++) { - // is it two numbers? - if (isNumber(url1[i]) && isNumber(url2[i])) { - int cmp = Integer.parseInt(url1[i]) - Integer.parseInt(url2[i]); - if (cmp != 0) { - return cmp; - } - } else { - - int v = url1[i].compareTo(url2[i]); - - if (v != 0) { - return v; - } - } - } - - return url1.length - url2.length; - } - }); - - return res; - } - - private static boolean isNumber(String s) { - try { - Integer.parseInt(s); - return true; - } catch (NumberFormatException e) { - return false; - } - } - - public synchronized Long getLifeTimeInSec() { - return lifeTimeInSec; - } - - public String getSmsNumber() { - return smsNumber; - } - - public String getLwM2mVersion() { - return lwM2mVersion; - } - - public BindingMode getBindingMode() { - return bindingMode; - } - - /** - * @return the path where the objects are hosted on the device - */ - public String getRootPath() { - return rootPath; - } - - /** - * Gets the unique name the client has registered with. - * - * @return the name - */ - public String getEndpoint() { - return endpoint; - } - - public Date getLastUpdate() { - return lastUpdate; - } - - public boolean isAlive() { - return lastUpdate.getTime() + lifeTimeInSec * 1000 > System.currentTimeMillis(); - } - - public Map getAdditionalRegistrationAttributes() { - return additionalRegistrationAttributes; - } - - public boolean usesQueueMode() { - return bindingMode.equals(BindingMode.UQ); - } - - @Override - public String toString() { - return String.format( - "Client [registrationDate=%s, address=%s, port=%s, registrationEndpoint=%s, lifeTimeInSec=%s, smsNumber=%s, lwM2mVersion=%s, bindingMode=%s, endpoint=%s, registrationId=%s, objectLinks=%s, lastUpdate=%s]", - registrationDate, address, port, registrationEndpointAddress, lifeTimeInSec, smsNumber, lwM2mVersion, - bindingMode, endpoint, registrationId, Arrays.toString(objectLinks), lastUpdate); - } - - /** - * Computes a hash code for this client. - * - * @return the hash code based on the endpoint property - */ - @Override - public int hashCode() { - return getEndpoint().hashCode(); - } - - /** - * Compares this Client to another object. - * - * @return true if the other object is a Client instance and its endpoint property has the - * same value as this Client - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof Client) { - Client other = (Client) obj; - return this.getEndpoint().equals(other.getEndpoint()); - } else { - return false; - } - } - - public static class Builder { - private final String registrationId; - private final String endpoint; - private final InetAddress address; - private final int port; - private final InetSocketAddress registrationEndpointAddress; - - private Date registrationDate; - private Date lastUpdate; - private Long lifeTimeInSec; - private String smsNumber; - private BindingMode bindingMode; - private String lwM2mVersion; - private LinkObject[] objectLinks; - private Map additionalRegistrationAttributes; - - public Builder(String registrationId, String endpoint, InetAddress address, int port, - InetSocketAddress registrationEndpointAddress) { - - Validate.notNull(registrationId); - Validate.notEmpty(endpoint); - Validate.notNull(address); - Validate.notNull(port); - Validate.notNull(registrationEndpointAddress); - this.registrationId = registrationId; - this.endpoint = endpoint; - this.address = address; - this.port = port; - this.registrationEndpointAddress = registrationEndpointAddress; - - } - - public Builder registrationDate(Date registrationDate) { - this.registrationDate = registrationDate; - return this; - } - - public Builder lastUpdate(Date lastUpdate) { - this.lastUpdate = lastUpdate; - return this; - } - - public Builder lifeTimeInSec(Long lifetimeInSec) { - this.lifeTimeInSec = lifetimeInSec; - return this; - } - - public Builder smsNumber(String smsNumber) { - this.smsNumber = smsNumber; - return this; - } - - public Builder bindingMode(BindingMode bindingMode) { - this.bindingMode = bindingMode; - return this; - } - - public Builder lwM2mVersion(String lwM2mVersion) { - this.lwM2mVersion = lwM2mVersion; - return this; - } - - public Builder objectLinks(LinkObject[] objectLinks) { - this.objectLinks = objectLinks; - return this; - } - - public Builder additionalRegistrationAttributes(Map additionalRegistrationAttributes) { - this.additionalRegistrationAttributes = additionalRegistrationAttributes; - return this; - } - - public Client build() { - return new Client(Builder.this.registrationId, Builder.this.endpoint, Builder.this.address, - Builder.this.port, Builder.this.lwM2mVersion, Builder.this.lifeTimeInSec, Builder.this.smsNumber, - this.bindingMode, this.objectLinks, this.registrationEndpointAddress, this.registrationDate, - this.lastUpdate, this.additionalRegistrationAttributes); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.client; + +import java.io.Serializable; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.core.request.BindingMode; +import org.eclipse.leshan.util.Validate; + +/** + * An immutable structure which represent a LW-M2M client registered on the server + */ +public class Client implements Serializable { + + private static final long serialVersionUID = 1L; + + private static final long DEFAULT_LIFETIME_IN_SEC = 86400L; + + private static final String DEFAULT_LWM2M_VERSION = "1.0"; + + private final Date registrationDate; + + private final InetAddress address; + + private final int port; + + /* + * The address of the LWM2M Server's CoAP end point the client used to register. + */ + private final InetSocketAddress registrationEndpointAddress; + + private final long lifeTimeInSec; + + private final String smsNumber; + + private final String lwM2mVersion; + + private final BindingMode bindingMode; + + /** + * The LWM2M Client's unique end point name. + */ + private final String endpoint; + + private final String registrationId; + + private final LinkObject[] objectLinks; + + private final Map additionalRegistrationAttributes; + + /** The location where LWM2M objects are hosted on the device */ + private final String rootPath; + + private final Date lastUpdate; + + protected Client(String registrationId, String endpoint, InetAddress address, int port, String lwM2mVersion, + Long lifetimeInSec, String smsNumber, BindingMode bindingMode, LinkObject[] objectLinks, + InetSocketAddress registrationEndpointAddress, + + Date registrationDate, Date lastUpdate, Map additionalRegistrationAttributes) { + + Validate.notNull(registrationId); + Validate.notEmpty(endpoint); + Validate.notNull(address); + Validate.notNull(port); + Validate.notNull(registrationEndpointAddress); + + this.registrationId = registrationId; + this.endpoint = endpoint; + this.address = address; + this.port = port; + this.smsNumber = smsNumber; + this.registrationEndpointAddress = registrationEndpointAddress; + + this.objectLinks = objectLinks; + // extract the root objects path from the object links + String rootPath = "/"; + if (objectLinks != null) { + for (LinkObject link : objectLinks) { + if (link != null && "oma.lwm2m".equals(link.getAttributes().get("rt"))) { + rootPath = link.getUrl(); + break; + } + } + } + this.rootPath = rootPath; + + this.lifeTimeInSec = lifetimeInSec == null ? DEFAULT_LIFETIME_IN_SEC : lifetimeInSec; + this.lwM2mVersion = lwM2mVersion == null ? DEFAULT_LWM2M_VERSION : lwM2mVersion; + this.bindingMode = bindingMode == null ? BindingMode.U : bindingMode; + this.registrationDate = registrationDate == null ? new Date() : registrationDate; + this.lastUpdate = lastUpdate == null ? new Date() : lastUpdate; + this.additionalRegistrationAttributes = additionalRegistrationAttributes == null + ? Collections.unmodifiableMap(new HashMap()) + : Collections.unmodifiableMap(additionalRegistrationAttributes); + + } + + public String getRegistrationId() { + return registrationId; + } + + public Date getRegistrationDate() { + return registrationDate; + } + + /** + * Gets the client's network address. + * + * @return the source address from the client's most recent CoAP message. + */ + public InetAddress getAddress() { + return address; + } + + /** + * Gets the client's network port number. + * + * @return the source port from the client's most recent CoAP message. + */ + public int getPort() { + return port; + } + + /** + * Gets the network address and port number of LWM2M Server's CoAP endpoint the client originally registered at. + * + * A LWM2M Server may listen on multiple CoAP end points, e.g. a non-secure and a secure one. Clients are often + * behind a firewall which will only let incoming UDP packets pass if they originate from the same address:port that + * the client has initiated communication with, e.g. by means of registering with the LWM2M Server. It is therefore + * important to know, which of the server's CoAP end points the client contacted for registration. + * + * This information can be used to uniquely identify the CoAP endpoint that should be used to access resources on + * the client. + * + * @return the network address and port number + */ + public InetSocketAddress getRegistrationEndpointAddress() { + return registrationEndpointAddress; + } + + public LinkObject[] getObjectLinks() { + return objectLinks; + } + + public LinkObject[] getSortedObjectLinks() { + // sort the list of objects + if (objectLinks == null) { + return null; + } + + LinkObject[] res = Arrays.copyOf(objectLinks, objectLinks.length); + + Arrays.sort(res, new Comparator() { + + /* sort by path */ + @Override + public int compare(LinkObject o1, LinkObject o2) { + if (o1 == null && o2 == null) + return 0; + if (o1 == null) + return -1; + if (o2 == null) + return 1; + // by URL + String[] url1 = o1.getUrl().split("/"); + String[] url2 = o2.getUrl().split("/"); + + for (int i = 0; i < url1.length && i < url2.length; i++) { + // is it two numbers? + if (isNumber(url1[i]) && isNumber(url2[i])) { + int cmp = Integer.parseInt(url1[i]) - Integer.parseInt(url2[i]); + if (cmp != 0) { + return cmp; + } + } else { + + int v = url1[i].compareTo(url2[i]); + + if (v != 0) { + return v; + } + } + } + + return url1.length - url2.length; + } + }); + + return res; + } + + private static boolean isNumber(String s) { + try { + Integer.parseInt(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public synchronized Long getLifeTimeInSec() { + return lifeTimeInSec; + } + + public String getSmsNumber() { + return smsNumber; + } + + public String getLwM2mVersion() { + return lwM2mVersion; + } + + public BindingMode getBindingMode() { + return bindingMode; + } + + /** + * @return the path where the objects are hosted on the device + */ + public String getRootPath() { + return rootPath; + } + + /** + * Gets the unique name the client has registered with. + * + * @return the name + */ + public String getEndpoint() { + return endpoint; + } + + public Date getLastUpdate() { + return lastUpdate; + } + + public boolean isAlive() { + return lastUpdate.getTime() + lifeTimeInSec * 1000 > System.currentTimeMillis(); + } + + public Map getAdditionalRegistrationAttributes() { + return additionalRegistrationAttributes; + } + + public boolean usesQueueMode() { + return bindingMode.equals(BindingMode.UQ); + } + + @Override + public String toString() { + return String.format( + "Client [registrationDate=%s, address=%s, port=%s, registrationEndpoint=%s, lifeTimeInSec=%s, smsNumber=%s, lwM2mVersion=%s, bindingMode=%s, endpoint=%s, registrationId=%s, objectLinks=%s, lastUpdate=%s]", + registrationDate, address, port, registrationEndpointAddress, lifeTimeInSec, smsNumber, lwM2mVersion, + bindingMode, endpoint, registrationId, Arrays.toString(objectLinks), lastUpdate); + } + + /** + * Computes a hash code for this client. + * + * @return the hash code based on the endpoint property + */ + @Override + public int hashCode() { + return getEndpoint().hashCode(); + } + + /** + * Compares this Client to another object. + * + * @return true if the other object is a Client instance and its endpoint property has the + * same value as this Client + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Client) { + Client other = (Client) obj; + return this.getEndpoint().equals(other.getEndpoint()); + } else { + return false; + } + } + + public static class Builder { + private final String registrationId; + private final String endpoint; + private final InetAddress address; + private final int port; + private final InetSocketAddress registrationEndpointAddress; + + private Date registrationDate; + private Date lastUpdate; + private Long lifeTimeInSec; + private String smsNumber; + private BindingMode bindingMode; + private String lwM2mVersion; + private LinkObject[] objectLinks; + private Map additionalRegistrationAttributes; + + public Builder(String registrationId, String endpoint, InetAddress address, int port, + InetSocketAddress registrationEndpointAddress) { + + Validate.notNull(registrationId); + Validate.notEmpty(endpoint); + Validate.notNull(address); + Validate.notNull(port); + Validate.notNull(registrationEndpointAddress); + this.registrationId = registrationId; + this.endpoint = endpoint; + this.address = address; + this.port = port; + this.registrationEndpointAddress = registrationEndpointAddress; + + } + + public Builder registrationDate(Date registrationDate) { + this.registrationDate = registrationDate; + return this; + } + + public Builder lastUpdate(Date lastUpdate) { + this.lastUpdate = lastUpdate; + return this; + } + + public Builder lifeTimeInSec(Long lifetimeInSec) { + this.lifeTimeInSec = lifetimeInSec; + return this; + } + + public Builder smsNumber(String smsNumber) { + this.smsNumber = smsNumber; + return this; + } + + public Builder bindingMode(BindingMode bindingMode) { + this.bindingMode = bindingMode; + return this; + } + + public Builder lwM2mVersion(String lwM2mVersion) { + this.lwM2mVersion = lwM2mVersion; + return this; + } + + public Builder objectLinks(LinkObject[] objectLinks) { + this.objectLinks = objectLinks; + return this; + } + + public Builder additionalRegistrationAttributes(Map additionalRegistrationAttributes) { + this.additionalRegistrationAttributes = additionalRegistrationAttributes; + return this; + } + + public Client build() { + return new Client(Builder.this.registrationId, Builder.this.endpoint, Builder.this.address, + Builder.this.port, Builder.this.lwM2mVersion, Builder.this.lifeTimeInSec, Builder.this.smsNumber, + this.bindingMode, this.objectLinks, this.registrationEndpointAddress, this.registrationDate, + this.lastUpdate, this.additionalRegistrationAttributes); + } + + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistry.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistry.java index 6685096..f34ef03 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistry.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistry.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.client; - -import java.util.Collection; - -/** - * A registry to access registered clients - */ -public interface ClientRegistry { - - /** - * Retrieves a registered client by end-point. - * - * @param endpoint - * @return the matching client or null if not found - */ - Client get(String endpoint); - - /** - * Returns an unmodifiable list of all registered clients. - * - * @return the registered clients - */ - Collection allClients(); - - /** - * Adds a new listener to be notified with client registration events. - * - * @param listener - */ - void addListener(ClientRegistryListener listener); - - /** - * Removes a client registration listener. - * - * @param listener the listener to be removed - */ - void removeListener(ClientRegistryListener listener); - - /** - * Registers a new client. - * - * An implementation must notify all registered listeners as part of processing the registration request. - * - * @param client the client to register, identified by its end-point. - * @return true if the client was properly registered and false if the registration is not - * allowed. - */ - boolean registerClient(Client client); - - /** - * Updates registration properties for a given client. - * - * @param update the registration properties to update - * @return the updated registered client or null if no client is registered under the given end-point - * name - */ - Client updateClient(ClientUpdate update); - - /** - * De-registers a client. - * - * @param registrationId the client registrationId - * @return the previously registered client or null if no client is registered under the given ID - */ - Client deregisterClient(String registrationId); - - /** - * Retrieves a registered client by registration id. - * - * @param registration id - * @return the matching client or null if not found - */ - Client findByRegistrationId(String id); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.client; + +import java.util.Collection; + +/** + * A registry to access registered clients + */ +public interface ClientRegistry { + + /** + * Retrieves a registered client by end-point. + * + * @param endpoint + * @return the matching client or null if not found + */ + Client get(String endpoint); + + /** + * Returns an unmodifiable list of all registered clients. + * + * @return the registered clients + */ + Collection allClients(); + + /** + * Adds a new listener to be notified with client registration events. + * + * @param listener + */ + void addListener(ClientRegistryListener listener); + + /** + * Removes a client registration listener. + * + * @param listener the listener to be removed + */ + void removeListener(ClientRegistryListener listener); + + /** + * Registers a new client. + * + * An implementation must notify all registered listeners as part of processing the registration request. + * + * @param client the client to register, identified by its end-point. + * @return true if the client was properly registered and false if the registration is not + * allowed. + */ + boolean registerClient(Client client); + + /** + * Updates registration properties for a given client. + * + * @param update the registration properties to update + * @return the updated registered client or null if no client is registered under the given end-point + * name + */ + Client updateClient(ClientUpdate update); + + /** + * De-registers a client. + * + * @param registrationId the client registrationId + * @return the previously registered client or null if no client is registered under the given ID + */ + Client deregisterClient(String registrationId); + + /** + * Retrieves a registered client by registration id. + * + * @param registration id + * @return the matching client or null if not found + */ + Client findByRegistrationId(String id); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistryListener.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistryListener.java index d839cb5..2161d16 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistryListener.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientRegistryListener.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.client; - -/** - * Listen for client registration events. - */ -public interface ClientRegistryListener { - - /** - * Invoked when a new client has been registered on the server. - * - * @param client - */ - void registered(Client client); - - /** - * Invoked when a client has been updated. - * - * @param update the registration properties to update - * @param clientUpdated the client after the update - */ - void updated(ClientUpdate update, Client clientUpdated); - - /** - * Invoked when a new client has been unregistered from the server. - * - * @param client - */ - void unregistered(Client client); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.client; + +/** + * Listen for client registration events. + */ +public interface ClientRegistryListener { + + /** + * Invoked when a new client has been registered on the server. + * + * @param client + */ + void registered(Client client); + + /** + * Invoked when a client has been updated. + * + * @param update the registration properties to update + * @param clientUpdated the client after the update + */ + void updated(ClientUpdate update, Client clientUpdated); + + /** + * Invoked when a new client has been unregistered from the server. + * + * @param client + */ + void unregistered(Client client); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientUpdate.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientUpdate.java index d28df4a..eff2cb1 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientUpdate.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/client/ClientUpdate.java @@ -1,119 +1,119 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.client; - -import java.net.InetAddress; -import java.util.Arrays; -import java.util.Date; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.core.request.BindingMode; -import org.eclipse.leshan.util.Validate; - -/** - * A container object for updating a LW-M2M client's registration properties on the server. - */ -public class ClientUpdate { - - private final String registrationId; - - private final InetAddress address; - private final Integer port; - - private final Long lifeTimeInSec; - private final String smsNumber; - private final BindingMode bindingMode; - private final LinkObject[] objectLinks; - - public ClientUpdate(String registrationId, InetAddress address, Integer port, Long lifeTimeInSec, String smsNumber, - BindingMode bindingMode, LinkObject[] objectLinks) { - Validate.notNull(registrationId); - Validate.notNull(address); - Validate.notNull(port); - this.registrationId = registrationId; - this.address = address; - this.port = port; - - this.lifeTimeInSec = lifeTimeInSec; - this.smsNumber = smsNumber; - this.bindingMode = bindingMode; - this.objectLinks = objectLinks; - } - - /** - * Returns an updated version of the client. - * - * @param client the registered client - * @return the updated client - */ - public Client updateClient(Client client) { - InetAddress address = this.address != null ? this.address : client.getAddress(); - int port = this.port != null ? this.port : client.getPort(); - LinkObject[] linkObject = this.objectLinks != null ? this.objectLinks : client.getObjectLinks(); - long lifeTimeInSec = this.lifeTimeInSec != null ? this.lifeTimeInSec : client.getLifeTimeInSec(); - BindingMode bindingMode = this.bindingMode != null ? this.bindingMode : client.getBindingMode(); - String smsNumber = this.smsNumber != null ? this.smsNumber : client.getSmsNumber(); - - // this needs to be done in any case, even if no properties have changed, in order - // to extend the client registration's time-to-live period ... - Date lastUpdate = new Date(); - - Client.Builder builder = new Client.Builder(client.getRegistrationId(), client.getEndpoint(), address, port, - client.getRegistrationEndpointAddress()); - - builder.lwM2mVersion(client.getLwM2mVersion()).lifeTimeInSec(lifeTimeInSec).smsNumber(smsNumber) - .bindingMode(bindingMode).objectLinks(linkObject).registrationDate(client.getRegistrationDate()) - .lastUpdate(lastUpdate).additionalRegistrationAttributes(client.getAdditionalRegistrationAttributes()); - - return builder.build(); - - } - - public String getRegistrationId() { - return registrationId; - } - - public InetAddress getAddress() { - return address; - } - - public Integer getPort() { - return port; - } - - public Long getLifeTimeInSec() { - return lifeTimeInSec; - } - - public String getSmsNumber() { - return smsNumber; - } - - public BindingMode getBindingMode() { - return bindingMode; - } - - public LinkObject[] getObjectLinks() { - return objectLinks; - } - - @Override - public String toString() { - return String.format( - "ClientUpdate [registrationId=%s, address=%s, port=%s, lifeTimeInSec=%s, smsNumber=%s, bindingMode=%s, objectLinks=%s]", - registrationId, address, port, lifeTimeInSec, smsNumber, bindingMode, Arrays.toString(objectLinks)); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.client; + +import java.net.InetAddress; +import java.util.Arrays; +import java.util.Date; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.core.request.BindingMode; +import org.eclipse.leshan.util.Validate; + +/** + * A container object for updating a LW-M2M client's registration properties on the server. + */ +public class ClientUpdate { + + private final String registrationId; + + private final InetAddress address; + private final Integer port; + + private final Long lifeTimeInSec; + private final String smsNumber; + private final BindingMode bindingMode; + private final LinkObject[] objectLinks; + + public ClientUpdate(String registrationId, InetAddress address, Integer port, Long lifeTimeInSec, String smsNumber, + BindingMode bindingMode, LinkObject[] objectLinks) { + Validate.notNull(registrationId); + Validate.notNull(address); + Validate.notNull(port); + this.registrationId = registrationId; + this.address = address; + this.port = port; + + this.lifeTimeInSec = lifeTimeInSec; + this.smsNumber = smsNumber; + this.bindingMode = bindingMode; + this.objectLinks = objectLinks; + } + + /** + * Returns an updated version of the client. + * + * @param client the registered client + * @return the updated client + */ + public Client updateClient(Client client) { + InetAddress address = this.address != null ? this.address : client.getAddress(); + int port = this.port != null ? this.port : client.getPort(); + LinkObject[] linkObject = this.objectLinks != null ? this.objectLinks : client.getObjectLinks(); + long lifeTimeInSec = this.lifeTimeInSec != null ? this.lifeTimeInSec : client.getLifeTimeInSec(); + BindingMode bindingMode = this.bindingMode != null ? this.bindingMode : client.getBindingMode(); + String smsNumber = this.smsNumber != null ? this.smsNumber : client.getSmsNumber(); + + // this needs to be done in any case, even if no properties have changed, in order + // to extend the client registration's time-to-live period ... + Date lastUpdate = new Date(); + + Client.Builder builder = new Client.Builder(client.getRegistrationId(), client.getEndpoint(), address, port, + client.getRegistrationEndpointAddress()); + + builder.lwM2mVersion(client.getLwM2mVersion()).lifeTimeInSec(lifeTimeInSec).smsNumber(smsNumber) + .bindingMode(bindingMode).objectLinks(linkObject).registrationDate(client.getRegistrationDate()) + .lastUpdate(lastUpdate).additionalRegistrationAttributes(client.getAdditionalRegistrationAttributes()); + + return builder.build(); + + } + + public String getRegistrationId() { + return registrationId; + } + + public InetAddress getAddress() { + return address; + } + + public Integer getPort() { + return port; + } + + public Long getLifeTimeInSec() { + return lifeTimeInSec; + } + + public String getSmsNumber() { + return smsNumber; + } + + public BindingMode getBindingMode() { + return bindingMode; + } + + public LinkObject[] getObjectLinks() { + return objectLinks; + } + + @Override + public String toString() { + return String.format( + "ClientUpdate [registrationId=%s, address=%s, port=%s, lifeTimeInSec=%s, smsNumber=%s, bindingMode=%s, objectLinks=%s]", + registrationId, address, port, lifeTimeInSec, smsNumber, bindingMode, Arrays.toString(objectLinks)); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Constants.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Constants.java index 80f0971..f1330cf 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Constants.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Constants.java @@ -1,105 +1,105 @@ -package org.eclipse.leshan.server.extension; - -import java.util.HashMap; -import java.util.Map; - -public class Constants { - - // Device Info - public static String OUI = "000001"; - - // request header - public static String CONTENT_TYPE = "application/json"; - public static String ORIGIN_BASE = "S"; - public static String UNNAMED = "unnamed"; - public static boolean USE_AUTH = false; - - // oneM2M info - public static final String BASIC_NAME_SPACE = "m2m"; - public static final String BASIC_AE_NAME = "lwm2m_ipe"; - public static final String BASIC_CONTAINER_LBL = "cnt"; - public static final String CONTAINER_NAME_CONTROL = "execute"; - public static final String CONTAINER_NAME_RESULT = "result"; - public static final String CONTAINER_NAME_STATUS = "status"; - - // oneM2M options - public static final long DAYS_FOR_EXPIRED = 3650L; - - // oneM2M Resource Type - public static final int MIXED = 0; - public static final int ACCESS_CTRL_PLCY = 1; - public static final int AE = 2; - public static final int CONTAINER = 3; - public static final int CONTENTINSTANCE = 4; - public static final int CSE_BASE = 5; - public static final int GROUP = 9; - public static final int POLLING_CHANNEL = 15; - public static final int SUBSCRIPTION = 23; - public static final int SEMANTIC_DESCRIPTOR = 24; - - - // LWM2M Resource(new) 2017.11.03 - public static final String[][] RESOURCE = { - {"info","Model_number","/3/0/1"}, - {"info","Package_uri","/5/0/1"}, - {"report","Humidity","/1024/10/1"}, - {"report","Temperature","/1024/10/3"}, - {"report","Distance","/1024/11/3"}, - {"control","Reboot","/3/0/4"}, - {"control","LEDPower","/1024/12/1"}, - {"control","SoundPower","/1024/12/3"} - }; - - - - public static String getResourceByUri(String uri){ - String result = null; - for(int i=0; i map = new HashMap(); - static { - for(REQUEST_METHOD_TYPE rmt : REQUEST_METHOD_TYPE.values()) { - map.put(rmt.value, rmt); - } - } - - public static REQUEST_METHOD_TYPE get(int value) { - REQUEST_METHOD_TYPE rmt = map.get(value); - return rmt; - } - } - - -} +package org.eclipse.leshan.server.extension; + +import java.util.HashMap; +import java.util.Map; + +public class Constants { + + // Device Info + public static String OUI = "000001"; + + // request header + public static String CONTENT_TYPE = "application/json"; + public static String ORIGIN_BASE = "S"; + public static String UNNAMED = "unnamed"; + public static boolean USE_AUTH = false; + + // oneM2M info + public static final String BASIC_NAME_SPACE = "m2m"; + public static final String BASIC_AE_NAME = "lwm2m_ipe"; + public static final String BASIC_CONTAINER_LBL = "cnt"; + public static final String CONTAINER_NAME_CONTROL = "execute"; + public static final String CONTAINER_NAME_RESULT = "result"; + public static final String CONTAINER_NAME_STATUS = "status"; + + // oneM2M options + public static final long DAYS_FOR_EXPIRED = 3650L; + + // oneM2M Resource Type + public static final int MIXED = 0; + public static final int ACCESS_CTRL_PLCY = 1; + public static final int AE = 2; + public static final int CONTAINER = 3; + public static final int CONTENTINSTANCE = 4; + public static final int CSE_BASE = 5; + public static final int GROUP = 9; + public static final int POLLING_CHANNEL = 15; + public static final int SUBSCRIPTION = 23; + public static final int SEMANTIC_DESCRIPTOR = 24; + + + // LWM2M Resource(new) 2017.11.03 + public static final String[][] RESOURCE = { + {"info","Model_number","/3/0/1"}, + {"info","Package_uri","/5/0/1"}, + {"report","Humidity","/1024/10/1"}, + {"report","Temperature","/1024/10/3"}, + {"report","Distance","/1024/11/3"}, + {"control","Reboot","/3/0/4"}, + {"control","LEDPower","/1024/12/1"}, + {"control","SoundPower","/1024/12/3"} + }; + + + + public static String getResourceByUri(String uri){ + String result = null; + for(int i=0; i map = new HashMap(); + static { + for(REQUEST_METHOD_TYPE rmt : REQUEST_METHOD_TYPE.values()) { + map.put(rmt.value, rmt); + } + } + + public static REQUEST_METHOD_TYPE get(int value) { + REQUEST_METHOD_TYPE rmt = map.get(value); + return rmt; + } + } + + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/HttpOperator.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/HttpOperator.java index 0ceb2ce..adcefa8 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/HttpOperator.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/HttpOperator.java @@ -1,313 +1,313 @@ -package org.eclipse.leshan.server.extension; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.json.JSONObject; - -public class HttpOperator { - - // send get with base header - public HttpURLConnection sendGet(String strUri){ - - URL url = null; - HttpURLConnection conn = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("GET"); - conn.setDoInput(true); - - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - - return conn; - } - - // send get with oneM2M header - public HttpURLConnection sendGet(String strUri, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("GET"); - conn.setDoInput(true); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - - return conn; - } - - // send post with base header - public HttpURLConnection sendPost(String strUri, JSONObject data){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setDoOutput(true); - conn.setDoInput(true); - - os = conn.getOutputStream(); - os.write(data.toString().getBytes()); - os.flush(); - - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - return conn; - } - - // send post with onem2m header - public HttpURLConnection sendPost(String strUri, JSONObject data, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setDoOutput(true); - conn.setDoInput(true); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - - os = conn.getOutputStream(); - os.write(data.toString().getBytes()); - os.flush(); - - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - return conn; - } - - // send delete with onem2m header - public HttpURLConnection sendLongPolling(String strUri, HashMap header){ - - URL url = null; - HttpURLConnection conn = null; - OutputStream os = null; - - try { - url = new URL(strUri); - conn = (HttpURLConnection)url.openConnection(); - - conn.setRequestMethod("DELETE"); - conn.setDoInput(true); - conn.setDoOutput(false); - if(header != null){ - // header print(출력) - // Util.printMap(header); - Iterator it = header.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - String value = header.get(key); - conn.addRequestProperty(key, value); - } - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - try{ - if(os != null){ - os.close(); - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - return conn; - } - - - // get response from the server - public JSONObject getResponse(HttpURLConnection conn){ - - JSONObject result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - int responseCode = conn.getResponseCode(); - - if (responseCode == HttpURLConnection.HTTP_OK) { - is = conn.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - byte[] byteData = null; - int nLength = 0; - while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { - baos.write(byteBuffer, 0, nLength); - } - byteData = baos.toByteArray(); - result = new JSONObject(new String(byteData)); - } else { - result = new JSONObject(); - result.put("RESPONSE-CODE", String.valueOf(responseCode)); - } - } catch(Exception e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - try { - if(is != null){ - is.close(); - } - if(baos != null){ - baos.close(); - } - if(conn != null){ - conn.disconnect(); - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - return result; - } - - public String getResponseString(HttpURLConnection conn){ - - String result = null; - InputStream is = null; - ByteArrayOutputStream baos = null; - - try{ - int responseCode = conn.getResponseCode(); - - if (responseCode >= HttpURLConnection.HTTP_OK && responseCode <= 202) { - is = conn.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - int nLength = 0; - while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { - baos.write(byteBuffer, 0, nLength); - } - result = new String(baos.toByteArray()); - } else { - JSONObject job = new JSONObject(); - job.put("RESPONSE-CODE", String.valueOf(responseCode)); - - result = job.toString(); - } - } catch(Exception e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - try { - if(is != null){ - is.close(); - } - if(baos != null){ - baos.close(); - } - if(conn != null){ - conn.disconnect(); - } - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - return result; - } -} +package org.eclipse.leshan.server.extension; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.json.JSONObject; + +public class HttpOperator { + + // send get with base header + public HttpURLConnection sendGet(String strUri){ + + URL url = null; + HttpURLConnection conn = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("GET"); + conn.setDoInput(true); + + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + + return conn; + } + + // send get with oneM2M header + public HttpURLConnection sendGet(String strUri, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("GET"); + conn.setDoInput(true); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + + return conn; + } + + // send post with base header + public HttpURLConnection sendPost(String strUri, JSONObject data){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + conn.setDoInput(true); + + os = conn.getOutputStream(); + os.write(data.toString().getBytes()); + os.flush(); + + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + return conn; + } + + // send post with onem2m header + public HttpURLConnection sendPost(String strUri, JSONObject data, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + conn.setDoInput(true); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + + os = conn.getOutputStream(); + os.write(data.toString().getBytes()); + os.flush(); + + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + return conn; + } + + // send delete with onem2m header + public HttpURLConnection sendLongPolling(String strUri, HashMap header){ + + URL url = null; + HttpURLConnection conn = null; + OutputStream os = null; + + try { + url = new URL(strUri); + conn = (HttpURLConnection)url.openConnection(); + + conn.setRequestMethod("DELETE"); + conn.setDoInput(true); + conn.setDoOutput(false); + if(header != null){ + // header print(출력) + // Util.printMap(header); + Iterator it = header.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + String value = header.get(key); + conn.addRequestProperty(key, value); + } + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + try{ + if(os != null){ + os.close(); + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + return conn; + } + + + // get response from the server + public JSONObject getResponse(HttpURLConnection conn){ + + JSONObject result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + int responseCode = conn.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + is = conn.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + byte[] byteData = null; + int nLength = 0; + while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { + baos.write(byteBuffer, 0, nLength); + } + byteData = baos.toByteArray(); + result = new JSONObject(new String(byteData)); + } else { + result = new JSONObject(); + result.put("RESPONSE-CODE", String.valueOf(responseCode)); + } + } catch(Exception e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + try { + if(is != null){ + is.close(); + } + if(baos != null){ + baos.close(); + } + if(conn != null){ + conn.disconnect(); + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + return result; + } + + public String getResponseString(HttpURLConnection conn){ + + String result = null; + InputStream is = null; + ByteArrayOutputStream baos = null; + + try{ + int responseCode = conn.getResponseCode(); + + if (responseCode >= HttpURLConnection.HTTP_OK && responseCode <= 202) { + is = conn.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + int nLength = 0; + while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { + baos.write(byteBuffer, 0, nLength); + } + result = new String(baos.toByteArray()); + } else { + JSONObject job = new JSONObject(); + job.put("RESPONSE-CODE", String.valueOf(responseCode)); + + result = job.toString(); + } + } catch(Exception e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + try { + if(is != null){ + is.close(); + } + if(baos != null){ + baos.close(); + } + if(conn != null){ + conn.disconnect(); + } + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + return result; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Lwm2mVO.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Lwm2mVO.java index d6e6d2f..fd9e24e 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Lwm2mVO.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Lwm2mVO.java @@ -1,39 +1,39 @@ -package org.eclipse.leshan.server.extension; - -import org.eclipse.leshan.server.client.Client; - -public class Lwm2mVO { - - private String authId = null; - private String authPwd = null; - private Client client = null; - - public String getAuthId() { - return authId; - } - public void setAuthId(String authId) { - this.authId = authId; - } - public String getAuthPwd() { - return authPwd; - } - public void setAuthPwd(String authPwd) { - this.authPwd = authPwd; - } - public Client getClient() { - return client; - } - public void setClient(Client client) { - this.client = client; - } - - private int currCount = 0; - - public int getCurrCount() { - return currCount; - } - public void setCurrCount(int currCount) { - this.currCount = currCount; - } - -} +package org.eclipse.leshan.server.extension; + +import org.eclipse.leshan.server.client.Client; + +public class Lwm2mVO { + + private String authId = null; + private String authPwd = null; + private Client client = null; + + public String getAuthId() { + return authId; + } + public void setAuthId(String authId) { + this.authId = authId; + } + public String getAuthPwd() { + return authPwd; + } + public void setAuthPwd(String authPwd) { + this.authPwd = authPwd; + } + public Client getClient() { + return client; + } + public void setClient(Client client) { + this.client = client; + } + + private int currCount = 0; + + public int getCurrCount() { + return currCount; + } + public void setCurrCount(int currCount) { + this.currCount = currCount; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/TaskTimer.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/TaskTimer.java index ff4d2fe..525dd50 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/TaskTimer.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/TaskTimer.java @@ -1,20 +1,20 @@ -package org.eclipse.leshan.server.extension; - -public class TaskTimer implements Runnable{ - - @Override - public void run() { - int count = 0; - while(true){ - System.out.println(count+" sec"); - try { - Thread.sleep(1000); - count += 1; - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - } - -} +package org.eclipse.leshan.server.extension; + +public class TaskTimer implements Runnable{ + + @Override + public void run() { + int count = 0; + while(true){ + System.out.println(count+" sec"); + try { + Thread.sleep(1000); + count += 1; + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Tokenization.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Tokenization.java index 9730744..75299d6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Tokenization.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Tokenization.java @@ -1,201 +1,201 @@ -package org.eclipse.leshan.server.extension; - -import java.util.HashMap; -import java.util.Iterator; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.extension.dm.handler.DmOperator; -import org.eclipse.leshan.util.Base64; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class Tokenization { - - // device info token - public JSONObject makeDeviceInfoToken(Lwm2mVO vo) throws JSONException{ - - JSONObject result = null; - DmOperator dmOperator = new DmOperator(); - - result = new JSONObject(); - HashMap deviceInfo = dmOperator.getDeviceInfo(vo.getAuthId()); - Iterator resources = deviceInfo.keySet().iterator(); - while(resources.hasNext()){ - String resource = resources.next(); - String value = deviceInfo.get(resource); - result.put(resource, value); - } - - result.put("authId", vo.getAuthId()); - result.put("authPwd", vo.getAuthPwd()); - - return result; - } - - // Using dm token when device connects, disconnects .. - public JSONObject makeDmToken(Lwm2mVO vo, String strConnect) throws JSONException{ - - JSONObject result = makeDeviceInfoToken(vo); - String[] uris = Util.getUri(vo.getClient().getObjectLinks()); - JSONArray objectModels = new JSONArray(); - for (String uri : uris) { - JSONObject uriWrap = new JSONObject(); - uriWrap.put("uri",uri); - objectModels.put(uriWrap); - } - result.put("conn", strConnect); - result.put("objectModels", objectModels); - - return result; - } - - - - - - - - - - public static JSONObject makesBasicToken(String authId, String connect){ - // 기본 인스턴스 생성 - JSONObject result = null; - - try{ - result = new JSONObject(); - result.put("conn", connect); - DmOperator dmOperator = new DmOperator(); - HashMap deviceInfo = dmOperator.getDeviceInfo(authId); - Iterator resources = deviceInfo.keySet().iterator(); - while(resources.hasNext()){ - try{ - String resource = resources.next(); - String value = deviceInfo.get(resource); - result.put(resource, value); - } catch(Exception e) { - e.printStackTrace(); - } - } - } catch(Exception e) {} - - - return result; - } - - public static String getDeviceInfoEncoded(String authId){ - - String result = null; - JSONObject info = new JSONObject(); - DmOperator dmOperator = new DmOperator(); - HashMap deviceInfo = dmOperator.getDeviceInfo(authId); - Iterator resources = deviceInfo.keySet().iterator(); - while(resources.hasNext()){ - try{ - String resource = resources.next(); - String value = deviceInfo.get(resource); - info.put(resource, value); - } catch(Exception e) { - System.out.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - - try{ - //info.put("authId", authId); - //info.put("authPwd", authPwd); - - result = Base64.encodeBase64String(info.toString().getBytes()); - System.out.println(result); - } catch(Exception e) { - System.out.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - - return result; - } - - - public static JSONObject makesTokenForConnect(String authId, String authPwd, Client client){ - - JSONObject result = null; - - try{ - result = makesBasicToken(authId, "connect"); - DmOperator dmOperator = new DmOperator(); - HashMap deviceInfo = dmOperator.getDeviceInfo(authId); - Util.printMap(deviceInfo); - Iterator resources = deviceInfo.keySet().iterator(); - while(resources.hasNext()){ - try{ - String resource = resources.next(); - String value = deviceInfo.get(resource); - result.put(resource, value); - } catch(Exception e) { - e.printStackTrace(); - } - } - - String[] uris = Util.getUri(client.getObjectLinks()); - JSONArray objectModels = new JSONArray(); - for (String uri : uris) { - JSONObject uriWrap = new JSONObject(); - uriWrap.put("uri",uri); - objectModels.put(uriWrap); - } - result.put("objectModels", objectModels); - - // 기본 속성 : 인증 속성 - result.put("authId", authId); - result.put("authPwd", authPwd); - - System.out.println("reseult = "+result); - - } catch(Exception e) {} - - return result; - } - - public static JSONObject makesTokenForDisconnect(String authId, Client client){ - - // 기본 인스턴스 생성 - JSONObject result = null; - - try{ - - result = makesBasicToken(authId, "disconnect"); - DmOperator dmOperator = new DmOperator(); - HashMap deviceInfo = dmOperator.getDeviceInfo(authId); - Iterator resources = deviceInfo.keySet().iterator(); - while(resources.hasNext()){ - try{ - String resource = resources.next(); - String value = deviceInfo.get(resource); - result.put(resource, value); - } catch(Exception e) { - e.printStackTrace(); - } - } - - String[] uris = Util.getUri(client.getObjectLinks()); - JSONArray objectModels = new JSONArray(); - for (String uri : uris) { - JSONObject uriWrap = new JSONObject(); - uriWrap.put("uri",uri); - objectModels.put(uriWrap); - } - result.put("objectModels", objectModels); - - // 기본 속성 : 인증 속성 - result.put("authId", authId); - - } catch(Exception e) {} - - return result; - } -} +package org.eclipse.leshan.server.extension; + +import java.util.HashMap; +import java.util.Iterator; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.extension.dm.handler.DmOperator; +import org.eclipse.leshan.util.Base64; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Tokenization { + + // device info token + public JSONObject makeDeviceInfoToken(Lwm2mVO vo) throws JSONException{ + + JSONObject result = null; + DmOperator dmOperator = new DmOperator(); + + result = new JSONObject(); + HashMap deviceInfo = dmOperator.getDeviceInfo(vo.getAuthId()); + Iterator resources = deviceInfo.keySet().iterator(); + while(resources.hasNext()){ + String resource = resources.next(); + String value = deviceInfo.get(resource); + result.put(resource, value); + } + + result.put("authId", vo.getAuthId()); + result.put("authPwd", vo.getAuthPwd()); + + return result; + } + + // Using dm token when device connects, disconnects .. + public JSONObject makeDmToken(Lwm2mVO vo, String strConnect) throws JSONException{ + + JSONObject result = makeDeviceInfoToken(vo); + String[] uris = Util.getUri(vo.getClient().getObjectLinks()); + JSONArray objectModels = new JSONArray(); + for (String uri : uris) { + JSONObject uriWrap = new JSONObject(); + uriWrap.put("uri",uri); + objectModels.put(uriWrap); + } + result.put("conn", strConnect); + result.put("objectModels", objectModels); + + return result; + } + + + + + + + + + + public static JSONObject makesBasicToken(String authId, String connect){ + // 기본 인스턴스 생성 + JSONObject result = null; + + try{ + result = new JSONObject(); + result.put("conn", connect); + DmOperator dmOperator = new DmOperator(); + HashMap deviceInfo = dmOperator.getDeviceInfo(authId); + Iterator resources = deviceInfo.keySet().iterator(); + while(resources.hasNext()){ + try{ + String resource = resources.next(); + String value = deviceInfo.get(resource); + result.put(resource, value); + } catch(Exception e) { + e.printStackTrace(); + } + } + } catch(Exception e) {} + + + return result; + } + + public static String getDeviceInfoEncoded(String authId){ + + String result = null; + JSONObject info = new JSONObject(); + DmOperator dmOperator = new DmOperator(); + HashMap deviceInfo = dmOperator.getDeviceInfo(authId); + Iterator resources = deviceInfo.keySet().iterator(); + while(resources.hasNext()){ + try{ + String resource = resources.next(); + String value = deviceInfo.get(resource); + info.put(resource, value); + } catch(Exception e) { + System.out.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + + try{ + //info.put("authId", authId); + //info.put("authPwd", authPwd); + + result = Base64.encodeBase64String(info.toString().getBytes()); + System.out.println(result); + } catch(Exception e) { + System.out.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + + return result; + } + + + public static JSONObject makesTokenForConnect(String authId, String authPwd, Client client){ + + JSONObject result = null; + + try{ + result = makesBasicToken(authId, "connect"); + DmOperator dmOperator = new DmOperator(); + HashMap deviceInfo = dmOperator.getDeviceInfo(authId); + Util.printMap(deviceInfo); + Iterator resources = deviceInfo.keySet().iterator(); + while(resources.hasNext()){ + try{ + String resource = resources.next(); + String value = deviceInfo.get(resource); + result.put(resource, value); + } catch(Exception e) { + e.printStackTrace(); + } + } + + String[] uris = Util.getUri(client.getObjectLinks()); + JSONArray objectModels = new JSONArray(); + for (String uri : uris) { + JSONObject uriWrap = new JSONObject(); + uriWrap.put("uri",uri); + objectModels.put(uriWrap); + } + result.put("objectModels", objectModels); + + // 기본 속성 : 인증 속성 + result.put("authId", authId); + result.put("authPwd", authPwd); + + System.out.println("reseult = "+result); + + } catch(Exception e) {} + + return result; + } + + public static JSONObject makesTokenForDisconnect(String authId, Client client){ + + // 기본 인스턴스 생성 + JSONObject result = null; + + try{ + + result = makesBasicToken(authId, "disconnect"); + DmOperator dmOperator = new DmOperator(); + HashMap deviceInfo = dmOperator.getDeviceInfo(authId); + Iterator resources = deviceInfo.keySet().iterator(); + while(resources.hasNext()){ + try{ + String resource = resources.next(); + String value = deviceInfo.get(resource); + result.put(resource, value); + } catch(Exception e) { + e.printStackTrace(); + } + } + + String[] uris = Util.getUri(client.getObjectLinks()); + JSONArray objectModels = new JSONArray(); + for (String uri : uris) { + JSONObject uriWrap = new JSONObject(); + uriWrap.put("uri",uri); + objectModels.put(uriWrap); + } + result.put("objectModels", objectModels); + + // 기본 속성 : 인증 속성 + result.put("authId", authId); + + } catch(Exception e) {} + + return result; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Util.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Util.java index 802046f..1a66d59 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Util.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/Util.java @@ -1,166 +1,166 @@ -package org.eclipse.leshan.server.extension; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathFactory; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.server.Lwm2mServerConfig; - -import org.json.JSONException; -import org.json.JSONObject; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -public class Util { - - - /*********************************************** - * common - ************************************************/ - - // null 이나 empty이면 true 반환 - public static boolean isNoE(String msg){ - boolean result = false; - if(msg==null || msg.equals("")){ - result = true; - } - return result; - } - - // null 이나 empty이면 true 반환 - public static boolean isNoEOprAnd(String ... msgs){ - boolean result = false; - int count = 0; - for(String msg : msgs){ - if(msg==null || msg.equals("")){ - count += 1; - } - } - if(count == msgs.length){ - result = true; - } - return result; - } - - // null 이나 empty이면 true 반환 - public static boolean isNoEOprOr(String ... msgs){ - boolean result = false; - for(String msg : msgs){ - if(msg==null || msg.equals("")){ - result = true; - break; - } - } - return result; - } - - // url 만들기 "/"로 구분 - public static String makeUrl(String ...paths){ - StringBuffer sb = new StringBuffer(paths[0]); - for(int i=1; i it = obj.sortedKeys(); - while(it.hasNext()){ - try{ - String key = it.next(); - Object value = obj.get(key); - System.out.println("["+key+"]-["+value+"]"); - } catch(JSONException e){ - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - } - - // HashMap 내용 전부 출력 - public static void printMap(HashMap map){ - Iterator it = map.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - Object value = map.get(key); - System.out.println("["+key+"]-["+value+"]"); - } - } - - /*********************************************** - * oneM2M - ************************************************/ - - - // pcu 결과 xml에서 con값 가져오기 - public static String getValue( String xml, String path ) { - Node node = null; - String make_xml = combineString(xml.substring(0,xml.indexOf(">")+1),"",xml.substring(xml.indexOf(">")+1),""); - try { - Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(make_xml.getBytes())); - doc.getDocumentElement().normalize(); - XPath xpath = XPathFactory.newInstance().newXPath(); - String pathResult = ""; - if( path.equals("sur") ){ - pathResult = "//pc/sgn/sur"; - } else { - pathResult = "//pc/sgn/nev/rep/cin/"+path; - } - node = (Node) xpath.evaluate(pathResult, doc, XPathConstants.NODE); - } catch( Exception e ) { - e.printStackTrace(); - } - return node.getTextContent(); - } - - - - // byte[] 를 hex code로 : psk - public static String byteArrayToHex(byte[] a) { - StringBuilder sb = new StringBuilder(); - for(final byte b: a) - sb.append(String.format("%02x", b&0xff)); - return sb.toString(); - } - - // device id 추출 - public static int[] getObjectId(LinkObject[] lo){ - int[] result = new int[lo.length-1]; - for (int i = 0; i < lo.length-1; i++) { - String value = lo[i+1].toString().substring(2,3); - result[i] = Integer.parseInt(value); - } - return result; - } - - // device id 추출 - public static String[] getUri(LinkObject[] lo){ - String[] result = new String[lo.length-1]; - for (int i = 0; i < lo.length-1; i++) { - result[i] = lo[i+1].toString().replace("<", "").replace(">", ""); - } - return result; - } - - - -} +package org.eclipse.leshan.server.extension; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.server.Lwm2mServerConfig; + +import org.json.JSONException; +import org.json.JSONObject; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +public class Util { + + + /*********************************************** + * common + ************************************************/ + + // null 이나 empty이면 true 반환 + public static boolean isNoE(String msg){ + boolean result = false; + if(msg==null || msg.equals("")){ + result = true; + } + return result; + } + + // null 이나 empty이면 true 반환 + public static boolean isNoEOprAnd(String ... msgs){ + boolean result = false; + int count = 0; + for(String msg : msgs){ + if(msg==null || msg.equals("")){ + count += 1; + } + } + if(count == msgs.length){ + result = true; + } + return result; + } + + // null 이나 empty이면 true 반환 + public static boolean isNoEOprOr(String ... msgs){ + boolean result = false; + for(String msg : msgs){ + if(msg==null || msg.equals("")){ + result = true; + break; + } + } + return result; + } + + // url 만들기 "/"로 구분 + public static String makeUrl(String ...paths){ + StringBuffer sb = new StringBuffer(paths[0]); + for(int i=1; i it = obj.sortedKeys(); + while(it.hasNext()){ + try{ + String key = it.next(); + Object value = obj.get(key); + System.out.println("["+key+"]-["+value+"]"); + } catch(JSONException e){ + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + } + + // HashMap 내용 전부 출력 + public static void printMap(HashMap map){ + Iterator it = map.keySet().iterator(); + while(it.hasNext()){ + String key = it.next(); + Object value = map.get(key); + System.out.println("["+key+"]-["+value+"]"); + } + } + + /*********************************************** + * oneM2M + ************************************************/ + + + // pcu 결과 xml에서 con값 가져오기 + public static String getValue( String xml, String path ) { + Node node = null; + String make_xml = combineString(xml.substring(0,xml.indexOf(">")+1),"",xml.substring(xml.indexOf(">")+1),""); + try { + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(make_xml.getBytes())); + doc.getDocumentElement().normalize(); + XPath xpath = XPathFactory.newInstance().newXPath(); + String pathResult = ""; + if( path.equals("sur") ){ + pathResult = "//pc/sgn/sur"; + } else { + pathResult = "//pc/sgn/nev/rep/cin/"+path; + } + node = (Node) xpath.evaluate(pathResult, doc, XPathConstants.NODE); + } catch( Exception e ) { + e.printStackTrace(); + } + return node.getTextContent(); + } + + + + // byte[] 를 hex code로 : psk + public static String byteArrayToHex(byte[] a) { + StringBuilder sb = new StringBuilder(); + for(final byte b: a) + sb.append(String.format("%02x", b&0xff)); + return sb.toString(); + } + + // device id 추출 + public static int[] getObjectId(LinkObject[] lo){ + int[] result = new int[lo.length-1]; + for (int i = 0; i < lo.length-1; i++) { + String value = lo[i+1].toString().substring(2,3); + result[i] = Integer.parseInt(value); + } + return result; + } + + // device id 추출 + public static String[] getUri(LinkObject[] lo){ + String[] result = new String[lo.length-1]; + for (int i = 0; i < lo.length-1; i++) { + result[i] = lo[i+1].toString().replace("<", "").replace(">", ""); + } + return result; + } + + + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/DmFormatter.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/DmFormatter.java index 21ec597..07dd1f6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/DmFormatter.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/DmFormatter.java @@ -1,5 +1,5 @@ -package org.eclipse.leshan.server.extension.dm; - -public class DmFormatter{ - -} +package org.eclipse.leshan.server.extension.dm; + +public class DmFormatter{ + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmConnector.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmConnector.java index a8056f3..00327fd 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmConnector.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmConnector.java @@ -1,49 +1,49 @@ -package org.eclipse.leshan.server.extension.dm.handler; - -import java.net.HttpURLConnection; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.extension.HttpOperator; -import org.eclipse.leshan.server.extension.Lwm2mVO; -import org.eclipse.leshan.server.extension.Tokenization; -import org.json.JSONException; -import org.json.JSONObject; - -public class DmConnector implements Runnable{ - - private Lwm2mVO vo = null; - public DmConnector(Lwm2mVO vo){ - this.vo = vo; - } - - @Override - public void run() { - - // token and operators - JSONObject token = null; - Tokenization tokenization = new Tokenization(); - HttpOperator httpOperator = new HttpOperator(); - HttpURLConnection conn = null; - - // string url - StringBuffer strUrl = new StringBuffer("http://"); - strUrl.append(Lwm2mServerConfig.getInstance().getDmIp()).append(":"); - strUrl.append(Lwm2mServerConfig.getInstance().getDmPort()).append("/hdm/lwm2m/connect.do"); - - // connect - try { - token = tokenization.makeDmToken(vo, "connect"); - conn = httpOperator.sendPost(strUrl.toString(), token); - String response = httpOperator.getResponseString(conn); - System.out.println(response); - - } catch (JSONException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - - } - -} +package org.eclipse.leshan.server.extension.dm.handler; + +import java.net.HttpURLConnection; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.extension.HttpOperator; +import org.eclipse.leshan.server.extension.Lwm2mVO; +import org.eclipse.leshan.server.extension.Tokenization; +import org.json.JSONException; +import org.json.JSONObject; + +public class DmConnector implements Runnable{ + + private Lwm2mVO vo = null; + public DmConnector(Lwm2mVO vo){ + this.vo = vo; + } + + @Override + public void run() { + + // token and operators + JSONObject token = null; + Tokenization tokenization = new Tokenization(); + HttpOperator httpOperator = new HttpOperator(); + HttpURLConnection conn = null; + + // string url + StringBuffer strUrl = new StringBuffer("http://"); + strUrl.append(Lwm2mServerConfig.getInstance().getDmIp()).append(":"); + strUrl.append(Lwm2mServerConfig.getInstance().getDmPort()).append("/hdm/lwm2m/connect.do"); + + // connect + try { + token = tokenization.makeDmToken(vo, "connect"); + conn = httpOperator.sendPost(strUrl.toString(), token); + String response = httpOperator.getResponseString(conn); + System.out.println(response); + + } catch (JSONException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmOperator.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmOperator.java index e64e3ef..30b71e2 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmOperator.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/dm/handler/DmOperator.java @@ -1,46 +1,46 @@ -package org.eclipse.leshan.server.extension.dm.handler; - -import java.net.*; -import java.util.HashMap; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.HttpOperator; -import org.json.JSONException; -import org.json.JSONObject; - -public class DmOperator { - - public HashMap getDeviceInfo(String deviceId){ - - StringBuffer strUrl = new StringBuffer("http://"); - strUrl.append(Lwm2mServerConfig.getInstance().getIpeIp()).append(":"); - strUrl.append(Lwm2mServerConfig.getInstance().getIpePortWeb()).append("/api/hdm/"); - strUrl.append(deviceId); - - HashMap deviceInfo = new HashMap(); - String[] resources = new String[]{"manufacturer","modelName","sn"}; - - HttpOperator operator = new HttpOperator(); - HttpURLConnection conn = null; - JSONObject response = null; - - for (int i = 0; i < 3; i++) { - try { - conn = operator.sendGet(strUrl.toString()+"/3/0/"+i); - response = operator.getResponse(conn); - deviceInfo.put(resources[i], response.getJSONObject("content").getString("value")); - } catch (JSONException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - deviceInfo.put("oui", Constants.OUI); - - return deviceInfo; - } - - -} +package org.eclipse.leshan.server.extension.dm.handler; + +import java.net.*; +import java.util.HashMap; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.extension.Constants; +import org.eclipse.leshan.server.extension.HttpOperator; +import org.json.JSONException; +import org.json.JSONObject; + +public class DmOperator { + + public HashMap getDeviceInfo(String deviceId){ + + StringBuffer strUrl = new StringBuffer("http://"); + strUrl.append(Lwm2mServerConfig.getInstance().getIpeIp()).append(":"); + strUrl.append(Lwm2mServerConfig.getInstance().getIpePortWeb()).append("/api/hdm/"); + strUrl.append(deviceId); + + HashMap deviceInfo = new HashMap(); + String[] resources = new String[]{"manufacturer","modelName","sn"}; + + HttpOperator operator = new HttpOperator(); + HttpURLConnection conn = null; + JSONObject response = null; + + for (int i = 0; i < 3; i++) { + try { + conn = operator.sendGet(strUrl.toString()+"/3/0/"+i); + response = operator.getResponse(conn); + deviceInfo.put(resources[i], response.getJSONObject("content").getString("value")); + } catch (JSONException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + deviceInfo.put("oui", Constants.OUI); + + return deviceInfo; + } + + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/Onem2mHeaderMaker.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/Onem2mHeaderMaker.java index 9bb6fa8..bcb7037 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/Onem2mHeaderMaker.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/Onem2mHeaderMaker.java @@ -1,40 +1,40 @@ -package org.eclipse.leshan.server.extension.onem2m; - -import java.util.HashMap; - -import org.eclipse.leshan.server.extension.Constants; - -public class Onem2mHeaderMaker { - - // PCU header - public HashMap getBasicHeader(){ - return getBasicHeader("10.10.0.23","RES_"+Long.toHexString(System.currentTimeMillis()),"SAE"); - } - public HashMap getBasicHeader(String host, String ri, String origin){ - HashMap header = new HashMap(); - header.put("Accept", "application/json"); - header.put("HOST", host); - header.put("X-M2M-RI", ri); - header.put("X-M2M-Origin", origin); - return header; - } - - - public HashMap getResourceCreationHeader(int type){ - - HashMap header = null; - - switch(type){ - case Constants.AE : - header = getBasicHeader("10.10.0.23","RES_"+Long.toHexString(System.currentTimeMillis()),"S"); - break; - default : - header = getBasicHeader(); - break; - } - - header.put("Content-Type","application/vnd.onem2m-res+json; ty="+type); - return header; - } - -} +package org.eclipse.leshan.server.extension.onem2m; + +import java.util.HashMap; + +import org.eclipse.leshan.server.extension.Constants; + +public class Onem2mHeaderMaker { + + // PCU header + public HashMap getBasicHeader(){ + return getBasicHeader("10.10.0.23","RES_"+Long.toHexString(System.currentTimeMillis()),"SAE"); + } + public HashMap getBasicHeader(String host, String ri, String origin){ + HashMap header = new HashMap(); + header.put("Accept", "application/json"); + header.put("HOST", host); + header.put("X-M2M-RI", ri); + header.put("X-M2M-Origin", origin); + return header; + } + + + public HashMap getResourceCreationHeader(int type){ + + HashMap header = null; + + switch(type){ + case Constants.AE : + header = getBasicHeader("10.10.0.23","RES_"+Long.toHexString(System.currentTimeMillis()),"S"); + break; + default : + header = getBasicHeader(); + break; + } + + header.put("Content-Type","application/vnd.onem2m-res+json; ty="+type); + return header; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Executor.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Executor.java index c4dfae4..61332f5 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Executor.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Executor.java @@ -1,116 +1,116 @@ -package org.eclipse.leshan.server.extension.onem2m.handler; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.json.JSONObject; - -public class Executor { - - // return value - private String result = null; - - // i/o - private HttpURLConnection conn = null; - private InputStream in = null; - private OutputStream out = null; - private ByteArrayOutputStream bout = null; - - // constructor - private int number = 0; - private JSONObject item = null; - public Executor(JSONObject item, int number){ - this.item = item; - this.number = number; - } - - public String execute(){ - - try{ - StringBuffer uri = new StringBuffer("http://"); - uri.append(Lwm2mServerConfig.getInstance().getIpeIp()).append(":"); - uri.append(Lwm2mServerConfig.getInstance().getIpePortWeb()).append("/api/clients/"); - uri.append(item.getString("authId")).append(item.getString("resourceUri")); - - /* - if(item.getOperation().equals("observe")){ - strUrl += "/observe"; - }//*/ - - if(Lwm2mServerConfig.getInstance().isDebug()){ - System.out.println(uri.toString()); - } - URL url = new URL(uri.toString()); - conn = (HttpURLConnection)url.openConnection(); - conn.setRequestProperty("Content-Type", "text/plain"); - - if( "read".equals(item.getString("operation")) ){ - conn.setRequestMethod("GET"); - } else if( "execute".equals(item.getString("operation")) ){ - conn.setRequestMethod("PUT"); - conn.setDoOutput(true); - - out = conn.getOutputStream(); - out.write(item.getString("sv").getBytes()); - out.flush(); - } - - in = conn.getInputStream(); - bout = new ByteArrayOutputStream(); - byte[] buf = new byte[1024 * 8]; - int length = 0; - while ((length = in.read(buf)) != -1) { - bout.write(buf, 0, length); - } - - result = new String(bout.toByteArray(), "UTF-8"); - System.out.println("["+String.format("%6d", number)+" RESULT ] " + result); - - } catch(Exception e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } finally { - if(bout != null){ - try { - bout.close(); - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - if(in != null){ - try { - in.close(); - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - }if(out != null){ - try { - out.close(); - } catch (IOException e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - if(conn != null){ - conn.disconnect(); - } - } - - return result; - } -} +package org.eclipse.leshan.server.extension.onem2m.handler; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.json.JSONObject; + +public class Executor { + + // return value + private String result = null; + + // i/o + private HttpURLConnection conn = null; + private InputStream in = null; + private OutputStream out = null; + private ByteArrayOutputStream bout = null; + + // constructor + private int number = 0; + private JSONObject item = null; + public Executor(JSONObject item, int number){ + this.item = item; + this.number = number; + } + + public String execute(){ + + try{ + StringBuffer uri = new StringBuffer("http://"); + uri.append(Lwm2mServerConfig.getInstance().getIpeIp()).append(":"); + uri.append(Lwm2mServerConfig.getInstance().getIpePortWeb()).append("/api/clients/"); + uri.append(item.getString("authId")).append(item.getString("resourceUri")); + + /* + if(item.getOperation().equals("observe")){ + strUrl += "/observe"; + }//*/ + + if(Lwm2mServerConfig.getInstance().isDebug()){ + System.out.println(uri.toString()); + } + URL url = new URL(uri.toString()); + conn = (HttpURLConnection)url.openConnection(); + conn.setRequestProperty("Content-Type", "text/plain"); + + if( "read".equals(item.getString("operation")) ){ + conn.setRequestMethod("GET"); + } else if( "execute".equals(item.getString("operation")) ){ + conn.setRequestMethod("PUT"); + conn.setDoOutput(true); + + out = conn.getOutputStream(); + out.write(item.getString("sv").getBytes()); + out.flush(); + } + + in = conn.getInputStream(); + bout = new ByteArrayOutputStream(); + byte[] buf = new byte[1024 * 8]; + int length = 0; + while ((length = in.read(buf)) != -1) { + bout.write(buf, 0, length); + } + + result = new String(bout.toByteArray(), "UTF-8"); + System.out.println("["+String.format("%6d", number)+" RESULT ] " + result); + + } catch(Exception e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } finally { + if(bout != null){ + try { + bout.close(); + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + if(in != null){ + try { + in.close(); + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + }if(out != null){ + try { + out.close(); + } catch (IOException e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + if(conn != null){ + conn.disconnect(); + } + } + + return result; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mConnector.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mConnector.java index 24146a1..acf6fbe 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mConnector.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mConnector.java @@ -1,41 +1,41 @@ -package org.eclipse.leshan.server.extension.onem2m.handler; - -import org.eclipse.leshan.server.extension.Lwm2mVO; - -public class Onem2mConnector implements Runnable{ - - private Lwm2mVO vo = null; - public Onem2mConnector(Lwm2mVO vo) { - this.vo = vo; - } - - private Onem2mOperator onem2mOperator = new Onem2mOperator(); - - @Override - public void run() { - - System.out.println("## Check AE exists."); - if( !onem2mOperator.isAEExist() ){ - System.out.println("## AE doesn't exist."); - System.out.println("## Create new repository."); - onem2mOperator.createRepository(vo); - } else { - System.out.println("## AE exists."); - } - - if( onem2mOperator.isAEExist() ){ - - System.out.println("## Start subscribe."); - Runnable rSubscribe = new TSubscribe(vo); - Thread tSubscribe = new Thread(rSubscribe); - tSubscribe.start(); - - System.out.println("## Start report."); - Runnable rReport = new TReport(vo); - Thread tReport = new Thread(rReport); - tReport.start(); - } - - - } -} +package org.eclipse.leshan.server.extension.onem2m.handler; + +import org.eclipse.leshan.server.extension.Lwm2mVO; + +public class Onem2mConnector implements Runnable{ + + private Lwm2mVO vo = null; + public Onem2mConnector(Lwm2mVO vo) { + this.vo = vo; + } + + private Onem2mOperator onem2mOperator = new Onem2mOperator(); + + @Override + public void run() { + + System.out.println("## Check AE exists."); + if( !onem2mOperator.isAEExist() ){ + System.out.println("## AE doesn't exist."); + System.out.println("## Create new repository."); + onem2mOperator.createRepository(vo); + } else { + System.out.println("## AE exists."); + } + + if( onem2mOperator.isAEExist() ){ + + System.out.println("## Start subscribe."); + Runnable rSubscribe = new TSubscribe(vo); + Thread tSubscribe = new Thread(rSubscribe); + tSubscribe.start(); + + System.out.println("## Start report."); + Runnable rReport = new TReport(vo); + Thread tReport = new Thread(rReport); + tReport.start(); + } + + + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mOperator.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mOperator.java index fe052d6..cc5598a 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mOperator.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/Onem2mOperator.java @@ -1,403 +1,403 @@ -package org.eclipse.leshan.server.extension.onem2m.handler; - -import java.net.HttpURLConnection; - -import org.json.JSONException; -import org.json.JSONObject; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.HttpOperator; -import org.eclipse.leshan.server.extension.Lwm2mVO; -import org.eclipse.leshan.server.extension.Util; -import org.eclipse.leshan.server.extension.onem2m.Onem2mHeaderMaker; -import org.eclipse.leshan.server.extension.onem2m.resources.AE; -import org.eclipse.leshan.server.extension.onem2m.resources.Container; -import org.eclipse.leshan.server.extension.onem2m.resources.ContentInstance; -import org.eclipse.leshan.server.extension.onem2m.resources.PollingChannel; -import org.eclipse.leshan.server.extension.onem2m.resources.SemanticDescriptor; -import org.eclipse.leshan.server.extension.onem2m.resources.Subscription; -import org.eclipse.leshan.util.Base64; - -public class Onem2mOperator { - - private HttpOperator httpOperator = new HttpOperator(); - private Onem2mHeaderMaker headerMaker = new Onem2mHeaderMaker(); - - - // AE 존재 체크 - public boolean isAEExist(){ - - boolean result = false; - - String strUri = Lwm2mServerConfig.getInstance().getSiUri()+"/"+Constants.BASIC_AE_NAME; - HttpURLConnection conn = httpOperator.sendGet(strUri, headerMaker.getBasicHeader()); - JSONObject response = httpOperator.getResponse(conn); - - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // AE 생성 - public boolean createAE(){ - - boolean result = false; - String strUri = Lwm2mServerConfig.getInstance().getSiUri(); - - AE ae = new AE(); - - HttpURLConnection conn = httpOperator.sendPost(strUri, ae.getJSON(), headerMaker.getResourceCreationHeader(Constants.AE)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // Container 생성 - public boolean createContainer(StringBuffer resUri, String resourceName){ - - boolean result = false; - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()).append("/").append(Constants.BASIC_AE_NAME); - sbUri.append(resUri); - - Container cnt = new Container(); - cnt.setRn(resourceName); - - HttpURLConnection conn = httpOperator.sendPost(sbUri.toString(), cnt.getJSON(), headerMaker.getResourceCreationHeader(Constants.CONTAINER)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // contentInstance 생성 - public boolean createContentInstance(String resourceName, JSONObject item) throws JSONException{ - - boolean result = false; - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()).append("/").append(Constants.BASIC_AE_NAME); - - ContentInstance cin = new ContentInstance(); - if(resourceName == null){ - sbUri.append("/").append(Constants.getResourceByUri(item.getString("resourceUri"))).append("/result"); - cin.setCon(item.getString("sv")); - cin.setCnf("text/plain:0"); - } else { - sbUri.append("/").append(resourceName).append("/status"); - cin.setCon(new String(Base64.encodeBase64(item.toString().getBytes()))); - } - - HttpURLConnection conn = httpOperator.sendPost(sbUri.toString(), cin.getJSON(), headerMaker.getResourceCreationHeader(Constants.CONTENTINSTANCE)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // PollingChannel 생성 - public boolean createPollingChannel(String resourceName){ - - boolean result = false; - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()).append("/").append(Constants.BASIC_AE_NAME); - - PollingChannel pch = new PollingChannel(); - pch.setRn(resourceName); - - HttpURLConnection conn = httpOperator.sendPost(sbUri.toString(), pch.getJSON(), headerMaker.getResourceCreationHeader(Constants.POLLING_CHANNEL)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // Subscription 생성 - public boolean createSubscription(StringBuffer resUri, String resourceName, String pchName){ - - boolean result = false; - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()).append("/").append(Constants.BASIC_AE_NAME); - sbUri.append(resUri); - - Subscription sub = new Subscription(); - sub.resetNu(); - sub.setRn(resourceName); - sub.addNu(Util.makeUrl(Lwm2mServerConfig.getInstance().getSiUri(), Constants.BASIC_AE_NAME, pchName, "pcu")); - - HttpURLConnection conn = httpOperator.sendPost(sbUri.toString(), sub.getJSON(), headerMaker.getResourceCreationHeader(Constants.SUBSCRIPTION)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // SemanticDescriptor 생성 - public boolean createSemanticDescriptor(){ - - boolean result = false; - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()).append("/").append(Constants.BASIC_AE_NAME); - - SemanticDescriptor sd = new SemanticDescriptor(); - - HttpURLConnection conn = httpOperator.sendPost(sbUri.toString(), sd.getJSON(), headerMaker.getResourceCreationHeader(Constants.SEMANTIC_DESCRIPTOR)); - JSONObject response = httpOperator.getResponse(conn); - if( !response.has("RESPONSE-CODE") ){ - result = true; - } - - return result; - } - - // LongPolling 대기 - public String retrievePCU(){ - - StringBuffer sbUri = new StringBuffer(Lwm2mServerConfig.getInstance().getSiUri()); - sbUri.append("/").append(Constants.BASIC_AE_NAME); - sbUri.append("/pch_srv/pcu"); - - System.out.println("strUri(LP) : "+sbUri); - HttpURLConnection conn = httpOperator.sendLongPolling(sbUri.toString(), headerMaker.getBasicHeader()); - String response = httpOperator.getResponseString(conn); - - return response; - } - - - // repository 생성 - public void createRepository(Lwm2mVO vo){ - - // AE 생성 - createAE(); - createSemanticDescriptor(); - createPollingChannel("pch_srv"); - createPollingChannel("pch_svc"); - - for(int i=0; i -1 && !(new JSONObject(response)).getString("RESPONSE-CODE").equals("408") ) { // RESPONSE-CODE 있는지 확인 - throw new Exception("NOT REACHABLE : "+response); - } else if( response.indexOf("") > -1 && response.indexOf("") > -1 ) { // con 태그가 존재하는지 확인 - byte[] decoded = Base64.decodeBase64(Util.getValue(response, "con")); - String strCon = new String(decoded); - item = new JSONObject(strCon); - - Executor exe = new Executor(item, number); - JSONObject result = new JSONObject(exe.execute()); - if(result.isNull("status")){ - throw new Exception("Cannot confirm status."); - } else { - if(result.getString("status").equals("CHANGED")){ - Util.printJSONObject(item); - // exe.execute() 결과 받은 처리 작성 할 부분 ex) {"status":"CHANGED"} - Onem2mOperator incseOperator = new Onem2mOperator(); - incseOperator.createContentInstance(null, item); - //incseOperator.createContentInstanceResult(item); - } else { - System.out.println("## execute() result = "+result); - } - } - } - } catch(Exception e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - } - } - -} +package org.eclipse.leshan.server.extension.onem2m.handler; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.extension.Util; +import org.eclipse.leshan.util.Base64; +import org.json.JSONObject; + +public class TDeviceControl implements Runnable{ + + private JSONObject item = null; + private String response = null; + private int number = 0; + public TDeviceControl(String response, int number){ + this.response = response; + this.number = number; + } + + @Override + public void run() { + + try{ + if( Util.isNoE(response) ){ + throw new Exception("response is null"); + } else if( response.indexOf("RESPONSE-CODE") > -1 && !(new JSONObject(response)).getString("RESPONSE-CODE").equals("408") ) { // RESPONSE-CODE 있는지 확인 + throw new Exception("NOT REACHABLE : "+response); + } else if( response.indexOf("") > -1 && response.indexOf("") > -1 ) { // con 태그가 존재하는지 확인 + byte[] decoded = Base64.decodeBase64(Util.getValue(response, "con")); + String strCon = new String(decoded); + item = new JSONObject(strCon); + + Executor exe = new Executor(item, number); + JSONObject result = new JSONObject(exe.execute()); + if(result.isNull("status")){ + throw new Exception("Cannot confirm status."); + } else { + if(result.getString("status").equals("CHANGED")){ + Util.printJSONObject(item); + // exe.execute() 결과 받은 처리 작성 할 부분 ex) {"status":"CHANGED"} + Onem2mOperator incseOperator = new Onem2mOperator(); + incseOperator.createContentInstance(null, item); + //incseOperator.createContentInstanceResult(item); + } else { + System.out.println("## execute() result = "+result); + } + } + } + } catch(Exception e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + } + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/TReport.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/TReport.java index 195dceb..4a1c916 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/TReport.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/handler/TReport.java @@ -1,61 +1,61 @@ -package org.eclipse.leshan.server.extension.onem2m.handler; - -import java.net.HttpURLConnection; -import java.util.Timer; -import java.util.TimerTask; - -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.HttpOperator; -import org.eclipse.leshan.server.extension.Lwm2mVO; -import org.json.JSONException; -import org.json.JSONObject; - -public class TReport extends TimerTask implements Runnable{ - - private Lwm2mVO vo = null; - public TReport(Lwm2mVO vo){ - this.vo = vo; - } - - private HttpOperator httpOperator = new HttpOperator(); - private Onem2mOperator onem2mOperator = new Onem2mOperator(); - - @Override - public void run() { - - StringBuffer baseUri = new StringBuffer("http://"); - baseUri.append(Lwm2mServerConfig.getInstance().getIpeIp()).append(":"); - baseUri.append(Lwm2mServerConfig.getInstance().getIpePortWeb()).append("/api/clients/"); - baseUri.append(vo.getAuthId()); - JSONObject result = null; - - for(int i=0; i -1 && !new JSONObject(response).getString("RESPONSE-CODE").equals("408") ){ - throw new Exception("[ERROR] LongPolling"); - } - - // 디바이스 제어 - Runnable runnable = new TDeviceControl(response, currCount); - Thread dct = new Thread(runnable); - dct.start(); - - // subscribe - Runnable rSubscribe = new TSubscribe(vo); - Thread tSubscribe = new Thread(rSubscribe); - tSubscribe.start(); - - } catch (Exception e) { - System.err.println(e.getMessage()); - if(Lwm2mServerConfig.getInstance().isDebug()){ - e.printStackTrace(); - } - // 대기 후 재시도 - TimerTask tSubscribeTask = new TSubscribe(vo); - Timer tSubscribe = new Timer(); - tSubscribe.schedule(tSubscribeTask, Lwm2mServerConfig.getInstance().getRetryInterval()); - } finally { - - System.out.println("[ "+String.format("%15s", vo.getAuthId())+" ][ "+String.format("%4d", currCount)+" ] LongPolling END"); - } - - } - -} +package org.eclipse.leshan.server.extension.onem2m.handler; + +import java.util.Timer; +import java.util.TimerTask; + +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.extension.Lwm2mVO; +import org.json.JSONObject; + +public class TSubscribe extends TimerTask implements Runnable{ + + private Lwm2mVO vo = null; + public TSubscribe(Lwm2mVO vo){ + this.vo = vo; + } + + @Override + public void run() { + + Onem2mOperator onem2mOperator = new Onem2mOperator(); + + vo.setCurrCount(vo.getCurrCount()+1); + int currCount = vo.getCurrCount(); + + System.out.println(); + System.out.println(); + System.out.println("[ "+String.format("%15s", vo.getAuthId())+" ][ "+String.format("%4d", currCount)+" ] LongPolling START"); + + try { + // longPolling + String response = onem2mOperator.retrievePCU(); + System.out.println(response); + + // exception + if( response.indexOf("RESPONSE-CODE") > -1 && !new JSONObject(response).getString("RESPONSE-CODE").equals("408") ){ + throw new Exception("[ERROR] LongPolling"); + } + + // 디바이스 제어 + Runnable runnable = new TDeviceControl(response, currCount); + Thread dct = new Thread(runnable); + dct.start(); + + // subscribe + Runnable rSubscribe = new TSubscribe(vo); + Thread tSubscribe = new Thread(rSubscribe); + tSubscribe.start(); + + } catch (Exception e) { + System.err.println(e.getMessage()); + if(Lwm2mServerConfig.getInstance().isDebug()){ + e.printStackTrace(); + } + // 대기 후 재시도 + TimerTask tSubscribeTask = new TSubscribe(vo); + Timer tSubscribe = new Timer(); + tSubscribe.schedule(tSubscribeTask, Lwm2mServerConfig.getInstance().getRetryInterval()); + } finally { + + System.out.println("[ "+String.format("%15s", vo.getAuthId())+" ][ "+String.format("%4d", currCount)+" ] LongPolling END"); + } + + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/AE.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/AE.java index 62db089..0e53d7c 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/AE.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/AE.java @@ -1,110 +1,110 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import java.io.IOException; -import java.util.ArrayList; - -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.Util; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class AE extends Resource{ - - public AE(){ - setShortName("ae"); - setRn(Constants.BASIC_AE_NAME); - setApi(Constants.BASIC_AE_NAME); - resetLbl(); - setExpired(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - - body.put("rn", getRn()); - body.put("apn", getApn()); - body.put("api", getApi()); - body.put("rr", isRr()); - body.put("et", getEt()); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public AE makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } - - /* - - // retrieve - public JSONObject retrieveAE(FoundItem oicDevice) { - - JSONObject jsonResponse = new JSONObject(); - - try { - String strOrigin = "OIC-" + this.deviceId; - - client.openConnection(); - client.setRequestHeader(this.host, this.deviceId, this.deviceId, strOrigin, MemberType.AE, Constants.REQUEST_METHOD_TYPE.GET.Value()); - jsonResponse = client.getResponse(); - - }catch(IOException ioe) { - ioe.printStackTrace(); - }catch(JSONException jsone) { - jsone.printStackTrace(); - }catch(Exception e) { - e.printStackTrace(); - } - - return jsonResponse; - } - // delete - public JSONObject deleteAE(FoundItem oicDevice) { - - JSONObject jsonResponse = new JSONObject(); - - try { - client.openConnection(); - client.setRequestHeader(this.host, this.deviceId, this.deviceId, oicDevice.getResourceUri(), MemberType.AE, Constants.REQUEST_METHOD_TYPE.DELETE.Value()); - - jsonResponse = client.getResponse(); - - }catch(IOException ioe) { - ioe.printStackTrace(); - }catch(JSONException jsone) { - jsone.printStackTrace(); - }catch(Exception e) { - e.printStackTrace(); - } - - return jsonResponse; - } - */ -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import java.io.IOException; +import java.util.ArrayList; + +import org.eclipse.leshan.server.extension.Constants; +import org.eclipse.leshan.server.extension.Util; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class AE extends Resource{ + + public AE(){ + setShortName("ae"); + setRn(Constants.BASIC_AE_NAME); + setApi(Constants.BASIC_AE_NAME); + resetLbl(); + setExpired(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + + body.put("rn", getRn()); + body.put("apn", getApn()); + body.put("api", getApi()); + body.put("rr", isRr()); + body.put("et", getEt()); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public AE makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } + + /* + + // retrieve + public JSONObject retrieveAE(FoundItem oicDevice) { + + JSONObject jsonResponse = new JSONObject(); + + try { + String strOrigin = "OIC-" + this.deviceId; + + client.openConnection(); + client.setRequestHeader(this.host, this.deviceId, this.deviceId, strOrigin, MemberType.AE, Constants.REQUEST_METHOD_TYPE.GET.Value()); + jsonResponse = client.getResponse(); + + }catch(IOException ioe) { + ioe.printStackTrace(); + }catch(JSONException jsone) { + jsone.printStackTrace(); + }catch(Exception e) { + e.printStackTrace(); + } + + return jsonResponse; + } + // delete + public JSONObject deleteAE(FoundItem oicDevice) { + + JSONObject jsonResponse = new JSONObject(); + + try { + client.openConnection(); + client.setRequestHeader(this.host, this.deviceId, this.deviceId, oicDevice.getResourceUri(), MemberType.AE, Constants.REQUEST_METHOD_TYPE.DELETE.Value()); + + jsonResponse = client.getResponse(); + + }catch(IOException ioe) { + ioe.printStackTrace(); + }catch(JSONException jsone) { + jsone.printStackTrace(); + }catch(Exception e) { + e.printStackTrace(); + } + + return jsonResponse; + } + */ +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Container.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Container.java index 7c2d3e4..ea14e93 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Container.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Container.java @@ -1,60 +1,60 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import org.eclipse.leshan.server.extension.Constants; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class Container extends Resource{ - - public Container(){ - setShortName("cnt"); - setMni(100); - setMbs(1000 * 1024); - setMia(36000); - resetLbl(); - setExpired(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - body.put("rn", getRn()); - body.put("mni", getMni()); - body.put("mbs", getMbs()); - body.put("mia", getMia()); - - body.put("et", getEt()); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public Container makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import org.eclipse.leshan.server.extension.Constants; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Container extends Resource{ + + public Container(){ + setShortName("cnt"); + setMni(100); + setMbs(1000 * 1024); + setMia(36000); + resetLbl(); + setExpired(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + body.put("rn", getRn()); + body.put("mni", getMni()); + body.put("mbs", getMbs()); + body.put("mia", getMia()); + + body.put("et", getEt()); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public Container makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ContentInstance.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ContentInstance.java index 309e97c..06103fa 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ContentInstance.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ContentInstance.java @@ -1,59 +1,59 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.eclipse.leshan.server.extension.Constants; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class ContentInstance extends Resource{ - public ContentInstance(){ - setShortName("cin"); - //setRn(getShortName()+"_"+getEt()); - setCnf("application/json:1"); - resetLbl(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - - body.put("rn", getRn()); - body.put("cnf", getCnf()); - body.put("con", getCon()); - body.put("et", getEt()); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public ContentInstance makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.eclipse.leshan.server.extension.Constants; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class ContentInstance extends Resource{ + public ContentInstance(){ + setShortName("cin"); + //setRn(getShortName()+"_"+getEt()); + setCnf("application/json:1"); + resetLbl(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + + body.put("rn", getRn()); + body.put("cnf", getCnf()); + body.put("con", getCon()); + body.put("et", getEt()); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public ContentInstance makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/PollingChannel.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/PollingChannel.java index cd6f14f..9779f09 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/PollingChannel.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/PollingChannel.java @@ -1,51 +1,51 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class PollingChannel extends Resource{ - public PollingChannel(){ - setShortName("pch"); - resetLbl(); - setExpired(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - body.put("rn", getRn()); - body.put("et", getEt()); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public PollingChannel makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class PollingChannel extends Resource{ + public PollingChannel(){ + setShortName("pch"); + resetLbl(); + setExpired(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + body.put("rn", getRn()); + body.put("et", getEt()); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public PollingChannel makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Resource.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Resource.java index 672ea2a..01281d4 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Resource.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Resource.java @@ -1,207 +1,207 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; - -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.Util; -import org.json.JSONObject; - -public class Resource { - - // lbl - public void resetLbl(){ - lbl = new ArrayList(); - } - public void addLbl(String txt){ - lbl.add(txt); - } - - // nu - public void resetNu(){ - nu = new ArrayList(); - } - public void addNu(String txt){ - nu.add(txt); - } - - private String strEndTime; - private Date today = new Date(); - public void setExpired(){ - Date endtime = new Date(today.getTime() + (1000L * 60L * 60L * 24L * Constants.DAYS_FOR_EXPIRED)); // after one year - SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd HHmmss"); - String tmpStr = sf.format(endtime); - String[] arrDateItem = tmpStr.split(" "); - strEndTime = arrDateItem[0] + "T" + arrDateItem[1]; - setEt(strEndTime); - } - - public String getNameSpace(Resource res){ - StringBuffer sb = new StringBuffer(); - if(!Util.isNoE(Constants.BASIC_NAME_SPACE)){ - sb.append(Constants.BASIC_NAME_SPACE); - sb.append(":"); - } - sb.append(res.getShortName()); - - return sb.toString(); - } - - - - - - // special variables - private String shortName; - private JSONObject resToJson; - - // variables - private boolean rr; - - private int mbs; - private int mni; - private int mia; - - private String api; - private String apn; - private String cnf; - private String con; - private String et; - private String rn; - private String dcrp; - private String dsp; - - private HashMap enc; - - private ArrayList rss; - - private ArrayList lbl; - private ArrayList nu; - private ArrayList poa; - - - // getter & setter - public boolean isRr() { - return rr; - } - public void setRr(boolean rr) { - this.rr = rr; - } - public String getApi() { - return api; - } - public void setApi(String api) { - this.api = api; - } - public String getApn() { - return apn; - } - public void setApn(String apn) { - this.apn = apn; - } - public String getEt() { - return et; - } - public void setEt(String et) { - this.et = et; - } - public String getRn() { - return rn; - } - public void setRn(String rn) { - this.rn = rn; - } - public ArrayList getPoa() { - return poa; - } - public void setPoa(ArrayList poa) { - this.poa = poa; - } - public ArrayList getLbl() { - return lbl; - } - public void setLbl(ArrayList lbl) { - this.lbl = lbl; - } - public String getShortName() { - return shortName; - } - public void setShortName(String shortName) { - this.shortName = shortName; - } - public JSONObject getResToJson() { - return resToJson; - } - public void setResToJson(JSONObject resToJson) { - this.resToJson = resToJson; - } - public int getMni() { - return mni; - } - public void setMni(int mni) { - this.mni = mni; - } - public int getMbs() { - return mbs; - } - public void setMbs(int mbs) { - this.mbs = mbs; - } - public int getMia() { - return mia; - } - public void setMia(int mia) { - this.mia = mia; - } - public String getCnf() { - return cnf; - } - public void setCnf(String cnf) { - this.cnf = cnf; - } - public String getCon() { - return con; - } - public void setCon(String con) { - this.con = con; - } - public HashMap getEnc() { - return enc; - } - public void setEnc(HashMap enc) { - this.enc = enc; - } - public ArrayList getRss() { - return rss; - } - public void setRss(ArrayList rss) { - this.rss = rss; - } - public ArrayList getNu() { - return nu; - } - public void setNu(ArrayList nu) { - this.nu = nu; - } - public String getDcrp() { - return dcrp; - } - public void setDcrp(String dcrp) { - this.dcrp = dcrp; - } - public String getDsp() { - return dsp; - } - public void setDsp(String dsp) { - this.dsp = dsp; - } - - - - - - - -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; + +import org.eclipse.leshan.server.extension.Constants; +import org.eclipse.leshan.server.extension.Util; +import org.json.JSONObject; + +public class Resource { + + // lbl + public void resetLbl(){ + lbl = new ArrayList(); + } + public void addLbl(String txt){ + lbl.add(txt); + } + + // nu + public void resetNu(){ + nu = new ArrayList(); + } + public void addNu(String txt){ + nu.add(txt); + } + + private String strEndTime; + private Date today = new Date(); + public void setExpired(){ + Date endtime = new Date(today.getTime() + (1000L * 60L * 60L * 24L * Constants.DAYS_FOR_EXPIRED)); // after one year + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd HHmmss"); + String tmpStr = sf.format(endtime); + String[] arrDateItem = tmpStr.split(" "); + strEndTime = arrDateItem[0] + "T" + arrDateItem[1]; + setEt(strEndTime); + } + + public String getNameSpace(Resource res){ + StringBuffer sb = new StringBuffer(); + if(!Util.isNoE(Constants.BASIC_NAME_SPACE)){ + sb.append(Constants.BASIC_NAME_SPACE); + sb.append(":"); + } + sb.append(res.getShortName()); + + return sb.toString(); + } + + + + + + // special variables + private String shortName; + private JSONObject resToJson; + + // variables + private boolean rr; + + private int mbs; + private int mni; + private int mia; + + private String api; + private String apn; + private String cnf; + private String con; + private String et; + private String rn; + private String dcrp; + private String dsp; + + private HashMap enc; + + private ArrayList rss; + + private ArrayList lbl; + private ArrayList nu; + private ArrayList poa; + + + // getter & setter + public boolean isRr() { + return rr; + } + public void setRr(boolean rr) { + this.rr = rr; + } + public String getApi() { + return api; + } + public void setApi(String api) { + this.api = api; + } + public String getApn() { + return apn; + } + public void setApn(String apn) { + this.apn = apn; + } + public String getEt() { + return et; + } + public void setEt(String et) { + this.et = et; + } + public String getRn() { + return rn; + } + public void setRn(String rn) { + this.rn = rn; + } + public ArrayList getPoa() { + return poa; + } + public void setPoa(ArrayList poa) { + this.poa = poa; + } + public ArrayList getLbl() { + return lbl; + } + public void setLbl(ArrayList lbl) { + this.lbl = lbl; + } + public String getShortName() { + return shortName; + } + public void setShortName(String shortName) { + this.shortName = shortName; + } + public JSONObject getResToJson() { + return resToJson; + } + public void setResToJson(JSONObject resToJson) { + this.resToJson = resToJson; + } + public int getMni() { + return mni; + } + public void setMni(int mni) { + this.mni = mni; + } + public int getMbs() { + return mbs; + } + public void setMbs(int mbs) { + this.mbs = mbs; + } + public int getMia() { + return mia; + } + public void setMia(int mia) { + this.mia = mia; + } + public String getCnf() { + return cnf; + } + public void setCnf(String cnf) { + this.cnf = cnf; + } + public String getCon() { + return con; + } + public void setCon(String con) { + this.con = con; + } + public HashMap getEnc() { + return enc; + } + public void setEnc(HashMap enc) { + this.enc = enc; + } + public ArrayList getRss() { + return rss; + } + public void setRss(ArrayList rss) { + this.rss = rss; + } + public ArrayList getNu() { + return nu; + } + public void setNu(ArrayList nu) { + this.nu = nu; + } + public String getDcrp() { + return dcrp; + } + public void setDcrp(String dcrp) { + this.dcrp = dcrp; + } + public String getDsp() { + return dsp; + } + public void setDsp(String dsp) { + this.dsp = dsp; + } + + + + + + + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ResourceHandler.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ResourceHandler.java index bb6b6b5..3446ba3 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ResourceHandler.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/ResourceHandler.java @@ -1,71 +1,71 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -public class ResourceHandler{ - - // singleton - private static ResourceHandler rh; - public static ResourceHandler getInstance(){ - if( rh == null ){ - rh = new ResourceHandler(); - } - return rh; - } - - // getBasicResourceWithSet - public Resource getBasicResourceWithSet(int resourceType){ - Resource result = null; - switch (resourceType) { - - // mixed - case 0: - - break; - - // accessControlPolicy - case 1: - - break; - - // AE - case 2: - AE r = new AE(); - result = r; - break; - - // container - case 3: - - break; - - // contentInstance - case 4: - - break; - - // CSEBase - case 5: - - break; - - // group - case 9: - - break; - - // pollingChannel - case 15: - - break; - - // subscription - case 23: - - break; - - default: - break; - } - - return result; - } -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +public class ResourceHandler{ + + // singleton + private static ResourceHandler rh; + public static ResourceHandler getInstance(){ + if( rh == null ){ + rh = new ResourceHandler(); + } + return rh; + } + + // getBasicResourceWithSet + public Resource getBasicResourceWithSet(int resourceType){ + Resource result = null; + switch (resourceType) { + + // mixed + case 0: + + break; + + // accessControlPolicy + case 1: + + break; + + // AE + case 2: + AE r = new AE(); + result = r; + break; + + // container + case 3: + + break; + + // contentInstance + case 4: + + break; + + // CSEBase + case 5: + + break; + + // group + case 9: + + break; + + // pollingChannel + case 15: + + break; + + // subscription + case 23: + + break; + + default: + break; + } + + return result; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/SemanticDescriptor.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/SemanticDescriptor.java index a11ac21..1bac225 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/SemanticDescriptor.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/SemanticDescriptor.java @@ -1,109 +1,109 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import java.io.IOException; -import java.util.ArrayList; - -import org.eclipse.leshan.server.extension.Constants; -import org.eclipse.leshan.server.extension.Util; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class SemanticDescriptor extends Resource{ - - public SemanticDescriptor(){ - setShortName("smd"); - setRn("semanticDescriptor"); - setApi(Constants.BASIC_AE_NAME); - resetLbl(); - setExpired(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - - body.put("rn", getRn()); - body.put("et", getEt()); - body.put("dcrp", "application/rdf+xml:1"); - body.put("dsp", "PHJkZjpSREYNCiAgICB4bWxuczpwcm90ZWdlPSJodHRwOi8vcHJvdGVnZS5zdGFuZm9yZC5lZHUvcGx1Z2lucy9vd2wvcHJvdGVnZSMiDQogICAgeG1sbnM6dW5pdD0iaHR0cDovL2RhdGEubmFzYS5nb3YvcXVkdC9vd2wvdW5pdCMiDQogICAgeG1sbnM6ZGltPSJodHRwOi8vZGF0YS5uYXNhLmdvdi9xdWR0L293bC9kaW1lbnNpb24jIg0KICAgIHhtbG5zOnNzbj0iaHR0cDovL3B1cmwub2NsYy5vcmcvTkVUL3Nzbngvc3NuIyINCiAgICB4bWxuczpkY3Rlcm1zPSJodHRwOi8vcHVybC5vcmcvZGMvdGVybXMvIg0KICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyINCiAgICB4bWxuczpiPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSMiDQogICAgeG1sbnM6eHNwPSJodHRwOi8vd3d3Lm93bC1vbnRvbG9naWVzLmNvbS8yMDA1LzA4LzA3L3hzcC5vd2wjIg0KICAgIHhtbG5zOmRjYW09Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY2FtLyINCiAgICB4bWxuczpza29zPSJodHRwOi8vd3d3LnczLm9yZy8yMDA0LzAyL3Nrb3MvY29yZSMiDQogICAgeG1sbnM6c3dybD0iaHR0cDovL3d3dy53My5vcmcvMjAwMy8xMS9zd3JsIyINCiAgICB4bWxuczpkdWw9Imh0dHA6Ly93d3cubG9hLWNuci5pdC9vbnRvbG9naWVzL0RVTC5vd2wjIg0KICAgIHhtbG5zOmhlcml0PSJodHRwOi8vaGVyaXQtaW4vaGVyaXQtY3NlLyINCiAgICB4bWxuczpvPSJodHRwOi8vd3d3LmlvdG9hc2lzLm9yZy9vbnRvbG9neS8iDQogICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyINCiAgICB4bWxuczp4c2Q9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIyINCiAgICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiDQogICAgeG1sbnM6c3dybGI9Imh0dHA6Ly93d3cudzMub3JnLzIwMDMvMTEvc3dybGIjIg0KICAgIHhtbG5zOnJkZnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSMiDQogICAgeG1sbnM6cXVkdD0iaHR0cDovL3F1ZHQub3JnLzEuMS9zY2hlbWEvcXVkdCMiDQogICAgeG1sbnM6b2VjYz0iaHR0cDovL3d3dy5vZWdvdi5vcmcvbW9kZWxzL2NvbW1vbi9jYyMiDQogICAgeG1sbnM6cXVhbnRpdHk9Imh0dHA6Ly9kYXRhLm5hc2EuZ292L3F1ZHQvb3dsL3F1YW50aXR5IyINCiAgICB4bWxuczpvd2w9Imh0dHA6Ly93d3cudzMub3JnLzIwMDIvMDcvb3dsIyINCiAgICB4bWxuczpqLjA9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5LyMiDQogICAgeG1sbnM6cDE9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIyINCiAgICB4bWxuczpmb2FmPSJodHRwOi8veG1sbnMuY29tL2ZvYWYvMC4xLyI+DQogIDxvd2w6Q2xhc3MgcmRmOm5vZGVJRD0iQTAiPg0KICAgIDxvd2w6dW5pb25PZj4NCiAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICA8cmRmOnJlc3Q+DQogICAgICAgICAgPHJkZnM6UmVzb3VyY2U+DQogICAgICAgICAgICA8cmRmOnJlc3Q+DQogICAgICAgICAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICAgICAgICAgIDxyZGY6cmVzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNuaWwiLz4NCiAgICAgICAgICAgICAgICA8cmRmOmZpcnN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub2NsYy5vcmcvTkVUL3Nzbngvc3NuI0RlcGxveW1lbnQiLz4NCiAgICAgICAgICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjTGlzdCIvPg0KICAgICAgICAgICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgICAgICAgICA8L3JkZjpyZXN0Pg0KICAgICAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly94bWxucy5jb20vZm9hZi8wLjEvQWdlbnQiLz4NCiAgICAgICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICAgICAgPC9yZGZzOlJlc291cmNlPg0KICAgICAgICA8L3JkZjpyZXN0Pg0KICAgICAgICA8cmRmOmZpcnN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjVGhpbmciLz4NCiAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI0xpc3QiLz4NCiAgICAgIDwvcmRmczpSZXNvdXJjZT4NCiAgICA8L293bDp1bmlvbk9mPg0KICAgIDxyZGZzOnN1YkNsYXNzT2YgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzAxL3JkZi1zY2hlbWEjUmVzb3VyY2UiLz4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpub2RlSUQ9IkEwIi8+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI0NsYXNzIi8+DQogIDwvb3dsOkNsYXNzPg0KICA8b3dsOkNsYXNzIHJkZjpub2RlSUQ9IkExIj4NCiAgICA8b3dsOnVuaW9uT2Y+DQogICAgICA8cmRmczpSZXNvdXJjZT4NCiAgICAgICAgPHJkZjpyZXN0Pg0KICAgICAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICAgICAgPHJkZjpyZXN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI25pbCIvPg0KICAgICAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I0RldmljZSIvPg0KICAgICAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI0xpc3QiLz4NCiAgICAgICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgICAgIDwvcmRmOnJlc3Q+DQogICAgICAgIDxyZGY6Zmlyc3QgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNGdW5jdGlvbmFsaXR5Ii8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgPC9vd2w6dW5pb25PZj4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6bm9kZUlEPSJBMSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICA8L293bDpDbGFzcz4NCiAgPG93bDpDbGFzcyByZGY6bm9kZUlEPSJBMiI+DQogICAgPG93bDp1bmlvbk9mPg0KICAgICAgPHJkZnM6UmVzb3VyY2U+DQogICAgICAgIDxyZGY6cmVzdD4NCiAgICAgICAgICA8cmRmczpSZXNvdXJjZT4NCiAgICAgICAgICAgIDxyZGY6cmVzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNuaWwiLz4NCiAgICAgICAgICAgIDxyZGY6Zmlyc3QgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LmxvYS1jbnIuaXQvb250b2xvZ2llcy9EVUwub3dsI0luZm9ybWF0aW9uT2JqZWN0Ii8+DQogICAgICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjTGlzdCIvPg0KICAgICAgICAgIDwvcmRmczpSZXNvdXJjZT4NCiAgICAgICAgPC9yZGY6cmVzdD4NCiAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I1RoaW5nIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgPC9vd2w6dW5pb25PZj4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6bm9kZUlEPSJBMiIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICA8L293bDpDbGFzcz4NCiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9Imh0dHA6Ly9oZXJpdC1pbi9oZXJpdC1jc2UvbHdtMm1faXBlL3NvdW5kX18tMTAyNC0xMi0zIj4NCiAgICA8ZGM6Y3JlYXRvciByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L2hlcml0Ii8+DQogICAgPGR1bDpoYXNMb2NhdGlvbiByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L2l0YnRfNjA2XzAwMSIvPg0KICAgIDxyZGY6dHlwZSByZGY6bm9kZUlEPSJBMCIvPg0KICAgIDxiOmhhc0NvbW1hbmQgcmRmOnJlc291cmNlPSJodHRwOi8vaGVyaXQtaW4vaGVyaXQtY3NlL2x3bTJtX2lwZS9zb3VuZF9fLTEwMjQtMTItMy93cml0ZSIvPg0KICAgIDxvOm5hbWU+TFdNMk0gQ2xpZW50KHJhc3BiZXJyeSkgLSBidXp6ZXI8L286bmFtZT4NCiAgICA8cmRmOnR5cGU+DQogICAgICA8b3dsOlJlc3RyaWN0aW9uIHJkZjpub2RlSUQ9IkEzIj4NCiAgICAgICAgPG93bDpvblByb3BlcnR5IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjY29uc2lzdHNPZiIvPg0KICAgICAgICA8b3dsOmFsbFZhbHVlc0Zyb20gcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNEZXZpY2UiLz4NCiAgICAgICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgICAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpub2RlSUQ9IkEzIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzAxL3JkZi1zY2hlbWEjQ2xhc3MiLz4NCiAgICAgIDwvb3dsOlJlc3RyaWN0aW9uPg0KICAgIDwvcmRmOnR5cGU+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjRGV2aWNlIi8+DQogICAgPHJkZjp0eXBlPkNscyhAQTIzXzBkOGNjOTUyXzViZWZfNDdmN184OTE0Xzk5YjRmNmE5NTgxYyk8L3JkZjp0eXBlPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDIvMDcvb3dsI1RoaW5nIi8+DQogICAgPG86aGFzRGV2aWNlVHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L0FsYXJtXzkiLz4NCiAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNJbnRlcndvcmtlZERldmljZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6bm9kZUlEPSJBMiIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I1RoaW5nIi8+DQogICAgPHNzbjpvblBsYXRmb3JtIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5pb3RvYXNpcy5vcmcvb250b2xvZ3kvb2FzaXMyLjAiLz4NCiAgICA8cmRmOnR5cGUgcmRmOm5vZGVJRD0iQTEiLz4NCiAgICA8cmRmOnR5cGU+DQogICAgICA8b3dsOlJlc3RyaWN0aW9uIHJkZjpub2RlSUQ9IkE0Ij4NCiAgICAgICAgPG93bDpvblByb3BlcnR5IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjaGFzVGhpbmdSZWxhdGlvbiIvPg0KICAgICAgICA8b3dsOmFsbFZhbHVlc0Zyb20gcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNUaGluZyIvPg0KICAgICAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgICAgIDxyZGZzOnN1YkNsYXNzT2YgcmRmOm5vZGVJRD0iQTQiLz4NCiAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICAgICAgPC9vd2w6UmVzdHJpY3Rpb24+DQogICAgPC9yZGY6dHlwZT4NCiAgICA8cmRmOnR5cGU+Q2xzKEBBMjRfMGQ4Y2M5NTJfNWJlZl80N2Y3Xzg5MTRfOTliNGY2YTk1ODFjKTwvcmRmOnR5cGU+DQogICAgPGI6aGFzRnVuY3Rpb25hbGl0eSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL2hlcml0LWluL2hlcml0LWNzZS9sd20ybV9pcGUvc291bmRfXy0xMDI0LTEyLTMvTnVtYmVyb2ZIdW1hbipBbGFybUZ1bmN0aW9uYWxpdHkiLz4NCiAgPC9yZGY6RGVzY3JpcHRpb24+DQo8L3JkZjpSREY+"); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public SemanticDescriptor makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } - - /* - - // retrieve - public JSONObject retrieveAE(FoundItem oicDevice) { - - JSONObject jsonResponse = new JSONObject(); - - try { - String strOrigin = "OIC-" + this.deviceId; - - client.openConnection(); - client.setRequestHeader(this.host, this.deviceId, this.deviceId, strOrigin, MemberType.AE, Constants.REQUEST_METHOD_TYPE.GET.Value()); - jsonResponse = client.getResponse(); - - }catch(IOException ioe) { - ioe.printStackTrace(); - }catch(JSONException jsone) { - jsone.printStackTrace(); - }catch(Exception e) { - e.printStackTrace(); - } - - return jsonResponse; - } - // delete - public JSONObject deleteAE(FoundItem oicDevice) { - - JSONObject jsonResponse = new JSONObject(); - - try { - client.openConnection(); - client.setRequestHeader(this.host, this.deviceId, this.deviceId, oicDevice.getResourceUri(), MemberType.AE, Constants.REQUEST_METHOD_TYPE.DELETE.Value()); - - jsonResponse = client.getResponse(); - - }catch(IOException ioe) { - ioe.printStackTrace(); - }catch(JSONException jsone) { - jsone.printStackTrace(); - }catch(Exception e) { - e.printStackTrace(); - } - - return jsonResponse; - } - */ -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import java.io.IOException; +import java.util.ArrayList; + +import org.eclipse.leshan.server.extension.Constants; +import org.eclipse.leshan.server.extension.Util; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class SemanticDescriptor extends Resource{ + + public SemanticDescriptor(){ + setShortName("smd"); + setRn("semanticDescriptor"); + setApi(Constants.BASIC_AE_NAME); + resetLbl(); + setExpired(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + + body.put("rn", getRn()); + body.put("et", getEt()); + body.put("dcrp", "application/rdf+xml:1"); + body.put("dsp", "PHJkZjpSREYNCiAgICB4bWxuczpwcm90ZWdlPSJodHRwOi8vcHJvdGVnZS5zdGFuZm9yZC5lZHUvcGx1Z2lucy9vd2wvcHJvdGVnZSMiDQogICAgeG1sbnM6dW5pdD0iaHR0cDovL2RhdGEubmFzYS5nb3YvcXVkdC9vd2wvdW5pdCMiDQogICAgeG1sbnM6ZGltPSJodHRwOi8vZGF0YS5uYXNhLmdvdi9xdWR0L293bC9kaW1lbnNpb24jIg0KICAgIHhtbG5zOnNzbj0iaHR0cDovL3B1cmwub2NsYy5vcmcvTkVUL3Nzbngvc3NuIyINCiAgICB4bWxuczpkY3Rlcm1zPSJodHRwOi8vcHVybC5vcmcvZGMvdGVybXMvIg0KICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyINCiAgICB4bWxuczpiPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSMiDQogICAgeG1sbnM6eHNwPSJodHRwOi8vd3d3Lm93bC1vbnRvbG9naWVzLmNvbS8yMDA1LzA4LzA3L3hzcC5vd2wjIg0KICAgIHhtbG5zOmRjYW09Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY2FtLyINCiAgICB4bWxuczpza29zPSJodHRwOi8vd3d3LnczLm9yZy8yMDA0LzAyL3Nrb3MvY29yZSMiDQogICAgeG1sbnM6c3dybD0iaHR0cDovL3d3dy53My5vcmcvMjAwMy8xMS9zd3JsIyINCiAgICB4bWxuczpkdWw9Imh0dHA6Ly93d3cubG9hLWNuci5pdC9vbnRvbG9naWVzL0RVTC5vd2wjIg0KICAgIHhtbG5zOmhlcml0PSJodHRwOi8vaGVyaXQtaW4vaGVyaXQtY3NlLyINCiAgICB4bWxuczpvPSJodHRwOi8vd3d3LmlvdG9hc2lzLm9yZy9vbnRvbG9neS8iDQogICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyINCiAgICB4bWxuczp4c2Q9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIyINCiAgICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiDQogICAgeG1sbnM6c3dybGI9Imh0dHA6Ly93d3cudzMub3JnLzIwMDMvMTEvc3dybGIjIg0KICAgIHhtbG5zOnJkZnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSMiDQogICAgeG1sbnM6cXVkdD0iaHR0cDovL3F1ZHQub3JnLzEuMS9zY2hlbWEvcXVkdCMiDQogICAgeG1sbnM6b2VjYz0iaHR0cDovL3d3dy5vZWdvdi5vcmcvbW9kZWxzL2NvbW1vbi9jYyMiDQogICAgeG1sbnM6cXVhbnRpdHk9Imh0dHA6Ly9kYXRhLm5hc2EuZ292L3F1ZHQvb3dsL3F1YW50aXR5IyINCiAgICB4bWxuczpvd2w9Imh0dHA6Ly93d3cudzMub3JnLzIwMDIvMDcvb3dsIyINCiAgICB4bWxuczpqLjA9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5LyMiDQogICAgeG1sbnM6cDE9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIyINCiAgICB4bWxuczpmb2FmPSJodHRwOi8veG1sbnMuY29tL2ZvYWYvMC4xLyI+DQogIDxvd2w6Q2xhc3MgcmRmOm5vZGVJRD0iQTAiPg0KICAgIDxvd2w6dW5pb25PZj4NCiAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICA8cmRmOnJlc3Q+DQogICAgICAgICAgPHJkZnM6UmVzb3VyY2U+DQogICAgICAgICAgICA8cmRmOnJlc3Q+DQogICAgICAgICAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICAgICAgICAgIDxyZGY6cmVzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNuaWwiLz4NCiAgICAgICAgICAgICAgICA8cmRmOmZpcnN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub2NsYy5vcmcvTkVUL3Nzbngvc3NuI0RlcGxveW1lbnQiLz4NCiAgICAgICAgICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjTGlzdCIvPg0KICAgICAgICAgICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgICAgICAgICA8L3JkZjpyZXN0Pg0KICAgICAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly94bWxucy5jb20vZm9hZi8wLjEvQWdlbnQiLz4NCiAgICAgICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICAgICAgPC9yZGZzOlJlc291cmNlPg0KICAgICAgICA8L3JkZjpyZXN0Pg0KICAgICAgICA8cmRmOmZpcnN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjVGhpbmciLz4NCiAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI0xpc3QiLz4NCiAgICAgIDwvcmRmczpSZXNvdXJjZT4NCiAgICA8L293bDp1bmlvbk9mPg0KICAgIDxyZGZzOnN1YkNsYXNzT2YgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzAxL3JkZi1zY2hlbWEjUmVzb3VyY2UiLz4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpub2RlSUQ9IkEwIi8+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI0NsYXNzIi8+DQogIDwvb3dsOkNsYXNzPg0KICA8b3dsOkNsYXNzIHJkZjpub2RlSUQ9IkExIj4NCiAgICA8b3dsOnVuaW9uT2Y+DQogICAgICA8cmRmczpSZXNvdXJjZT4NCiAgICAgICAgPHJkZjpyZXN0Pg0KICAgICAgICAgIDxyZGZzOlJlc291cmNlPg0KICAgICAgICAgICAgPHJkZjpyZXN0IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI25pbCIvPg0KICAgICAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I0RldmljZSIvPg0KICAgICAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI0xpc3QiLz4NCiAgICAgICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgICAgIDwvcmRmOnJlc3Q+DQogICAgICAgIDxyZGY6Zmlyc3QgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNGdW5jdGlvbmFsaXR5Ii8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgPC9vd2w6dW5pb25PZj4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6bm9kZUlEPSJBMSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICA8L293bDpDbGFzcz4NCiAgPG93bDpDbGFzcyByZGY6bm9kZUlEPSJBMiI+DQogICAgPG93bDp1bmlvbk9mPg0KICAgICAgPHJkZnM6UmVzb3VyY2U+DQogICAgICAgIDxyZGY6cmVzdD4NCiAgICAgICAgICA8cmRmczpSZXNvdXJjZT4NCiAgICAgICAgICAgIDxyZGY6cmVzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNuaWwiLz4NCiAgICAgICAgICAgIDxyZGY6Zmlyc3QgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LmxvYS1jbnIuaXQvb250b2xvZ2llcy9EVUwub3dsI0luZm9ybWF0aW9uT2JqZWN0Ii8+DQogICAgICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjTGlzdCIvPg0KICAgICAgICAgIDwvcmRmczpSZXNvdXJjZT4NCiAgICAgICAgPC9yZGY6cmVzdD4NCiAgICAgICAgPHJkZjpmaXJzdCByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I1RoaW5nIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyNMaXN0Ii8+DQogICAgICA8L3JkZnM6UmVzb3VyY2U+DQogICAgPC9vd2w6dW5pb25PZj4NCiAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6bm9kZUlEPSJBMiIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICA8L293bDpDbGFzcz4NCiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9Imh0dHA6Ly9oZXJpdC1pbi9oZXJpdC1jc2UvbHdtMm1faXBlL3NvdW5kX18tMTAyNC0xMi0zIj4NCiAgICA8ZGM6Y3JlYXRvciByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L2hlcml0Ii8+DQogICAgPGR1bDpoYXNMb2NhdGlvbiByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L2l0YnRfNjA2XzAwMSIvPg0KICAgIDxyZGY6dHlwZSByZGY6bm9kZUlEPSJBMCIvPg0KICAgIDxiOmhhc0NvbW1hbmQgcmRmOnJlc291cmNlPSJodHRwOi8vaGVyaXQtaW4vaGVyaXQtY3NlL2x3bTJtX2lwZS9zb3VuZF9fLTEwMjQtMTItMy93cml0ZSIvPg0KICAgIDxvOm5hbWU+TFdNMk0gQ2xpZW50KHJhc3BiZXJyeSkgLSBidXp6ZXI8L286bmFtZT4NCiAgICA8cmRmOnR5cGU+DQogICAgICA8b3dsOlJlc3RyaWN0aW9uIHJkZjpub2RlSUQ9IkEzIj4NCiAgICAgICAgPG93bDpvblByb3BlcnR5IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjY29uc2lzdHNPZiIvPg0KICAgICAgICA8b3dsOmFsbFZhbHVlc0Zyb20gcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNEZXZpY2UiLz4NCiAgICAgICAgPHJkZnM6c3ViQ2xhc3NPZiByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgICAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpub2RlSUQ9IkEzIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgICAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzAxL3JkZi1zY2hlbWEjQ2xhc3MiLz4NCiAgICAgIDwvb3dsOlJlc3RyaWN0aW9uPg0KICAgIDwvcmRmOnR5cGU+DQogICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjRGV2aWNlIi8+DQogICAgPHJkZjp0eXBlPkNscyhAQTIzXzBkOGNjOTUyXzViZWZfNDdmN184OTE0Xzk5YjRmNmE5NTgxYyk8L3JkZjp0eXBlPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDIvMDcvb3dsI1RoaW5nIi8+DQogICAgPG86aGFzRGV2aWNlVHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL29udG9sb2d5L0FsYXJtXzkiLz4NCiAgICA8cmRmOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNJbnRlcndvcmtlZERldmljZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6bm9kZUlEPSJBMiIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNSZXNvdXJjZSIvPg0KICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cub25lbTJtLm9yZy9vbnRvbG9neS9CYXNlX09udG9sb2d5I1RoaW5nIi8+DQogICAgPHNzbjpvblBsYXRmb3JtIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5pb3RvYXNpcy5vcmcvb250b2xvZ3kvb2FzaXMyLjAiLz4NCiAgICA8cmRmOnR5cGUgcmRmOm5vZGVJRD0iQTEiLz4NCiAgICA8cmRmOnR5cGU+DQogICAgICA8b3dsOlJlc3RyaWN0aW9uIHJkZjpub2RlSUQ9IkE0Ij4NCiAgICAgICAgPG93bDpvblByb3BlcnR5IHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy5vbmVtMm0ub3JnL29udG9sb2d5L0Jhc2VfT250b2xvZ3kjaGFzVGhpbmdSZWxhdGlvbiIvPg0KICAgICAgICA8b3dsOmFsbFZhbHVlc0Zyb20gcmRmOnJlc291cmNlPSJodHRwOi8vd3d3Lm9uZW0ybS5vcmcvb250b2xvZ3kvQmFzZV9PbnRvbG9neSNUaGluZyIvPg0KICAgICAgICA8cmRmczpzdWJDbGFzc09mIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgICAgIDxyZGZzOnN1YkNsYXNzT2YgcmRmOm5vZGVJRD0iQTQiLz4NCiAgICAgICAgPHJkZjp0eXBlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI1Jlc291cmNlIi8+DQogICAgICAgIDxyZGY6dHlwZSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDEvcmRmLXNjaGVtYSNDbGFzcyIvPg0KICAgICAgPC9vd2w6UmVzdHJpY3Rpb24+DQogICAgPC9yZGY6dHlwZT4NCiAgICA8cmRmOnR5cGU+Q2xzKEBBMjRfMGQ4Y2M5NTJfNWJlZl80N2Y3Xzg5MTRfOTliNGY2YTk1ODFjKTwvcmRmOnR5cGU+DQogICAgPGI6aGFzRnVuY3Rpb25hbGl0eSByZGY6cmVzb3VyY2U9Imh0dHA6Ly93d3cuaW90b2FzaXMub3JnL2hlcml0LWluL2hlcml0LWNzZS9sd20ybV9pcGUvc291bmRfXy0xMDI0LTEyLTMvTnVtYmVyb2ZIdW1hbipBbGFybUZ1bmN0aW9uYWxpdHkiLz4NCiAgPC9yZGY6RGVzY3JpcHRpb24+DQo8L3JkZjpSREY+"); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public SemanticDescriptor makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } + + /* + + // retrieve + public JSONObject retrieveAE(FoundItem oicDevice) { + + JSONObject jsonResponse = new JSONObject(); + + try { + String strOrigin = "OIC-" + this.deviceId; + + client.openConnection(); + client.setRequestHeader(this.host, this.deviceId, this.deviceId, strOrigin, MemberType.AE, Constants.REQUEST_METHOD_TYPE.GET.Value()); + jsonResponse = client.getResponse(); + + }catch(IOException ioe) { + ioe.printStackTrace(); + }catch(JSONException jsone) { + jsone.printStackTrace(); + }catch(Exception e) { + e.printStackTrace(); + } + + return jsonResponse; + } + // delete + public JSONObject deleteAE(FoundItem oicDevice) { + + JSONObject jsonResponse = new JSONObject(); + + try { + client.openConnection(); + client.setRequestHeader(this.host, this.deviceId, this.deviceId, oicDevice.getResourceUri(), MemberType.AE, Constants.REQUEST_METHOD_TYPE.DELETE.Value()); + + jsonResponse = client.getResponse(); + + }catch(IOException ioe) { + ioe.printStackTrace(); + }catch(JSONException jsone) { + jsone.printStackTrace(); + }catch(Exception e) { + e.printStackTrace(); + } + + return jsonResponse; + } + */ +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Subscription.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Subscription.java index 89cdbb0..74171d1 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Subscription.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/extension/onem2m/resources/Subscription.java @@ -1,60 +1,60 @@ -package org.eclipse.leshan.server.extension.onem2m.resources; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -public class Subscription extends Resource { - public Subscription(){ - setShortName("sub"); - resetLbl(); - resetNu(); - setExpired(); - } - - // for create - public JSONObject setForCreate() { - - JSONObject body_wrap = new JSONObject(); - JSONObject body = new JSONObject(); - JSONArray lbl = new JSONArray(); - JSONArray nu = new JSONArray(); - - try { - if( getLbl() != null ){ - for(String label : getLbl()) { - lbl.put(label); - } - body.put("lbl", lbl); - } - - if( getNu() != null ){ - for(String url : getNu()) { - nu.put(url); - } - body.put("nu", nu); - } - body.put("rn", getRn()); - body.put("et", getEt()); - - body_wrap.put(getNameSpace(this),body); - - } catch(JSONException jsone) { - jsone.printStackTrace(); - } catch(Exception e) { - e.printStackTrace(); - } - - return body_wrap; - } - - public Subscription makes(){ - setResToJson(setForCreate()); - return this; - } - - public JSONObject getJSON(){ - makes(); - return getResToJson(); - } -} +package org.eclipse.leshan.server.extension.onem2m.resources; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Subscription extends Resource { + public Subscription(){ + setShortName("sub"); + resetLbl(); + resetNu(); + setExpired(); + } + + // for create + public JSONObject setForCreate() { + + JSONObject body_wrap = new JSONObject(); + JSONObject body = new JSONObject(); + JSONArray lbl = new JSONArray(); + JSONArray nu = new JSONArray(); + + try { + if( getLbl() != null ){ + for(String label : getLbl()) { + lbl.put(label); + } + body.put("lbl", lbl); + } + + if( getNu() != null ){ + for(String url : getNu()) { + nu.put(url); + } + body.put("nu", nu); + } + body.put("rn", getRn()); + body.put("et", getEt()); + + body_wrap.put(getNameSpace(this),body); + + } catch(JSONException jsone) { + jsone.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + + return body_wrap; + } + + public Subscription makes(){ + setResToJson(setForCreate()); + return this; + } + + public JSONObject getJSON(){ + makes(); + return getResToJson(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/BootstrapSessionManagerImpl.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/BootstrapSessionManagerImpl.java index 1959c64..e2f4667 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/BootstrapSessionManagerImpl.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/BootstrapSessionManagerImpl.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import java.util.List; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.server.bootstrap.BootstrapSession; -import org.eclipse.leshan.server.bootstrap.BootstrapSessionManager; -import org.eclipse.leshan.server.security.BootstrapSecurityStore; -import org.eclipse.leshan.server.security.SecurityCheck; -import org.eclipse.leshan.server.security.SecurityInfo; - -/** - * Implementation of a session manager. - * - * Starting a session only checks credentials from BootstrapSecurityStore. - * - * Nothing specific is done on session's end. - * - */ -public class BootstrapSessionManagerImpl implements BootstrapSessionManager { - - private BootstrapSecurityStore bsSecurityStore; - - public BootstrapSessionManagerImpl(BootstrapSecurityStore bsSecurityStore) { - this.bsSecurityStore = bsSecurityStore; - } - - @Override - public BootstrapSession begin(String endpoint, Identity clientIdentity) { - List securityInfos = bsSecurityStore.getAllByEndpoint(endpoint); - boolean authorized = SecurityCheck.checkSecurityInfos(endpoint, clientIdentity, securityInfos); - if (authorized) { - return BootstrapSession.authorized(endpoint, clientIdentity); - } else { - return BootstrapSession.unauthorized(); - } - } - - @Override - public void end(BootstrapSession bsSession) { - } - - @Override - public void failed(BootstrapSession bsSession, DownlinkRequest request, Exception e) { - } - -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import java.util.List; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.server.bootstrap.BootstrapSession; +import org.eclipse.leshan.server.bootstrap.BootstrapSessionManager; +import org.eclipse.leshan.server.security.BootstrapSecurityStore; +import org.eclipse.leshan.server.security.SecurityCheck; +import org.eclipse.leshan.server.security.SecurityInfo; + +/** + * Implementation of a session manager. + * + * Starting a session only checks credentials from BootstrapSecurityStore. + * + * Nothing specific is done on session's end. + * + */ +public class BootstrapSessionManagerImpl implements BootstrapSessionManager { + + private BootstrapSecurityStore bsSecurityStore; + + public BootstrapSessionManagerImpl(BootstrapSecurityStore bsSecurityStore) { + this.bsSecurityStore = bsSecurityStore; + } + + @Override + public BootstrapSession begin(String endpoint, Identity clientIdentity) { + List securityInfos = bsSecurityStore.getAllByEndpoint(endpoint); + boolean authorized = SecurityCheck.checkSecurityInfos(endpoint, clientIdentity, securityInfos); + if (authorized) { + return BootstrapSession.authorized(endpoint, clientIdentity); + } else { + return BootstrapSession.unauthorized(); + } + } + + @Override + public void end(BootstrapSession bsSession) { + } + + @Override + public void failed(BootstrapSession bsSession, DownlinkRequest request, Exception e) { + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/ClientRegistryImpl.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/ClientRegistryImpl.java index 36ee6a5..792c176 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/ClientRegistryImpl.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/ClientRegistryImpl.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.eclipse.leshan.server.Startable; -import org.eclipse.leshan.server.Stoppable; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.client.ClientRegistryListener; -import org.eclipse.leshan.server.client.ClientUpdate; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * In memory client registry - */ -public class ClientRegistryImpl implements ClientRegistry, Startable, Stoppable { - - private static final Logger LOG = LoggerFactory.getLogger(ClientRegistryImpl.class); - - private final Map clientsByEp = new ConcurrentHashMap<>(); - - private final List listeners = new CopyOnWriteArrayList<>(); - - @Override - public void addListener(ClientRegistryListener listener) { - listeners.add(listener); - } - - @Override - public void removeListener(ClientRegistryListener listener) { - listeners.remove(listener); - } - - @Override - public Collection allClients() { - return Collections.unmodifiableCollection(clientsByEp.values()); - } - - @Override - public Client get(String endpoint) { - return clientsByEp.get(endpoint); - } - - @Override - public boolean registerClient(Client client) { - Validate.notNull(client); - - LOG.debug("Registering new client: {}", client); - - Client previous = clientsByEp.put(client.getEndpoint(), client); - if (previous != null) { - for (ClientRegistryListener l : listeners) { - l.unregistered(previous); - } - } - for (ClientRegistryListener l : listeners) { - l.registered(client); - } - - return true; - } - - @Override - public Client updateClient(ClientUpdate update) { - Validate.notNull(update); - - LOG.debug("Updating registration for client: {}", update); - Client client = findByRegistrationId(update.getRegistrationId()); - if (client == null) { - return null; - } else { - Client clientUpdated = update.updateClient(client); - clientsByEp.put(clientUpdated.getEndpoint(), clientUpdated); - - // notify listener - for (ClientRegistryListener l : listeners) { - l.updated(update, clientUpdated); - } - return clientUpdated; - } - } - - @Override - public Client deregisterClient(String registrationId) { - Validate.notNull(registrationId); - - LOG.debug("Deregistering client with registrationId: {}", registrationId); - - Client toBeUnregistered = findByRegistrationId(registrationId); - if (toBeUnregistered == null) { - return null; - } else { - Client unregistered = clientsByEp.remove(toBeUnregistered.getEndpoint()); - for (ClientRegistryListener l : listeners) { - l.unregistered(unregistered); - } - LOG.debug("Deregistered client: {}", unregistered); - return unregistered; - } - } - - @Override - public Client findByRegistrationId(String id) { - Client result = null; - if (id != null) { - for (Client client : clientsByEp.values()) { - if (id.equals(client.getRegistrationId())) { - result = client; - break; - } - } - } - return result; - } - - /** - * start the registration manager, will start regular cleanup of dead registrations. - */ - @Override - public void start() { - // every 2 seconds clean the registration list - // TODO re-consider clean-up interval: wouldn't 5 minutes do as well? - schedExecutor.scheduleAtFixedRate(new Cleaner(), 2, 2, TimeUnit.SECONDS); - } - - /** - * Stop the underlying cleanup of the registrations. - */ - @Override - public void stop() { - schedExecutor.shutdownNow(); - try { - schedExecutor.awaitTermination(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - LOG.warn("Clean up registration thread was interrupted.", e); - } - } - - private final ScheduledExecutorService schedExecutor = Executors.newScheduledThreadPool(1); - - private class Cleaner implements Runnable { - - @Override - public void run() { - for (Client client : clientsByEp.values()) { - synchronized (client) { - if (!client.isAlive()) { - // force de-registration - deregisterClient(client.getRegistrationId()); - } - } - } - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.eclipse.leshan.server.Startable; +import org.eclipse.leshan.server.Stoppable; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.client.ClientRegistryListener; +import org.eclipse.leshan.server.client.ClientUpdate; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * In memory client registry + */ +public class ClientRegistryImpl implements ClientRegistry, Startable, Stoppable { + + private static final Logger LOG = LoggerFactory.getLogger(ClientRegistryImpl.class); + + private final Map clientsByEp = new ConcurrentHashMap<>(); + + private final List listeners = new CopyOnWriteArrayList<>(); + + @Override + public void addListener(ClientRegistryListener listener) { + listeners.add(listener); + } + + @Override + public void removeListener(ClientRegistryListener listener) { + listeners.remove(listener); + } + + @Override + public Collection allClients() { + return Collections.unmodifiableCollection(clientsByEp.values()); + } + + @Override + public Client get(String endpoint) { + return clientsByEp.get(endpoint); + } + + @Override + public boolean registerClient(Client client) { + Validate.notNull(client); + + LOG.debug("Registering new client: {}", client); + + Client previous = clientsByEp.put(client.getEndpoint(), client); + if (previous != null) { + for (ClientRegistryListener l : listeners) { + l.unregistered(previous); + } + } + for (ClientRegistryListener l : listeners) { + l.registered(client); + } + + return true; + } + + @Override + public Client updateClient(ClientUpdate update) { + Validate.notNull(update); + + LOG.debug("Updating registration for client: {}", update); + Client client = findByRegistrationId(update.getRegistrationId()); + if (client == null) { + return null; + } else { + Client clientUpdated = update.updateClient(client); + clientsByEp.put(clientUpdated.getEndpoint(), clientUpdated); + + // notify listener + for (ClientRegistryListener l : listeners) { + l.updated(update, clientUpdated); + } + return clientUpdated; + } + } + + @Override + public Client deregisterClient(String registrationId) { + Validate.notNull(registrationId); + + LOG.debug("Deregistering client with registrationId: {}", registrationId); + + Client toBeUnregistered = findByRegistrationId(registrationId); + if (toBeUnregistered == null) { + return null; + } else { + Client unregistered = clientsByEp.remove(toBeUnregistered.getEndpoint()); + for (ClientRegistryListener l : listeners) { + l.unregistered(unregistered); + } + LOG.debug("Deregistered client: {}", unregistered); + return unregistered; + } + } + + @Override + public Client findByRegistrationId(String id) { + Client result = null; + if (id != null) { + for (Client client : clientsByEp.values()) { + if (id.equals(client.getRegistrationId())) { + result = client; + break; + } + } + } + return result; + } + + /** + * start the registration manager, will start regular cleanup of dead registrations. + */ + @Override + public void start() { + // every 2 seconds clean the registration list + // TODO re-consider clean-up interval: wouldn't 5 minutes do as well? + schedExecutor.scheduleAtFixedRate(new Cleaner(), 2, 2, TimeUnit.SECONDS); + } + + /** + * Stop the underlying cleanup of the registrations. + */ + @Override + public void stop() { + schedExecutor.shutdownNow(); + try { + schedExecutor.awaitTermination(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOG.warn("Clean up registration thread was interrupted.", e); + } + } + + private final ScheduledExecutorService schedExecutor = Executors.newScheduledThreadPool(1); + + private class Cleaner implements Runnable { + + @Override + public void run() { + for (Client client : clientsByEp.values()) { + synchronized (client) { + if (!client.isAlive()) { + // force de-registration + deregisterClient(client.getRegistrationId()); + } + } + } + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/LwM2mRequestSenderImpl.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/LwM2mRequestSenderImpl.java index c221734..a710ec1 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/LwM2mRequestSenderImpl.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/LwM2mRequestSenderImpl.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Bosch Software Innovations GmbH - * - initial implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.server.Stoppable; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.queue.impl.QueuedRequestSender; -import org.eclipse.leshan.server.request.LwM2mRequestSender; -import org.eclipse.leshan.server.response.ResponseListener; - -/** - * a wrapper delegating the actual invocation to either {@link QueuedRequestSender} or a default - * {@link LwM2mRequestSender} depending upon whether the client has connected in Queue mode or not. - */ -public class LwM2mRequestSenderImpl implements LwM2mRequestSender, Stoppable { - - private final LwM2mRequestSender defaultRequestSender; - private final LwM2mRequestSender queuedRequestSender; - - /** - * default constructor. - * - * @param defaultRequestSender used to send messages to a LWM2M Client using a non-queue mode. - * @param queuedRequestSender used to send messages to a LWM2M Client using a queue-mode. - */ - public LwM2mRequestSenderImpl(LwM2mRequestSender defaultRequestSender, LwM2mRequestSender queuedRequestSender) { - this.defaultRequestSender = defaultRequestSender; - this.queuedRequestSender = queuedRequestSender; - } - - @SuppressWarnings("deprecation") - @Override - public T send(Client destination, DownlinkRequest request, Long timeout) - throws InterruptedException { - return defaultRequestSender.send(destination, request, timeout); - } - - @SuppressWarnings("deprecation") - @Override - public void send(Client destination, DownlinkRequest request, - ResponseCallback responseCallback, ErrorCallback errorCallback) { - if (destination.usesQueueMode()) { - queuedRequestSender.send(destination, request, responseCallback, errorCallback); - } else { - defaultRequestSender.send(destination, request, responseCallback, errorCallback); - } - } - - @Override - public void send(Client destination, String requestTicket, DownlinkRequest request) { - if (destination.usesQueueMode()) { - queuedRequestSender.send(destination, requestTicket, request); - } else { - defaultRequestSender.send(destination, requestTicket, request); - } - } - - @Override - public void addResponseListener(ResponseListener listener) { - queuedRequestSender.addResponseListener(listener); - defaultRequestSender.addResponseListener(listener); - } - - @Override - public void removeResponseListener(ResponseListener listener) { - queuedRequestSender.removeResponseListener(listener); - defaultRequestSender.removeResponseListener(listener); - } - - @Override - public void stop() { - if (queuedRequestSender instanceof Stoppable) { - ((Stoppable) queuedRequestSender).stop(); - } - if (defaultRequestSender instanceof Stoppable) { - ((Stoppable) defaultRequestSender).stop(); - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Bosch Software Innovations GmbH + * - initial implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.eclipse.leshan.server.Stoppable; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.queue.impl.QueuedRequestSender; +import org.eclipse.leshan.server.request.LwM2mRequestSender; +import org.eclipse.leshan.server.response.ResponseListener; + +/** + * a wrapper delegating the actual invocation to either {@link QueuedRequestSender} or a default + * {@link LwM2mRequestSender} depending upon whether the client has connected in Queue mode or not. + */ +public class LwM2mRequestSenderImpl implements LwM2mRequestSender, Stoppable { + + private final LwM2mRequestSender defaultRequestSender; + private final LwM2mRequestSender queuedRequestSender; + + /** + * default constructor. + * + * @param defaultRequestSender used to send messages to a LWM2M Client using a non-queue mode. + * @param queuedRequestSender used to send messages to a LWM2M Client using a queue-mode. + */ + public LwM2mRequestSenderImpl(LwM2mRequestSender defaultRequestSender, LwM2mRequestSender queuedRequestSender) { + this.defaultRequestSender = defaultRequestSender; + this.queuedRequestSender = queuedRequestSender; + } + + @SuppressWarnings("deprecation") + @Override + public T send(Client destination, DownlinkRequest request, Long timeout) + throws InterruptedException { + return defaultRequestSender.send(destination, request, timeout); + } + + @SuppressWarnings("deprecation") + @Override + public void send(Client destination, DownlinkRequest request, + ResponseCallback responseCallback, ErrorCallback errorCallback) { + if (destination.usesQueueMode()) { + queuedRequestSender.send(destination, request, responseCallback, errorCallback); + } else { + defaultRequestSender.send(destination, request, responseCallback, errorCallback); + } + } + + @Override + public void send(Client destination, String requestTicket, DownlinkRequest request) { + if (destination.usesQueueMode()) { + queuedRequestSender.send(destination, requestTicket, request); + } else { + defaultRequestSender.send(destination, requestTicket, request); + } + } + + @Override + public void addResponseListener(ResponseListener listener) { + queuedRequestSender.addResponseListener(listener); + defaultRequestSender.addResponseListener(listener); + } + + @Override + public void removeResponseListener(ResponseListener listener) { + queuedRequestSender.removeResponseListener(listener); + defaultRequestSender.removeResponseListener(listener); + } + + @Override + public void stop() { + if (queuedRequestSender instanceof Stoppable) { + ((Stoppable) queuedRequestSender).stop(); + } + if (defaultRequestSender instanceof Stoppable) { + ((Stoppable) defaultRequestSender).stop(); + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/SecurityRegistryImpl.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/SecurityRegistryImpl.java index f314134..65d3235 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/SecurityRegistryImpl.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/SecurityRegistryImpl.java @@ -1,275 +1,275 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.eclipse.leshan.server.security.NonUniqueSecurityInfoException; -import org.eclipse.leshan.server.security.SecurityInfo; -import org.eclipse.leshan.server.security.SecurityRegistry; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * An in-memory security store. - *

- * This implementation serializes the registry content into a file to be able to re-load the security infos when the - * server is restarted. - *

- */ -public class SecurityRegistryImpl implements SecurityRegistry { - - private static final Logger LOG = LoggerFactory.getLogger(SecurityRegistryImpl.class); - - // lock for the two maps - private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); - private final Lock readLock = readWriteLock.readLock(); - private final Lock writeLock = readWriteLock.writeLock(); - - // by client end-point - private Map securityByEp = new HashMap<>(); - - // by PSK identity - private Map securityByIdentity = new HashMap<>(); - - // the name of the file used to persist the registry content - private final String filename; - - private PublicKey serverPublicKey; - - private PrivateKey serverPrivateKey; - - private X509Certificate[] serverX509CertChain; - - private Certificate[] trustedCertificates = null; // TODO retrieve certs from JRE trustStore ? - - // default location for persistence - private static final String DEFAULT_FILE = "data/security.data"; - - public SecurityRegistryImpl() { - this(DEFAULT_FILE, null, null); - } - - /** - * Constructor for RPK - */ - public SecurityRegistryImpl(PrivateKey serverPrivateKey, PublicKey serverPublicKey) { - this(DEFAULT_FILE, serverPrivateKey, serverPublicKey); - } - - /** - * Constructor for X509 certificates - */ - public SecurityRegistryImpl(PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain, - Certificate[] trustedCertificates) { - this(DEFAULT_FILE, serverPrivateKey, serverX509CertChain, trustedCertificates); - } - - /** - * @param file the file path to persist the registry - */ - public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, PublicKey serverPublicKey) { - Validate.notEmpty(file); - - filename = file; - this.serverPrivateKey = serverPrivateKey; - this.serverPublicKey = serverPublicKey; - loadFromFile(); - } - - /** - * @param file the file path to persist the registry - */ - public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain, - Certificate[] trustedCertificates) { - Validate.notEmpty(file); - Validate.notEmpty(serverX509CertChain); - Validate.notEmpty(trustedCertificates); - - filename = file; - this.serverPrivateKey = serverPrivateKey; - this.serverX509CertChain = serverX509CertChain; - // extract the raw public key from the first certificate in the chain - this.serverPublicKey = serverX509CertChain[0].getPublicKey(); - this.trustedCertificates = trustedCertificates; - loadFromFile(); - } - - /** - * {@inheritDoc} - */ - @Override - public SecurityInfo getByEndpoint(String endpoint) { - readLock.lock(); - try { - return securityByEp.get(endpoint); - } finally { - readLock.unlock(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public SecurityInfo getByIdentity(String identity) { - readLock.lock(); - try { - return securityByIdentity.get(identity); - } finally { - readLock.unlock(); - } - } - - @Override - public Collection getAll() { - readLock.lock(); - try { - return Collections.unmodifiableCollection(securityByEp.values()); - } finally { - readLock.unlock(); - } - } - - private SecurityInfo addToRegistry(SecurityInfo info) throws NonUniqueSecurityInfoException { - writeLock.lock(); - try { - String identity = info.getIdentity(); - if (identity != null) { - SecurityInfo infoByIdentity = securityByIdentity.get(info.getIdentity()); - if (infoByIdentity != null && !info.getEndpoint().equals(infoByIdentity.getEndpoint())) { - throw new NonUniqueSecurityInfoException("PSK Identity " + info.getIdentity() + " is already used"); - } - - securityByIdentity.put(info.getIdentity(), info); - } - - SecurityInfo previous = securityByEp.put(info.getEndpoint(), info); - - return previous; - } finally { - writeLock.unlock(); - } - } - - @Override - public SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException { - writeLock.lock(); - try { - SecurityInfo previous = addToRegistry(info); - saveToFile(); - return previous; - } finally { - writeLock.unlock(); - } - } - - @Override - public SecurityInfo remove(String endpoint) { - writeLock.lock(); - try { - SecurityInfo info = securityByEp.get(endpoint); - if (info != null) { - if (info.getIdentity() != null) { - securityByIdentity.remove(info.getIdentity()); - } - securityByEp.remove(endpoint); - - saveToFile(); - } - return info; - } finally { - writeLock.unlock(); - } - } - - protected void loadFromFile() { - File file = new File(filename); - if (!file.exists()) { - return; - } - - try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));) { - SecurityInfo[] infos = (SecurityInfo[]) in.readObject(); - - if (infos != null) { - for (SecurityInfo info : infos) { - addToRegistry(info); - } - if (infos.length > 0) { - LOG.debug("{} security infos loaded", infos.length); - } - } - } catch (NonUniqueSecurityInfoException | IOException | ClassNotFoundException e) { - LOG.error("Could not load security infos from file", e); - } - } - - protected void saveToFile() { - try { - File file = new File(filename); - if (!file.exists()) { - File parent = file.getParentFile(); - if (parent != null) { - parent.mkdirs(); - } - file.createNewFile(); - } - try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));) { - out.writeObject(this.getAll().toArray(new SecurityInfo[0])); - } - } catch (IOException e) { - LOG.error("Could not save security infos to file", e); - } - } - - @Override - public PublicKey getServerPublicKey() { - return serverPublicKey; - } - - @Override - public PrivateKey getServerPrivateKey() { - return serverPrivateKey; - } - - @Override - public X509Certificate[] getServerX509CertChain() { - return serverX509CertChain; - } - - @Override - public Certificate[] getTrustedCertificates() { - return trustedCertificates; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.eclipse.leshan.server.security.NonUniqueSecurityInfoException; +import org.eclipse.leshan.server.security.SecurityInfo; +import org.eclipse.leshan.server.security.SecurityRegistry; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * An in-memory security store. + *

+ * This implementation serializes the registry content into a file to be able to re-load the security infos when the + * server is restarted. + *

+ */ +public class SecurityRegistryImpl implements SecurityRegistry { + + private static final Logger LOG = LoggerFactory.getLogger(SecurityRegistryImpl.class); + + // lock for the two maps + private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + private final Lock readLock = readWriteLock.readLock(); + private final Lock writeLock = readWriteLock.writeLock(); + + // by client end-point + private Map securityByEp = new HashMap<>(); + + // by PSK identity + private Map securityByIdentity = new HashMap<>(); + + // the name of the file used to persist the registry content + private final String filename; + + private PublicKey serverPublicKey; + + private PrivateKey serverPrivateKey; + + private X509Certificate[] serverX509CertChain; + + private Certificate[] trustedCertificates = null; // TODO retrieve certs from JRE trustStore ? + + // default location for persistence + private static final String DEFAULT_FILE = "data/security.data"; + + public SecurityRegistryImpl() { + this(DEFAULT_FILE, null, null); + } + + /** + * Constructor for RPK + */ + public SecurityRegistryImpl(PrivateKey serverPrivateKey, PublicKey serverPublicKey) { + this(DEFAULT_FILE, serverPrivateKey, serverPublicKey); + } + + /** + * Constructor for X509 certificates + */ + public SecurityRegistryImpl(PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain, + Certificate[] trustedCertificates) { + this(DEFAULT_FILE, serverPrivateKey, serverX509CertChain, trustedCertificates); + } + + /** + * @param file the file path to persist the registry + */ + public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, PublicKey serverPublicKey) { + Validate.notEmpty(file); + + filename = file; + this.serverPrivateKey = serverPrivateKey; + this.serverPublicKey = serverPublicKey; + loadFromFile(); + } + + /** + * @param file the file path to persist the registry + */ + public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain, + Certificate[] trustedCertificates) { + Validate.notEmpty(file); + Validate.notEmpty(serverX509CertChain); + Validate.notEmpty(trustedCertificates); + + filename = file; + this.serverPrivateKey = serverPrivateKey; + this.serverX509CertChain = serverX509CertChain; + // extract the raw public key from the first certificate in the chain + this.serverPublicKey = serverX509CertChain[0].getPublicKey(); + this.trustedCertificates = trustedCertificates; + loadFromFile(); + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityInfo getByEndpoint(String endpoint) { + readLock.lock(); + try { + return securityByEp.get(endpoint); + } finally { + readLock.unlock(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityInfo getByIdentity(String identity) { + readLock.lock(); + try { + return securityByIdentity.get(identity); + } finally { + readLock.unlock(); + } + } + + @Override + public Collection getAll() { + readLock.lock(); + try { + return Collections.unmodifiableCollection(securityByEp.values()); + } finally { + readLock.unlock(); + } + } + + private SecurityInfo addToRegistry(SecurityInfo info) throws NonUniqueSecurityInfoException { + writeLock.lock(); + try { + String identity = info.getIdentity(); + if (identity != null) { + SecurityInfo infoByIdentity = securityByIdentity.get(info.getIdentity()); + if (infoByIdentity != null && !info.getEndpoint().equals(infoByIdentity.getEndpoint())) { + throw new NonUniqueSecurityInfoException("PSK Identity " + info.getIdentity() + " is already used"); + } + + securityByIdentity.put(info.getIdentity(), info); + } + + SecurityInfo previous = securityByEp.put(info.getEndpoint(), info); + + return previous; + } finally { + writeLock.unlock(); + } + } + + @Override + public SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException { + writeLock.lock(); + try { + SecurityInfo previous = addToRegistry(info); + saveToFile(); + return previous; + } finally { + writeLock.unlock(); + } + } + + @Override + public SecurityInfo remove(String endpoint) { + writeLock.lock(); + try { + SecurityInfo info = securityByEp.get(endpoint); + if (info != null) { + if (info.getIdentity() != null) { + securityByIdentity.remove(info.getIdentity()); + } + securityByEp.remove(endpoint); + + saveToFile(); + } + return info; + } finally { + writeLock.unlock(); + } + } + + protected void loadFromFile() { + File file = new File(filename); + if (!file.exists()) { + return; + } + + try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));) { + SecurityInfo[] infos = (SecurityInfo[]) in.readObject(); + + if (infos != null) { + for (SecurityInfo info : infos) { + addToRegistry(info); + } + if (infos.length > 0) { + LOG.debug("{} security infos loaded", infos.length); + } + } + } catch (NonUniqueSecurityInfoException | IOException | ClassNotFoundException e) { + LOG.error("Could not load security infos from file", e); + } + } + + protected void saveToFile() { + try { + File file = new File(filename); + if (!file.exists()) { + File parent = file.getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + file.createNewFile(); + } + try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));) { + out.writeObject(this.getAll().toArray(new SecurityInfo[0])); + } + } catch (IOException e) { + LOG.error("Could not save security infos to file", e); + } + } + + @Override + public PublicKey getServerPublicKey() { + return serverPublicKey; + } + + @Override + public PrivateKey getServerPrivateKey() { + return serverPrivateKey; + } + + @Override + public X509Certificate[] getServerX509CertChain() { + return serverX509CertChain; + } + + @Override + public Certificate[] getTrustedCertificates() { + return trustedCertificates; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/LwM2mModelProvider.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/LwM2mModelProvider.java index 714c6d9..f3705f4 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/LwM2mModelProvider.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/LwM2mModelProvider.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.model; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder; -import org.eclipse.leshan.core.node.codec.LwM2mNodeEncoder; -import org.eclipse.leshan.server.client.Client; - -/** - * A LwM2mModelProvider implementation is in charge of returning the description of the LWM2M objects for - * each registered client. - *

- * The description of each object is mainly used by the {@link LwM2mNodeEncoder}/{@link LwM2mNodeDecoder} to - * encode/decode the requests/responses payload. - *

- *

- * A typical use case to implement a custom provider is the need to support several version of the specification. - *

- */ -public interface LwM2mModelProvider { - - /** - * Returns the description of the objects supported by the given client. - * - * @param client the registered client - * @return the list of object descriptions - */ - LwM2mModel getObjectModel(Client client); - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.model; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder; +import org.eclipse.leshan.core.node.codec.LwM2mNodeEncoder; +import org.eclipse.leshan.server.client.Client; + +/** + * A LwM2mModelProvider implementation is in charge of returning the description of the LWM2M objects for + * each registered client. + *

+ * The description of each object is mainly used by the {@link LwM2mNodeEncoder}/{@link LwM2mNodeDecoder} to + * encode/decode the requests/responses payload. + *

+ *

+ * A typical use case to implement a custom provider is the need to support several version of the specification. + *

+ */ +public interface LwM2mModelProvider { + + /** + * Returns the description of the objects supported by the given client. + * + * @param client the registered client + * @return the list of object descriptions + */ + LwM2mModel getObjectModel(Client client); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StandardModelProvider.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StandardModelProvider.java index 9a2a2f7..d46fed8 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StandardModelProvider.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StandardModelProvider.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.model; - -import org.eclipse.leshan.core.model.ObjectLoader; - -/** - * A static model provider which uses the default model embedded in Leshan.
- *
- * The MODELS_FOLDER environment variable can be used to add more model definitions.
- * The MODELS_FOLDER should be set with the folder path where your custom models are available. Currently the Leshan - * JSON format and OMA DDF file format are supported. - */ -public class StandardModelProvider extends StaticModelProvider { - - public StandardModelProvider() { - super(ObjectLoader.loadDefault()); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.model; + +import org.eclipse.leshan.core.model.ObjectLoader; + +/** + * A static model provider which uses the default model embedded in Leshan.
+ *
+ * The MODELS_FOLDER environment variable can be used to add more model definitions.
+ * The MODELS_FOLDER should be set with the folder path where your custom models are available. Currently the Leshan + * JSON format and OMA DDF file format are supported. + */ +public class StandardModelProvider extends StaticModelProvider { + + public StandardModelProvider() { + super(ObjectLoader.loadDefault()); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StaticModelProvider.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StaticModelProvider.java index d5a763f..59f6b34 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StaticModelProvider.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/model/StaticModelProvider.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.model; - -import java.util.Collection; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ObjectModel; -import org.eclipse.leshan.server.client.Client; - -/** - * A LwM2mModelProvider which uses only one model for all registered clients. - */ -public class StaticModelProvider implements LwM2mModelProvider { - private final LwM2mModel model; - - public StaticModelProvider(Collection objects) { - this(new LwM2mModel(objects)); - } - - public StaticModelProvider(LwM2mModel model) { - this.model = model; - } - - @Override - public LwM2mModel getObjectModel(Client client) { - // same model for all clients - return model; - } -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.model; + +import java.util.Collection; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.server.client.Client; + +/** + * A LwM2mModelProvider which uses only one model for all registered clients. + */ +public class StaticModelProvider implements LwM2mModelProvider { + private final LwM2mModel model; + + public StaticModelProvider(Collection objects) { + this(new LwM2mModel(objects)); + } + + public StaticModelProvider(LwM2mModel model) { + this.model = model; + } + + @Override + public LwM2mModel getObjectModel(Client client) { + // same model for all clients + return model; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistry.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistry.java index 9b974c9..20f6023 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistry.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistry.java @@ -1,79 +1,79 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.observation; - -import java.util.Set; - -import org.eclipse.leshan.core.observation.Observation; -import org.eclipse.leshan.server.client.Client; - -/** - * A registry for keeping track of observed resources implemented by LWM2M Clients. - * - */ -public interface ObservationRegistry { - - /** - * Adds an observation of resource(s) to the registry. - * - * @param observation the observation - */ - void addObservation(Observation observation); - - /** - * Cancels all active observations of resource(s) implemented by a particular LWM2M Client. - * - * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of - * the canceled observation. - * - * @param client the LWM2M Client to cancel observations for - * @return the number of canceled observations - */ - int cancelObservations(Client client); - - /** - * Cancels all active observations for the given resource of a given client. - * - * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of - * the canceled observation. - * - * @param client the LWM2M Client to cancel observation for - * @param resourcepath resource to cancel observation for - * @return the number of canceled observations - */ - int cancelObservations(Client client, String resourcepath); - - /** - * Cancels an observation. - * - * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of - * the canceled observation. - * - * @param observation the observation to cancel. - */ - void cancelObservation(Observation observation); - - /** - * Get all running observation for a given client - * - * @return an unmodifiable set of observation - */ - Set getObservations(Client client); - - void addListener(ObservationRegistryListener listener); - - void removeListener(ObservationRegistryListener listener); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.observation; + +import java.util.Set; + +import org.eclipse.leshan.core.observation.Observation; +import org.eclipse.leshan.server.client.Client; + +/** + * A registry for keeping track of observed resources implemented by LWM2M Clients. + * + */ +public interface ObservationRegistry { + + /** + * Adds an observation of resource(s) to the registry. + * + * @param observation the observation + */ + void addObservation(Observation observation); + + /** + * Cancels all active observations of resource(s) implemented by a particular LWM2M Client. + * + * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of + * the canceled observation. + * + * @param client the LWM2M Client to cancel observations for + * @return the number of canceled observations + */ + int cancelObservations(Client client); + + /** + * Cancels all active observations for the given resource of a given client. + * + * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of + * the canceled observation. + * + * @param client the LWM2M Client to cancel observation for + * @param resourcepath resource to cancel observation for + * @return the number of canceled observations + */ + int cancelObservations(Client client, String resourcepath); + + /** + * Cancels an observation. + * + * As a consequence the LWM2M Client will stop sending notifications about updated values of resources in scope of + * the canceled observation. + * + * @param observation the observation to cancel. + */ + void cancelObservation(Observation observation); + + /** + * Get all running observation for a given client + * + * @return an unmodifiable set of observation + */ + Set getObservations(Client client); + + void addListener(ObservationRegistryListener listener); + + void removeListener(ObservationRegistryListener listener); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistryListener.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistryListener.java index 20a680c..f3bb49e 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistryListener.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/observation/ObservationRegistryListener.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.observation; - -import java.util.List; - -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.observation.Observation; - -public interface ObservationRegistryListener { - void newObservation(Observation observation); - - void cancelled(Observation observation); - - /** - * Called on new notification. - * - * @param observation the observation for which new data are received - * @param mostRecentValue the most recent value - * @param timestampedValues the list of time-stamped value (could be null) - */ - void newValue(Observation observation, LwM2mNode mostRecentValue, List timestampedValues); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.observation; + +import java.util.List; + +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.observation.Observation; + +public interface ObservationRegistryListener { + void newObservation(Observation observation); + + void cancelled(Observation observation); + + /** + * Called on new notification. + * + * @param observation the observation for which new data are received + * @param mostRecentValue the most recent value + * @param timestampedValues the list of time-stamped value (could be null) + */ + void newValue(Observation observation, LwM2mNode mostRecentValue, List timestampedValues); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/ClientState.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/ClientState.java index b3a510c..a50d82e 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/ClientState.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/ClientState.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue; - -/** - * Possible states of a LWM2M client connected to a Server. - * - */ -public enum ClientState { - /** Client can be reached from server. */ - REACHABLE, - /** Client is currently receiving queued messages */ - RECEIVING, - /** Client cannot be reached from server */ - UNREACHABLE -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue; + +/** + * Possible states of a LWM2M client connected to a Server. + * + */ +public enum ClientState { + /** Client can be reached from server. */ + REACHABLE, + /** Client is currently receiving queued messages */ + RECEIVING, + /** Client cannot be reached from server */ + UNREACHABLE +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/MessageStore.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/MessageStore.java index a0edbc9..8a6accf 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/MessageStore.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/MessageStore.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - added removeAll method - *******************************************************************************/ -package org.eclipse.leshan.server.queue; - -/** - * a message store provide basic operations to handle storage of requests destined for a client which has connected in - * Queue Mode. Messages in the message store will be present until one of the following events occur - *

- * - Message was sent to the client and was acknowledged either with a response or an error.
- * - Client has de-registered
- * - Client has not sent registration update within the time out period.
- *

- * When the last two events occur, the queue is emptied for the client. - * - * @see QueuedRequest - */ -public interface MessageStore { - /** - * Adds a new queue request entity to the queue. - * - * @param entity queue request to add to the queue - */ - void add(QueuedRequest entity); - - /** - * Retrieves first (next, topmost) queue request entity from a given client's queue. - * - * @param endpoint client's endpoint - * @return queue request entity - */ - QueuedRequest retrieveFirst(String endpoint); - - /** - * checks whether there are any queued message for the given endpoint - * - * @param endpoint client's endpoint - * @return true if no messages are available, false otherwise. - */ - boolean isEmpty(String endpoint); - - /** - * deletes all queued request for a given client endpoint. - * - * @param endpoint client's endpoint - */ - void removeAll(String endpoint); - - /** - * Deletes the first request from message queue for the given client. - * - * @param endpoint client endpoint name - */ - void deleteFirst(String endpoint); -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - added removeAll method + *******************************************************************************/ +package org.eclipse.leshan.server.queue; + +/** + * a message store provide basic operations to handle storage of requests destined for a client which has connected in + * Queue Mode. Messages in the message store will be present until one of the following events occur + *

+ * - Message was sent to the client and was acknowledged either with a response or an error.
+ * - Client has de-registered
+ * - Client has not sent registration update within the time out period.
+ *

+ * When the last two events occur, the queue is emptied for the client. + * + * @see QueuedRequest + */ +public interface MessageStore { + /** + * Adds a new queue request entity to the queue. + * + * @param entity queue request to add to the queue + */ + void add(QueuedRequest entity); + + /** + * Retrieves first (next, topmost) queue request entity from a given client's queue. + * + * @param endpoint client's endpoint + * @return queue request entity + */ + QueuedRequest retrieveFirst(String endpoint); + + /** + * checks whether there are any queued message for the given endpoint + * + * @param endpoint client's endpoint + * @return true if no messages are available, false otherwise. + */ + boolean isEmpty(String endpoint); + + /** + * deletes all queued request for a given client endpoint. + * + * @param endpoint client's endpoint + */ + void removeAll(String endpoint); + + /** + * Deletes the first request from message queue for the given client. + * + * @param endpoint client endpoint name + */ + void deleteFirst(String endpoint); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/QueuedRequest.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/QueuedRequest.java index 988b1eb..c29e9a7 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/QueuedRequest.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/QueuedRequest.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * QueuedRequest is wrapper around {@link DownlinkRequest} along with the current state of the request. - */ -public interface QueuedRequest { - - /** - * requestTicket represents the correlation identifier used to correlate any response for this request from LWM2M - * Client. - * - * @return ID. - */ - String getRequestTicket(); - - /** - * @return client's endpoint to send the request to - */ - String getEndpoint(); - - /** - * @return the actual downlink request which is to be send - */ - DownlinkRequest getDownlinkRequest(); -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * QueuedRequest is wrapper around {@link DownlinkRequest} along with the current state of the request. + */ +public interface QueuedRequest { + + /** + * requestTicket represents the correlation identifier used to correlate any response for this request from LWM2M + * Client. + * + * @return ID. + */ + String getRequestTicket(); + + /** + * @return client's endpoint to send the request to + */ + String getEndpoint(); + + /** + * @return the actual downlink request which is to be send + */ + DownlinkRequest getDownlinkRequest(); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/ClientStatusTracker.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/ClientStatusTracker.java index e8fbe27..11b4e05 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/ClientStatusTracker.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/ClientStatusTracker.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Balasubramanian Azhagappan, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue.impl; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.eclipse.leshan.server.queue.ClientState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tracks the status of each client endpoint. Also ensures that the state transitions are carried out - * - * A client starts with a REACHABLE state on a Register event. Before the first message is sent, the status is set to - * RECEIVING. For further queued messages the client remains in this state until there are no more messages to be - * delivered. When there are no more messages left, the state is set to REACHABLE. On timeout of a message, the status - * is set to UNREACHABLE. - * - * On Client updates or notifies, the UNREACHABLE state is changed to REACHABLE and then set to RECEIVING before sending - * any messages. This is done to ensure that messages are sent only once in a multi-threaded message queue processing. - * - * @see ClientState - */ -public final class ClientStatusTracker { - private static final Logger LOG = LoggerFactory.getLogger(ClientStatusTracker.class); - private final ConcurrentMap clientStatus = new ConcurrentHashMap<>(); - - public boolean setClientUnreachable(String endpoint) { - return transitState(endpoint, ClientState.RECEIVING, ClientState.UNREACHABLE); - } - - public boolean setClientReachable(String endpoint) { - return transitState(endpoint, ClientState.UNREACHABLE, ClientState.REACHABLE) - || clientStatus.putIfAbsent(endpoint, ClientState.REACHABLE) == null; - } - - public boolean startClientReceiving(String endpoint) { - return transitState(endpoint, ClientState.REACHABLE, ClientState.RECEIVING); - } - - public boolean stopClientReceiving(String endpoint) { - return transitState(endpoint, ClientState.RECEIVING, ClientState.REACHABLE); - } - - public void clearClientState(String endpoint) { - clientStatus.remove(endpoint); - } - - private boolean transitState(String endpoint, ClientState from, ClientState to) { - boolean updated = clientStatus.replace(endpoint, from, to); - if (LOG.isDebugEnabled()) { - if (updated) { - LOG.debug("Client {} state update {} -> {}", endpoint, from, to); - } else { - LOG.debug("Cannot update Client {} state {} -> {}. Current state is {}", endpoint, from, to, - clientStatus.get(endpoint)); - } - } - return updated; - } -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Balasubramanian Azhagappan, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue.impl; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.eclipse.leshan.server.queue.ClientState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Tracks the status of each client endpoint. Also ensures that the state transitions are carried out + * + * A client starts with a REACHABLE state on a Register event. Before the first message is sent, the status is set to + * RECEIVING. For further queued messages the client remains in this state until there are no more messages to be + * delivered. When there are no more messages left, the state is set to REACHABLE. On timeout of a message, the status + * is set to UNREACHABLE. + * + * On Client updates or notifies, the UNREACHABLE state is changed to REACHABLE and then set to RECEIVING before sending + * any messages. This is done to ensure that messages are sent only once in a multi-threaded message queue processing. + * + * @see ClientState + */ +public final class ClientStatusTracker { + private static final Logger LOG = LoggerFactory.getLogger(ClientStatusTracker.class); + private final ConcurrentMap clientStatus = new ConcurrentHashMap<>(); + + public boolean setClientUnreachable(String endpoint) { + return transitState(endpoint, ClientState.RECEIVING, ClientState.UNREACHABLE); + } + + public boolean setClientReachable(String endpoint) { + return transitState(endpoint, ClientState.UNREACHABLE, ClientState.REACHABLE) + || clientStatus.putIfAbsent(endpoint, ClientState.REACHABLE) == null; + } + + public boolean startClientReceiving(String endpoint) { + return transitState(endpoint, ClientState.REACHABLE, ClientState.RECEIVING); + } + + public boolean stopClientReceiving(String endpoint) { + return transitState(endpoint, ClientState.RECEIVING, ClientState.REACHABLE); + } + + public void clearClientState(String endpoint) { + clientStatus.remove(endpoint); + } + + private boolean transitState(String endpoint, ClientState from, ClientState to) { + boolean updated = clientStatus.replace(endpoint, from, to); + if (LOG.isDebugEnabled()) { + if (updated) { + LOG.debug("Client {} state update {} -> {}", endpoint, from, to); + } else { + LOG.debug("Cannot update Client {} state {} -> {}. Current state is {}", endpoint, from, to, + clientStatus.get(endpoint)); + } + } + return updated; + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/InMemoryMessageStore.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/InMemoryMessageStore.java index 7d02613..f1f319c 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/InMemoryMessageStore.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/InMemoryMessageStore.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - added isEmpty method - *******************************************************************************/ -package org.eclipse.leshan.server.queue.impl; - -import org.eclipse.leshan.server.queue.MessageStore; -import org.eclipse.leshan.server.queue.QueuedRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * provides a simple in-memory persistence implementation of the request queue. - */ -public class InMemoryMessageStore implements MessageStore { - private static Logger LOG = LoggerFactory.getLogger(InMemoryMessageStore.class); - private final ConcurrentMap> requestQueueMap = new ConcurrentHashMap<>(); - - @Override - public void add(QueuedRequest entity) { - LOG.debug("Add entity {}", entity); - String endpoint = entity.getEndpoint(); - BlockingQueue requestQueue = getMessageQueueForEndpoint(endpoint); - requestQueue.add(entity); - requestQueueMap.putIfAbsent(endpoint, requestQueue); - } - - @Override - public boolean isEmpty(String endpoint) { - return getMessageQueueForEndpoint(endpoint).isEmpty(); - } - - @Override - public QueuedRequest retrieveFirst(String endpoint) { - LOG.trace("Retrieve first for endpoint {}", endpoint); - BlockingQueue requests = getMessageQueueForEndpoint(endpoint); - return requests.peek(); - } - - @Override - public void removeAll(String endpoint) { - LOG.debug("Emptying messages for client {}", endpoint); - // If client has registers and de-registers without any other messages - // then the queue would not have been initialized. - if (requestQueueMap.get(endpoint) != null) { - requestQueueMap.remove(endpoint); - } - } - - @Override - public void deleteFirst(String endpoint) { - LOG.debug("Delete first entity of endpoint {}", endpoint); - BlockingQueue requests = requestQueueMap.get(endpoint); - if (requests != null) { - requests.poll(); - } - } - - /** - * Retrieves a whole queue for a given client's endpoint, in order of processing. Used only for testing purposes. - * - * @param endpoint client's endpoint - * @return list of queue request entities in order of processing. - */ - public List retrieveAll(String endpoint) { - LOG.debug("Retrieve all for endpoint {}", endpoint); - BlockingQueue requests = getMessageQueueForEndpoint(endpoint); - if (requests.isEmpty()) { - return Collections.emptyList(); - } else { - return new ArrayList<>(requests); - } - } - - private BlockingQueue getMessageQueueForEndpoint(String endpoint) { - return requestQueueMap.get(endpoint) != null ? requestQueueMap.get(endpoint) - : new LinkedBlockingQueue(); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - added isEmpty method + *******************************************************************************/ +package org.eclipse.leshan.server.queue.impl; + +import org.eclipse.leshan.server.queue.MessageStore; +import org.eclipse.leshan.server.queue.QueuedRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * provides a simple in-memory persistence implementation of the request queue. + */ +public class InMemoryMessageStore implements MessageStore { + private static Logger LOG = LoggerFactory.getLogger(InMemoryMessageStore.class); + private final ConcurrentMap> requestQueueMap = new ConcurrentHashMap<>(); + + @Override + public void add(QueuedRequest entity) { + LOG.debug("Add entity {}", entity); + String endpoint = entity.getEndpoint(); + BlockingQueue requestQueue = getMessageQueueForEndpoint(endpoint); + requestQueue.add(entity); + requestQueueMap.putIfAbsent(endpoint, requestQueue); + } + + @Override + public boolean isEmpty(String endpoint) { + return getMessageQueueForEndpoint(endpoint).isEmpty(); + } + + @Override + public QueuedRequest retrieveFirst(String endpoint) { + LOG.trace("Retrieve first for endpoint {}", endpoint); + BlockingQueue requests = getMessageQueueForEndpoint(endpoint); + return requests.peek(); + } + + @Override + public void removeAll(String endpoint) { + LOG.debug("Emptying messages for client {}", endpoint); + // If client has registers and de-registers without any other messages + // then the queue would not have been initialized. + if (requestQueueMap.get(endpoint) != null) { + requestQueueMap.remove(endpoint); + } + } + + @Override + public void deleteFirst(String endpoint) { + LOG.debug("Delete first entity of endpoint {}", endpoint); + BlockingQueue requests = requestQueueMap.get(endpoint); + if (requests != null) { + requests.poll(); + } + } + + /** + * Retrieves a whole queue for a given client's endpoint, in order of processing. Used only for testing purposes. + * + * @param endpoint client's endpoint + * @return list of queue request entities in order of processing. + */ + public List retrieveAll(String endpoint) { + LOG.debug("Retrieve all for endpoint {}", endpoint); + BlockingQueue requests = getMessageQueueForEndpoint(endpoint); + if (requests.isEmpty()) { + return Collections.emptyList(); + } else { + return new ArrayList<>(requests); + } + } + + private BlockingQueue getMessageQueueForEndpoint(String endpoint) { + return requestQueueMap.get(endpoint) != null ? requestQueueMap.get(endpoint) + : new LinkedBlockingQueue(); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/QueuedRequestSender.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/QueuedRequestSender.java index 3949e5c..c8d587f 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/QueuedRequestSender.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/QueuedRequestSender.java @@ -1,393 +1,393 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier, Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue.impl; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.observation.Observation; -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.request.exception.TimeoutException; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.server.Stoppable; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.client.ClientRegistryListener; -import org.eclipse.leshan.server.client.ClientUpdate; -import org.eclipse.leshan.server.observation.ObservationRegistry; -import org.eclipse.leshan.server.observation.ObservationRegistryListener; -import org.eclipse.leshan.server.queue.MessageStore; -import org.eclipse.leshan.server.queue.QueuedRequest; -import org.eclipse.leshan.server.request.LwM2mRequestSender; -import org.eclipse.leshan.server.response.ResponseListener; -import org.eclipse.leshan.server.response.ResponseProcessingTask; -import org.eclipse.leshan.util.NamedThreadFactory; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This sender is a special implementation of a {@link LwM2mRequestSender} . This sender assumes the client is using "Q" - * (queue) mode and processes the request using the internal queue, i.e. the request is enqueued first and then sent if - * a client is back online. - */ -public class QueuedRequestSender implements LwM2mRequestSender, Stoppable { - private static final Logger LOG = LoggerFactory.getLogger(QueuedRequestSender.class); - private final LwM2mRequestSender delegateSender; - private final ExecutorService processingExecutor = Executors.newCachedThreadPool(new NamedThreadFactory( - "leshan-qmode-processingExecutor-%d")); - private final MessageStore messageStore; - private final QueueModeClientRegistryListener queueModeClientRegistryListener; - private final QueueModeObservationRegistryListener queueModeObservationRegistryListener; - private final ClientRegistry clientRegistry; - private final ObservationRegistry observationRegistry; - private final ClientStatusTracker clientStatusTracker; - private final Collection responseListeners = new ConcurrentLinkedQueue<>(); - - /** - * Creates a new QueueRequestSender using given builder. - * - * @param builder sender builder - */ - private QueuedRequestSender(Builder builder) { - this.messageStore = builder.messageStore; - this.clientRegistry = builder.clientRegistry; - this.observationRegistry = builder.observationRegistry; - this.delegateSender = builder.delegateSender; - - this.clientStatusTracker = new ClientStatusTracker(); - - this.queueModeClientRegistryListener = new QueueModeClientRegistryListener(); - clientRegistry.addListener(queueModeClientRegistryListener); - this.queueModeObservationRegistryListener = new QueueModeObservationRegistryListener(); - observationRegistry.addListener(queueModeObservationRegistryListener); - delegateSender.addResponseListener(createResponseListener()); - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public T send(Client destination, DownlinkRequest request, Long requestTimeout) - throws InterruptedException { - throw new UnsupportedOperationException("QueueMode doesn't support sending of messages synchronously"); - } - - @Override - public void send(Client destination, DownlinkRequest request, - ResponseCallback responseCallback, ErrorCallback errorCallback) { - throw new UnsupportedOperationException( - "QueueMode doesn't support sending of messages with callbacks. Use a request ticket instead and register your response listeners"); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.leshan.server.request.LwM2mRequestSender#send(org.eclipse. leshan.server.client.Client, - * java.lang.String, org.eclipse.leshan.core.request.DownlinkRequest) - */ - @Override - public void send(Client destination, String requestTicket, DownlinkRequest request) { - LOG.trace("send(requestTicket={})", requestTicket); - // safe because DownlinkRequest does not use generic itself - @SuppressWarnings("unchecked") - DownlinkRequest castedDownlinkRequest = (DownlinkRequest) request; - LOG.trace("Sending request {} with queue mode", castedDownlinkRequest); - - String endpoint = destination.getEndpoint(); - - // Accept messages only when the client is already known to - // ClientRegistry - if (clientRegistry.get(endpoint) != null) { - QueuedRequest queuedRequest = new QueuedRequestImpl(endpoint, castedDownlinkRequest, requestTicket); - messageStore.add(queuedRequest); - // If Client is reachable and this is the first message, we send it - // immediately. - if (clientStatusTracker.startClientReceiving(endpoint)) { - processingExecutor.execute(newRequestSendingTask(endpoint)); - } - } else { - LOG.warn("Ignoring a message received in Queue Mode for the unknown client [{}]", endpoint); - } - } - - @Override - public void addResponseListener(ResponseListener listener) { - responseListeners.add(listener); - } - - @Override - public void removeResponseListener(ResponseListener listener) { - responseListeners.remove(listener); - } - - @Override - public void stop() { - clientRegistry.removeListener(queueModeClientRegistryListener); - observationRegistry.removeListener(queueModeObservationRegistryListener); - processingExecutor.shutdown(); - try { - boolean queueProcessingExecutorTerminated = processingExecutor.awaitTermination(5, TimeUnit.SECONDS); - if (!(queueProcessingExecutorTerminated)) { - LOG.debug("Could not stop all executors within timeout. processingExecutor stopped: {}, ", - queueProcessingExecutorTerminated); - } - } catch (InterruptedException e) { - LOG.debug("Interrupted while stopping. Abort stopping."); - Thread.currentThread().interrupt(); - } - } - - /** - * creates a response listener for response and error responses from clients using queue mode. - * - * @return instance of {@link ResponseListener} - */ - private ResponseListener createResponseListener() { - return new ResponseListener() { - - @Override - public void onResponse(String clientEndpoint, String requestTicket, LwM2mResponse response) { - Client registrationInfo = clientRegistry.get(clientEndpoint); - // process only if the client has used Queue mode. - if (registrationInfo != null && registrationInfo.usesQueueMode()) { - LOG.trace("response received in Queue mode successfully: {}", requestTicket); - processResponse(clientEndpoint, requestTicket, response); - } - } - - @Override - public void onError(String clientEndpoint, String requestTicket, Exception exception) { - Client registrationInfo = clientRegistry.get(clientEndpoint); - // process only if the client has used Queue mode. - if (registrationInfo != null && registrationInfo.usesQueueMode()) { - LOG.debug("exception on sending the request: {}", requestTicket, exception); - if (exception instanceof TimeoutException) { - timeout(clientEndpoint); - } else { - processException(clientEndpoint, requestTicket, exception); - } - } - } - }; - } - - private void processResponse(String clientEndpoint, String requestTicket, LwM2mResponse response) { - LOG.debug("Received Response -> {}", requestTicket); - messageStore.deleteFirst(clientEndpoint); - processingExecutor.execute(new ResponseProcessingTask(clientEndpoint, requestTicket, responseListeners, - response)); - processingExecutor.execute(newRequestSendingTask(clientEndpoint)); - } - - private void processException(String clientEndpoint, String requestTicket, Exception exception) { - LOG.debug("Received error response {}", requestTicket); - messageStore.deleteFirst(clientEndpoint); - processingExecutor.execute(new ResponseProcessingTask(clientEndpoint, requestTicket, responseListeners, - exception)); - processingExecutor.execute(newRequestSendingTask(clientEndpoint)); - } - - private void timeout(String clientEndpoint) { - LOG.debug("Client {} timed out", clientEndpoint); - clientStatusTracker.setClientUnreachable(clientEndpoint); - } - - private RequestSendingTask newRequestSendingTask(String endpoint) { - return new RequestSendingTask(clientRegistry, delegateSender, clientStatusTracker, messageStore, endpoint); - } - - private final class QueueModeObservationRegistryListener implements ObservationRegistryListener { - @Override - public void newValue(Observation observation, LwM2mNode value, List timestampedValues) { - Client client = clientRegistry.findByRegistrationId(observation.getRegistrationId()); - if (client.usesQueueMode() && clientStatusTracker.setClientReachable(client.getEndpoint()) - && clientStatusTracker.startClientReceiving(client.getEndpoint())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Notify from {}. Sending queued requests.", client.getEndpoint()); - } - processingExecutor.execute(newRequestSendingTask(client.getEndpoint())); - } - } - - @Override - public void cancelled(Observation observation) { - // not used here - } - - @Override - public void newObservation(Observation observation) { - // not used here - } - } - - private final class QueueModeClientRegistryListener implements ClientRegistryListener { - @Override - public void registered(Client client) { - // When client is in QueueMode - if (client.usesQueueMode()) { - clientStatusTracker.setClientReachable(client.getEndpoint()); - if (LOG.isDebugEnabled()) { - LOG.debug("Client {} registered.", client.getEndpoint()); - } - } - } - - @Override - public void updated(ClientUpdate update, Client clientUpdated) { - // When client is in QueueMode and was previously in unreachable - // state and when RECEIVING state could be set - // i.e:- there is no other message currently being sent - if (clientUpdated.usesQueueMode() && clientStatusTracker.setClientReachable(clientUpdated.getEndpoint()) - && clientStatusTracker.startClientReceiving(clientUpdated.getEndpoint())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Client {} updated. Sending queued request.", clientUpdated.getEndpoint()); - } - processingExecutor.execute(newRequestSendingTask(clientUpdated.getEndpoint())); - } - } - - @Override - public void unregistered(Client client) { - if (client.usesQueueMode()) { - clientStatusTracker.clearClientState(client.getEndpoint()); - if (LOG.isDebugEnabled()) { - LOG.debug("Client {} de-registered. Removing all queued requests.", client.getEndpoint()); - } - messageStore.removeAll(client.getEndpoint()); - // TODO: Also cancel any CoAP retries? - } - } - } - - /** - * Builder, which helps to create a QueuedRequestSender instance. - */ - public static class Builder { - - private MessageStore messageStore; - private LwM2mRequestSender delegateSender; - private ClientRegistry clientRegistry; - private ObservationRegistry observationRegistry; - - public Builder setMessageStore(MessageStore messageStore) { - this.messageStore = messageStore; - return this; - } - - public Builder setRequestSender(LwM2mRequestSender delegateSender) { - this.delegateSender = delegateSender; - return this; - } - - public Builder setClientRegistry(ClientRegistry clientRegistry) { - this.clientRegistry = clientRegistry; - return this; - } - - public Builder setObservationRegistry(ObservationRegistry observationRegistry) { - this.observationRegistry = observationRegistry; - return this; - } - - public QueuedRequestSender build() { - Validate.notNull(messageStore, "messageStore cannot be null"); - Validate.notNull(delegateSender, "delegateSender cannot be null"); - Validate.notNull(clientRegistry, "clientRegistry cannot be null"); - Validate.notNull(observationRegistry, "observationRegistry cannot be null"); - - return new QueuedRequestSender(this); - } - } - - /** - * An instance of a queued request along with its meta data (endpoint and requestTicket). - */ - static class QueuedRequestImpl implements QueuedRequest { - - private final DownlinkRequest downlinkRequest; - private final String endpoint; - private final String requestTicket; - - private QueuedRequestImpl(String endpoint, DownlinkRequest downlinkRequest, String requestTicket) { - Validate.notNull(endpoint, "endpoint may not be null"); - Validate.notNull(downlinkRequest, "request may not be null"); - this.downlinkRequest = downlinkRequest; - this.endpoint = endpoint; - this.requestTicket = requestTicket; - } - - @Override - public String getEndpoint() { - return endpoint; - } - - @Override - public DownlinkRequest getDownlinkRequest() { - return downlinkRequest; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.leshan.server.queue.QueuedRequest#getRequestTicket() - */ - @Override - public String getRequestTicket() { - return this.requestTicket; - } - - @Override - public String toString() { - return new StringBuilder().append("QueuedRequestImpl [requestTicket=").append(requestTicket) - .append(", downlinkRequest=").append(downlinkRequest).append(", endpoint=" + endpoint) - .append(", requestId=").append("]").toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (requestTicket.hashCode() ^ (requestTicket.hashCode() >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - QueuedRequestImpl other = (QueuedRequestImpl) obj; - return requestTicket == other.requestTicket; - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier, Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue.impl; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.observation.Observation; +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.exception.TimeoutException; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.eclipse.leshan.server.Stoppable; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.client.ClientRegistryListener; +import org.eclipse.leshan.server.client.ClientUpdate; +import org.eclipse.leshan.server.observation.ObservationRegistry; +import org.eclipse.leshan.server.observation.ObservationRegistryListener; +import org.eclipse.leshan.server.queue.MessageStore; +import org.eclipse.leshan.server.queue.QueuedRequest; +import org.eclipse.leshan.server.request.LwM2mRequestSender; +import org.eclipse.leshan.server.response.ResponseListener; +import org.eclipse.leshan.server.response.ResponseProcessingTask; +import org.eclipse.leshan.util.NamedThreadFactory; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This sender is a special implementation of a {@link LwM2mRequestSender} . This sender assumes the client is using "Q" + * (queue) mode and processes the request using the internal queue, i.e. the request is enqueued first and then sent if + * a client is back online. + */ +public class QueuedRequestSender implements LwM2mRequestSender, Stoppable { + private static final Logger LOG = LoggerFactory.getLogger(QueuedRequestSender.class); + private final LwM2mRequestSender delegateSender; + private final ExecutorService processingExecutor = Executors.newCachedThreadPool(new NamedThreadFactory( + "leshan-qmode-processingExecutor-%d")); + private final MessageStore messageStore; + private final QueueModeClientRegistryListener queueModeClientRegistryListener; + private final QueueModeObservationRegistryListener queueModeObservationRegistryListener; + private final ClientRegistry clientRegistry; + private final ObservationRegistry observationRegistry; + private final ClientStatusTracker clientStatusTracker; + private final Collection responseListeners = new ConcurrentLinkedQueue<>(); + + /** + * Creates a new QueueRequestSender using given builder. + * + * @param builder sender builder + */ + private QueuedRequestSender(Builder builder) { + this.messageStore = builder.messageStore; + this.clientRegistry = builder.clientRegistry; + this.observationRegistry = builder.observationRegistry; + this.delegateSender = builder.delegateSender; + + this.clientStatusTracker = new ClientStatusTracker(); + + this.queueModeClientRegistryListener = new QueueModeClientRegistryListener(); + clientRegistry.addListener(queueModeClientRegistryListener); + this.queueModeObservationRegistryListener = new QueueModeObservationRegistryListener(); + observationRegistry.addListener(queueModeObservationRegistryListener); + delegateSender.addResponseListener(createResponseListener()); + } + + public static Builder builder() { + return new Builder(); + } + + @Override + public T send(Client destination, DownlinkRequest request, Long requestTimeout) + throws InterruptedException { + throw new UnsupportedOperationException("QueueMode doesn't support sending of messages synchronously"); + } + + @Override + public void send(Client destination, DownlinkRequest request, + ResponseCallback responseCallback, ErrorCallback errorCallback) { + throw new UnsupportedOperationException( + "QueueMode doesn't support sending of messages with callbacks. Use a request ticket instead and register your response listeners"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.leshan.server.request.LwM2mRequestSender#send(org.eclipse. leshan.server.client.Client, + * java.lang.String, org.eclipse.leshan.core.request.DownlinkRequest) + */ + @Override + public void send(Client destination, String requestTicket, DownlinkRequest request) { + LOG.trace("send(requestTicket={})", requestTicket); + // safe because DownlinkRequest does not use generic itself + @SuppressWarnings("unchecked") + DownlinkRequest castedDownlinkRequest = (DownlinkRequest) request; + LOG.trace("Sending request {} with queue mode", castedDownlinkRequest); + + String endpoint = destination.getEndpoint(); + + // Accept messages only when the client is already known to + // ClientRegistry + if (clientRegistry.get(endpoint) != null) { + QueuedRequest queuedRequest = new QueuedRequestImpl(endpoint, castedDownlinkRequest, requestTicket); + messageStore.add(queuedRequest); + // If Client is reachable and this is the first message, we send it + // immediately. + if (clientStatusTracker.startClientReceiving(endpoint)) { + processingExecutor.execute(newRequestSendingTask(endpoint)); + } + } else { + LOG.warn("Ignoring a message received in Queue Mode for the unknown client [{}]", endpoint); + } + } + + @Override + public void addResponseListener(ResponseListener listener) { + responseListeners.add(listener); + } + + @Override + public void removeResponseListener(ResponseListener listener) { + responseListeners.remove(listener); + } + + @Override + public void stop() { + clientRegistry.removeListener(queueModeClientRegistryListener); + observationRegistry.removeListener(queueModeObservationRegistryListener); + processingExecutor.shutdown(); + try { + boolean queueProcessingExecutorTerminated = processingExecutor.awaitTermination(5, TimeUnit.SECONDS); + if (!(queueProcessingExecutorTerminated)) { + LOG.debug("Could not stop all executors within timeout. processingExecutor stopped: {}, ", + queueProcessingExecutorTerminated); + } + } catch (InterruptedException e) { + LOG.debug("Interrupted while stopping. Abort stopping."); + Thread.currentThread().interrupt(); + } + } + + /** + * creates a response listener for response and error responses from clients using queue mode. + * + * @return instance of {@link ResponseListener} + */ + private ResponseListener createResponseListener() { + return new ResponseListener() { + + @Override + public void onResponse(String clientEndpoint, String requestTicket, LwM2mResponse response) { + Client registrationInfo = clientRegistry.get(clientEndpoint); + // process only if the client has used Queue mode. + if (registrationInfo != null && registrationInfo.usesQueueMode()) { + LOG.trace("response received in Queue mode successfully: {}", requestTicket); + processResponse(clientEndpoint, requestTicket, response); + } + } + + @Override + public void onError(String clientEndpoint, String requestTicket, Exception exception) { + Client registrationInfo = clientRegistry.get(clientEndpoint); + // process only if the client has used Queue mode. + if (registrationInfo != null && registrationInfo.usesQueueMode()) { + LOG.debug("exception on sending the request: {}", requestTicket, exception); + if (exception instanceof TimeoutException) { + timeout(clientEndpoint); + } else { + processException(clientEndpoint, requestTicket, exception); + } + } + } + }; + } + + private void processResponse(String clientEndpoint, String requestTicket, LwM2mResponse response) { + LOG.debug("Received Response -> {}", requestTicket); + messageStore.deleteFirst(clientEndpoint); + processingExecutor.execute(new ResponseProcessingTask(clientEndpoint, requestTicket, responseListeners, + response)); + processingExecutor.execute(newRequestSendingTask(clientEndpoint)); + } + + private void processException(String clientEndpoint, String requestTicket, Exception exception) { + LOG.debug("Received error response {}", requestTicket); + messageStore.deleteFirst(clientEndpoint); + processingExecutor.execute(new ResponseProcessingTask(clientEndpoint, requestTicket, responseListeners, + exception)); + processingExecutor.execute(newRequestSendingTask(clientEndpoint)); + } + + private void timeout(String clientEndpoint) { + LOG.debug("Client {} timed out", clientEndpoint); + clientStatusTracker.setClientUnreachable(clientEndpoint); + } + + private RequestSendingTask newRequestSendingTask(String endpoint) { + return new RequestSendingTask(clientRegistry, delegateSender, clientStatusTracker, messageStore, endpoint); + } + + private final class QueueModeObservationRegistryListener implements ObservationRegistryListener { + @Override + public void newValue(Observation observation, LwM2mNode value, List timestampedValues) { + Client client = clientRegistry.findByRegistrationId(observation.getRegistrationId()); + if (client.usesQueueMode() && clientStatusTracker.setClientReachable(client.getEndpoint()) + && clientStatusTracker.startClientReceiving(client.getEndpoint())) { + if (LOG.isDebugEnabled()) { + LOG.debug("Notify from {}. Sending queued requests.", client.getEndpoint()); + } + processingExecutor.execute(newRequestSendingTask(client.getEndpoint())); + } + } + + @Override + public void cancelled(Observation observation) { + // not used here + } + + @Override + public void newObservation(Observation observation) { + // not used here + } + } + + private final class QueueModeClientRegistryListener implements ClientRegistryListener { + @Override + public void registered(Client client) { + // When client is in QueueMode + if (client.usesQueueMode()) { + clientStatusTracker.setClientReachable(client.getEndpoint()); + if (LOG.isDebugEnabled()) { + LOG.debug("Client {} registered.", client.getEndpoint()); + } + } + } + + @Override + public void updated(ClientUpdate update, Client clientUpdated) { + // When client is in QueueMode and was previously in unreachable + // state and when RECEIVING state could be set + // i.e:- there is no other message currently being sent + if (clientUpdated.usesQueueMode() && clientStatusTracker.setClientReachable(clientUpdated.getEndpoint()) + && clientStatusTracker.startClientReceiving(clientUpdated.getEndpoint())) { + if (LOG.isDebugEnabled()) { + LOG.debug("Client {} updated. Sending queued request.", clientUpdated.getEndpoint()); + } + processingExecutor.execute(newRequestSendingTask(clientUpdated.getEndpoint())); + } + } + + @Override + public void unregistered(Client client) { + if (client.usesQueueMode()) { + clientStatusTracker.clearClientState(client.getEndpoint()); + if (LOG.isDebugEnabled()) { + LOG.debug("Client {} de-registered. Removing all queued requests.", client.getEndpoint()); + } + messageStore.removeAll(client.getEndpoint()); + // TODO: Also cancel any CoAP retries? + } + } + } + + /** + * Builder, which helps to create a QueuedRequestSender instance. + */ + public static class Builder { + + private MessageStore messageStore; + private LwM2mRequestSender delegateSender; + private ClientRegistry clientRegistry; + private ObservationRegistry observationRegistry; + + public Builder setMessageStore(MessageStore messageStore) { + this.messageStore = messageStore; + return this; + } + + public Builder setRequestSender(LwM2mRequestSender delegateSender) { + this.delegateSender = delegateSender; + return this; + } + + public Builder setClientRegistry(ClientRegistry clientRegistry) { + this.clientRegistry = clientRegistry; + return this; + } + + public Builder setObservationRegistry(ObservationRegistry observationRegistry) { + this.observationRegistry = observationRegistry; + return this; + } + + public QueuedRequestSender build() { + Validate.notNull(messageStore, "messageStore cannot be null"); + Validate.notNull(delegateSender, "delegateSender cannot be null"); + Validate.notNull(clientRegistry, "clientRegistry cannot be null"); + Validate.notNull(observationRegistry, "observationRegistry cannot be null"); + + return new QueuedRequestSender(this); + } + } + + /** + * An instance of a queued request along with its meta data (endpoint and requestTicket). + */ + static class QueuedRequestImpl implements QueuedRequest { + + private final DownlinkRequest downlinkRequest; + private final String endpoint; + private final String requestTicket; + + private QueuedRequestImpl(String endpoint, DownlinkRequest downlinkRequest, String requestTicket) { + Validate.notNull(endpoint, "endpoint may not be null"); + Validate.notNull(downlinkRequest, "request may not be null"); + this.downlinkRequest = downlinkRequest; + this.endpoint = endpoint; + this.requestTicket = requestTicket; + } + + @Override + public String getEndpoint() { + return endpoint; + } + + @Override + public DownlinkRequest getDownlinkRequest() { + return downlinkRequest; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.leshan.server.queue.QueuedRequest#getRequestTicket() + */ + @Override + public String getRequestTicket() { + return this.requestTicket; + } + + @Override + public String toString() { + return new StringBuilder().append("QueuedRequestImpl [requestTicket=").append(requestTicket) + .append(", downlinkRequest=").append(downlinkRequest).append(", endpoint=" + endpoint) + .append(", requestId=").append("]").toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (requestTicket.hashCode() ^ (requestTicket.hashCode() >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + QueuedRequestImpl other = (QueuedRequestImpl) obj; + return requestTicket == other.requestTicket; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/RequestSendingTask.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/RequestSendingTask.java index 565591e..d1cb495 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/RequestSendingTask.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/queue/impl/RequestSendingTask.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier, Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue.impl; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.queue.MessageStore; -import org.eclipse.leshan.server.queue.QueuedRequest; -import org.eclipse.leshan.server.request.LwM2mRequestSender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Request sending task is a Runnable, which is responsible for the actual sending of a queue request. The queue request - * is sent asynchronously; upon receiving a response or an error the message is removed from queue and a new task is - * scheduled to process the next message from queue. - */ -class RequestSendingTask implements Runnable { - private static final Logger LOG = LoggerFactory.getLogger(RequestSendingTask.class); - private final ClientRegistry clientRegistry; - private final LwM2mRequestSender requestSender; - private final String endpoint; - private final MessageStore messageStore; - private final ClientStatusTracker clientStatusTracker; - - /** - * Creates a new task which is responsible for sending a queue request. - * - * @param clientRegistry client registry - * @param requestSender sender to perform send on (delegate) - * @param clientStatusTracker tracks the status of the client - * @param messageStore holds queued messages for the client - * @param endpoint clients endpoint identifier - */ - public RequestSendingTask(ClientRegistry clientRegistry, LwM2mRequestSender delegateSender, - ClientStatusTracker clientStatusTracker, MessageStore messageStore, String endpoint) { - this.clientRegistry = clientRegistry; - this.requestSender = delegateSender; - this.clientStatusTracker = clientStatusTracker; - this.endpoint = endpoint; - this.messageStore = messageStore; - } - - @Override - public void run() { - try { - executeAction(); - } catch (Exception e) { - LOG.info("error while executing runnable", e); - throw new RuntimeException(e); - } - } - - private void executeAction() { - QueuedRequest firstRequest = messageStore.retrieveFirst(endpoint); - - if (firstRequest != null) { - DownlinkRequest downlinkRequest = firstRequest.getDownlinkRequest(); - LOG.debug("Sending request: {}", downlinkRequest); - Client client = clientRegistry.get(firstRequest.getEndpoint()); - if (client == null) { - // client not registered anymore -> ignore this request - // Actually this should never happen. - LOG.debug("Client {} not registered anymore: {}", endpoint, downlinkRequest); - } else { - requestSender.send(client, firstRequest.getRequestTicket(), downlinkRequest); - } - } else { - LOG.debug("No more requests to send to client {}", endpoint); - clientStatusTracker.stopClientReceiving(endpoint); - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier, Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue.impl; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.queue.MessageStore; +import org.eclipse.leshan.server.queue.QueuedRequest; +import org.eclipse.leshan.server.request.LwM2mRequestSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Request sending task is a Runnable, which is responsible for the actual sending of a queue request. The queue request + * is sent asynchronously; upon receiving a response or an error the message is removed from queue and a new task is + * scheduled to process the next message from queue. + */ +class RequestSendingTask implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(RequestSendingTask.class); + private final ClientRegistry clientRegistry; + private final LwM2mRequestSender requestSender; + private final String endpoint; + private final MessageStore messageStore; + private final ClientStatusTracker clientStatusTracker; + + /** + * Creates a new task which is responsible for sending a queue request. + * + * @param clientRegistry client registry + * @param requestSender sender to perform send on (delegate) + * @param clientStatusTracker tracks the status of the client + * @param messageStore holds queued messages for the client + * @param endpoint clients endpoint identifier + */ + public RequestSendingTask(ClientRegistry clientRegistry, LwM2mRequestSender delegateSender, + ClientStatusTracker clientStatusTracker, MessageStore messageStore, String endpoint) { + this.clientRegistry = clientRegistry; + this.requestSender = delegateSender; + this.clientStatusTracker = clientStatusTracker; + this.endpoint = endpoint; + this.messageStore = messageStore; + } + + @Override + public void run() { + try { + executeAction(); + } catch (Exception e) { + LOG.info("error while executing runnable", e); + throw new RuntimeException(e); + } + } + + private void executeAction() { + QueuedRequest firstRequest = messageStore.retrieveFirst(endpoint); + + if (firstRequest != null) { + DownlinkRequest downlinkRequest = firstRequest.getDownlinkRequest(); + LOG.debug("Sending request: {}", downlinkRequest); + Client client = clientRegistry.get(firstRequest.getEndpoint()); + if (client == null) { + // client not registered anymore -> ignore this request + // Actually this should never happen. + LOG.debug("Client {} not registered anymore: {}", endpoint, downlinkRequest); + } else { + requestSender.send(client, firstRequest.getRequestTicket(), downlinkRequest); + } + } else { + LOG.debug("No more requests to send to client {}", endpoint); + clientStatusTracker.stopClientReceiving(endpoint); + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/registration/RegistrationHandler.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/registration/RegistrationHandler.java index 93365eb..f611ce7 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/registration/RegistrationHandler.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/registration/RegistrationHandler.java @@ -1,233 +1,233 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.registration; - -import java.net.InetSocketAddress; -import java.util.Date; - -import org.eclipse.leshan.core.request.DeregisterRequest; -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.core.request.RegisterRequest; -import org.eclipse.leshan.core.request.UpdateRequest; -import org.eclipse.leshan.core.response.DeregisterResponse; -import org.eclipse.leshan.core.response.RegisterResponse; -import org.eclipse.leshan.core.response.UpdateResponse; -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.client.ClientUpdate; -import org.eclipse.leshan.server.extension.Lwm2mVO; -import org.eclipse.leshan.server.extension.Util; -import org.eclipse.leshan.server.extension.dm.handler.DmConnector; -import org.eclipse.leshan.server.extension.onem2m.handler.Onem2mConnector; -import org.eclipse.leshan.server.security.SecurityCheck; -import org.eclipse.leshan.server.security.SecurityInfo; -import org.eclipse.leshan.server.security.SecurityStore; -import org.eclipse.leshan.util.RandomStringUtils; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - - -/** - * Handle the client registration logic. Check if the client is allowed to register, with the wanted security scheme. - * Create the {@link Client} representing the registered client and add it to the {@link ClientRegistry} - */ -public class RegistrationHandler { - - private static final Logger LOG = LoggerFactory.getLogger(RegistrationHandler.class); - - private SecurityStore securityStore; - private ClientRegistry clientRegistry; - - private String authId; - private String authPwd; - private Client client; - private Lwm2mVO vo = null; - - - public RegistrationHandler(ClientRegistry clientRegistry, SecurityStore securityStore) { - this.clientRegistry = clientRegistry; - this.securityStore = securityStore; - } - - public RegisterResponse register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint){ - - - if (registerRequest.getEndpointName() == null || registerRequest.getEndpointName().isEmpty() || sender == null) { - return RegisterResponse.badRequest(null); - } - - // We must check if the client is using the right identity. - if (!isAuthorized(registerRequest.getEndpointName(), sender)) { - return RegisterResponse.forbidden(null); - } - - Client.Builder builder = new Client.Builder(RegistrationHandler.createRegistrationId(), - registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() - .getPort(), serverEndpoint); - - builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) - .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) - .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) - .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); - - client = builder.build(); - - - if (clientRegistry.registerClient(client)) { - LOG.debug("New registered client: {}", client); - RegisterResponse res = RegisterResponse.success(client.getRegistrationId()); - - // MSH-START - - // set lwm2m info to VO - if(Lwm2mServerConfig.getInstance().isDmUsing() || Lwm2mServerConfig.getInstance().isIpeUsing()){ - vo = new Lwm2mVO(); - vo.setAuthId(authId); - vo.setAuthPwd(authPwd); - vo.setClient(client); - } - - // DM-Server - // connect - if(Lwm2mServerConfig.getInstance().isDmUsing()){ - Runnable rDmOperator = new DmConnector(vo); - Thread tDmOperator = new Thread(rDmOperator); - tDmOperator.start(); - } - - // IN-CSE - // createRepository, subscribe, report - if(Lwm2mServerConfig.getInstance().isIpeUsing()){ - Runnable rIncseOperator = new Onem2mConnector(vo); - Thread tIncseOperator = new Thread(rIncseOperator); - tIncseOperator.start(); - } - - // MSH-END - - return res; - } else { - return RegisterResponse.forbidden(null); - } - } - - public UpdateResponse update(Identity sender, UpdateRequest updateRequest) { - - System.out.println("#################### update test "); - - if (sender == null) { - return UpdateResponse.badRequest(null); - } - - // We must check if the client is using the right identity. - client = clientRegistry.findByRegistrationId(updateRequest.getRegistrationId()); - if (client == null) { - return UpdateResponse.notFound(); - } - if (!isAuthorized(client.getEndpoint(), sender)) { - return UpdateResponse.badRequest("forbidden"); - } - - client = clientRegistry.updateClient(new ClientUpdate(updateRequest.getRegistrationId(), sender - .getPeerAddress().getAddress(), sender.getPeerAddress().getPort(), updateRequest.getLifeTimeInSec(), - updateRequest.getSmsNumber(), updateRequest.getBindingMode(), updateRequest.getObjectLinks())); - if (client == null) { - return UpdateResponse.notFound(); - } else { - return UpdateResponse.success(); - } - } - - public DeregisterResponse deregister(Identity sender, DeregisterRequest deregisterRequest) { - - if (sender == null) { - return DeregisterResponse.badRequest(null); - } - - // We must check if the client is using the right identity. - client = clientRegistry.findByRegistrationId(deregisterRequest.getRegistrationID()); - authId = deregisterRequest.getRegistrationID(); - if (client == null) { - return DeregisterResponse.notFound(); - } - if (!isAuthorized(client.getEndpoint(), sender)) { - return DeregisterResponse.badRequest("forbidden"); - } - - /* - new Thread(new Runnable(){ - @Override - public void run() { - try{ - System.out.println("**************************** DISCONNECT FROM DEVICE MANAGEMENT SERVER [START] ****************************"); - - // 토큰화 - JSONObject token = Tokenization.makesTokenForDisconnect(authId, client); - - // 커넥션 - Connector conn = Connector.getInstance().connect(); - conn.sendRequest(token); - JSONObject result = conn.getResponse(); - - System.out.println("**************************** DISCONNECT FROM DEVICE MANAGEMENT SERVER [END] ****************************"); - - isConnected = false; - } catch(Exception e) { - e.printStackTrace(); - } - } - }).start(); - */ - - Client unregistered = clientRegistry.deregisterClient(deregisterRequest.getRegistrationID()); - if (unregistered != null) { - return DeregisterResponse.success(); - } else { - LOG.debug("Invalid deregistration"); - return DeregisterResponse.notFound(); - } - - - } - - - - private static String createRegistrationId() { - return RandomStringUtils.random(10, true, true); - } - - /** - * Return true if the client with the given lightweight M2M endPoint is authorized to communicate with the given - * security parameters. - * - * @param lwM2mEndPointName the lightweight M2M endPoint name - * @param clientIdentity the identity at TLS level - * @return true if device get authorization - */ - private boolean isAuthorized(String lwM2mEndPointName, Identity clientIdentity) { - // do we have security information for this client? - SecurityInfo expectedSecurityInfo = securityStore.getByEndpoint(lwM2mEndPointName); - if( expectedSecurityInfo != null ){ - authId = expectedSecurityInfo.getIdentity(); - authPwd = Util.byteArrayToHex(expectedSecurityInfo.getPreSharedKey()); - } - return SecurityCheck.checkSecurityInfo(lwM2mEndPointName, clientIdentity, expectedSecurityInfo); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.registration; + +import java.net.InetSocketAddress; +import java.util.Date; + +import org.eclipse.leshan.core.request.DeregisterRequest; +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.core.request.RegisterRequest; +import org.eclipse.leshan.core.request.UpdateRequest; +import org.eclipse.leshan.core.response.DeregisterResponse; +import org.eclipse.leshan.core.response.RegisterResponse; +import org.eclipse.leshan.core.response.UpdateResponse; +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.client.ClientUpdate; +import org.eclipse.leshan.server.extension.Lwm2mVO; +import org.eclipse.leshan.server.extension.Util; +import org.eclipse.leshan.server.extension.dm.handler.DmConnector; +import org.eclipse.leshan.server.extension.onem2m.handler.Onem2mConnector; +import org.eclipse.leshan.server.security.SecurityCheck; +import org.eclipse.leshan.server.security.SecurityInfo; +import org.eclipse.leshan.server.security.SecurityStore; +import org.eclipse.leshan.util.RandomStringUtils; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +/** + * Handle the client registration logic. Check if the client is allowed to register, with the wanted security scheme. + * Create the {@link Client} representing the registered client and add it to the {@link ClientRegistry} + */ +public class RegistrationHandler { + + private static final Logger LOG = LoggerFactory.getLogger(RegistrationHandler.class); + + private SecurityStore securityStore; + private ClientRegistry clientRegistry; + + private String authId; + private String authPwd; + private Client client; + private Lwm2mVO vo = null; + + + public RegistrationHandler(ClientRegistry clientRegistry, SecurityStore securityStore) { + this.clientRegistry = clientRegistry; + this.securityStore = securityStore; + } + + public RegisterResponse register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint){ + + + if (registerRequest.getEndpointName() == null || registerRequest.getEndpointName().isEmpty() || sender == null) { + return RegisterResponse.badRequest(null); + } + + // We must check if the client is using the right identity. + if (!isAuthorized(registerRequest.getEndpointName(), sender)) { + return RegisterResponse.forbidden(null); + } + + Client.Builder builder = new Client.Builder(RegistrationHandler.createRegistrationId(), + registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() + .getPort(), serverEndpoint); + + builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) + .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) + .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) + .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); + + client = builder.build(); + + + if (clientRegistry.registerClient(client)) { + LOG.debug("New registered client: {}", client); + RegisterResponse res = RegisterResponse.success(client.getRegistrationId()); + + // MSH-START + + // set lwm2m info to VO + if(Lwm2mServerConfig.getInstance().isDmUsing() || Lwm2mServerConfig.getInstance().isIpeUsing()){ + vo = new Lwm2mVO(); + vo.setAuthId(authId); + vo.setAuthPwd(authPwd); + vo.setClient(client); + } + + // DM-Server + // connect + if(Lwm2mServerConfig.getInstance().isDmUsing()){ + Runnable rDmOperator = new DmConnector(vo); + Thread tDmOperator = new Thread(rDmOperator); + tDmOperator.start(); + } + + // IN-CSE + // createRepository, subscribe, report + if(Lwm2mServerConfig.getInstance().isIpeUsing()){ + Runnable rIncseOperator = new Onem2mConnector(vo); + Thread tIncseOperator = new Thread(rIncseOperator); + tIncseOperator.start(); + } + + // MSH-END + + return res; + } else { + return RegisterResponse.forbidden(null); + } + } + + public UpdateResponse update(Identity sender, UpdateRequest updateRequest) { + + System.out.println("#################### update test "); + + if (sender == null) { + return UpdateResponse.badRequest(null); + } + + // We must check if the client is using the right identity. + client = clientRegistry.findByRegistrationId(updateRequest.getRegistrationId()); + if (client == null) { + return UpdateResponse.notFound(); + } + if (!isAuthorized(client.getEndpoint(), sender)) { + return UpdateResponse.badRequest("forbidden"); + } + + client = clientRegistry.updateClient(new ClientUpdate(updateRequest.getRegistrationId(), sender + .getPeerAddress().getAddress(), sender.getPeerAddress().getPort(), updateRequest.getLifeTimeInSec(), + updateRequest.getSmsNumber(), updateRequest.getBindingMode(), updateRequest.getObjectLinks())); + if (client == null) { + return UpdateResponse.notFound(); + } else { + return UpdateResponse.success(); + } + } + + public DeregisterResponse deregister(Identity sender, DeregisterRequest deregisterRequest) { + + if (sender == null) { + return DeregisterResponse.badRequest(null); + } + + // We must check if the client is using the right identity. + client = clientRegistry.findByRegistrationId(deregisterRequest.getRegistrationID()); + authId = deregisterRequest.getRegistrationID(); + if (client == null) { + return DeregisterResponse.notFound(); + } + if (!isAuthorized(client.getEndpoint(), sender)) { + return DeregisterResponse.badRequest("forbidden"); + } + + /* + new Thread(new Runnable(){ + @Override + public void run() { + try{ + System.out.println("**************************** DISCONNECT FROM DEVICE MANAGEMENT SERVER [START] ****************************"); + + // 토큰화 + JSONObject token = Tokenization.makesTokenForDisconnect(authId, client); + + // 커넥션 + Connector conn = Connector.getInstance().connect(); + conn.sendRequest(token); + JSONObject result = conn.getResponse(); + + System.out.println("**************************** DISCONNECT FROM DEVICE MANAGEMENT SERVER [END] ****************************"); + + isConnected = false; + } catch(Exception e) { + e.printStackTrace(); + } + } + }).start(); + */ + + Client unregistered = clientRegistry.deregisterClient(deregisterRequest.getRegistrationID()); + if (unregistered != null) { + return DeregisterResponse.success(); + } else { + LOG.debug("Invalid deregistration"); + return DeregisterResponse.notFound(); + } + + + } + + + + private static String createRegistrationId() { + return RandomStringUtils.random(10, true, true); + } + + /** + * Return true if the client with the given lightweight M2M endPoint is authorized to communicate with the given + * security parameters. + * + * @param lwM2mEndPointName the lightweight M2M endPoint name + * @param clientIdentity the identity at TLS level + * @return true if device get authorization + */ + private boolean isAuthorized(String lwM2mEndPointName, Identity clientIdentity) { + // do we have security information for this client? + SecurityInfo expectedSecurityInfo = securityStore.getByEndpoint(lwM2mEndPointName); + if( expectedSecurityInfo != null ){ + authId = expectedSecurityInfo.getIdentity(); + authPwd = Util.byteArrayToHex(expectedSecurityInfo.getPreSharedKey()); + } + return SecurityCheck.checkSecurityInfo(lwM2mEndPointName, clientIdentity, expectedSecurityInfo); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/request/LwM2mRequestSender.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/request/LwM2mRequestSender.java index 6a60919..3a5927a 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/request/LwM2mRequestSender.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/request/LwM2mRequestSender.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Bosch Software Innovations GmbH - extension of ticket based asynchronous call. - *******************************************************************************/ -package org.eclipse.leshan.server.request; - -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.response.ResponseListener; - -public interface LwM2mRequestSender { - - /** - * @Deprecated Synchronous send of a message will not be supported in the future. It is replaced by - * {@link #send(Client, String, DownlinkRequest)} - */ - @Deprecated - T send(Client destination, DownlinkRequest request, Long timeout) - throws InterruptedException; - - /** - * @Deprecated Asynchronous send of a message with a callback will not be supported in the future. It is replaced by - * {@link #send(Client, String, DownlinkRequest)} - */ - @Deprecated - void send(Client destination, DownlinkRequest request, - ResponseCallback responseCallback, ErrorCallback errorCallback); - - /** - * sends a Lightweight M2M request asynchronously and uses the requestTicket to correlate the response from a LWM2M - * Client. - * - * @param destination registration meta data of a LWM2M client. - * @param requestTicket a globally unique identifier for correlating the response - * @param request an instance of downlink request. - * @param instance of LwM2mResponse - */ - void send(Client destination, String requestTicket, DownlinkRequest request); - - /** - * adds the listener for the given LWM2M client. This method shall be used to re-register a listener for already - * sent messages or pending messages. - * - * @param listener global listener for handling the responses from a LWM2M client. - */ - void addResponseListener(ResponseListener listener); - - /** - * removes the given instance of response listener from LWM2M Sender's list of response listeners. - * - * @param listener target listener to be removed. - */ - void removeResponseListener(ResponseListener listener); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Bosch Software Innovations GmbH - extension of ticket based asynchronous call. + *******************************************************************************/ +package org.eclipse.leshan.server.request; + +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.response.ResponseListener; + +public interface LwM2mRequestSender { + + /** + * @Deprecated Synchronous send of a message will not be supported in the future. It is replaced by + * {@link #send(Client, String, DownlinkRequest)} + */ + @Deprecated + T send(Client destination, DownlinkRequest request, Long timeout) + throws InterruptedException; + + /** + * @Deprecated Asynchronous send of a message with a callback will not be supported in the future. It is replaced by + * {@link #send(Client, String, DownlinkRequest)} + */ + @Deprecated + void send(Client destination, DownlinkRequest request, + ResponseCallback responseCallback, ErrorCallback errorCallback); + + /** + * sends a Lightweight M2M request asynchronously and uses the requestTicket to correlate the response from a LWM2M + * Client. + * + * @param destination registration meta data of a LWM2M client. + * @param requestTicket a globally unique identifier for correlating the response + * @param request an instance of downlink request. + * @param instance of LwM2mResponse + */ + void send(Client destination, String requestTicket, DownlinkRequest request); + + /** + * adds the listener for the given LWM2M client. This method shall be used to re-register a listener for already + * sent messages or pending messages. + * + * @param listener global listener for handling the responses from a LWM2M client. + */ + void addResponseListener(ResponseListener listener); + + /** + * removes the given instance of response listener from LWM2M Sender's list of response listeners. + * + * @param listener target listener to be removed. + */ + void removeResponseListener(ResponseListener listener); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseListener.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseListener.java index 3c9f9c3..01265c0 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseListener.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseListener.java @@ -1,42 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2016 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Bosch Software Innovations GmbH - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.response; - -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * The listener is responsible for handling all the success and error responses for a given requestTicket. - */ -public interface ResponseListener { - - /** - * this method is invoked when a response is received from LWM2M Client correlated by the request ticket. - * - * @param clientEndpoint unique identifier of the LWM2M client - * @param requestTicket globally unique identifier used to correlate the response to the orginial request - * @param response from LWM2M client - */ - void onResponse(String clientEndpoint, String requestTicket, LwM2mResponse response); - - /** - * this method is invoked when a an error response is received from LWM2M Client correlated by the request ticket. - * - * @param clientEndpoint unique identifier of the LWM2M client - * @param requestTicket globally unique identifier used to correlate the response to the orginial request - * @param exception error from LWM2M client - */ - void onError(String clientEndpoint, String requestTicket, Exception exception); -} +/******************************************************************************* + * Copyright (c) 2016 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Bosch Software Innovations GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.response; + +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * The listener is responsible for handling all the success and error responses for a given requestTicket. + */ +public interface ResponseListener { + + /** + * this method is invoked when a response is received from LWM2M Client correlated by the request ticket. + * + * @param clientEndpoint unique identifier of the LWM2M client + * @param requestTicket globally unique identifier used to correlate the response to the orginial request + * @param response from LWM2M client + */ + void onResponse(String clientEndpoint, String requestTicket, LwM2mResponse response); + + /** + * this method is invoked when a an error response is received from LWM2M Client correlated by the request ticket. + * + * @param clientEndpoint unique identifier of the LWM2M client + * @param requestTicket globally unique identifier used to correlate the response to the orginial request + * @param exception error from LWM2M client + */ + void onError(String clientEndpoint, String requestTicket, Exception exception); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseProcessingTask.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseProcessingTask.java index 0c840df..cdad5f1 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseProcessingTask.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/response/ResponseProcessingTask.java @@ -1,103 +1,103 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.response; - -import java.util.Collection; - -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A response processing task is responsible for calling back the registered listeners with response or error result. - * - */ -public class ResponseProcessingTask implements Runnable { - - private final Logger LOG = LoggerFactory.getLogger(ResponseProcessingTask.class); - - private final Exception exception; - private final boolean hasException; - private final LwM2mResponse response; - private final Collection responseListeners; - private final String endpoint; - private final String requestTicket; - - /** - * Creates a new task for processing response on an ordinary response result. - * - * @param clientEndpoint - * @param request request being processed - * @param responseContext response context map for mapping response ID to the callback - * @param response response to propagate - */ - public ResponseProcessingTask(String clientEndpoint, String requestTicket, - Collection responseListeners, LwM2mResponse response) { - this.requestTicket = requestTicket; - this.exception = null; - this.hasException = false; - this.responseListeners = responseListeners; - this.response = response; - this.endpoint = clientEndpoint; - } - - /** - * Creates a new task for processing response on exception. - * - * @param clientEndpoint - * @param request request being processed - * @param responseListeners response context map for mapping response ID to the callback - * @param exception exception to propagate - */ - public ResponseProcessingTask(String clientEndpoint, String requestTicket, - Collection responseListeners, Exception exception) { - this.requestTicket = requestTicket; - this.exception = exception; - this.responseListeners = responseListeners; - this.hasException = true; - this.response = null; - this.endpoint = clientEndpoint; - } - - @Override - public void run() { - try { - executeAction(); - } catch (Exception e) { - LOG.info("error while executing runnable", e); - throw new RuntimeException(e); - } - } - - private void executeAction() { - LOG.trace("response processing for {}", requestTicket); - - for (ResponseListener listener : responseListeners) { - if (listener != null) { - if (hasException) { - LOG.debug("invoke response listener for requestTicket {} with exception {}", requestTicket, - exception); - listener.onError(endpoint, requestTicket, exception); - } else { - LOG.trace("invoke response listener for requestTicket {} with response {}", requestTicket, - response); - listener.onResponse(endpoint, requestTicket, response); - } - } - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.response; + +import java.util.Collection; + +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A response processing task is responsible for calling back the registered listeners with response or error result. + * + */ +public class ResponseProcessingTask implements Runnable { + + private final Logger LOG = LoggerFactory.getLogger(ResponseProcessingTask.class); + + private final Exception exception; + private final boolean hasException; + private final LwM2mResponse response; + private final Collection responseListeners; + private final String endpoint; + private final String requestTicket; + + /** + * Creates a new task for processing response on an ordinary response result. + * + * @param clientEndpoint + * @param request request being processed + * @param responseContext response context map for mapping response ID to the callback + * @param response response to propagate + */ + public ResponseProcessingTask(String clientEndpoint, String requestTicket, + Collection responseListeners, LwM2mResponse response) { + this.requestTicket = requestTicket; + this.exception = null; + this.hasException = false; + this.responseListeners = responseListeners; + this.response = response; + this.endpoint = clientEndpoint; + } + + /** + * Creates a new task for processing response on exception. + * + * @param clientEndpoint + * @param request request being processed + * @param responseListeners response context map for mapping response ID to the callback + * @param exception exception to propagate + */ + public ResponseProcessingTask(String clientEndpoint, String requestTicket, + Collection responseListeners, Exception exception) { + this.requestTicket = requestTicket; + this.exception = exception; + this.responseListeners = responseListeners; + this.hasException = true; + this.response = null; + this.endpoint = clientEndpoint; + } + + @Override + public void run() { + try { + executeAction(); + } catch (Exception e) { + LOG.info("error while executing runnable", e); + throw new RuntimeException(e); + } + } + + private void executeAction() { + LOG.trace("response processing for {}", requestTicket); + + for (ResponseListener listener : responseListeners) { + if (listener != null) { + if (hasException) { + LOG.debug("invoke response listener for requestTicket {} with exception {}", requestTicket, + exception); + listener.onError(endpoint, requestTicket, exception); + } else { + LOG.trace("invoke response listener for requestTicket {} with response {}", requestTicket, + response); + listener.onResponse(endpoint, requestTicket, response); + } + } + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/BootstrapSecurityStore.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/BootstrapSecurityStore.java index 42d94f7..56bdc2f 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/BootstrapSecurityStore.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/BootstrapSecurityStore.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -import java.util.List; - -public interface BootstrapSecurityStore { - - /** - * Returns all acceptable security information for a given end-point. - * - * @param endpoint the client end-point - * @return the security information of null if not found. - */ - List getAllByEndpoint(String endpoint); - - /** - * Returns the security information for an identity. - * - * @param identity of the client - * @return the security information of null if not found. - */ - SecurityInfo getByIdentity(String identity); -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +import java.util.List; + +public interface BootstrapSecurityStore { + + /** + * Returns all acceptable security information for a given end-point. + * + * @param endpoint the client end-point + * @return the security information of null if not found. + */ + List getAllByEndpoint(String endpoint); + + /** + * Returns the security information for an identity. + * + * @param identity of the client + * @return the security information of null if not found. + */ + SecurityInfo getByIdentity(String identity); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/NonUniqueSecurityInfoException.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/NonUniqueSecurityInfoException.java index 5e8eb52..78ce1ff 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/NonUniqueSecurityInfoException.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/NonUniqueSecurityInfoException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -public class NonUniqueSecurityInfoException extends Exception { - - private static final long serialVersionUID = 1L; - - /** - * Constructs a {@code NonUniqueSecurityInfoException} with the specified message and root cause. - * - * @param msg the detail message - * @param t the root cause - */ - public NonUniqueSecurityInfoException(String msg, Throwable t) { - super(msg, t); - } - - /** - * Constructs a {@code NonUniqueSecurityInfoException} with the specified message and no root cause. - * - * @param msg the detail message - */ - public NonUniqueSecurityInfoException(String msg) { - super(msg); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +public class NonUniqueSecurityInfoException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Constructs a {@code NonUniqueSecurityInfoException} with the specified message and root cause. + * + * @param msg the detail message + * @param t the root cause + */ + public NonUniqueSecurityInfoException(String msg, Throwable t) { + super(msg, t); + } + + /** + * Constructs a {@code NonUniqueSecurityInfoException} with the specified message and no root cause. + * + * @param msg the detail message + */ + public NonUniqueSecurityInfoException(String msg) { + super(msg); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityCheck.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityCheck.java index 959bb6e..65f1f06 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityCheck.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityCheck.java @@ -1,162 +1,162 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -import java.security.PublicKey; -import java.util.List; - -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.util.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SecurityCheck { - - private static final Logger LOG = LoggerFactory.getLogger(SecurityCheck.class); - - /** - * Return true if any of the securityInfos is valid for the given endpoint and client identity. - * - * @see #checkSecurityInfo(String, Identity, SecurityInfo) - * - * @param endpoint - * @param clientIdentity - * @param securityInfos - * - */ - public static boolean checkSecurityInfos(String endpoint, Identity clientIdentity, - List securityInfos) { - // if this is a secure end-point, we must check that the registering client is using the right identity. - if (clientIdentity.isSecure()) { - if (securityInfos == null || securityInfos.isEmpty()) { - LOG.warn("Client '{}' without security info try to connect through the secure endpoint", endpoint); - return false; - } else { - for (SecurityInfo securityInfo : securityInfos) { - if (checkSecurityInfo(endpoint, clientIdentity, securityInfo)) { - return true; - } - } - return false; - } - } else if (securityInfos != null && !securityInfos.isEmpty()) { - LOG.warn("Client '{}' must connect using DTLS", endpoint); - return false; - } - return true; - } - - /** - * Validates security info against a known endpoint and identity. - * - * @param endpoint - * @param clientIdentity - * @param securityInfo - * @return true if the security info are valid. - */ - public static boolean checkSecurityInfo(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { - - // if this is a secure end-point, we must check that the registering client is using the right identity. - if (clientIdentity.isSecure()) { - if (securityInfo == null) { - - LOG.warn("Client '{}' without security info try to connect through the secure endpoint", endpoint); - return false; - - } else if (clientIdentity.isPSK()) { - - return checkPskIdentity(endpoint, clientIdentity, securityInfo); - - } else if (clientIdentity.isRPK()) { - - return checkRpkIdentity(endpoint, clientIdentity, securityInfo); - - } else if (clientIdentity.isX509()) { - - return checkX509Identity(endpoint, clientIdentity, securityInfo); - - } else { - LOG.warn("Unable to authenticate client '{}': unknown authentication mode", endpoint); - return false; - } - } else { - if (securityInfo != null) { - LOG.warn("Client '{}' must connect using DTLS", endpoint); - return false; - } - } - return true; - } - - private static boolean checkPskIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { - // Manage PSK authentication - // ---------------------------------------------------- - String pskIdentity = clientIdentity.getPskIdentity(); - LOG.debug("Registration request received using the secure endpoint with identity {}", pskIdentity); - - if (pskIdentity == null || !pskIdentity.equals(securityInfo.getIdentity())) { - LOG.warn("Invalid identity for client '{}': expected '{}' but was '{}'", endpoint, - securityInfo.getIdentity(), pskIdentity); - return false; - } else { - LOG.debug("Authenticated client '{}' using DTLS PSK", endpoint); - return true; - } - } - - private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { - // Manage RPK authentication - // ---------------------------------------------------- - PublicKey publicKey = clientIdentity.getRawPublicKey(); - if (LOG.isDebugEnabled()) { - LOG.debug("Registration request received using the secure endpoint with rpk '{}'", - Hex.encodeHexString(publicKey.getEncoded())); - } - - if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) { - if (LOG.isWarnEnabled()) { - LOG.warn("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint, - Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()), - Hex.encodeHexString(publicKey.getEncoded())); - } - return false; - } else { - LOG.debug("authenticated client '{}' using DTLS RPK", endpoint); - return true; - } - } - - private static boolean checkX509Identity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { - // Manage X509 certificate authentication - // ---------------------------------------------------- - String x509CommonName = clientIdentity.getX509CommonName(); - LOG.debug("Registration request received using the secure endpoint with X509 identity {}", x509CommonName); - - if (!securityInfo.useX509Cert()) { - LOG.warn("Client '{}' is not supposed to use X509 certificate to authenticate", endpoint); - return false; - } - - if (!x509CommonName.equals(endpoint)) { - LOG.warn("Invalid certificate common name for client '{}': expected \n'{}'\n but was \n'{}'", endpoint, - endpoint, x509CommonName); - return false; - } else { - LOG.debug("authenticated client '{}' using DTLS X509 certificates", endpoint); - return true; - } - } -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +import java.security.PublicKey; +import java.util.List; + +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.util.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SecurityCheck { + + private static final Logger LOG = LoggerFactory.getLogger(SecurityCheck.class); + + /** + * Return true if any of the securityInfos is valid for the given endpoint and client identity. + * + * @see #checkSecurityInfo(String, Identity, SecurityInfo) + * + * @param endpoint + * @param clientIdentity + * @param securityInfos + * + */ + public static boolean checkSecurityInfos(String endpoint, Identity clientIdentity, + List securityInfos) { + // if this is a secure end-point, we must check that the registering client is using the right identity. + if (clientIdentity.isSecure()) { + if (securityInfos == null || securityInfos.isEmpty()) { + LOG.warn("Client '{}' without security info try to connect through the secure endpoint", endpoint); + return false; + } else { + for (SecurityInfo securityInfo : securityInfos) { + if (checkSecurityInfo(endpoint, clientIdentity, securityInfo)) { + return true; + } + } + return false; + } + } else if (securityInfos != null && !securityInfos.isEmpty()) { + LOG.warn("Client '{}' must connect using DTLS", endpoint); + return false; + } + return true; + } + + /** + * Validates security info against a known endpoint and identity. + * + * @param endpoint + * @param clientIdentity + * @param securityInfo + * @return true if the security info are valid. + */ + public static boolean checkSecurityInfo(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { + + // if this is a secure end-point, we must check that the registering client is using the right identity. + if (clientIdentity.isSecure()) { + if (securityInfo == null) { + + LOG.warn("Client '{}' without security info try to connect through the secure endpoint", endpoint); + return false; + + } else if (clientIdentity.isPSK()) { + + return checkPskIdentity(endpoint, clientIdentity, securityInfo); + + } else if (clientIdentity.isRPK()) { + + return checkRpkIdentity(endpoint, clientIdentity, securityInfo); + + } else if (clientIdentity.isX509()) { + + return checkX509Identity(endpoint, clientIdentity, securityInfo); + + } else { + LOG.warn("Unable to authenticate client '{}': unknown authentication mode", endpoint); + return false; + } + } else { + if (securityInfo != null) { + LOG.warn("Client '{}' must connect using DTLS", endpoint); + return false; + } + } + return true; + } + + private static boolean checkPskIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { + // Manage PSK authentication + // ---------------------------------------------------- + String pskIdentity = clientIdentity.getPskIdentity(); + LOG.debug("Registration request received using the secure endpoint with identity {}", pskIdentity); + + if (pskIdentity == null || !pskIdentity.equals(securityInfo.getIdentity())) { + LOG.warn("Invalid identity for client '{}': expected '{}' but was '{}'", endpoint, + securityInfo.getIdentity(), pskIdentity); + return false; + } else { + LOG.debug("Authenticated client '{}' using DTLS PSK", endpoint); + return true; + } + } + + private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { + // Manage RPK authentication + // ---------------------------------------------------- + PublicKey publicKey = clientIdentity.getRawPublicKey(); + if (LOG.isDebugEnabled()) { + LOG.debug("Registration request received using the secure endpoint with rpk '{}'", + Hex.encodeHexString(publicKey.getEncoded())); + } + + if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) { + if (LOG.isWarnEnabled()) { + LOG.warn("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint, + Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()), + Hex.encodeHexString(publicKey.getEncoded())); + } + return false; + } else { + LOG.debug("authenticated client '{}' using DTLS RPK", endpoint); + return true; + } + } + + private static boolean checkX509Identity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) { + // Manage X509 certificate authentication + // ---------------------------------------------------- + String x509CommonName = clientIdentity.getX509CommonName(); + LOG.debug("Registration request received using the secure endpoint with X509 identity {}", x509CommonName); + + if (!securityInfo.useX509Cert()) { + LOG.warn("Client '{}' is not supposed to use X509 certificate to authenticate", endpoint); + return false; + } + + if (!x509CommonName.equals(endpoint)) { + LOG.warn("Invalid certificate common name for client '{}': expected \n'{}'\n but was \n'{}'", endpoint, + endpoint, x509CommonName); + return false; + } else { + LOG.debug("authenticated client '{}' using DTLS X509 certificates", endpoint); + return true; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityInfo.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityInfo.java index d2234dd..ed374df 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityInfo.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityInfo.java @@ -1,149 +1,149 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -import java.io.Serializable; -import java.security.PublicKey; -import java.util.Arrays; - -import org.eclipse.leshan.util.Validate; - -/** - * The security info for a client. - *

- * The following security modes are supported: - *

    - *
  • Pre-Shared Key: an identity and a key are needed
  • - *
  • Raw Public Key Certificate: a public key is needed
  • - *
  • X509 Certificate: an X509 certificate is needed
  • - *
- */ -public class SecurityInfo implements Serializable { - - private static final long serialVersionUID = 1L; - - // the client end-point - private final String endpoint; - - // PSK - private final String identity; - private final byte[] preSharedKey; - - private final PublicKey rawPublicKey; - - private final boolean useX509Cert; - - private SecurityInfo(String endpoint, String identity, byte[] preSharedKey, PublicKey rawPublicKey, - boolean useX509Cert) { - Validate.notEmpty(endpoint); - this.endpoint = endpoint; - this.identity = identity; - this.preSharedKey = preSharedKey; - this.rawPublicKey = rawPublicKey; - this.useX509Cert = useX509Cert; - } - - /** - * Construct a {@link SecurityInfo} when using DTLS with Pre-Shared Keys. - */ - public static SecurityInfo newPreSharedKeyInfo(String endpoint, String identity, byte[] preSharedKey) { - Validate.notEmpty(identity); - Validate.notNull(preSharedKey); - return new SecurityInfo(endpoint, identity, preSharedKey, null, false); - } - - /** - * Construct a {@link SecurityInfo} when using DTLS with Raw Public Key (RPK). - */ - public static SecurityInfo newRawPublicKeyInfo(String endpoint, PublicKey rawPublicKey) { - Validate.notNull(rawPublicKey); - return new SecurityInfo(endpoint, null, null, rawPublicKey, false); - } - - /** - * Construct a {@link SecurityInfo} when using DTLS with an X509 Certificate. - */ - public static SecurityInfo newX509CertInfo(String endpoint) { - return new SecurityInfo(endpoint, null, null, null, true); - } - - public String getEndpoint() { - return endpoint; - } - - /** - * The Pre-Shared-Key identity - */ - public String getIdentity() { - return identity; - } - - public byte[] getPreSharedKey() { - return preSharedKey; - } - - public PublicKey getRawPublicKey() { - return rawPublicKey; - } - - public boolean useX509Cert() { - return useX509Cert; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((endpoint == null) ? 0 : endpoint.hashCode()); - result = prime * result + ((identity == null) ? 0 : identity.hashCode()); - result = prime * result + Arrays.hashCode(preSharedKey); - result = prime * result + ((rawPublicKey == null) ? 0 : rawPublicKey.hashCode()); - result = prime * result + (useX509Cert ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SecurityInfo other = (SecurityInfo) obj; - if (endpoint == null) { - if (other.endpoint != null) - return false; - } else if (!endpoint.equals(other.endpoint)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - if (!Arrays.equals(preSharedKey, other.preSharedKey)) - return false; - if (rawPublicKey == null) { - if (other.rawPublicKey != null) - return false; - } else if (!rawPublicKey.equals(other.rawPublicKey)) - return false; - if (useX509Cert != other.useX509Cert) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +import java.io.Serializable; +import java.security.PublicKey; +import java.util.Arrays; + +import org.eclipse.leshan.util.Validate; + +/** + * The security info for a client. + *

+ * The following security modes are supported: + *

    + *
  • Pre-Shared Key: an identity and a key are needed
  • + *
  • Raw Public Key Certificate: a public key is needed
  • + *
  • X509 Certificate: an X509 certificate is needed
  • + *
+ */ +public class SecurityInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + // the client end-point + private final String endpoint; + + // PSK + private final String identity; + private final byte[] preSharedKey; + + private final PublicKey rawPublicKey; + + private final boolean useX509Cert; + + private SecurityInfo(String endpoint, String identity, byte[] preSharedKey, PublicKey rawPublicKey, + boolean useX509Cert) { + Validate.notEmpty(endpoint); + this.endpoint = endpoint; + this.identity = identity; + this.preSharedKey = preSharedKey; + this.rawPublicKey = rawPublicKey; + this.useX509Cert = useX509Cert; + } + + /** + * Construct a {@link SecurityInfo} when using DTLS with Pre-Shared Keys. + */ + public static SecurityInfo newPreSharedKeyInfo(String endpoint, String identity, byte[] preSharedKey) { + Validate.notEmpty(identity); + Validate.notNull(preSharedKey); + return new SecurityInfo(endpoint, identity, preSharedKey, null, false); + } + + /** + * Construct a {@link SecurityInfo} when using DTLS with Raw Public Key (RPK). + */ + public static SecurityInfo newRawPublicKeyInfo(String endpoint, PublicKey rawPublicKey) { + Validate.notNull(rawPublicKey); + return new SecurityInfo(endpoint, null, null, rawPublicKey, false); + } + + /** + * Construct a {@link SecurityInfo} when using DTLS with an X509 Certificate. + */ + public static SecurityInfo newX509CertInfo(String endpoint) { + return new SecurityInfo(endpoint, null, null, null, true); + } + + public String getEndpoint() { + return endpoint; + } + + /** + * The Pre-Shared-Key identity + */ + public String getIdentity() { + return identity; + } + + public byte[] getPreSharedKey() { + return preSharedKey; + } + + public PublicKey getRawPublicKey() { + return rawPublicKey; + } + + public boolean useX509Cert() { + return useX509Cert; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((endpoint == null) ? 0 : endpoint.hashCode()); + result = prime * result + ((identity == null) ? 0 : identity.hashCode()); + result = prime * result + Arrays.hashCode(preSharedKey); + result = prime * result + ((rawPublicKey == null) ? 0 : rawPublicKey.hashCode()); + result = prime * result + (useX509Cert ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SecurityInfo other = (SecurityInfo) obj; + if (endpoint == null) { + if (other.endpoint != null) + return false; + } else if (!endpoint.equals(other.endpoint)) + return false; + if (identity == null) { + if (other.identity != null) + return false; + } else if (!identity.equals(other.identity)) + return false; + if (!Arrays.equals(preSharedKey, other.preSharedKey)) + return false; + if (rawPublicKey == null) { + if (other.rawPublicKey != null) + return false; + } else if (!rawPublicKey.equals(other.rawPublicKey)) + return false; + if (useX509Cert != other.useX509Cert) + return false; + return true; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityRegistry.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityRegistry.java index 17e307b..bc3597f 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityRegistry.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityRegistry.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Collection; - -public interface SecurityRegistry extends SecurityStore { - - /** - * Returns the {@link SecurityInfo} for all end-points. - * - * @return an unmodifiable collection of {@link SecurityInfo} - */ - Collection getAll(); - - /** - * Registers new security information for a client end-point. - * - * @param info the new security information - * @return the {@link SecurityInfo} previously stored for the end-point or null if there was no - * security information for the end-point. - * @throws NonUniqueSecurityInfoException if some identifiers (PSK identity, RPK public key...) are not unique among - * all end-points. - */ - SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException; - - /** - * Removes the security information for a given end-point. - * - * @param endpoint the client end-point - * @return the removed {@link SecurityInfo} or null if no info for the end-point. - */ - SecurityInfo remove(String endpoint); - - /** - * Returns the Server Public Key - */ - PublicKey getServerPublicKey(); - - /** - * Returns the Server Private Key - */ - PrivateKey getServerPrivateKey(); - - /** - * Returns the Server X509 Certificate Chain - */ - X509Certificate[] getServerX509CertChain(); - - /** - * Returns the trusted certificates - */ - Certificate[] getTrustedCertificates(); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Collection; + +public interface SecurityRegistry extends SecurityStore { + + /** + * Returns the {@link SecurityInfo} for all end-points. + * + * @return an unmodifiable collection of {@link SecurityInfo} + */ + Collection getAll(); + + /** + * Registers new security information for a client end-point. + * + * @param info the new security information + * @return the {@link SecurityInfo} previously stored for the end-point or null if there was no + * security information for the end-point. + * @throws NonUniqueSecurityInfoException if some identifiers (PSK identity, RPK public key...) are not unique among + * all end-points. + */ + SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException; + + /** + * Removes the security information for a given end-point. + * + * @param endpoint the client end-point + * @return the removed {@link SecurityInfo} or null if no info for the end-point. + */ + SecurityInfo remove(String endpoint); + + /** + * Returns the Server Public Key + */ + PublicKey getServerPublicKey(); + + /** + * Returns the Server Private Key + */ + PrivateKey getServerPrivateKey(); + + /** + * Returns the Server X509 Certificate Chain + */ + X509Certificate[] getServerX509CertChain(); + + /** + * Returns the trusted certificates + */ + Certificate[] getTrustedCertificates(); +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityStore.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityStore.java index 040ac24..4a8ff6a 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityStore.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/security/SecurityStore.java @@ -1,39 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.security; - -/** - * A store for {@link SecurityInfo}. - */ -public interface SecurityStore { - - /** - * Returns the security information for a given end-point. - * - * @param endpoint the client end-point - * @return the security information of null if not found. - */ - SecurityInfo getByEndpoint(String endpoint); - - /** - * Returns the security information for a identity. - * - * @param identity of the client - * @return the security information of null if not found. - */ - SecurityInfo getByIdentity(String identity); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.security; + +/** + * A store for {@link SecurityInfo}. + */ +public interface SecurityStore { + + /** + * Returns the security information for a given end-point. + * + * @param endpoint the client end-point + * @return the security information of null if not found. + */ + SecurityInfo getByEndpoint(String endpoint); + + /** + * Returns the security information for a identity. + * + * @param identity of the client + * @return the security information of null if not found. + */ + SecurityInfo getByIdentity(String identity); + +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/bootstrap/BootstrapHandlerTest.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/bootstrap/BootstrapHandlerTest.java index b989857..11ecdc6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/bootstrap/BootstrapHandlerTest.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/bootstrap/BootstrapHandlerTest.java @@ -1,166 +1,166 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.bootstrap; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.net.InetSocketAddress; -import java.util.concurrent.Executor; - -import org.eclipse.leshan.ResponseCode; -import org.eclipse.leshan.core.request.BootstrapDeleteRequest; -import org.eclipse.leshan.core.request.BootstrapFinishRequest; -import org.eclipse.leshan.core.request.BootstrapRequest; -import org.eclipse.leshan.core.request.BootstrapWriteRequest; -import org.eclipse.leshan.core.request.DownlinkRequest; -import org.eclipse.leshan.core.request.Identity; -import org.eclipse.leshan.core.response.BootstrapDeleteResponse; -import org.eclipse.leshan.core.response.BootstrapFinishResponse; -import org.eclipse.leshan.core.response.BootstrapResponse; -import org.eclipse.leshan.core.response.BootstrapWriteResponse; -import org.eclipse.leshan.core.response.ErrorCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.junit.Test; - -public class BootstrapHandlerTest { - - @Test - public void error_if_not_authorized() { - final BootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(false); - - BootstrapHandler bsHandler = new BootstrapHandler(null, null, bsSessionManager); - BootstrapResponse bootstrapResponse = bsHandler - .bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); - assertEquals(ResponseCode.BAD_REQUEST, bootstrapResponse.getCode()); - } - - @Test - public void notifies_at_end_of_successful_bootstrap() { - final MockBootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(true); - final LwM2mBootstrapRequestSender requestSender = new MockRequestSender(true); - - final BootstrapStore bsStore = new BootstrapStore() { - @Override - public BootstrapConfig getBootstrap(String endpoint) { - return new BootstrapConfig(); - } - }; - - BootstrapHandler bsHandler = new BootstrapHandler(bsStore, requestSender, bsSessionManager, new Executor() { - - @Override - public void execute(Runnable command) { - command.run(); - } - }); - - bsHandler.bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); - - assertTrue(bsSessionManager.endWasCalled()); - } - - @Test - public void does_not_notifies_at_end_of_failed_bootstrap() { - final MockBootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(true); - final LwM2mBootstrapRequestSender requestSender = new MockRequestSender(false); - - final BootstrapStore bsStore = new BootstrapStore() { - @Override - public BootstrapConfig getBootstrap(String endpoint) { - return new BootstrapConfig(); - } - }; - - BootstrapHandler bsHandler = new BootstrapHandler(bsStore, requestSender, bsSessionManager, new Executor() { - - @Override - public void execute(Runnable command) { - command.run(); - } - }); - - bsHandler.bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); - - assertFalse(bsSessionManager.endWasCalled()); - } - - private class MockRequestSender implements LwM2mBootstrapRequestSender { - - private boolean success; - - public MockRequestSender(boolean success) { - this.success = success; - } - - @Override - public T send(String clientEndpoint, InetSocketAddress client, boolean secure, - DownlinkRequest request, Long timeout) throws InterruptedException { - return null; - } - - @SuppressWarnings("unchecked") - @Override - public void send(String clientEndpoint, InetSocketAddress client, boolean secure, - DownlinkRequest request, ResponseCallback responseCallback, ErrorCallback errorCallback) { - if (request instanceof BootstrapDeleteRequest) { - ((ResponseCallback) responseCallback) - .onResponse(BootstrapDeleteResponse.success()); - } else if (request instanceof BootstrapWriteRequest) { - ((ResponseCallback) responseCallback) - .onResponse(BootstrapWriteResponse.success()); - } else if (request instanceof BootstrapFinishRequest) { - if (this.success) { - ((ResponseCallback) responseCallback) - .onResponse(BootstrapFinishResponse.success()); - } else { - ((ResponseCallback) responseCallback) - .onResponse(BootstrapFinishResponse.internalServerError("failed")); - } - } - } - } - - private class MockBootstrapSessionManager implements BootstrapSessionManager { - - private boolean authorized; - private BootstrapSession endBsSession = null; - - public MockBootstrapSessionManager(boolean authorized) { - this.authorized = authorized; - } - - @Override - public BootstrapSession begin(String endpoint, Identity clientIdentity) { - return new BootstrapSession(endpoint, clientIdentity, authorized); - } - - @Override - public void end(BootstrapSession bsSession) { - endBsSession = bsSession; - } - - public boolean endWasCalled() { - return this.endBsSession != null; - } - - @Override - public void failed(BootstrapSession bsSession, DownlinkRequest request, Exception e) { - } - } -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.bootstrap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executor; + +import org.eclipse.leshan.ResponseCode; +import org.eclipse.leshan.core.request.BootstrapDeleteRequest; +import org.eclipse.leshan.core.request.BootstrapFinishRequest; +import org.eclipse.leshan.core.request.BootstrapRequest; +import org.eclipse.leshan.core.request.BootstrapWriteRequest; +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.Identity; +import org.eclipse.leshan.core.response.BootstrapDeleteResponse; +import org.eclipse.leshan.core.response.BootstrapFinishResponse; +import org.eclipse.leshan.core.response.BootstrapResponse; +import org.eclipse.leshan.core.response.BootstrapWriteResponse; +import org.eclipse.leshan.core.response.ErrorCallback; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ResponseCallback; +import org.junit.Test; + +public class BootstrapHandlerTest { + + @Test + public void error_if_not_authorized() { + final BootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(false); + + BootstrapHandler bsHandler = new BootstrapHandler(null, null, bsSessionManager); + BootstrapResponse bootstrapResponse = bsHandler + .bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); + assertEquals(ResponseCode.BAD_REQUEST, bootstrapResponse.getCode()); + } + + @Test + public void notifies_at_end_of_successful_bootstrap() { + final MockBootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(true); + final LwM2mBootstrapRequestSender requestSender = new MockRequestSender(true); + + final BootstrapStore bsStore = new BootstrapStore() { + @Override + public BootstrapConfig getBootstrap(String endpoint) { + return new BootstrapConfig(); + } + }; + + BootstrapHandler bsHandler = new BootstrapHandler(bsStore, requestSender, bsSessionManager, new Executor() { + + @Override + public void execute(Runnable command) { + command.run(); + } + }); + + bsHandler.bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); + + assertTrue(bsSessionManager.endWasCalled()); + } + + @Test + public void does_not_notifies_at_end_of_failed_bootstrap() { + final MockBootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(true); + final LwM2mBootstrapRequestSender requestSender = new MockRequestSender(false); + + final BootstrapStore bsStore = new BootstrapStore() { + @Override + public BootstrapConfig getBootstrap(String endpoint) { + return new BootstrapConfig(); + } + }; + + BootstrapHandler bsHandler = new BootstrapHandler(bsStore, requestSender, bsSessionManager, new Executor() { + + @Override + public void execute(Runnable command) { + command.run(); + } + }); + + bsHandler.bootstrap(Identity.psk(new InetSocketAddress(4242), "pskdentity"), new BootstrapRequest("enpoint")); + + assertFalse(bsSessionManager.endWasCalled()); + } + + private class MockRequestSender implements LwM2mBootstrapRequestSender { + + private boolean success; + + public MockRequestSender(boolean success) { + this.success = success; + } + + @Override + public T send(String clientEndpoint, InetSocketAddress client, boolean secure, + DownlinkRequest request, Long timeout) throws InterruptedException { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public void send(String clientEndpoint, InetSocketAddress client, boolean secure, + DownlinkRequest request, ResponseCallback responseCallback, ErrorCallback errorCallback) { + if (request instanceof BootstrapDeleteRequest) { + ((ResponseCallback) responseCallback) + .onResponse(BootstrapDeleteResponse.success()); + } else if (request instanceof BootstrapWriteRequest) { + ((ResponseCallback) responseCallback) + .onResponse(BootstrapWriteResponse.success()); + } else if (request instanceof BootstrapFinishRequest) { + if (this.success) { + ((ResponseCallback) responseCallback) + .onResponse(BootstrapFinishResponse.success()); + } else { + ((ResponseCallback) responseCallback) + .onResponse(BootstrapFinishResponse.internalServerError("failed")); + } + } + } + } + + private class MockBootstrapSessionManager implements BootstrapSessionManager { + + private boolean authorized; + private BootstrapSession endBsSession = null; + + public MockBootstrapSessionManager(boolean authorized) { + this.authorized = authorized; + } + + @Override + public BootstrapSession begin(String endpoint, Identity clientIdentity) { + return new BootstrapSession(endpoint, clientIdentity, authorized); + } + + @Override + public void end(BootstrapSession bsSession) { + endBsSession = bsSession; + } + + public boolean endWasCalled() { + return this.endBsSession != null; + } + + @Override + public void failed(BootstrapSession bsSession, DownlinkRequest request, Exception e) { + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/client/ClientSortObjectTest.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/client/ClientSortObjectTest.java index a2b1317..782e8e6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/client/ClientSortObjectTest.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/client/ClientSortObjectTest.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ - -package org.eclipse.leshan.server.client; - -import java.net.Inet4Address; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - -import org.eclipse.leshan.LinkObject; -import org.junit.Assert; -import org.junit.Test; - -public class ClientSortObjectTest { - - @Test - public void sort_link_object_on_get() throws UnknownHostException { - LinkObject[] objs = new LinkObject[3]; - objs[0] = new LinkObject("/0/1024/2"); - objs[1] = new LinkObject("/0/2"); - objs[2] = null; - - Client.Builder builder = new Client.Builder("registrationId", "endpoint", Inet4Address.getByName("127.0.0.1"), - 1, new InetSocketAddress(212)).objectLinks(objs); - - Client c = builder.build(); - - LinkObject[] res = c.getSortedObjectLinks(); - Assert.assertEquals(3, res.length); - Assert.assertNull(res[0]); - Assert.assertEquals("/0/2", res[1].getUrl()); - Assert.assertEquals("/0/1024/2", res[2].getUrl()); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ + +package org.eclipse.leshan.server.client; + +import java.net.Inet4Address; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +import org.eclipse.leshan.LinkObject; +import org.junit.Assert; +import org.junit.Test; + +public class ClientSortObjectTest { + + @Test + public void sort_link_object_on_get() throws UnknownHostException { + LinkObject[] objs = new LinkObject[3]; + objs[0] = new LinkObject("/0/1024/2"); + objs[1] = new LinkObject("/0/2"); + objs[2] = null; + + Client.Builder builder = new Client.Builder("registrationId", "endpoint", Inet4Address.getByName("127.0.0.1"), + 1, new InetSocketAddress(212)).objectLinks(objs); + + Client c = builder.build(); + + LinkObject[] res = c.getSortedObjectLinks(); + Assert.assertEquals(3, res.length); + Assert.assertNull(res[0]); + Assert.assertEquals("/0/2", res[1].getUrl()); + Assert.assertEquals("/0/1024/2", res[2].getUrl()); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/BasicTestSupport.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/BasicTestSupport.java index 828c785..6d2daa6 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/BasicTestSupport.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/BasicTestSupport.java @@ -1,39 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - -import org.eclipse.leshan.server.client.Client; - -public class BasicTestSupport { - - public Client client; - public InetAddress destination; - public int destinationPort = 5000; - public InetSocketAddress registrationAddress; - - public void givenASimpleClient() throws UnknownHostException { - registrationAddress = InetSocketAddress.createUnresolved("localhost", 5683); - - Client.Builder builder = new Client.Builder("ID", "urn:client", InetAddress.getLocalHost(), 10000, - registrationAddress); - - client = builder.build(); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +import org.eclipse.leshan.server.client.Client; + +public class BasicTestSupport { + + public Client client; + public InetAddress destination; + public int destinationPort = 5000; + public InetSocketAddress registrationAddress; + + public void givenASimpleClient() throws UnknownHostException { + registrationAddress = InetSocketAddress.createUnresolved("localhost", 5683); + + Client.Builder builder = new Client.Builder("ID", "urn:client", InetAddress.getLocalHost(), 10000, + registrationAddress); + + client = builder.build(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/ClientRegistryImplTest.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/ClientRegistryImplTest.java index c5478d3..f81b0bd 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/ClientRegistryImplTest.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/impl/ClientRegistryImplTest.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.impl; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.core.request.BindingMode; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.client.ClientUpdate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class ClientRegistryImplTest { - - ClientRegistryImpl registry; - String ep = "urn:endpoint"; - InetAddress address; - int port = 23452; - Long lifetime = 10000L; - String sms = "0171-32423545"; - BindingMode binding = BindingMode.UQS; - LinkObject[] objectLinks = LinkObject.parse("".getBytes(org.eclipse.leshan.util.Charsets.UTF_8)); - String registrationId = "4711"; - Client client; - - @Before - public void setUp() throws Exception { - address = InetAddress.getLocalHost(); - registry = new ClientRegistryImpl(); - } - - @Test - public void update_registration_keeps_properties_unchanged() { - givenASimpleClient(lifetime); - registry.registerClient(client); - - ClientUpdate update = new ClientUpdate(registrationId, address, port, null, null, null, null); - Client updatedClient = registry.updateClient(update); - Assert.assertEquals(lifetime, updatedClient.getLifeTimeInSec()); - Assert.assertSame(binding, updatedClient.getBindingMode()); - Assert.assertEquals(sms, updatedClient.getSmsNumber()); - - Client registeredClient = registry.get(ep); - Assert.assertEquals(lifetime, registeredClient.getLifeTimeInSec()); - Assert.assertSame(binding, registeredClient.getBindingMode()); - Assert.assertEquals(sms, registeredClient.getSmsNumber()); - } - - @Test - public void client_registration_sets_time_to_live() { - givenASimpleClient(lifetime); - registry.registerClient(client); - Assert.assertTrue(client.isAlive()); - } - - @Test - public void update_registration_to_extend_time_to_live() { - givenASimpleClient(0L); - registry.registerClient(client); - Assert.assertFalse(client.isAlive()); - - ClientUpdate update = new ClientUpdate(registrationId, address, port, lifetime, null, null, null); - Client updatedClient = registry.updateClient(update); - Assert.assertTrue(updatedClient.isAlive()); - - Client registeredClient = registry.get(ep); - Assert.assertTrue(registeredClient.isAlive()); - } - - private void givenASimpleClient(Long lifetime) { - - Client.Builder builder = new Client.Builder(registrationId, ep, address, port, - InetSocketAddress.createUnresolved("localhost", 5683)); - - client = builder.lifeTimeInSec(lifetime).smsNumber(sms).bindingMode(binding).objectLinks(objectLinks).build(); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.impl; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.core.request.BindingMode; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.client.ClientUpdate; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ClientRegistryImplTest { + + ClientRegistryImpl registry; + String ep = "urn:endpoint"; + InetAddress address; + int port = 23452; + Long lifetime = 10000L; + String sms = "0171-32423545"; + BindingMode binding = BindingMode.UQS; + LinkObject[] objectLinks = LinkObject.parse("".getBytes(org.eclipse.leshan.util.Charsets.UTF_8)); + String registrationId = "4711"; + Client client; + + @Before + public void setUp() throws Exception { + address = InetAddress.getLocalHost(); + registry = new ClientRegistryImpl(); + } + + @Test + public void update_registration_keeps_properties_unchanged() { + givenASimpleClient(lifetime); + registry.registerClient(client); + + ClientUpdate update = new ClientUpdate(registrationId, address, port, null, null, null, null); + Client updatedClient = registry.updateClient(update); + Assert.assertEquals(lifetime, updatedClient.getLifeTimeInSec()); + Assert.assertSame(binding, updatedClient.getBindingMode()); + Assert.assertEquals(sms, updatedClient.getSmsNumber()); + + Client registeredClient = registry.get(ep); + Assert.assertEquals(lifetime, registeredClient.getLifeTimeInSec()); + Assert.assertSame(binding, registeredClient.getBindingMode()); + Assert.assertEquals(sms, registeredClient.getSmsNumber()); + } + + @Test + public void client_registration_sets_time_to_live() { + givenASimpleClient(lifetime); + registry.registerClient(client); + Assert.assertTrue(client.isAlive()); + } + + @Test + public void update_registration_to_extend_time_to_live() { + givenASimpleClient(0L); + registry.registerClient(client); + Assert.assertFalse(client.isAlive()); + + ClientUpdate update = new ClientUpdate(registrationId, address, port, lifetime, null, null, null); + Client updatedClient = registry.updateClient(update); + Assert.assertTrue(updatedClient.isAlive()); + + Client registeredClient = registry.get(ep); + Assert.assertTrue(registeredClient.isAlive()); + } + + private void givenASimpleClient(Long lifetime) { + + Client.Builder builder = new Client.Builder(registrationId, ep, address, port, + InetSocketAddress.createUnresolved("localhost", 5683)); + + client = builder.lifeTimeInSec(lifetime).smsNumber(sms).bindingMode(binding).objectLinks(objectLinks).build(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/queue/impl/ClientStatusTrackerTest.java b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/queue/impl/ClientStatusTrackerTest.java index 4fd56c4..b6a35ad 100644 --- a/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/queue/impl/ClientStatusTrackerTest.java +++ b/si-modules/LWM2M_IPE_Server/leshan-server-core/src/test/java/org/eclipse/leshan/server/queue/impl/ClientStatusTrackerTest.java @@ -1,72 +1,72 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - *

- * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - *

- * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - *

- * Contributors: - * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.server.queue.impl; - -import static junit.framework.TestCase.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -/** - * Tests whether client state transitions are handled properly in {@link ClientStatusTracker} - */ -public class ClientStatusTrackerTest { - public static final String ENDPOINT = "urn:testEndpoint"; - private ClientStatusTracker instanceUnderTest; - - @Before - public void setup() throws Exception { - instanceUnderTest = new ClientStatusTracker(); - } - - @Test - public void set_client_unreachable() throws Exception { - // clients initial starting state. - assertTrue(instanceUnderTest.setClientReachable(ENDPOINT)); - // set state of the client in Receiving before setting unreachable. - assertTrue(instanceUnderTest.startClientReceiving(ENDPOINT)); - // now set the client as unreachable. - instanceUnderTest.setClientUnreachable(ENDPOINT); - } - - @Test - public void set_client_reachable() throws Exception { - assertTrue("Expected client status set to reachable", instanceUnderTest.setClientReachable(ENDPOINT)); - } - - @Test - public void set_client_unreachable_not_allowed() throws Exception { - assertTrue(instanceUnderTest.setClientReachable(ENDPOINT)); - instanceUnderTest.clearClientState(ENDPOINT); - // Now when client state is not known, state cannot be set to unreachable. - assertFalse(instanceUnderTest.setClientUnreachable(ENDPOINT)); - } - - @Test - public void set_start_client_receiving() throws Exception { - instanceUnderTest.setClientReachable(ENDPOINT); - assertTrue("Expected client status set to receiving", instanceUnderTest.startClientReceiving(ENDPOINT)); - } - - @Test - public void set_stop_client_receiving() throws Exception { - instanceUnderTest.setClientReachable(ENDPOINT); - instanceUnderTest.startClientReceiving(ENDPOINT); - assertTrue("Expected client status set to reachable", instanceUnderTest.stopClientReceiving(ENDPOINT)); - } +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + *

+ * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + *

+ * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + *

+ * Contributors: + * Balasubramanian Azhagappan (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.server.queue.impl; + +import static junit.framework.TestCase.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +/** + * Tests whether client state transitions are handled properly in {@link ClientStatusTracker} + */ +public class ClientStatusTrackerTest { + public static final String ENDPOINT = "urn:testEndpoint"; + private ClientStatusTracker instanceUnderTest; + + @Before + public void setup() throws Exception { + instanceUnderTest = new ClientStatusTracker(); + } + + @Test + public void set_client_unreachable() throws Exception { + // clients initial starting state. + assertTrue(instanceUnderTest.setClientReachable(ENDPOINT)); + // set state of the client in Receiving before setting unreachable. + assertTrue(instanceUnderTest.startClientReceiving(ENDPOINT)); + // now set the client as unreachable. + instanceUnderTest.setClientUnreachable(ENDPOINT); + } + + @Test + public void set_client_reachable() throws Exception { + assertTrue("Expected client status set to reachable", instanceUnderTest.setClientReachable(ENDPOINT)); + } + + @Test + public void set_client_unreachable_not_allowed() throws Exception { + assertTrue(instanceUnderTest.setClientReachable(ENDPOINT)); + instanceUnderTest.clearClientState(ENDPOINT); + // Now when client state is not known, state cannot be set to unreachable. + assertFalse(instanceUnderTest.setClientUnreachable(ENDPOINT)); + } + + @Test + public void set_start_client_receiving() throws Exception { + instanceUnderTest.setClientReachable(ENDPOINT); + assertTrue("Expected client status set to receiving", instanceUnderTest.startClientReceiving(ENDPOINT)); + } + + @Test + public void set_stop_client_receiving() throws Exception { + instanceUnderTest.setClientReachable(ENDPOINT); + instanceUnderTest.startClientReceiving(ENDPOINT); + assertTrue("Expected client status set to reachable", instanceUnderTest.stopClientReceiving(ENDPOINT)); + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/.classpath b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/.classpath deleted file mode 100644 index baf96d0..0000000 --- a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/Californium.properties b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/Californium.properties index f1ecb65..9fa55ca 100644 --- a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/Californium.properties +++ b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/Californium.properties @@ -1,42 +1,42 @@ -#Californium CoAP Properties file -#Tue Aug 02 15:06:02 KST 2016 -HTTP_SERVER_SOCKET_BUFFER_SIZE=8192 -UDP_CONNECTOR_OUT_CAPACITY=2147483647 -CONGESTION_CONTROL_ALGORITHM=Cocoa -USE_CONGESTION_CONTROL=false -ACK_TIMEOUT=2000 -NOTIFICATION_CHECK_INTERVAL_COUNT=100 -MAX_MESSAGE_SIZE=1024 -DEDUPLICATOR=DEDUPLICATOR_MARK_AND_SWEEP -COAP_PORT=5683 -ACK_TIMEOUT_SCALE=2.0 -PREFERRED_BLOCK_SIZE=512 -NETWORK_STAGE_RECEIVER_THREAD_COUNT=4 -PROTOCOL_STAGE_THREAD_COUNT=4 -MAX_TRANSMIT_WAIT=93000 -USE_STRICT_RESPONSE_MATCHING=false -UDP_CONNECTOR_RECEIVE_BUFFER=0 -EXCHANGE_LIFETIME=247000 -HTTP_SERVER_SOCKET_TIMEOUT=100000 -CROP_ROTATION_PERIOD=2000 -UDP_CONNECTOR_DATAGRAM_SIZE=2048 -MAX_RETRANSMIT=4 -NOTIFICATION_CHECK_INTERVAL=86400000 -LEISURE=5000 -HTTP_CACHE_RESPONSE_MAX_AGE=86400 -BLOCKWISE_STATUS_LIFETIME=600000 -UDP_CONNECTOR_SEND_BUFFER=0 -HEALTH_STATUS_PRINT_LEVEL=FINEST -NETWORK_STAGE_SENDER_THREAD_COUNT=4 -NON_LIFETIME=145000 -TOKEN_SIZE_LIMIT=8 -HTTP_PORT=8080 -MARK_AND_SWEEP_INTERVAL=10000 -HEALTH_STATUS_INTERVAL=60 -ACK_RANDOM_FACTOR=1.5 -NSTART=1 -USE_RANDOM_MID_START=true -HTTP_CACHE_SIZE=32 -PROBING_RATE=1.0 -NOTIFICATION_REREGISTRATION_BACKOFF=2000 -COAP_SECURE_PORT=5684 +#Californium CoAP Properties file +#Tue Aug 02 15:06:02 KST 2016 +HTTP_SERVER_SOCKET_BUFFER_SIZE=8192 +UDP_CONNECTOR_OUT_CAPACITY=2147483647 +CONGESTION_CONTROL_ALGORITHM=Cocoa +USE_CONGESTION_CONTROL=false +ACK_TIMEOUT=2000 +NOTIFICATION_CHECK_INTERVAL_COUNT=100 +MAX_MESSAGE_SIZE=1024 +DEDUPLICATOR=DEDUPLICATOR_MARK_AND_SWEEP +COAP_PORT=5683 +ACK_TIMEOUT_SCALE=2.0 +PREFERRED_BLOCK_SIZE=512 +NETWORK_STAGE_RECEIVER_THREAD_COUNT=4 +PROTOCOL_STAGE_THREAD_COUNT=4 +MAX_TRANSMIT_WAIT=93000 +USE_STRICT_RESPONSE_MATCHING=false +UDP_CONNECTOR_RECEIVE_BUFFER=0 +EXCHANGE_LIFETIME=247000 +HTTP_SERVER_SOCKET_TIMEOUT=100000 +CROP_ROTATION_PERIOD=2000 +UDP_CONNECTOR_DATAGRAM_SIZE=2048 +MAX_RETRANSMIT=4 +NOTIFICATION_CHECK_INTERVAL=86400000 +LEISURE=5000 +HTTP_CACHE_RESPONSE_MAX_AGE=86400 +BLOCKWISE_STATUS_LIFETIME=600000 +UDP_CONNECTOR_SEND_BUFFER=0 +HEALTH_STATUS_PRINT_LEVEL=FINEST +NETWORK_STAGE_SENDER_THREAD_COUNT=4 +NON_LIFETIME=145000 +TOKEN_SIZE_LIMIT=8 +HTTP_PORT=8080 +MARK_AND_SWEEP_INTERVAL=10000 +HEALTH_STATUS_INTERVAL=60 +ACK_RANDOM_FACTOR=1.5 +NSTART=1 +USE_RANDOM_MID_START=true +HTTP_CACHE_SIZE=32 +PROBING_RATE=1.0 +NOTIFICATION_REREGISTRATION_BACKOFF=2000 +COAP_SECURE_PORT=5684 diff --git a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/config.xml b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/config.xml index a0fd467..873aaa4 100644 --- a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/config.xml +++ b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/config.xml @@ -1,53 +1,53 @@ - - - - - - - 10.10.0.23 - - 8080 - 8081 - - no - herit-in - herit-cse - 10 - - - - yes - - 10.10.0.23 - 8089 - - - - - no - 10.10.0.23 - - 5683 - 5684 - 8085 - - - 10 - - - - - no - - + + + + + + + 10.10.0.23 + + 8080 + 8081 + + no + herit-in + herit-cse + 10 + + + + yes + + 10.10.0.23 + 8089 + + + + + no + 10.10.0.23 + + 5683 + 5684 + 8085 + + + 10 + + + + + no + + \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/Lwm2mServerMain.java b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/Lwm2mServerMain.java index 629d445..bec14b2 100644 --- a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/Lwm2mServerMain.java +++ b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/Lwm2mServerMain.java @@ -1,173 +1,173 @@ -package net.herit.iot.lwm2m.dms; - -import java.math.BigInteger; -import java.net.BindException; -import java.net.URI; -import java.security.AlgorithmParameters; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.ECGenParameterSpec; -import java.security.spec.ECParameterSpec; -import java.security.spec.ECPoint; -import java.security.spec.ECPrivateKeySpec; -import java.security.spec.ECPublicKeySpec; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.InvalidParameterSpecException; -import java.security.spec.KeySpec; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeDecoder; -import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeEncoder; -import org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder; -import org.eclipse.leshan.server.Lwm2mServerConfig; -import org.eclipse.leshan.server.californium.LeshanServerBuilder; -import org.eclipse.leshan.server.californium.impl.LeshanServer; -import org.eclipse.leshan.server.client.ClientRegistry; -import org.eclipse.leshan.server.demo.cluster.RedisClientRegistry; -import org.eclipse.leshan.server.demo.cluster.RedisObservationRegistry; -import org.eclipse.leshan.server.demo.cluster.RedisSecurityRegistry; - -import net.herit.iot.lwm2m.dms.servlet.ApiServlet; -import net.herit.iot.lwm2m.dms.servlet.ClientServlet; -import net.herit.iot.lwm2m.dms.servlet.EventServlet; -import net.herit.iot.lwm2m.dms.servlet.ObjectSpecServlet; -import net.herit.iot.lwm2m.dms.servlet.SecurityServlet; -import org.eclipse.leshan.server.impl.SecurityRegistryImpl; -import org.eclipse.leshan.server.model.LwM2mModelProvider; -import org.eclipse.leshan.server.model.StandardModelProvider; -import org.eclipse.leshan.util.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.util.Pool; - -public class Lwm2mServerMain { - private static final Logger LOG = LoggerFactory.getLogger(Lwm2mServerMain.class); - - private final static String USAGE = "java -jar leshan-server-demo.jar [OPTION]"; - private final static String FOOTER = "All options could be passed using environment variables.(using long option name in uppercase)"; - - public static void main(String[] args) throws Exception { - try { -// /Lwm2mServerConfig config = Lwm2mServerConfig.getInstance(); - - String localAddress = Lwm2mServerConfig.getInstance().getIpeIp(); - int localPort = Lwm2mServerConfig.getInstance().getIpePortNormal(); - String secureLocalAddress = Lwm2mServerConfig.getInstance().getIpeIp(); - int secureLocalPort = Lwm2mServerConfig.getInstance().getIpePortSecure(); - int webPort = Lwm2mServerConfig.getInstance().getIpePortWeb(); - String redisUrl = null; - - createAndStartServer(webPort, localAddress, localPort, secureLocalAddress, secureLocalPort, redisUrl); - } catch (BindException e) { - e.printStackTrace(); - } catch (Exception e) { - LOG.error("Jetty stopped with unexcepted error ...", e); - } - - } - - public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, - int secureLocalPort, String redisUrl) throws Exception { - // Prepare LWM2M server - LeshanServerBuilder builder = new LeshanServerBuilder(); - builder.setLocalAddress(localAddress, localPort); - builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort); - builder.setEncoder(new DefaultLwM2mNodeEncoder()); - LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder(); - builder.setDecoder(decoder); - - // connect to redis if needed - Pool jedis = null; - if (redisUrl != null) { - // TODO: support sentinel pool and make pool configurable - jedis = new JedisPool(new URI(redisUrl)); - } - - // Get public and private server key - PrivateKey privateKey = null; - PublicKey publicKey = null; - try { - // Get point values - byte[] publicX = Hex - .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray()); - byte[] publicY = Hex - .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray()); - byte[] privateS = Hex - .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray()); - - // Get Elliptic Curve Parameter spec for secp256r1 - AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); - algoParameters.init(new ECGenParameterSpec("secp256r1")); - ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); - - // Create key specs - KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), - parameterSpec); - KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); - - // Get keys - publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); - - LwM2mModelProvider modelProvider = new StandardModelProvider(); - builder.setObjectModelProvider(modelProvider); - - if (jedis == null) { - // in memory security registry (with file persistence) - builder.setSecurityRegistry(new SecurityRegistryImpl(privateKey, publicKey)); - } else { - // use Redis - ClientRegistry clientRegistry = new RedisClientRegistry(jedis); - builder.setSecurityRegistry(new RedisSecurityRegistry(jedis, privateKey, publicKey)); - builder.setClientRegistry(clientRegistry); - builder.setObservationRegistry( - new RedisObservationRegistry(jedis, clientRegistry, modelProvider, decoder)); - } - } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) { - LOG.error("Unable to initialize RPK.", e); - System.exit(-1); - } - - // Create and start LWM2M server - LeshanServer lwServer = builder.build(); - - // Now prepare Jetty - Server server = new Server(webPort); - WebAppContext root = new WebAppContext(); - root.setContextPath("/"); - root.setResourceBase(Lwm2mServerMain.class.getClassLoader().getResource("webapp").toExternalForm()); - root.setParentLoaderPriority(true); - server.setHandler(root); - - // Create Servlet - EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort()); - ServletHolder eventServletHolder = new ServletHolder(eventServlet); - root.addServlet(eventServletHolder, "/event/*"); - - ServletHolder clientServletHolder = new ServletHolder( - new ClientServlet(lwServer, lwServer.getSecureAddress().getPort())); - root.addServlet(clientServletHolder, "/api/clients/*"); - - ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(lwServer.getSecurityRegistry())); - root.addServlet(securityServletHolder, "/api/security/*"); - - ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet(lwServer.getModelProvider())); - root.addServlet(objectSpecServletHolder, "/api/objectspecs/*"); - - ServletHolder apitServletHolder = new ServletHolder(new ApiServlet(lwServer, lwServer.getSecureAddress().getPort())); - root.addServlet(apitServletHolder, "/api/hdm/*"); - - // Start Jetty & Leshan - lwServer.start(); - server.start(); - LOG.info("Web server started at {}.", server.getURI()); - } - -} +package net.herit.iot.lwm2m.dms; + +import java.math.BigInteger; +import java.net.BindException; +import java.net.URI; +import java.security.AlgorithmParameters; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPrivateKeySpec; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.InvalidParameterSpecException; +import java.security.spec.KeySpec; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.webapp.WebAppContext; +import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeDecoder; +import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeEncoder; +import org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder; +import org.eclipse.leshan.server.Lwm2mServerConfig; +import org.eclipse.leshan.server.californium.LeshanServerBuilder; +import org.eclipse.leshan.server.californium.impl.LeshanServer; +import org.eclipse.leshan.server.client.ClientRegistry; +import org.eclipse.leshan.server.demo.cluster.RedisClientRegistry; +import org.eclipse.leshan.server.demo.cluster.RedisObservationRegistry; +import org.eclipse.leshan.server.demo.cluster.RedisSecurityRegistry; + +import net.herit.iot.lwm2m.dms.servlet.ApiServlet; +import net.herit.iot.lwm2m.dms.servlet.ClientServlet; +import net.herit.iot.lwm2m.dms.servlet.EventServlet; +import net.herit.iot.lwm2m.dms.servlet.ObjectSpecServlet; +import net.herit.iot.lwm2m.dms.servlet.SecurityServlet; +import org.eclipse.leshan.server.impl.SecurityRegistryImpl; +import org.eclipse.leshan.server.model.LwM2mModelProvider; +import org.eclipse.leshan.server.model.StandardModelProvider; +import org.eclipse.leshan.util.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.util.Pool; + +public class Lwm2mServerMain { + private static final Logger LOG = LoggerFactory.getLogger(Lwm2mServerMain.class); + + private final static String USAGE = "java -jar leshan-server-demo.jar [OPTION]"; + private final static String FOOTER = "All options could be passed using environment variables.(using long option name in uppercase)"; + + public static void main(String[] args) throws Exception { + try { +// /Lwm2mServerConfig config = Lwm2mServerConfig.getInstance(); + + String localAddress = Lwm2mServerConfig.getInstance().getIpeIp(); + int localPort = Lwm2mServerConfig.getInstance().getIpePortNormal(); + String secureLocalAddress = Lwm2mServerConfig.getInstance().getIpeIp(); + int secureLocalPort = Lwm2mServerConfig.getInstance().getIpePortSecure(); + int webPort = Lwm2mServerConfig.getInstance().getIpePortWeb(); + String redisUrl = null; + + createAndStartServer(webPort, localAddress, localPort, secureLocalAddress, secureLocalPort, redisUrl); + } catch (BindException e) { + e.printStackTrace(); + } catch (Exception e) { + LOG.error("Jetty stopped with unexcepted error ...", e); + } + + } + + public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, + int secureLocalPort, String redisUrl) throws Exception { + // Prepare LWM2M server + LeshanServerBuilder builder = new LeshanServerBuilder(); + builder.setLocalAddress(localAddress, localPort); + builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort); + builder.setEncoder(new DefaultLwM2mNodeEncoder()); + LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder(); + builder.setDecoder(decoder); + + // connect to redis if needed + Pool jedis = null; + if (redisUrl != null) { + // TODO: support sentinel pool and make pool configurable + jedis = new JedisPool(new URI(redisUrl)); + } + + // Get public and private server key + PrivateKey privateKey = null; + PublicKey publicKey = null; + try { + // Get point values + byte[] publicX = Hex + .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray()); + byte[] publicY = Hex + .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray()); + byte[] privateS = Hex + .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray()); + + // Get Elliptic Curve Parameter spec for secp256r1 + AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); + algoParameters.init(new ECGenParameterSpec("secp256r1")); + ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); + + // Create key specs + KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), + parameterSpec); + KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); + + // Get keys + publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); + privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); + + LwM2mModelProvider modelProvider = new StandardModelProvider(); + builder.setObjectModelProvider(modelProvider); + + if (jedis == null) { + // in memory security registry (with file persistence) + builder.setSecurityRegistry(new SecurityRegistryImpl(privateKey, publicKey)); + } else { + // use Redis + ClientRegistry clientRegistry = new RedisClientRegistry(jedis); + builder.setSecurityRegistry(new RedisSecurityRegistry(jedis, privateKey, publicKey)); + builder.setClientRegistry(clientRegistry); + builder.setObservationRegistry( + new RedisObservationRegistry(jedis, clientRegistry, modelProvider, decoder)); + } + } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) { + LOG.error("Unable to initialize RPK.", e); + System.exit(-1); + } + + // Create and start LWM2M server + LeshanServer lwServer = builder.build(); + + // Now prepare Jetty + Server server = new Server(webPort); + WebAppContext root = new WebAppContext(); + root.setContextPath("/"); + root.setResourceBase(Lwm2mServerMain.class.getClassLoader().getResource("webapp").toExternalForm()); + root.setParentLoaderPriority(true); + server.setHandler(root); + + // Create Servlet + EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort()); + ServletHolder eventServletHolder = new ServletHolder(eventServlet); + root.addServlet(eventServletHolder, "/event/*"); + + ServletHolder clientServletHolder = new ServletHolder( + new ClientServlet(lwServer, lwServer.getSecureAddress().getPort())); + root.addServlet(clientServletHolder, "/api/clients/*"); + + ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(lwServer.getSecurityRegistry())); + root.addServlet(securityServletHolder, "/api/security/*"); + + ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet(lwServer.getModelProvider())); + root.addServlet(objectSpecServletHolder, "/api/objectspecs/*"); + + ServletHolder apitServletHolder = new ServletHolder(new ApiServlet(lwServer, lwServer.getSecureAddress().getPort())); + root.addServlet(apitServletHolder, "/api/hdm/*"); + + // Start Jetty & Leshan + lwServer.start(); + server.start(); + LOG.info("Web server started at {}.", server.getURI()); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/servlet/ApiServlet.java b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/servlet/ApiServlet.java index 56e08b4..84778c3 100644 --- a/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/servlet/ApiServlet.java +++ b/si-modules/LWM2M_IPE_Server/lwm2m-server-dms/src/main/java/net/herit/iot/lwm2m/dms/servlet/ApiServlet.java @@ -1,509 +1,509 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package net.herit.iot.lwm2m.dms.servlet; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.core.request.DeleteRequest; -import org.eclipse.leshan.core.request.ExecuteRequest; -import org.eclipse.leshan.core.request.ObserveRequest; -import org.eclipse.leshan.core.request.ReadRequest; -import org.eclipse.leshan.core.request.WriteRequest; -import org.eclipse.leshan.core.request.WriteRequest.Mode; -import org.eclipse.leshan.core.request.exception.RequestFailedException; -import org.eclipse.leshan.core.request.exception.ResourceAccessException; -import org.eclipse.leshan.core.response.DeleteResponse; -import org.eclipse.leshan.core.response.ExecuteResponse; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ObserveResponse; -import org.eclipse.leshan.core.response.ReadResponse; -import org.eclipse.leshan.core.response.WriteResponse; -import org.eclipse.leshan.server.LwM2mServer; -import org.eclipse.leshan.server.client.Client; -import org.eclipse.leshan.server.extension.Util; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; - -import net.herit.iot.lwm2m.dms.servlet.json.ClientSerializer; -import net.herit.iot.lwm2m.dms.servlet.json.LwM2mNodeDeserializer; -import net.herit.iot.lwm2m.dms.servlet.json.LwM2mNodeSerializer; -import net.herit.iot.lwm2m.dms.servlet.json.ResponseSerializer; - -/** - * Service HTTP REST API calls. - */ -public class ApiServlet extends HttpServlet { - - private static final String FORMAT_PARAM = "format"; - - private static final Logger LOG = LoggerFactory.getLogger(ApiServlet.class); - - private static final long TIMEOUT = 5000; // ms - - private static final long serialVersionUID = 1L; - - private final LwM2mServer server; - - private final Gson gson; - - private JSONArray result; - - - public ApiServlet(LwM2mServer server, int securePort) { - this.server = server; - - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort)); - gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer()); - gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer()); - gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer()); - gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - this.gson = gsonBuilder.create(); - } - - - private JSONObject getRequestBody(HttpServletRequest req) { - // body - InputStream is = null; - ByteArrayOutputStream baos = null; - byte[] byteData = null; - JSONObject result = null; - try{ - is = req.getInputStream(); - baos = new ByteArrayOutputStream(); - byte[] byteBuffer = new byte[1024]; - int nLength = 0; - while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { - baos.write(byteBuffer, 0, nLength); - } - byteData = baos.toByteArray(); - result = new JSONObject(new String(byteData).replace("-", "0")); - } catch(Exception e){ - e.printStackTrace(); - } finally { - try{ - if(baos != null){ baos.close(); } - if(is != null){ is.close(); } - } catch(Exception e) { - e.printStackTrace(); - } - } - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - // all registered clients - if (req.getPathInfo() == null) { - Collection clients = server.getClientRegistry().allClients(); - - String json = this.gson.toJson(clients.toArray(new Client[] {})); - resp.setContentType("application/json"); - resp.getOutputStream().write(json.getBytes("UTF-8")); - resp.setStatus(HttpServletResponse.SC_OK); - return; - } - - String[] path = StringUtils.split(req.getPathInfo(), '/'); - if (path.length < 1) { - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path"); - return; - } - String clientEndpoint = path[0]; - - // /endPoint : get client - if (path.length == 1) { - Client client = server.getClientRegistry().get(clientEndpoint); - if (client != null) { - resp.setContentType("application/json"); - resp.getOutputStream().write(this.gson.toJson(client).getBytes("UTF-8")); - resp.setStatus(HttpServletResponse.SC_OK); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); - } - return; - } - - // /clients/endPoint/LWRequest : do LightWeight M2M read request on a given client. - try { - String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint); - Client client = server.getClientRegistry().get(clientEndpoint); - if (client != null) { - // get content format - String contentFormatParam = req.getParameter(FORMAT_PARAM); - ContentFormat contentFormat = contentFormatParam != null - ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null; - - // create & process request - ReadRequest request = new ReadRequest(contentFormat, target); - ReadResponse cResponse = server.send(client, request, TIMEOUT); - processDeviceResponse(req, resp, cResponse); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("No registered client with id '%s'", clientEndpoint).flush(); - } - } catch (IllegalArgumentException e) { - LOG.warn("Invalid request", e); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().append(e.getMessage()).flush(); - } catch (ResourceAccessException | RequestFailedException e) { - LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (InterruptedException e) { - LOG.warn("Thread Interrupted", e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - result = new JSONArray(); - - // end point - String endPoint = req.getPathInfo().substring(1); - - try { - JSONObject msg = getRequestBody(req); - JSONArray e = msg.getJSONArray("e"); - - if(msg.getString("o").equals("e")) { - String target = e.getJSONObject(0).getString("n"); - Client client = server.getClientRegistry().get(endPoint); - - if (client != null) { - // get content format - String contentFormatParam = req.getParameter(FORMAT_PARAM); - ContentFormat contentFormat = contentFormatParam != null - ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null; - - // create & process request - LwM2mNode node = extractLwM2mNode(target, req, e.getJSONObject(0).getString("sv").equals("ON")?"1":"0"); - WriteRequest request = new WriteRequest(Mode.REPLACE, contentFormat, target, node); - WriteResponse cResponse = server.send(client, request, TIMEOUT); - - String cRes = this.gson.toJson(cResponse); - JSONObject withUri = new JSONObject(cRes); - withUri.put("uri", target); - result.put(withUri); - processDeviceResponse(req, resp, result); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("No registered client with id '%s'", endPoint).flush(); - } - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - result = new JSONArray(); - - // end point - String endPoint = req.getPathInfo().substring(1); - - try { - JSONObject msg = getRequestBody(req); - JSONArray e = msg.getJSONArray("e"); - - if(msg.getString("o").equals("o")){ - // observe - observe(req, resp, e, endPoint); - - } else if(msg.getString("o").equals("r")) { - // read - read(req, resp, e, endPoint); - - } else if(msg.getString("o").equals("rb")) { - // reboot - execute(req, resp, msg, endPoint); - - } - - } catch (Exception e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - System.out.println("none of data"); - } - } - - private synchronized void read(HttpServletRequest req, HttpServletResponse resp, JSONArray resources, String endPoint) throws IOException{ - - result = new JSONArray(); - - for(int i=0; i -1 ){ - JSONObject content = withUri.getJSONObject("content"); - content.put("value", withUri.getJSONObject("content").getJSONObject("values").getString("0")); - withUri.put("content", content); - } - result.put(withUri); - - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("No registered client with id '%s'", endPoint).flush(); - } - } catch (IllegalArgumentException e) { - LOG.warn("Invalid request", e); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().append(e.getMessage()).flush(); - } catch (ResourceAccessException | RequestFailedException e) { - LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (InterruptedException e) { - LOG.warn("Thread Interrupted", e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - processDeviceResponse(req, resp, result); - - } - - private synchronized void observe(HttpServletRequest req, HttpServletResponse resp, JSONArray resources, String endPoint) throws JSONException, InterruptedException, IOException{ - - for(int i=0; i -1 ){ - JSONObject content = withUri.getJSONObject("content"); - content.put("value", withUri.getJSONObject("content").getJSONObject("values").getString("0")); - withUri.put("content", content); - } - result.put(withUri); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("no registered client with id '%s'", endPoint).flush(); - } - - } catch (IllegalArgumentException e) { - LOG.warn("Invalid request", e); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().append(e.getMessage()).flush(); - } catch (ResourceAccessException | RequestFailedException e) { - LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (InterruptedException e) { - LOG.warn("Thread Interrupted", e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - processDeviceResponse(req, resp, result); - } - - private synchronized void execute(HttpServletRequest req, HttpServletResponse resp, JSONObject msg, String endPoint) throws JSONException, InterruptedException, IOException{ - - String target = msg.getString("n"); - Client client = server.getClientRegistry().get(endPoint); - - if (client != null) { - - ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream())); - ExecuteResponse cResponse = server.send(client, request, TIMEOUT); - processDeviceResponse(req, resp, cResponse); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("no registered client with id '%s'", endPoint).flush(); - } - - } - - @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - String[] path = StringUtils.split(req.getPathInfo(), '/'); - String clientEndpoint = path[0]; - - // /clients/endPoint/LWRequest/observe : cancel observation for the given resource. - if (path.length >= 4 && "observe".equals(path[path.length - 1])) { - try { - String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0]; - Client client = server.getClientRegistry().get(clientEndpoint); - if (client != null) { - server.getObservationRegistry().cancelObservations(client, target); - resp.setStatus(HttpServletResponse.SC_OK); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); - } - } catch (IllegalArgumentException e) { - LOG.warn("Invalid request", e); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().append(e.getMessage()).flush(); - } catch (ResourceAccessException | RequestFailedException e) { - LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } - return; - } - - // /clients/endPoint/LWRequest/ : delete instance - try { - String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint); - Client client = server.getClientRegistry().get(clientEndpoint); - if (client != null) { - DeleteRequest request = new DeleteRequest(target); - DeleteResponse cResponse = server.send(client, request, TIMEOUT); - processDeviceResponse(req, resp, cResponse); - } else { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); - } - } catch (IllegalArgumentException e) { - LOG.warn("Invalid request", e); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().append(e.getMessage()).flush(); - } catch (ResourceAccessException | RequestFailedException e) { - LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } catch (InterruptedException e) { - LOG.warn("Interrupted request", e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append(e.getMessage()).flush(); - } - } - - private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, LwM2mResponse cResponse) - throws IOException { - String response = null; - if (cResponse == null) { - LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo())); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append("Request timeout").flush(); - } else { - response = this.gson.toJson(cResponse); - resp.setContentType("application/json"); - resp.getOutputStream().write(response.getBytes()); - resp.setStatus(HttpServletResponse.SC_OK); - } - } - - private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, JSONArray result) - throws IOException { - - String response = result.toString(); - System.out.println("resp : "+response); - if ( Util.isNoE(response) && result.length() == 0 ) { - LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo())); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().append("Request timeout").flush(); - } else { - resp.setContentType("application/json"); - resp.getOutputStream().write(response.getBytes()); - resp.setStatus(HttpServletResponse.SC_OK); - } - } - - private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req) throws IOException { - String contentType = StringUtils.substringBefore(req.getContentType(), ";"); - - if ("application/json".equals(contentType)) { - String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); - LwM2mNode node; - try { - node = gson.fromJson(content, LwM2mNode.class); - } catch (JsonSyntaxException e) { - throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e); - } - return node; - } else if ("text/plain".equals(contentType)) { - String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); - int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1)); - return LwM2mSingleResource.newStringResource(rscId, content); - } - throw new IllegalArgumentException("content type " + req.getContentType() + " not supported"); - } - - private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req, String content) throws IOException { - int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1)); - return LwM2mSingleResource.newStringResource(rscId, content); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package net.herit.iot.lwm2m.dms.servlet; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.core.request.DeleteRequest; +import org.eclipse.leshan.core.request.ExecuteRequest; +import org.eclipse.leshan.core.request.ObserveRequest; +import org.eclipse.leshan.core.request.ReadRequest; +import org.eclipse.leshan.core.request.WriteRequest; +import org.eclipse.leshan.core.request.WriteRequest.Mode; +import org.eclipse.leshan.core.request.exception.RequestFailedException; +import org.eclipse.leshan.core.request.exception.ResourceAccessException; +import org.eclipse.leshan.core.response.DeleteResponse; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ObserveResponse; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.response.WriteResponse; +import org.eclipse.leshan.server.LwM2mServer; +import org.eclipse.leshan.server.client.Client; +import org.eclipse.leshan.server.extension.Util; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; + +import net.herit.iot.lwm2m.dms.servlet.json.ClientSerializer; +import net.herit.iot.lwm2m.dms.servlet.json.LwM2mNodeDeserializer; +import net.herit.iot.lwm2m.dms.servlet.json.LwM2mNodeSerializer; +import net.herit.iot.lwm2m.dms.servlet.json.ResponseSerializer; + +/** + * Service HTTP REST API calls. + */ +public class ApiServlet extends HttpServlet { + + private static final String FORMAT_PARAM = "format"; + + private static final Logger LOG = LoggerFactory.getLogger(ApiServlet.class); + + private static final long TIMEOUT = 5000; // ms + + private static final long serialVersionUID = 1L; + + private final LwM2mServer server; + + private final Gson gson; + + private JSONArray result; + + + public ApiServlet(LwM2mServer server, int securePort) { + this.server = server; + + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort)); + gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer()); + gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer()); + gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer()); + gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + this.gson = gsonBuilder.create(); + } + + + private JSONObject getRequestBody(HttpServletRequest req) { + // body + InputStream is = null; + ByteArrayOutputStream baos = null; + byte[] byteData = null; + JSONObject result = null; + try{ + is = req.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] byteBuffer = new byte[1024]; + int nLength = 0; + while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { + baos.write(byteBuffer, 0, nLength); + } + byteData = baos.toByteArray(); + result = new JSONObject(new String(byteData).replace("-", "0")); + } catch(Exception e){ + e.printStackTrace(); + } finally { + try{ + if(baos != null){ baos.close(); } + if(is != null){ is.close(); } + } catch(Exception e) { + e.printStackTrace(); + } + } + + return result; + } + + /** + * {@inheritDoc} + */ + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + // all registered clients + if (req.getPathInfo() == null) { + Collection clients = server.getClientRegistry().allClients(); + + String json = this.gson.toJson(clients.toArray(new Client[] {})); + resp.setContentType("application/json"); + resp.getOutputStream().write(json.getBytes("UTF-8")); + resp.setStatus(HttpServletResponse.SC_OK); + return; + } + + String[] path = StringUtils.split(req.getPathInfo(), '/'); + if (path.length < 1) { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path"); + return; + } + String clientEndpoint = path[0]; + + // /endPoint : get client + if (path.length == 1) { + Client client = server.getClientRegistry().get(clientEndpoint); + if (client != null) { + resp.setContentType("application/json"); + resp.getOutputStream().write(this.gson.toJson(client).getBytes("UTF-8")); + resp.setStatus(HttpServletResponse.SC_OK); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); + } + return; + } + + // /clients/endPoint/LWRequest : do LightWeight M2M read request on a given client. + try { + String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint); + Client client = server.getClientRegistry().get(clientEndpoint); + if (client != null) { + // get content format + String contentFormatParam = req.getParameter(FORMAT_PARAM); + ContentFormat contentFormat = contentFormatParam != null + ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null; + + // create & process request + ReadRequest request = new ReadRequest(contentFormat, target); + ReadResponse cResponse = server.send(client, request, TIMEOUT); + processDeviceResponse(req, resp, cResponse); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("No registered client with id '%s'", clientEndpoint).flush(); + } + } catch (IllegalArgumentException e) { + LOG.warn("Invalid request", e); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().append(e.getMessage()).flush(); + } catch (ResourceAccessException | RequestFailedException e) { + LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (InterruptedException e) { + LOG.warn("Thread Interrupted", e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + result = new JSONArray(); + + // end point + String endPoint = req.getPathInfo().substring(1); + + try { + JSONObject msg = getRequestBody(req); + JSONArray e = msg.getJSONArray("e"); + + if(msg.getString("o").equals("e")) { + String target = e.getJSONObject(0).getString("n"); + Client client = server.getClientRegistry().get(endPoint); + + if (client != null) { + // get content format + String contentFormatParam = req.getParameter(FORMAT_PARAM); + ContentFormat contentFormat = contentFormatParam != null + ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null; + + // create & process request + LwM2mNode node = extractLwM2mNode(target, req, e.getJSONObject(0).getString("sv").equals("ON")?"1":"0"); + WriteRequest request = new WriteRequest(Mode.REPLACE, contentFormat, target, node); + WriteResponse cResponse = server.send(client, request, TIMEOUT); + + String cRes = this.gson.toJson(cResponse); + JSONObject withUri = new JSONObject(cRes); + withUri.put("uri", target); + result.put(withUri); + processDeviceResponse(req, resp, result); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("No registered client with id '%s'", endPoint).flush(); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + result = new JSONArray(); + + // end point + String endPoint = req.getPathInfo().substring(1); + + try { + JSONObject msg = getRequestBody(req); + JSONArray e = msg.getJSONArray("e"); + + if(msg.getString("o").equals("o")){ + // observe + observe(req, resp, e, endPoint); + + } else if(msg.getString("o").equals("r")) { + // read + read(req, resp, e, endPoint); + + } else if(msg.getString("o").equals("rb")) { + // reboot + execute(req, resp, msg, endPoint); + + } + + } catch (Exception e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + System.out.println("none of data"); + } + } + + private synchronized void read(HttpServletRequest req, HttpServletResponse resp, JSONArray resources, String endPoint) throws IOException{ + + result = new JSONArray(); + + for(int i=0; i -1 ){ + JSONObject content = withUri.getJSONObject("content"); + content.put("value", withUri.getJSONObject("content").getJSONObject("values").getString("0")); + withUri.put("content", content); + } + result.put(withUri); + + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("No registered client with id '%s'", endPoint).flush(); + } + } catch (IllegalArgumentException e) { + LOG.warn("Invalid request", e); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().append(e.getMessage()).flush(); + } catch (ResourceAccessException | RequestFailedException e) { + LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (InterruptedException e) { + LOG.warn("Thread Interrupted", e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + processDeviceResponse(req, resp, result); + + } + + private synchronized void observe(HttpServletRequest req, HttpServletResponse resp, JSONArray resources, String endPoint) throws JSONException, InterruptedException, IOException{ + + for(int i=0; i -1 ){ + JSONObject content = withUri.getJSONObject("content"); + content.put("value", withUri.getJSONObject("content").getJSONObject("values").getString("0")); + withUri.put("content", content); + } + result.put(withUri); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("no registered client with id '%s'", endPoint).flush(); + } + + } catch (IllegalArgumentException e) { + LOG.warn("Invalid request", e); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().append(e.getMessage()).flush(); + } catch (ResourceAccessException | RequestFailedException e) { + LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (InterruptedException e) { + LOG.warn("Thread Interrupted", e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + processDeviceResponse(req, resp, result); + } + + private synchronized void execute(HttpServletRequest req, HttpServletResponse resp, JSONObject msg, String endPoint) throws JSONException, InterruptedException, IOException{ + + String target = msg.getString("n"); + Client client = server.getClientRegistry().get(endPoint); + + if (client != null) { + + ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream())); + ExecuteResponse cResponse = server.send(client, request, TIMEOUT); + processDeviceResponse(req, resp, cResponse); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("no registered client with id '%s'", endPoint).flush(); + } + + } + + @Override + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + String[] path = StringUtils.split(req.getPathInfo(), '/'); + String clientEndpoint = path[0]; + + // /clients/endPoint/LWRequest/observe : cancel observation for the given resource. + if (path.length >= 4 && "observe".equals(path[path.length - 1])) { + try { + String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0]; + Client client = server.getClientRegistry().get(clientEndpoint); + if (client != null) { + server.getObservationRegistry().cancelObservations(client, target); + resp.setStatus(HttpServletResponse.SC_OK); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); + } + } catch (IllegalArgumentException e) { + LOG.warn("Invalid request", e); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().append(e.getMessage()).flush(); + } catch (ResourceAccessException | RequestFailedException e) { + LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } + return; + } + + // /clients/endPoint/LWRequest/ : delete instance + try { + String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint); + Client client = server.getClientRegistry().get(clientEndpoint); + if (client != null) { + DeleteRequest request = new DeleteRequest(target); + DeleteResponse cResponse = server.send(client, request, TIMEOUT); + processDeviceResponse(req, resp, cResponse); + } else { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush(); + } + } catch (IllegalArgumentException e) { + LOG.warn("Invalid request", e); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().append(e.getMessage()).flush(); + } catch (ResourceAccessException | RequestFailedException e) { + LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } catch (InterruptedException e) { + LOG.warn("Interrupted request", e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append(e.getMessage()).flush(); + } + } + + private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, LwM2mResponse cResponse) + throws IOException { + String response = null; + if (cResponse == null) { + LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo())); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append("Request timeout").flush(); + } else { + response = this.gson.toJson(cResponse); + resp.setContentType("application/json"); + resp.getOutputStream().write(response.getBytes()); + resp.setStatus(HttpServletResponse.SC_OK); + } + } + + private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, JSONArray result) + throws IOException { + + String response = result.toString(); + System.out.println("resp : "+response); + if ( Util.isNoE(response) && result.length() == 0 ) { + LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo())); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().append("Request timeout").flush(); + } else { + resp.setContentType("application/json"); + resp.getOutputStream().write(response.getBytes()); + resp.setStatus(HttpServletResponse.SC_OK); + } + } + + private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req) throws IOException { + String contentType = StringUtils.substringBefore(req.getContentType(), ";"); + + if ("application/json".equals(contentType)) { + String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); + LwM2mNode node; + try { + node = gson.fromJson(content, LwM2mNode.class); + } catch (JsonSyntaxException e) { + throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e); + } + return node; + } else if ("text/plain".equals(contentType)) { + String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); + int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1)); + return LwM2mSingleResource.newStringResource(rscId, content); + } + throw new IllegalArgumentException("content type " + req.getContentType() + " not supported"); + } + + private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req, String content) throws IOException { + int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1)); + return LwM2mSingleResource.newStringResource(rscId, content); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LinkObject.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LinkObject.java index 858d319..7d06019 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LinkObject.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LinkObject.java @@ -1,190 +1,190 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.eclipse.leshan.util.Charsets; -import org.eclipse.leshan.util.StringUtils; - -/** - * A Link Format object. see (http://tools.ietf.org/html/rfc6690) - */ -// TODO this class should not have a lwM2M flavor. -// TODO we should have a look at org.eclipse.californium.core.coap.LinkFormat -public class LinkObject implements Serializable { - - private static final long serialVersionUID = 1L; - - private final String url; - - private final Map attributes; - - /** - * Creates a new link object without attributes. - * - * @param url the object link URL - */ - public LinkObject(String url) { - this(url, null); - } - - /** - * Creates a new instance from a URL and attributes. - * - * @param url the object link URL - * @param attributes the object link attributes or null if the link has no attributes - */ - public LinkObject(String url, Map attributes) { - this.url = url; - if (attributes != null) { - this.attributes = Collections.unmodifiableMap(new HashMap(attributes)); - } else { - this.attributes = Collections.unmodifiableMap(new HashMap()); - } - } - - public String getUrl() { - return url; - } - - /** - * Gets the link attributes - * - * @return an unmodifiable map containing the link attributes - */ - public Map getAttributes() { - return attributes; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append('<'); - builder.append(getUrl()); - builder.append('>'); - - final Map attributes = getAttributes(); - if (attributes != null && !attributes.isEmpty()) { - for (Entry entry : attributes.entrySet()) { - builder.append(";"); - builder.append(entry.getKey()); - if (entry.getValue() != null) { - builder.append("="); - if (entry.getValue() instanceof String) { - builder.append("\"").append(entry.getValue()).append("\""); - } else { - builder.append(entry.getValue()); - } - } - } - } - return builder.toString(); - } - - public static LinkObject[] parse(byte[] content) { - String s = new String(content, Charsets.UTF_8); - String[] links = s.split(","); - LinkObject[] linksResult = new LinkObject[links.length]; - int index = 0; - for (String link : links) { - String[] linkParts = link.split(";"); - - // clean URL - String url = StringUtils.trim(linkParts[0]); - url = StringUtils.removeStart(StringUtils.removeEnd(url, ">"), "<"); - - // parse attributes - Map attributes = new HashMap<>(); - - if (linkParts.length > 1) { - for (int i = 1; i < linkParts.length; i++) { - String[] attParts = linkParts[i].split("="); - if (attParts.length > 0) { - String key = attParts[0]; - Object value = null; - if (attParts.length > 1) { - String rawvalue = attParts[1]; - try { - value = Integer.valueOf(rawvalue); - } catch (NumberFormatException e) { - - value = rawvalue.replaceFirst("^\"(.*)\"$", "$1"); - } - } - attributes.put(key, value); - } - } - } - linksResult[index] = new LinkObject(url, attributes); - index++; - } - return linksResult; - } - - public static final String INVALID_LINK_PAYLOAD = "<>"; - private static final String TRAILER = ", "; - - public static String serialize(LinkObject... linkObjects) { - try { - final StringBuilder builder = new StringBuilder(); - for (final LinkObject link : linkObjects) { - builder.append(link.toString()).append(TRAILER); - } - - builder.delete(builder.length() - TRAILER.length(), builder.length()); - - return builder.toString(); - } catch (final Exception e) { - return null; - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); - result = prime * result + ((url == null) ? 0 : url.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LinkObject other = (LinkObject) obj; - if (attributes == null) { - if (other.attributes != null) - return false; - } else if (!attributes.equals(other.attributes)) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - return true; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.eclipse.leshan.util.Charsets; +import org.eclipse.leshan.util.StringUtils; + +/** + * A Link Format object. see (http://tools.ietf.org/html/rfc6690) + */ +// TODO this class should not have a lwM2M flavor. +// TODO we should have a look at org.eclipse.californium.core.coap.LinkFormat +public class LinkObject implements Serializable { + + private static final long serialVersionUID = 1L; + + private final String url; + + private final Map attributes; + + /** + * Creates a new link object without attributes. + * + * @param url the object link URL + */ + public LinkObject(String url) { + this(url, null); + } + + /** + * Creates a new instance from a URL and attributes. + * + * @param url the object link URL + * @param attributes the object link attributes or null if the link has no attributes + */ + public LinkObject(String url, Map attributes) { + this.url = url; + if (attributes != null) { + this.attributes = Collections.unmodifiableMap(new HashMap(attributes)); + } else { + this.attributes = Collections.unmodifiableMap(new HashMap()); + } + } + + public String getUrl() { + return url; + } + + /** + * Gets the link attributes + * + * @return an unmodifiable map containing the link attributes + */ + public Map getAttributes() { + return attributes; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append('<'); + builder.append(getUrl()); + builder.append('>'); + + final Map attributes = getAttributes(); + if (attributes != null && !attributes.isEmpty()) { + for (Entry entry : attributes.entrySet()) { + builder.append(";"); + builder.append(entry.getKey()); + if (entry.getValue() != null) { + builder.append("="); + if (entry.getValue() instanceof String) { + builder.append("\"").append(entry.getValue()).append("\""); + } else { + builder.append(entry.getValue()); + } + } + } + } + return builder.toString(); + } + + public static LinkObject[] parse(byte[] content) { + String s = new String(content, Charsets.UTF_8); + String[] links = s.split(","); + LinkObject[] linksResult = new LinkObject[links.length]; + int index = 0; + for (String link : links) { + String[] linkParts = link.split(";"); + + // clean URL + String url = StringUtils.trim(linkParts[0]); + url = StringUtils.removeStart(StringUtils.removeEnd(url, ">"), "<"); + + // parse attributes + Map attributes = new HashMap<>(); + + if (linkParts.length > 1) { + for (int i = 1; i < linkParts.length; i++) { + String[] attParts = linkParts[i].split("="); + if (attParts.length > 0) { + String key = attParts[0]; + Object value = null; + if (attParts.length > 1) { + String rawvalue = attParts[1]; + try { + value = Integer.valueOf(rawvalue); + } catch (NumberFormatException e) { + + value = rawvalue.replaceFirst("^\"(.*)\"$", "$1"); + } + } + attributes.put(key, value); + } + } + } + linksResult[index] = new LinkObject(url, attributes); + index++; + } + return linksResult; + } + + public static final String INVALID_LINK_PAYLOAD = "<>"; + private static final String TRAILER = ", "; + + public static String serialize(LinkObject... linkObjects) { + try { + final StringBuilder builder = new StringBuilder(); + for (final LinkObject link : linkObjects) { + builder.append(link.toString()).append(TRAILER); + } + + builder.delete(builder.length() - TRAILER.length(), builder.length()); + + return builder.toString(); + } catch (final Exception e) { + return null; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + LinkObject other = (LinkObject) obj; + if (attributes == null) { + if (other.attributes != null) + return false; + } else if (!attributes.equals(other.attributes)) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + return true; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LwM2mId.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LwM2mId.java index fe530c7..6b24cb9 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LwM2mId.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/LwM2mId.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan; - -/** - * LWM2M Object/Resource IDs - */ -public interface LwM2mId { - - /* OBJECTS */ - - public static final int SECURITY = 0; - public static final int SERVER = 1; - public static final int ACCESS_CONTROL = 2; - public static final int DEVICE = 3; - public static final int CONNECTIVITY_MONITORING = 4; - public static final int FIRMWARE = 5; - public static final int LOCATION = 6; - public static final int CONNECTIVITY_STATISTICS = 7; - public static final int SOFTWARE_MANAGEMENT = 9; - - /* SECURITY RESOURCES */ - - public static final int SEC_SERVER_URI = 0; - public static final int SEC_BOOTSTRAP = 1; - public static final int SEC_SECURITY_MODE = 2; - public static final int SEC_PUBKEY_IDENTITY = 3; - public static final int SEC_SERVER_PUBKEY = 4; - public static final int SEC_SECRET_KEY = 5; - public static final int SEC_SERVER_ID = 10; - - /* SERVER RESOURCES */ - - public static final int SRV_SERVER_ID = 0; - public static final int SRV_LIFETIME = 1; - public static final int SRV_BINDING = 7; -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan; + +/** + * LWM2M Object/Resource IDs + */ +public interface LwM2mId { + + /* OBJECTS */ + + public static final int SECURITY = 0; + public static final int SERVER = 1; + public static final int ACCESS_CONTROL = 2; + public static final int DEVICE = 3; + public static final int CONNECTIVITY_MONITORING = 4; + public static final int FIRMWARE = 5; + public static final int LOCATION = 6; + public static final int CONNECTIVITY_STATISTICS = 7; + public static final int SOFTWARE_MANAGEMENT = 9; + + /* SECURITY RESOURCES */ + + public static final int SEC_SERVER_URI = 0; + public static final int SEC_BOOTSTRAP = 1; + public static final int SEC_SECURITY_MODE = 2; + public static final int SEC_PUBKEY_IDENTITY = 3; + public static final int SEC_SERVER_PUBKEY = 4; + public static final int SEC_SECRET_KEY = 5; + public static final int SEC_SERVER_ID = 10; + + /* SERVER RESOURCES */ + + public static final int SRV_SERVER_ID = 0; + public static final int SRV_LIFETIME = 1; + public static final int SRV_BINDING = 7; +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ObserveSpec.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ObserveSpec.java index 80c7cd0..ebb4459 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ObserveSpec.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ObserveSpec.java @@ -1,182 +1,182 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan; - -import java.util.LinkedList; -import java.util.List; - -/** - * A container for attributes describing the intended behavior of a LWM2M Client regarding sending notifications for an - * observed resource. - * - * The Lightweight M2M spec defines the following attributes: - *

    - *
  • minimum period
  • - *
  • maximum period
  • - *
  • greater than
  • - *
  • less than
  • - *
  • step
  • - *
  • cancel
  • - *
- */ -public final class ObserveSpec { - - private static final String PARAM_MIN_PERIOD = "pmin=%s"; - private static final String PARAM_MAX_PERIOD = "pmax=%s"; - private static final String PARAM_GREATER_THAN = "gt=%s"; - private static final String PARAM_LESS_THAN = "lt=%s"; - private static final String PARAM_STEP = "st=%s"; - private static final String PARAM_CANCEL = "cancel"; - private Integer minPeriod; - private Integer maxPeriod; - private Float greaterThan; - private Float lessThan; - private Float step; - private boolean cancel; - - private ObserveSpec() { - } - - public Integer getMinPeriod() { - return this.minPeriod; - } - - public Integer getMaxPeriod() { - return this.maxPeriod; - } - - public Float getGreaterThan() { - return this.greaterThan; - } - - public Float getLessThan() { - return this.lessThan; - } - - public Float getStep() { - return this.step; - } - - public Boolean getCancel() { - return this.cancel; - } - - public String[] toQueryParams() { - List queries = new LinkedList<>(); - if (this.cancel) { - queries.add(PARAM_CANCEL); - } else { - if (this.minPeriod != null) { - queries.add(String.format(PARAM_MIN_PERIOD, this.minPeriod)); - } - if (this.maxPeriod != null) { - queries.add(String.format(PARAM_MAX_PERIOD, this.maxPeriod)); - } - if (this.lessThan != null) { - queries.add(String.format(PARAM_LESS_THAN, this.lessThan)); - } - if (this.greaterThan != null) { - queries.add(String.format(PARAM_GREATER_THAN, this.greaterThan)); - } - if (this.step != null) { - queries.add(String.format(PARAM_STEP, this.step)); - } - } - return queries.toArray(new String[queries.size()]); - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - for (String query : toQueryParams()) { - b.append(query).append("&"); - } - return b.toString(); - } - - /** - * A builder for ObserveSpec instances. - * - * Provides a fluid API for setting attributes. Creating an ObserveSpec instance works like this: - * - *
-     * ObserveSpec spec = new ObserveSpec.Builder().minPeriod(10).greaterThan(34.12).build();
-     * 
- */ - public static class Builder { - - private boolean cancel; - private Float step; - private Float greaterThan; - private Float lessThan; - private Integer minPeriod; - private Integer maxPeriod; - - public Builder() { - super(); - } - - public ObserveSpec build() { - ObserveSpec spec = new ObserveSpec(); - if (this.cancel) { - spec.cancel = Boolean.TRUE; - return spec; - } - - if (this.maxPeriod != null && this.minPeriod != null && this.maxPeriod < this.minPeriod) { - throw new IllegalStateException("minPeriod must be smaller than maxPeriod"); - } else { - spec.greaterThan = this.greaterThan; - spec.lessThan = this.lessThan; - spec.minPeriod = this.minPeriod; - spec.maxPeriod = this.maxPeriod; - spec.step = this.step; - return spec; - } - } - - public Builder cancel() { - this.cancel = true; - return this; - } - - public Builder step(float step) { - this.step = step; - return this; - } - - public Builder greaterThan(float threshold) { - this.greaterThan = threshold; - return this; - } - - public Builder lessThan(float threshold) { - this.lessThan = threshold; - return this; - } - - public Builder minPeriod(int seconds) { - this.minPeriod = seconds; - return this; - } - - public Builder maxPeriod(int seconds) { - this.maxPeriod = seconds; - return this; - } - - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan; + +import java.util.LinkedList; +import java.util.List; + +/** + * A container for attributes describing the intended behavior of a LWM2M Client regarding sending notifications for an + * observed resource. + * + * The Lightweight M2M spec defines the following attributes: + *
    + *
  • minimum period
  • + *
  • maximum period
  • + *
  • greater than
  • + *
  • less than
  • + *
  • step
  • + *
  • cancel
  • + *
+ */ +public final class ObserveSpec { + + private static final String PARAM_MIN_PERIOD = "pmin=%s"; + private static final String PARAM_MAX_PERIOD = "pmax=%s"; + private static final String PARAM_GREATER_THAN = "gt=%s"; + private static final String PARAM_LESS_THAN = "lt=%s"; + private static final String PARAM_STEP = "st=%s"; + private static final String PARAM_CANCEL = "cancel"; + private Integer minPeriod; + private Integer maxPeriod; + private Float greaterThan; + private Float lessThan; + private Float step; + private boolean cancel; + + private ObserveSpec() { + } + + public Integer getMinPeriod() { + return this.minPeriod; + } + + public Integer getMaxPeriod() { + return this.maxPeriod; + } + + public Float getGreaterThan() { + return this.greaterThan; + } + + public Float getLessThan() { + return this.lessThan; + } + + public Float getStep() { + return this.step; + } + + public Boolean getCancel() { + return this.cancel; + } + + public String[] toQueryParams() { + List queries = new LinkedList<>(); + if (this.cancel) { + queries.add(PARAM_CANCEL); + } else { + if (this.minPeriod != null) { + queries.add(String.format(PARAM_MIN_PERIOD, this.minPeriod)); + } + if (this.maxPeriod != null) { + queries.add(String.format(PARAM_MAX_PERIOD, this.maxPeriod)); + } + if (this.lessThan != null) { + queries.add(String.format(PARAM_LESS_THAN, this.lessThan)); + } + if (this.greaterThan != null) { + queries.add(String.format(PARAM_GREATER_THAN, this.greaterThan)); + } + if (this.step != null) { + queries.add(String.format(PARAM_STEP, this.step)); + } + } + return queries.toArray(new String[queries.size()]); + } + + @Override + public String toString() { + StringBuilder b = new StringBuilder(); + for (String query : toQueryParams()) { + b.append(query).append("&"); + } + return b.toString(); + } + + /** + * A builder for ObserveSpec instances. + * + * Provides a fluid API for setting attributes. Creating an ObserveSpec instance works like this: + * + *
+     * ObserveSpec spec = new ObserveSpec.Builder().minPeriod(10).greaterThan(34.12).build();
+     * 
+ */ + public static class Builder { + + private boolean cancel; + private Float step; + private Float greaterThan; + private Float lessThan; + private Integer minPeriod; + private Integer maxPeriod; + + public Builder() { + super(); + } + + public ObserveSpec build() { + ObserveSpec spec = new ObserveSpec(); + if (this.cancel) { + spec.cancel = Boolean.TRUE; + return spec; + } + + if (this.maxPeriod != null && this.minPeriod != null && this.maxPeriod < this.minPeriod) { + throw new IllegalStateException("minPeriod must be smaller than maxPeriod"); + } else { + spec.greaterThan = this.greaterThan; + spec.lessThan = this.lessThan; + spec.minPeriod = this.minPeriod; + spec.maxPeriod = this.maxPeriod; + spec.step = this.step; + return spec; + } + } + + public Builder cancel() { + this.cancel = true; + return this; + } + + public Builder step(float step) { + this.step = step; + return this; + } + + public Builder greaterThan(float threshold) { + this.greaterThan = threshold; + return this; + } + + public Builder lessThan(float threshold) { + this.lessThan = threshold; + return this; + } + + public Builder minPeriod(int seconds) { + this.minPeriod = seconds; + return this; + } + + public Builder maxPeriod(int seconds) { + this.maxPeriod = seconds; + return this; + } + + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ResponseCode.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ResponseCode.java index 3e1e114..3a324c2 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ResponseCode.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/ResponseCode.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan; - -/** - * Response codes defined for LWM2M enabler - */ -public enum ResponseCode { - /** Resource correctly created */ - CREATED, - /** Resource correctly deleted */ - DELETED, - /** Resource correctly changed */ - CHANGED, - /** Content correctly delivered */ - CONTENT, - /** Access Right Permission Denied */ - UNAUTHORIZED, - /** Bad request format (missing parameters, bad encoding ...) */ - BAD_REQUEST, - /** This method (GET/PUT/POST/DELETE) is not allowed on this resource */ - METHOD_NOT_ALLOWED, - /** The End-point Client Name results in a duplicate entry on the LWM2M Server */ - FORBIDDEN, - /** Resource not found */ - NOT_FOUND, - /** None of the preferred Content-Formats can be returned */ - NOT_ACCEPTABLE, - /** The specified format is not supported */ - UNSUPPORTED_CONTENT_FORMAT, - /** generic response code for unexpected error */ - INTERNAL_SERVER_ERROR; - - public boolean isError() { - switch (this) { - case UNAUTHORIZED: - case BAD_REQUEST: - case METHOD_NOT_ALLOWED: - case FORBIDDEN: - case NOT_FOUND: - case INTERNAL_SERVER_ERROR: - case UNSUPPORTED_CONTENT_FORMAT: - case NOT_ACCEPTABLE: - return true; - default: - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan; + +/** + * Response codes defined for LWM2M enabler + */ +public enum ResponseCode { + /** Resource correctly created */ + CREATED, + /** Resource correctly deleted */ + DELETED, + /** Resource correctly changed */ + CHANGED, + /** Content correctly delivered */ + CONTENT, + /** Access Right Permission Denied */ + UNAUTHORIZED, + /** Bad request format (missing parameters, bad encoding ...) */ + BAD_REQUEST, + /** This method (GET/PUT/POST/DELETE) is not allowed on this resource */ + METHOD_NOT_ALLOWED, + /** The End-point Client Name results in a duplicate entry on the LWM2M Server */ + FORBIDDEN, + /** Resource not found */ + NOT_FOUND, + /** None of the preferred Content-Formats can be returned */ + NOT_ACCEPTABLE, + /** The specified format is not supported */ + UNSUPPORTED_CONTENT_FORMAT, + /** generic response code for unexpected error */ + INTERNAL_SERVER_ERROR; + + public boolean isError() { + switch (this) { + case UNAUTHORIZED: + case BAD_REQUEST: + case METHOD_NOT_ALLOWED: + case FORBIDDEN: + case NOT_FOUND: + case INTERNAL_SERVER_ERROR: + case UNSUPPORTED_CONTENT_FORMAT: + case NOT_ACCEPTABLE: + return true; + default: + return false; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyDevice.java.bak.org b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyDevice.java.bak.org index c57dae5..f53e258 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyDevice.java.bak.org +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyDevice.java.bak.org @@ -1,154 +1,154 @@ -package org.eclipse.leshan.client.demo; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.TimeZone; -import java.util.Timer; -import java.util.TimerTask; - -import org.eclipse.leshan.client.resource.BaseInstanceEnabler; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.response.ExecuteResponse; -import org.eclipse.leshan.core.response.ReadResponse; -import org.eclipse.leshan.core.response.WriteResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MyDevice extends BaseInstanceEnabler { - - private static final Logger LOG = LoggerFactory.getLogger(MyDevice.class); - - public MyDevice() { - // notify new date each 5 second - Timer timer = new Timer(); - timer.schedule(new TimerTask() { - @Override - public void run() { - fireResourcesChange(13); - } - }, 5000, 5000); - } - - @Override - public ReadResponse read(int resourceid) { - LOG.info("Read on Device Resource " + resourceid); - switch (resourceid) { - case 0: - return ReadResponse.success(resourceid, getManufacturer()); - case 1: - return ReadResponse.success(resourceid, getModelNumber()); - case 2: - return ReadResponse.success(resourceid, getSerialNumber()); - case 3: - return ReadResponse.success(resourceid, getFirmwareVersion()); - case 9: - return ReadResponse.success(resourceid, getBatteryLevel()); - case 10: - return ReadResponse.success(resourceid, getMemoryFree()); - case 11: - Map errorCodes = new HashMap<>(); - errorCodes.put(0, getErrorCode()); - return ReadResponse.success(resourceid, errorCodes, Type.INTEGER); - case 13: - return ReadResponse.success(resourceid, getCurrentTime()); - case 14: - return ReadResponse.success(resourceid, getUtcOffset()); - case 15: - return ReadResponse.success(resourceid, getTimezone()); - case 16: - return ReadResponse.success(resourceid, getSupportedBinding()); - default: - return super.read(resourceid); - } - } - - @Override - public ExecuteResponse execute(int resourceid, String params) { - LOG.info("Execute on Device resource " + resourceid); - if (params != null && params.length() != 0) - System.out.println("\t params " + params); - return ExecuteResponse.success(); - } - - @Override - public WriteResponse write(int resourceid, LwM2mResource value) { - LOG.info("Write on Device Resource " + resourceid + " value " + value); - switch (resourceid) { - case 13: - return WriteResponse.notFound(); - case 14: - setUtcOffset((String) value.getValue()); - fireResourcesChange(resourceid); - return WriteResponse.success(); - case 15: - setTimezone((String) value.getValue()); - fireResourcesChange(resourceid); - return WriteResponse.success(); - default: - return super.write(resourceid, value); - } - } - - private String getManufacturer() { - return "Leshan Demo Device"; - } - - private String getModelNumber() { - return "Model 500"; - } - - private String getSerialNumber() { - return "LT-500-000-0001"; - } - - private String getFirmwareVersion() { - return "1.0.0"; - } - - private long getErrorCode() { - return 0; - } - - private int getBatteryLevel() { - final Random rand = new Random(); - return rand.nextInt(100); - } - - private int getMemoryFree() { - final Random rand = new Random(); - return rand.nextInt(50) + 114; - } - - private Date getCurrentTime() { - return new Date(); - } - - private String utcOffset = new SimpleDateFormat("X").format(Calendar.getInstance().getTime());; - - private String getUtcOffset() { - return utcOffset; - } - - private void setUtcOffset(String t) { - utcOffset = t; - } - - private String timeZone = TimeZone.getDefault().getID(); - - private String getTimezone() { - return timeZone; - } - - private void setTimezone(String t) { - timeZone = t; - } - - private String getSupportedBinding() { - return "U"; - } +package org.eclipse.leshan.client.demo; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.TimeZone; +import java.util.Timer; +import java.util.TimerTask; + +import org.eclipse.leshan.client.resource.BaseInstanceEnabler; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.response.WriteResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyDevice extends BaseInstanceEnabler { + + private static final Logger LOG = LoggerFactory.getLogger(MyDevice.class); + + public MyDevice() { + // notify new date each 5 second + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + @Override + public void run() { + fireResourcesChange(13); + } + }, 5000, 5000); + } + + @Override + public ReadResponse read(int resourceid) { + LOG.info("Read on Device Resource " + resourceid); + switch (resourceid) { + case 0: + return ReadResponse.success(resourceid, getManufacturer()); + case 1: + return ReadResponse.success(resourceid, getModelNumber()); + case 2: + return ReadResponse.success(resourceid, getSerialNumber()); + case 3: + return ReadResponse.success(resourceid, getFirmwareVersion()); + case 9: + return ReadResponse.success(resourceid, getBatteryLevel()); + case 10: + return ReadResponse.success(resourceid, getMemoryFree()); + case 11: + Map errorCodes = new HashMap<>(); + errorCodes.put(0, getErrorCode()); + return ReadResponse.success(resourceid, errorCodes, Type.INTEGER); + case 13: + return ReadResponse.success(resourceid, getCurrentTime()); + case 14: + return ReadResponse.success(resourceid, getUtcOffset()); + case 15: + return ReadResponse.success(resourceid, getTimezone()); + case 16: + return ReadResponse.success(resourceid, getSupportedBinding()); + default: + return super.read(resourceid); + } + } + + @Override + public ExecuteResponse execute(int resourceid, String params) { + LOG.info("Execute on Device resource " + resourceid); + if (params != null && params.length() != 0) + System.out.println("\t params " + params); + return ExecuteResponse.success(); + } + + @Override + public WriteResponse write(int resourceid, LwM2mResource value) { + LOG.info("Write on Device Resource " + resourceid + " value " + value); + switch (resourceid) { + case 13: + return WriteResponse.notFound(); + case 14: + setUtcOffset((String) value.getValue()); + fireResourcesChange(resourceid); + return WriteResponse.success(); + case 15: + setTimezone((String) value.getValue()); + fireResourcesChange(resourceid); + return WriteResponse.success(); + default: + return super.write(resourceid, value); + } + } + + private String getManufacturer() { + return "Leshan Demo Device"; + } + + private String getModelNumber() { + return "Model 500"; + } + + private String getSerialNumber() { + return "LT-500-000-0001"; + } + + private String getFirmwareVersion() { + return "1.0.0"; + } + + private long getErrorCode() { + return 0; + } + + private int getBatteryLevel() { + final Random rand = new Random(); + return rand.nextInt(100); + } + + private int getMemoryFree() { + final Random rand = new Random(); + return rand.nextInt(50) + 114; + } + + private Date getCurrentTime() { + return new Date(); + } + + private String utcOffset = new SimpleDateFormat("X").format(Calendar.getInstance().getTime());; + + private String getUtcOffset() { + return utcOffset; + } + + private void setUtcOffset(String t) { + utcOffset = t; + } + + private String timeZone = TimeZone.getDefault().getID(); + + private String getTimezone() { + return timeZone; + } + + private void setTimezone(String t) { + timeZone = t; + } + + private String getSupportedBinding() { + return "U"; + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyLocation.java.bak.org b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyLocation.java.bak.org index 85dea85..067b384 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyLocation.java.bak.org +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/demo/MyLocation.java.bak.org @@ -1,82 +1,82 @@ -package org.eclipse.leshan.client.demo; - -import java.util.Date; -import java.util.Random; - -import org.eclipse.leshan.client.resource.BaseInstanceEnabler; -import org.eclipse.leshan.core.response.ReadResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MyLocation extends BaseInstanceEnabler { - - private static final Logger LOG = LoggerFactory.getLogger(MyLocation.class); - - private Random random; - private float latitude; - private float longitude; - private Date timestamp; - - public MyLocation() { - random = new Random(); - latitude = Float.valueOf(random.nextInt(180)); - longitude = Float.valueOf(random.nextInt(360)); - timestamp = new Date(); - } - - @Override - public ReadResponse read(int resourceid) { - LOG.info("Read on Location Resource " + resourceid); - switch (resourceid) { - case 0: - return ReadResponse.success(resourceid, getLatitude()); - case 1: - return ReadResponse.success(resourceid, getLongitude()); - case 5: - return ReadResponse.success(resourceid, getTimestamp()); - default: - return super.read(resourceid); - } - } - - public void moveLocation(String nextMove) { - switch (nextMove.charAt(0)) { - case 'w': - moveLatitude(1.0f); - break; - case 'a': - moveLongitude(-1.0f); - break; - case 's': - moveLatitude(-1.0f); - break; - case 'd': - moveLongitude(1.0f); - break; - } - } - - private void moveLatitude(float delta) { - latitude = latitude + delta; - timestamp = new Date(); - fireResourcesChange(0, 5); - } - - private void moveLongitude(float delta) { - longitude = longitude + delta; - timestamp = new Date(); - fireResourcesChange(1, 5); - } - - public String getLatitude() { - return Float.toString(latitude - 90.0f); - } - - public String getLongitude() { - return Float.toString(longitude - 180.f); - } - - public Date getTimestamp() { - return timestamp; - } +package org.eclipse.leshan.client.demo; + +import java.util.Date; +import java.util.Random; + +import org.eclipse.leshan.client.resource.BaseInstanceEnabler; +import org.eclipse.leshan.core.response.ReadResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyLocation extends BaseInstanceEnabler { + + private static final Logger LOG = LoggerFactory.getLogger(MyLocation.class); + + private Random random; + private float latitude; + private float longitude; + private Date timestamp; + + public MyLocation() { + random = new Random(); + latitude = Float.valueOf(random.nextInt(180)); + longitude = Float.valueOf(random.nextInt(360)); + timestamp = new Date(); + } + + @Override + public ReadResponse read(int resourceid) { + LOG.info("Read on Location Resource " + resourceid); + switch (resourceid) { + case 0: + return ReadResponse.success(resourceid, getLatitude()); + case 1: + return ReadResponse.success(resourceid, getLongitude()); + case 5: + return ReadResponse.success(resourceid, getTimestamp()); + default: + return super.read(resourceid); + } + } + + public void moveLocation(String nextMove) { + switch (nextMove.charAt(0)) { + case 'w': + moveLatitude(1.0f); + break; + case 'a': + moveLongitude(-1.0f); + break; + case 's': + moveLatitude(-1.0f); + break; + case 'd': + moveLongitude(1.0f); + break; + } + } + + private void moveLatitude(float delta) { + latitude = latitude + delta; + timestamp = new Date(); + fireResourcesChange(0, 5); + } + + private void moveLongitude(float delta) { + longitude = longitude + delta; + timestamp = new Date(); + fireResourcesChange(1, 5); + } + + public String getLatitude() { + return Float.toString(latitude - 90.0f); + } + + public String getLongitude() { + return Float.toString(longitude - 180.f); + } + + public Date getTimestamp() { + return timestamp; + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapHandler.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapHandler.class deleted file mode 100644 index 47f68ede2047e4d33549ca4dba5460b083e96a25..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4742 zcmcIo`F9i775<*Jj4h9`V{C#kV7nwnnA&PE0g5RhF}M*mCW%-Ap|oS^*&dK*#LUP* zlP*cObW69i6uNJr3u&Dc3?}FF^r!Zm{@ngC?Kx@ty&26&B8p3({bls#&3$+I?sxBf z_Fw;X`;P!daU+FIc&-KS!zm3PO(BNU>g8kV@$nQNMl+^U$fKaXNwu13#%v06FjMHp znO2-dQNw&II$*WJMyVC&;HZbI!P8JyVhbs(!FeTfK^?uQ)PJG{&*KH9_LC`m3ZG8l zGk7tDm+;vXK8Me1_=1Kn3bakzw&!||Q7W0%tbjNv&{?-PX?XcLfrls07z;+G?3u+( z-nQ~($B~wo8Mn)px8FW*`C?-NtE0m?=`2VmYt7gKBa^l>o00jVS#o8jDBU^3%J5C8 zaD6#9QQR26joH=V5UfGcX&((k36TB7;Yc`X$JUJ_!u@y`^ z(zVM@US=lGAKEs5*f)8=GNy|>wwIQYdrZsp_7akGy`8Zw#{}Zzc7ZOmPnwpTD$h?# z=ZHE==}9|p6ptB>sopD_ac|CKINMinCq&|jFegtMRzdk9uqwc#;vDs?skd>l6xum` zhpYcnNL1L(GX%w*lLdj-(kn#c$a7`sdSPA*%(dxVY@80;k(p3Fihjbk^Gu*-Y)eB^ z!9llVTjbR{P6qpgui31a7ueQNPe8@cg$flzmzm=*=8880yBeywi#S+wInT(SC6_DA zNET#KdgRUj7tZ~@m3x6RJQ=~6GA-9Lth~&U1gjg=oIsQLkU&>W)nq;C7@n=jtOrC7 z>P=v0Lny#mrFhU)C{*%{qp#RmU+L7wENYuYbm|=lhNR>98I42k2_} zijJ@1YdT(0mcEW}2&}j4{*tr`9Ab6ye$F&}Qyuu0j&I{t4d2o6U0f1)^xbFD3WGt% z_i$Om6&>Hl56BT6Kg5r8{1`uBKKyuVrw{Yd$Vx4|b;Q&0Q~XRp@^c-J;TI~pU+PF> zi-y;9T*a?+{2IT}@LL_%@VbWIso&pgSk&=`dVf>LA8?&ru94OHd3$H}NcO7xVL^3P zGZ+@Iz{aYa8nTX4E_t#L5mxa!tLV9_krP4aD|c)XZQ3YARXkN0X+E$y&ta19ZydDb z!)ps~8g4nCXKf4YN#ECuc@NQsDGyK(xZeQl^|8Zh3r4Xl56|$Pz*IDB&~4Ssauf-~ zW~C=ESPOMP0zzHQcV$c9L5e@VV3Gu$b8fo`$gu~o$_|D`LG_xTWc)NESbF%`Bio)t)>vpx-9ZQK#V0dsG+lo0Y@ zT-*h5!UNF|eQ$Jo$MFqSL~HKjM>t82a#|6*+=21KQ~PrQeKqN5AWEPUhMG_8*Xe`* zMOLNZ{f)}HzPD7zA4^#=rBGl?B{?>RxwE9l8@lvzcK&Siovy6&!)o|dVC|i!D|&e@ z-N>ohHX9B-a*+-_C8ZNN)m3LR+D`K3X%y*nccY>>i2?qZwTXY{#nGh39al|ijQPLp z*!=BO6AeVn-y4R;^$0SQ`v7;&`6q$ip_>pxu^VU_dJC}=@tcU>Kw@a?4J6;7SPYNw zxdsV7M|dQS7Ao(insrpO&HvWKXD|QY+|FOMdek?&gKM28gPq~Xk)3pX7e2^$<;F{N zC&u5wq3dY6jP*lXm!MriOK0;fv@CKnv4qquv@Uk)YJ-x2N9&N}dOL&Kfp+YqM`Kuz zJ?O_?->d#WYvk1+c2h!mGf1fq(du5V30`-K{yc_#fj{D9>ecw=cHqxqtv_wbpJeN|+E@QJ=bqPvz?@kPFeG6+&#CsUXgEz5u89gx^ zzxwaLD_yY~UBUTCTcRgX(Uw-Line4=+*cRtN!F|T+byi~F>0$~v;%F7WSsFFAVw3! zXo}GvMix)uG@gcmqi}iSxrF0*9nWGBCvhF8eEd!^&sm;$98WO!qs;v{_7ks5m?Io!56u%E2&n49;wxd_0#9GPL+r#B0!7<%fHL=v^ccUZ@Fe bGzx8$X?>PP6=F%mS~l{2x) diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapListener.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/BootstrapListener.class deleted file mode 100644 index c88211f62737a7fc58787f2a593c26a7d6218b3b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 183 zcmZXOF%H5o5Cr!^AV38TZ-9m?@&k%gNEAr)PB`uSiS%)ZA{IOS~B9zXz zERE4a5H=DzWjQUek%RbAeBeKnu$f>s%C>x|duif=K**9BKzTAiJ~hl!W>|ayFyJ!D diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/DmServerInfo.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/DmServerInfo.class deleted file mode 100644 index 6f903c1bdcbad6bbdf8ddd5aaca2aaa2cecd77b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 863 zcmah{+iuf95IvKd6JvTw!<|AJC?si`MdAq+cz_D2mD@^~R*EVfoOF|J<=C)x@?9Vy zQ6a$x@KK1dof1nF@iLdQXJ&TK?9X4{egJrit_c&j%eZ6UZUq&r#^#=h`>4m!nu!J; z7t20XSL1x}=s8`qjG`^=rX!gKwRNKs~(PB75}`9{Ulm$T*F zm~CMZON5Q>y?WZXemv3Y#d_GOUr3WAGhsM>Pgt7IIq09sL1f_(9$UBq%RtjY3vCNm zv0z}sLI<0K?qzEJ`(=dA{|n|q5GtuYhguO9QW<<1iNm)$EWyJ3x^@sR*O>$Y zE6v@kYVk1_WZrk7ZfO|ku^SPdHUC!mI0L1EY-PL7c7ZkiekT9X94MBGBZ^g;A-o69 zmpK#ciG8vC74$hduCgs9U=1rATPXoGT;q&z9XHs<#rBNXsOC!Fk?-Z(Ur=y*1$M=A dl$>6XBf~jI`4h8qn0H>ybZ-3Vd^2I)`VCRg(xm_Z diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine$1.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine$1.class deleted file mode 100644 index 09cd71fa1ea5210792615db18eeb95eb3356e47b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 273 zcmbV{K}thG42J*M+Sfh{zMb1Hy6#XEFCZ0Mh@dB!zJ}?PAyXz}59h)I^iajTb$2Et z;e+snoG(AW03I=K&@^ZX?N|OTJ-^1pgojTKQETxvX4y!H!mEQndBXih`jj;_?Cr%9nCDRHP%LsCrBHZ#2t;zSWKvXNwl z&NMH=3-mfO>4fwm570;IbUN818PE`>VSIDW+0|;#e&7B`fB*N_8vxhvSi>l0hIuhH z7?{;i#+=3vD#NJadKzEhhSc4Z%hz(5SFs@XZ-%g##x2}daYx0sDwYVT@TnW*X9?FE zZQn74-EupDFk2#cYI!D0!VAqn_`AXn%r)V-LFikd+xBXn<9cGAJuJAM8!i%V7W#8B z{fIEQ)ZP??(FXfm?QU-ff8E+>u_n`K+g9t5<-1buDFKu`eMOW%>6cLs_+5|Jf($m@39X%oyd+|i5)lrOL^VqCe#mbGh{Ez5Jvx)%!H z?{-45S=+NkN7Bn?BhApVpRHJ(2(^m4oJJKj0th>Oa(#wali=ed=gadFwz9`%qU@Ck zH~Mu$(3i7X`I+}7>#{?n!|J>^M5sW9Byge6k{p8%^Ow6eGNypFlg;49KGu|m8uGizR9&Bt0 zJLK{{R;_hCFRuBk@4qimP~5ujw@*SnOe&$$&x@Qx%eF-jM5X*g5;&j{q-Oz2B zT;p8tXMmA_UEAY9WQT2^pgJOqd+~PRgxBdaRBFO0M`3J=UDp;X+?ZmUhaXRo(GyO& zHKVj0#?BGAL2bJe{uWJ$$HxrKNrw8KiwQ^9q@zRLD@ma$h4DfRG-y4kZ1F&H9N|kW zGQUY34_Y@GS`$5@qWRMdeb;li$C2Z&ioxUMLy%#}{^Kvs02JAdto?|k3QG#_TCwye zl;SH4ykJSeB(Ev90Zrm#KI`%f4WHlw?}UrU#vW*_=izzrC6ogU9^ivU=_OLHp%V5{ zjnzZ@co?6C_c0Qmv_G(L^mOh>S2)FP{K!r_vOCu}fSwt7jdKcKMB#bZL7D-|;1?M> z=sePN0h4qQQPqX-)<|5EJ_LYW>OH3re zXZTaN9NqN1N5mDrDTCC%sH(`1jr{|IKf|AC2AJXkTS|)WGC>2pr;4RlpwsDpM@s}(qxQg?l=n830I9Y!acVGVI)HH_f7G%utXmBv&t zCjEE^a$US6uVPZgl!|FWEI4%h%ot&+SoO-Luq#f@7iLBHhn8z{CfvaEg?A!6-`o~u z#}7O!aH{T#TXtMA%LsFh>jVpgf)Ng4c$W}es_qLycabsQ)<5kDZ^zoJa3xu++E!)P z@*J7Bicv|L(D$LXZv~>A)sE#K6Z8$&72Za{@ZubkSVCZ*yf@ls&f$6HpdaRTm#iWve3pF@fk?nvXalCyHk z{Z>xL2{U0~2wJIH_iVB1$S(D__n4MnXmdDhfJYVphkTH1pCdAW0bf zzkoVk;Wc5XeV25-(foA49Zx&gs*kF8qhk?Egv~G${g1X264xBx?Hvg_;NiS3ZP#75 zIk8ircI9T|!z|=RShg*EKQleXT@8H)KVAdnB+y^fiS{Jlo=nOlWehh)$gdpakIZ7V zToxXWdqN(iy~a1(aSy75UZd@@lmgFj%RG}v^Y<&x*WorOk&yGk-?j)8IX+yy!&#m) zg}s&?`35C>fyg;$3Q}xi{0?Xly&UT@hK4@eV^6q`ffm9=3t>I`70M-|XUH|9TW2tu zQS1!yW~6>W>guU>Rl8lhL}ya_jxGh~jhzZS%N@*B^2qYOpjBwJh7_%1kTzh@CUR6n zfl8R8_n4<`tkF(`YacV3=QR)Tuz|JSVm-)MoroHVMHP=U)}jZGTZdTYB@uoc%Z^-t rZk8b3e4_;><$1z_N?BsaV5lL(Q_d7T!(H}Cj&%M%^s`U1N222o=l7`z diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/RegistrationEngine.class deleted file mode 100644 index e2b98305d61f6dc4cb878863114aee6d78692d3b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13227 zcmcIr33yc1^*?7a$$ObRAcU}QK@dVn2s;RfEJ+}k1W3ZJ;w1Bu3`}O?ECf{QUabqR zRdMNN)oQUS3L#RptySw*tF_j;TU*?^X{)w%`~S|{=1nq5z<&RH-@N6%d(S=hoZngQ zc`r|X`M^U&G}DveqiZ=U8wW+MR5@hJ!6$7wKDwSYANS+_ayvlbTp#&ZlbeBZ$dkh$ zIpoV>u*ySJ9-70$c(}?VR354FD3wR6JVxcQLbgERaXuQ!$K>#Mo*-k6_3=cWl+A@a zS>>V}p2EdGF5#&vm-=`bPnVV%ay3&9vlO1~qscrchv)J2UsEnt}VWu3w&Dw07*ZFuoZ;-2vKHkKeeYBEKQut(9-zh3@5&Eb4Xf-dA zgI@&EpmL+i0ePaU+$8N_Xtgl3fSXlrQ8}paRv(?pbF7tQysPjwl|#~_)kguL7T}6( z4s%3EwyAuYv>0oOO0Sq4;wmRp-mY@H!aIBv`WgeObWYH{)V)irSjR* zXz+24%IEs{JU-vzz_THnFW_&A?k=>MI$!0BvKC*y*pRi4zr`0Te2I@P;bWxlr6PjM za(Fjip2Ju0<-+Hca=1$2tA)-ra`?8w*ZTN6zFy%y3g5s)Oj>0)tVfrH{IQrGV;Zuy zE#QyqwR&?f7LWSl!AQ8?AKS*1+r25HYSnV4ysAjFxil7PnzgmGD$?AnM;9>pmey^l zudFU#wYHv#E1CK&i-cowe>lF*A4=#Mf)`9yR$g1ayt1yoc1eBZsv6gbl}su~)Rx!R zZbWC#2Hfl6KwBgjj?0u={oDPeA%D2Jv@RYEhMO^ERtz2VDAPiNA-ypaY>VloAwAaO z50~Oj564TR`e_M07B8)8ub$Dm%xJ4Mo9c|wpwmCnuvKr2mxuigAw3F_3@~R)#Dk&I zYJVHLWY-0o!~S?8sxxg)eY()aT4gw{i#U4aCl*OW8+DVRRqmM=EW%8=4UtG(6w$WA z9}a*Yrdhp^i|Ntr;JI{Zmr_SOwA5%;L3ut76!w? z_#&pK3%hqnrP(`}`T%z?dhZcAy^QGA=^7Bxwjg<@s=QjIH#8xZ7$uus65;Z@{nRb%eYNT1~eVpsf)vC3SNPrMJ6}}mft$atL-X?Yrtb$vKld{sRK&v_9 zv?G|YtTkoPGt&-9S*eM5J?bnJsS+|D@PnA=FfqGtLS;^O7b(Q|EYs;SP4AnAog87>%cOpa3qtQegAUVYB=;p}k9*alX09l~SibsY^7Rxq}gk}mM`)1bvL{;=g~R?`d?1ehS4IIir!qt?e80x~`GCe9^bFIqbV4vao|(irQOwHEWxZhHpvIm20Mm?~$M+N)!1-DusTcNo z;Cy~Ty&2EI`5}#e$`5M%5a7iR3)2G~rp)nrK-P7a#y{hqGfi+kl|2P~RDr)C5{>JD zBw0A6WVa?DK87?D!kVh_FZe;GVXmisSOA7XlE(8#_?H?#N}q~49@F@7{uR^sWcQde zXDF)s13PUNLHP;c@kwBvpW>$#en#V8^Ro*7M&sxBc?9Wnvh3L*Gc8IYAZo>)o?vBK zLn@@0Mx`O(UhMNI3N zpoNwsMYBPp`{@p*(QdOVXtFe7V?^WE=mU*khfe5y`haPSO$It`55`*xLdZBJS16ct z#;!?InZ}M!|0mWK#;#N2H~3Aak!h#3f$$dpk!f*Kgvkux=(I2=R7^nt>E()iDOSfjs+A01hymqcy&*(sr8E%%9yyu)v5 z{H};=bPp4lGG$ttltseWeHNIcEq=Os%k;3G)H@NEWJ`LMk||j;xv}vL6u;N2Sy(8x zN7-Uci5dmg!n&gv*wy$0J`BT50iHD=mOvh(2jEElBH%nGT_2mMjnTh~&}S$8t%YxK zz5XzKld(T2E|9bil8#4r76il4UCf9Xe-lIgyTbp__(T3kBMyMO?7GRRhYTf1Y3N`DU3+VpMnWGNSzA*TjT%me--{rqkl-&@wSA8G0AFF zx(rg|&-n|DzvQp5r};X3DIU^1?D3%Hketb^6=A#lbtq1l&Xg8{sUoT~%SqHKgK}lBYTcVM6bK`G{%1FXo#UZ=6f*sY6u-@)eb}$f;Y;`0OLclMqbf?0u(N1@p zjId$WX!<2{KID5y>)K?eI?uh`H|4m%Rd=yk+$p`)#B|!%%(RbS&yxm^(-+95rX;zD zBUm-E%~+zLHHdX$tCdtjZ6a(WKMQ)0qEkgX0zkQNQN9Dk$ws4ureJ4e>VB~`u~RZN z^Z%pSh35*|+(l(%+t`~)scx`)Syo+5{b395CG#%<1XshR|1b*N-YJ$io6X4+SA32aIYooTnlrtsf=x=m@p>`u?twqY-~ z%?e&_)2fP~RG%IUDb)_6Jnz&edUbNWRj^QKjD#JXTUp!JP%!kNHHIQF-N8sU1TIlg zw3FZN55_TzQTVE`QhLa;aHSx_&4DvSOvS8?j<@#4U2MZ%yL5tn2cUnspuZY3`kSF< zZ26P6Z5e^9rDv~(wYXWTKuT-iCUBIfPX~e&u3g-?jMUrik77rhYwnM$@dih4#rpw> zF>AZL8N$Ud8|{YsSQZI|kQgI}h8*&ft}xjy@JHRoZ#bbLDT6Dmb_~r+4z*jMBgsFy z)^8kVuZDt6y3{vO#!3oXFpPqb!R@Lhra{oNYpn*v@w_1z4q)#M_nl5sjc#*UYIdzQ zb)9zeW4bXzASkA9tB6Ef{qYrgs7=Zc`GO{+N0}aLj0TPBB-2U@B3;GkV%Ap7=5##D zM2;+O?HzB%s=E_TN4CeMcOTvtTjq#llmWH}N5bwv>ezg@vK`)Cb?NI^XZewsLQ09U zJL?jVy3lt_t?B6Lr*Y~>U~EGp;nZ!9BaX3s5JXL@W>x)`idAcCAgFQa^q4X~3UyuQ za>Uu~i6e;f|NlYN7lcGl10rEF^LNCfEL*XpW_dZ5?mTmraZtv!8=V?&{FNgz*ktL? zxWCQy{C3Kd`ZW6HNnzSJqrQ#)KQYGNjdql-jdoP8jW!gnj5A8YPQMP!g$=B8{{Y6J zDsJ>c5!`8ii1Km$F#Qbue~!;XvMGbI&}&;!2Ps9F2T9#e*+qxQx3PnA_LEjLWk2;R zD&9|7MZ>-OsejS%%>6W=sANCo7Tr%;-oU)PP8yU!>y5koyuq%!A$dbxcf<0An|HF9 z4EhC*bEqGVRpg}=q){aerD_^QH4y45nnbIqglcI9)ze~Hi`I2?60N7Lw1FPMs6{5* z^h4tw9uK|GUxO6!;Tpdy<~Q z5#qtDSw^2xMHvTZL=hI5eTYVGEJBTYR40x0pe#Q|*5fhO)8CkDGpL_LBk5#=Pjik@ z7M~t@jbV!3b0cUgP{9^Z%{mBgFy($Kc$^08BTwGAPCCXz8GG@lzce49@q4&Lo=h-r zkL{$186?-$=#yJ~fF|Krc!(x%#C^XGD&kI>k_kN**OWX?Q)Fm~K@^V%JO-WORNP5Z zG0Pk;Zu%df(!t)nB?oBQ9y&|9Pw%7|9+F4-H1hz>zJV0)?c_!G!QMS4#W_7u%(N+H z$`Xv#3CX!r47SnaVqu<#ymMRwq~memV?KThI%%O-ctHQbaw<+fINqDe`ur?(kYxZB7yhET_RI+vG2O_$OO#`$&5lrs_)o8hy+5xy7u+W{*!RdhC8T1_O zq8HHTb@V<=XX9njIrMLE=ArXBlXmj}x{$}wMO;YV;`#XS>v*))(Up8MU1dON7FKdE zokG8+X949CSf$^9rU$&dL(kK11$?~40-DO}G1u<^-WRc!X{3ElBNh7n7u2ZGOA7r# z8@HH0r*W)}|1XUEE0}^up_kEvSfN*P=v9pJV)WIZkC$#HWce`q!H9SQByB@>aVITd zc%G$lSjJdwS#_}m<8lkeqK*pSbGfa40qhF=Di6_01F*&S(}@SEigB)Hp>9y+gH(eX zt%FwCa9%BNo>;{DX^l{=bs_M4bQMh3dFXa(2TmV|a*@V{3_??svkJf{e4WO=h%rcX`4xSol7_P4ap01~{bOVj2 z8{yh+qEbYP;}HwaM0_|KQQ-nic{$wJweat^z;WFPN4AgdrVeQRQM|5r7FRFA%fAE9 z{ulW6FX=(x<{=&m=ko|=C^B{9AYhb*fU)THI=ulMo(byD)0;qwpkf$heL*0r+iAY=rdYMpCeR!i7@dMp&(7CGt)V6@s~hLm%$LPgMYmVuKPBmUU#vN4l%w` zfQFuh`+t#hq0PLc4)M~_%y0Su0j4{j00fxE+)U>|hwoTA94y8>%U0n!1%yhvC=j1f zz@tlAv&BkljEv%}fu0Qq>1@+ALrBRCC!fyQN9T1CK3ndd=kOfL<+=Fud!E6sndg*P z{CebdsWsU-rrV&o@DeBH(*?mLVoetoT%1oAMGn%%?ujokQmab~_R(e5w7Zk(Ri5E} zj;Cy1M5Fiwn!}5YsS70X(Ohe4xe@^(ou{cVh+6?#kGxQ{*x6v*6Ai*rcRz-V7N?P& zbh(GtCo@wclj9Af@J7nx&BioCFc8C>X$H~X;gZb&n?X>UM_w6Ov((^Dl1rIoj5*5~ zZzo-mW|mVh%NESycgfM7MclMOo8{9Ii}rb-Eh`>s_%|f(SB~66D$ZA}M}Ag)FS=zT z{U40rZ6-8hj65?yncM{7wNO6}V!mxOn77gp4mm;`0-_%Q*Rsx`&N_#})7a}&DI;&G z0@!1Yj~#}tfntQALP1X_UBkw9ARB3;0iSPsX?-^ieF%dSyKvZs|A~mw2#(Phj?;MF zP7^snlepdCaFUC|LWje`R1U}69DV|uGyz|Vv#3MT%r*Dm!c5qW0G z2W2EJ%iQFoT?)9D1&G%eg|qy5VZR~zzb9~n1C9wMQYn23}GP5#F+_~|IruU zeDkFb^swa%|3JX?8~>mz0ZMv{{7=G0GF_#A&IY&=)rA` zVnT{La(g$y@A4N@kykLO;T{Sa+EG+7CD&=Gxv%1Zf`@WnlH!pRGg3U3;%h0sQ7|hb zK2b5(f^YFu!FL+c_+G&e8Vt+}#0t}Q1X2aZt>nDw;?Q!g;8ZH6J1n4jrn_dk`2_(n zDUb}eGp;3YsIY9T89CeZb2AU~wADPbTzAc)vtSA|k65CA=--1NgGLaAIRq)_dB>)-Y5T^;?TxZo^DW0_ zka*2;ee$0tt6q7@Tn%Uo$d6`IP-d$I20ongAQqIx9SYPDavL^HD>-$yY))9RMQwW= z56Y}M`fx_aDV)}E9yfI4@P&?EoD?`d<~Y9RyGAV&I%VeSt~J{0Jr!u*Lp(jdY?gfj z*0BIn$0A5!yzCe?9ZR^Z!@{yaLMqruJvwJPR-{2yid89WDI6*KP!mW;jrVb><5Oe= zx@T-TYZ>3km>a}e_A`=$3_GIWnGP3B+Pxd+JgA+I)C7j5fYI30m1&+0~%Rdq%a>_p>a zx6pWoM=H;A6o$I%cmxy#HT)%B1hjZiH{H$9c)~R*t2~DSwP?u3;71^TP?P@{qxWs( zWzxR?qT=wZ8?G&o{eLizmRx6D_I_A~={mqTFFzdJAAf=~;>gk^so~uy&>M9huNt1m z#_abT#%H{Hlf1~|=$7NhH$mOWVC4}CR-PTMD!=e#QTB6}<0`l&vacb2=1UXKQZ@(5 z>uCnf962{&x5=& z{{+jG`8$|DaRkjjK8F&2iFoWMDr1pC&P4)sG=N;9O#)4AH)Rb&xZJ=rOl1%=rN;k6 zayBMwD{VvD5AMPNF_ZF=3Ihq*k2rH|W?!LYB;E7^eJP#qt*>zCIkb+hOCv9FIMueR zQaZYZM&zzI@He{CGp+g(41;3zCru!0F65Mq|y|J`5fWX`5IkYQ@`L? z>iGHJ(H%o}i$IE4=1q3ALB<&WP=l2w2vWnB=)x6_%~cY0ja|J?UT^TrO^o6e#xaIT z$|CME!X&T4dss&yC_2l+s%T||D~!w%^Tm diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/ServersInfo.class b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/client/servers/ServersInfo.class deleted file mode 100644 index 924b42cb79bb9b260c77f1407f557df399fe3148..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 875 zcmb7C!EVz)5Ph3CcI+CGh61655@-u)1oeRvO348b0?7p-qe@Z5VdHL{tsFbDH~B7* zKt&+<06q#awnK4&L%Dco-p;;x^E}^weEtUD0q$DRv1Z`9g$mY8n7C2Lx`CTn*s*X6 zw+(DCn4>sWsY>{iVaJV=z!82Zr>Ss4k&b!fP$nYfq#~J%Bz3&}d=VYReTL?tm`h*m z@hA`zs!ACe?lGTpXQpK6?C~iTnVt+Hu4ai~czyPEw@5>J@3?Uk^v@yS>7*oKK>Yfy zjHDVcRJ+^z4BC_UkUBM78Hty($w(w`_$VZ#<;Fe__jw|-d;w}|EJ-zWKj-A>V)VL- zJ(b8PU|8vHm*yx?(q(z^Eb+xNnKf?~qVv}~nL{?3SY}xM?bdUij>$0_HZG8&(u2;y z=}&sJmEP<8={kXLsYOned--Z~EPQ3d!jgea8(X-;aR0wXJj3^EQvE1SCR{N*?EXFR zK?y1Z^#9=tEuKl63EE1s2ul>PY-0Le%+W@EL*@|DB4mInML@H60@nM2%J2l$kI>%d z)tBg-Z8&fl8dkAFkzLdia)mO6t7tE{9;24uwOh5?SLnlP?*j~PsL`Q$pHP2C^%Z2C RdS16);%lGsUCXOhe*$9l-c4C(1*2;^eKou5>u_MEwuJQ-w!=K$8&o8qyP55YL))(%!HlL4UcnrPBMG% zo%=oRcYojS`*vS``?(hY+=N#(EJe459`shh!Y+viBnlcT(49gbYzaq068%+3V7CSr zMF~%XjsdlOPZjoJUlsP_ed_Uki4SO)f)7^VLwHc)Aq~^<;S`lUoWgQ^B#B3=@KHP} zaX`Z?bW40p!yJ4(#mQq5pO84HA%jn<`KQ$5afv51)F@wS)JhE=Q;)~hdZ)wb?3 z_88d#&njfwjQ&*%u1zbIB`jZ4{Z$Jp%PIzelLAZ2N;)y7deH%M>nR)tL z^b9+1QaWbM6POlpzQr?LBRJlYvI@sW=8nD~HlZ_u!JZRnvrR9%xxFQ~-}a1s&HM6Z zzh^l%O(u(Ge!#W7{Q?sm-=Ah%U5m@hm=y6ug^??xyTeTaw_L_8*DN{%Zhp*ZLqY1A z5QOTYrV15uS|y-}t*eFrHEE$&mPzrtvf||ePe~d0K(Xt_f^vWVC@{B;4Z`YRS}^RM zY>Vxg3i@R&1~+rL5Uf!_$azNo0S4Dk1D`#fB!Q45B)&#EU;;B81yVVy$2PnHmsfi5 z5_tb#UAp#ENv>vo28plb{QF*OsWeXqSS%_qUd+>am6$qKqCw&*9bd;cB%ajqO?*pW z`S|yKnJ@}09$zlJ-Y8{A4C?qcz9X=(oSXuRYwjK}i(aNwjJD&Wd8Ls0vp3!jv&q|!saSEq-xjN2ZNXIaq6IgP!nnt-o#|VBX@w|=~l>B6$ z?tDx(I!?hfY#l#R+FwMIj$5!opm9^L>6#gXFAT}oPh4X z3fW1Zy0kOrxt7|y5-;iaIewwzWhGF5Wz$g>)bUH4llYZ_+OKu|2IqDB7Hw+!I~~8r z9|UGaUATlG>3fU4$0%4`8M0@lhC~r@G2m|a+v=)rH?vR4WWb|^t+}KSft8H0OhNM`QSs(@GhwR~_B{%`=V=3<8(m0?T zWwjtd!b|RAb@nSrWv(N)skv>u>UTL|a$$mwtG>Zy+6g>Sds$j7=RkQP9w(#6X$pef z#eTgaxelHXB1;pHB%9el- zl;TSN!ufLMn3qjXp}?jhDDKlrLZx-qd@F1#6j-8~MB7G^k3#X}zY{ooQDx)1L z&#>2UZGq|03%O>KynH-@zCr2=18@iErg@sG!>MS&8|gW2reXKE*>FhLd-V5 z=}i`_Zqu{+=;9TtOrvFYk?8`#+spYjZY)O&RYZlly3Rl&0eg*-)m`QuD{r>3xiR~Q zTB2)e?fNJ?DE_92c>e&Au_Eeh$Q%F5BvJ8;aiFC%QZq7aKJ33mxp zn6B%%Dzze3!?%%@O}(zOSM{|1Ezh_V7i;}55bS?b#8vQRMxZ9DvZ-Jciy>b`5w(in zkCyZMA0TkODzhBLIc9gm=PJ&!{1p7Gs5=Ak3e)`JaLgZFTj!fm*n zyC@t#0*NY$OstC!AvTP7jP*RxT9=5-+7_OLTyzc<;`j(EI?kYS!@?7gBS?0{&mc7n zEsoQudJ%dN3~icCV{_oYPDLHjxl!#3r}GYL&cL&)e!2_$zf#U zxMvWRgBK1CVnIVvh49A2^H|yu9~+w75N=ZYm&GyocJJcj#LEHkn)nBn@HYj8rbh`w z;6_X&6lY@@<`I resources = new ArrayList<>(); - - for (int i = 0; i < object.getChildNodes().getLength(); i++) { - Node field = object.getChildNodes().item(i); - switch (field.getNodeName()) { - case "ObjectID": - id = Integer.valueOf(field.getTextContent()); - break; - case "Name": - name = field.getTextContent(); - break; - case "Description1": - description = field.getTextContent(); - break; - case "MultipleInstances": - multiple = "Multiple".equals(field.getTextContent()); - break; - case "Mandatory": - mandatory = "Mandatory".equals(field.getTextContent()); - break; - case "Resources": - for (int j = 0; j < field.getChildNodes().getLength(); j++) { - Node item = field.getChildNodes().item(j); - if (item.getNodeName().equals("Item")) { - resources.add(this.parseResource(item)); - } - } - break; - } - } - - return new ObjectModel(id, name, description, multiple, mandatory, resources); - - } - - private ResourceModel parseResource(Node item) { - - Integer id = Integer.valueOf(item.getAttributes().getNamedItem("ID").getTextContent()); - String name = null; - Operations operations = Operations.NONE; - boolean multiple = false; - boolean mandatory = false; - Type type = Type.STRING; - String rangeEnumeration = null; - String units = null; - String description = null; - - for (int i = 0; i < item.getChildNodes().getLength(); i++) { - Node field = item.getChildNodes().item(i); - switch (field.getNodeName()) { - case "Name": - name = field.getTextContent(); - break; - case "Operations": - String strOp = field.getTextContent(); - if (strOp != null && !strOp.isEmpty()) { - operations = Operations.valueOf(strOp); - } - break; - case "MultipleInstances": - multiple = "Multiple".equals(field.getTextContent()); - break; - case "Mandatory": - mandatory = "Mandatory".equals(field.getTextContent()); - break; - case "Type": - switch (field.getTextContent()) { - case "String": - type = Type.STRING; - break; - case "Integer": - type = Type.INTEGER; - break; - case "Float": - type = Type.FLOAT; - break; - case "Boolean": - type = Type.BOOLEAN; - break; - case "Opaque": - type = Type.OPAQUE; - break; - case "Time": - type = Type.TIME; - break; - } - break; - case "RangeEnumeration": - rangeEnumeration = field.getTextContent(); - break; - case "Units": - units = field.getTextContent(); - break; - case "Description": - description = field.getTextContent(); - break; - } - - } - - return new ResourceModel(id, name, operations, multiple, mandatory, type, rangeEnumeration, units, description); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.eclipse.leshan.core.model.ResourceModel.Operations; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +/** + * A parser for Object DDF files. + */ +public class DDFFileParser { + + private static final Logger LOG = LoggerFactory.getLogger(DDFFileParser.class); + + private final DocumentBuilderFactory factory; + + public DDFFileParser() { + factory = DocumentBuilderFactory.newInstance(); + } + + public ObjectModel parse(File ddfFile) { + try (InputStream input = new FileInputStream(ddfFile)) { + return parse(input, ddfFile.getName()); + } catch (IOException e) { + LOG.error("Could not parse the resource definition file " + ddfFile.getName(), e); + } + return null; + } + + public ObjectModel parse(InputStream inputStream, String streamName) { + streamName = streamName == null ? "" : streamName; + + LOG.debug("Parsing DDF file {}", streamName); + + ObjectModel result = null; + try { + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(inputStream); + + Node object = document.getDocumentElement().getElementsByTagName("Object").item(0); + result = this.parseObject(object); + + } catch (SAXException | IOException | ParserConfigurationException e) { + LOG.error("Could not parse the resource definition file " + streamName, e); + } + + return result; + } + + private ObjectModel parseObject(Node object) { + + Integer id = null; + String name = null; + String description = null; + boolean multiple = false; + boolean mandatory = false; + List resources = new ArrayList<>(); + + for (int i = 0; i < object.getChildNodes().getLength(); i++) { + Node field = object.getChildNodes().item(i); + switch (field.getNodeName()) { + case "ObjectID": + id = Integer.valueOf(field.getTextContent()); + break; + case "Name": + name = field.getTextContent(); + break; + case "Description1": + description = field.getTextContent(); + break; + case "MultipleInstances": + multiple = "Multiple".equals(field.getTextContent()); + break; + case "Mandatory": + mandatory = "Mandatory".equals(field.getTextContent()); + break; + case "Resources": + for (int j = 0; j < field.getChildNodes().getLength(); j++) { + Node item = field.getChildNodes().item(j); + if (item.getNodeName().equals("Item")) { + resources.add(this.parseResource(item)); + } + } + break; + } + } + + return new ObjectModel(id, name, description, multiple, mandatory, resources); + + } + + private ResourceModel parseResource(Node item) { + + Integer id = Integer.valueOf(item.getAttributes().getNamedItem("ID").getTextContent()); + String name = null; + Operations operations = Operations.NONE; + boolean multiple = false; + boolean mandatory = false; + Type type = Type.STRING; + String rangeEnumeration = null; + String units = null; + String description = null; + + for (int i = 0; i < item.getChildNodes().getLength(); i++) { + Node field = item.getChildNodes().item(i); + switch (field.getNodeName()) { + case "Name": + name = field.getTextContent(); + break; + case "Operations": + String strOp = field.getTextContent(); + if (strOp != null && !strOp.isEmpty()) { + operations = Operations.valueOf(strOp); + } + break; + case "MultipleInstances": + multiple = "Multiple".equals(field.getTextContent()); + break; + case "Mandatory": + mandatory = "Mandatory".equals(field.getTextContent()); + break; + case "Type": + switch (field.getTextContent()) { + case "String": + type = Type.STRING; + break; + case "Integer": + type = Type.INTEGER; + break; + case "Float": + type = Type.FLOAT; + break; + case "Boolean": + type = Type.BOOLEAN; + break; + case "Opaque": + type = Type.OPAQUE; + break; + case "Time": + type = Type.TIME; + break; + } + break; + case "RangeEnumeration": + rangeEnumeration = field.getTextContent(); + break; + case "Units": + units = field.getTextContent(); + break; + case "Description": + description = field.getTextContent(); + break; + } + + } + + return new ResourceModel(id, name, operations, multiple, mandatory, type, rangeEnumeration, units, description); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/Ddf2JsonGenerator.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/Ddf2JsonGenerator.java index 4d67cc6..9d234d8 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/Ddf2JsonGenerator.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/Ddf2JsonGenerator.java @@ -1,108 +1,108 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.eclipse.leshan.core.model.json.ObjectModelSerializer; -import org.eclipse.leshan.core.model.json.ResourceModelSerializer; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class Ddf2JsonGenerator { - - private Gson gson; - - public Ddf2JsonGenerator() { - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(ObjectModel.class, new ObjectModelSerializer()); - gsonBuilder.registerTypeAdapter(ResourceModel.class, new ResourceModelSerializer()); - gsonBuilder.setPrettyPrinting(); - gson = gsonBuilder.create(); - } - - private void generate(Collection objectModels, OutputStream output) throws IOException { - try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output)) { - gson.toJson(objectModels, outputStreamWriter); - } - } - - private void generate(File input, OutputStream output) throws IOException { - // check input exists - if (!input.exists()) - throw new FileNotFoundException(input.toString()); - - // get input files. - File[] files; - if (input.isDirectory()) { - files = input.listFiles(); - } else { - files = new File[] { input }; - } - - // parse DDF file - List objectModels = new ArrayList(); - DDFFileParser ddfParser = new DDFFileParser(); - for (File f : files) { - if (f.canRead()) { - ObjectModel objectModel = ddfParser.parse(f); - if (objectModel != null) { - objectModels.add(objectModel); - } - } - } - - // sort object by id - Collections.sort(objectModels, new Comparator() { - @Override - public int compare(ObjectModel o1, ObjectModel o2) { - return o1.id - o2.id; - } - }); - - // generate json - generate(objectModels, output); - } - - public static void main(String[] args) throws FileNotFoundException, IOException { - // default value - String ddfFilesPath = "ddffiles"; - String outputPath = "src/main/resources/objectspec.json"; - - // use arguments if they exit - if (args.length >= 1) - ddfFilesPath = args[0]; // the path to a DDF file or a folder which contains DDF files. - if (args.length >= 2) - outputPath = args[1]; // the path of the output file. - - // generate object spec file - Ddf2JsonGenerator ddfJsonGenerator = new Ddf2JsonGenerator(); - try (FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) { - ddfJsonGenerator.generate(new File(ddfFilesPath), fileOutputStream); - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.leshan.core.model.json.ObjectModelSerializer; +import org.eclipse.leshan.core.model.json.ResourceModelSerializer; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class Ddf2JsonGenerator { + + private Gson gson; + + public Ddf2JsonGenerator() { + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeAdapter(ObjectModel.class, new ObjectModelSerializer()); + gsonBuilder.registerTypeAdapter(ResourceModel.class, new ResourceModelSerializer()); + gsonBuilder.setPrettyPrinting(); + gson = gsonBuilder.create(); + } + + private void generate(Collection objectModels, OutputStream output) throws IOException { + try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output)) { + gson.toJson(objectModels, outputStreamWriter); + } + } + + private void generate(File input, OutputStream output) throws IOException { + // check input exists + if (!input.exists()) + throw new FileNotFoundException(input.toString()); + + // get input files. + File[] files; + if (input.isDirectory()) { + files = input.listFiles(); + } else { + files = new File[] { input }; + } + + // parse DDF file + List objectModels = new ArrayList(); + DDFFileParser ddfParser = new DDFFileParser(); + for (File f : files) { + if (f.canRead()) { + ObjectModel objectModel = ddfParser.parse(f); + if (objectModel != null) { + objectModels.add(objectModel); + } + } + } + + // sort object by id + Collections.sort(objectModels, new Comparator() { + @Override + public int compare(ObjectModel o1, ObjectModel o2) { + return o1.id - o2.id; + } + }); + + // generate json + generate(objectModels, output); + } + + public static void main(String[] args) throws FileNotFoundException, IOException { + // default value + String ddfFilesPath = "ddffiles"; + String outputPath = "src/main/resources/objectspec.json"; + + // use arguments if they exit + if (args.length >= 1) + ddfFilesPath = args[0]; // the path to a DDF file or a folder which contains DDF files. + if (args.length >= 2) + outputPath = args[1]; // the path of the output file. + + // generate object spec file + Ddf2JsonGenerator ddfJsonGenerator = new Ddf2JsonGenerator(); + try (FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) { + ddfJsonGenerator.generate(new File(ddfFilesPath), fileOutputStream); + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/LwM2mModel.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/LwM2mModel.java index 232ef47..694124b 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/LwM2mModel.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/LwM2mModel.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A collection of LWM2M object definitions. - */ -public class LwM2mModel { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mModel.class); - - private final Map objects; // objects by ID - - public LwM2mModel(ObjectModel... objectModels) { - this(Arrays.asList(objectModels)); - } - - public LwM2mModel(Collection objectModels) { - if (objectModels == null) { - objects = new HashMap<>(); - } else { - Map map = new HashMap<>(); - for (ObjectModel model : objectModels) { - ObjectModel old = map.put(model.id, model); - if (old != null) { - LOG.debug("Model already exists for object {}. Overriding it.", model.id); - } - } - objects = Collections.unmodifiableMap(map); - } - } - - /** - * Returns the description of a given resource. - * - * @param objectId the object identifier - * @param resourceId the resource identifier - * @return the resource specification or null if not found - */ - public ResourceModel getResourceModel(int objectId, int resourceId) { - ObjectModel object = objects.get(objectId); - if (object != null) { - return object.resources.get(resourceId); - } - return null; - } - - /** - * Returns the description of a given object. - * - * @param objectId the object identifier - * @return the object definition or null if not found - */ - public ObjectModel getObjectModel(int objectId) { - return objects.get(objectId); - } - - /** - * @return all the objects descriptions known. - */ - public Collection getObjectModels() { - return objects.values(); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A collection of LWM2M object definitions. + */ +public class LwM2mModel { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mModel.class); + + private final Map objects; // objects by ID + + public LwM2mModel(ObjectModel... objectModels) { + this(Arrays.asList(objectModels)); + } + + public LwM2mModel(Collection objectModels) { + if (objectModels == null) { + objects = new HashMap<>(); + } else { + Map map = new HashMap<>(); + for (ObjectModel model : objectModels) { + ObjectModel old = map.put(model.id, model); + if (old != null) { + LOG.debug("Model already exists for object {}. Overriding it.", model.id); + } + } + objects = Collections.unmodifiableMap(map); + } + } + + /** + * Returns the description of a given resource. + * + * @param objectId the object identifier + * @param resourceId the resource identifier + * @return the resource specification or null if not found + */ + public ResourceModel getResourceModel(int objectId, int resourceId) { + ObjectModel object = objects.get(objectId); + if (object != null) { + return object.resources.get(resourceId); + } + return null; + } + + /** + * Returns the description of a given object. + * + * @param objectId the object identifier + * @return the object definition or null if not found + */ + public ObjectModel getObjectModel(int objectId) { + return objects.get(objectId); + } + + /** + * @return all the objects descriptions known. + */ + public Collection getObjectModels() { + return objects.values(); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectLoader.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectLoader.java index 20580f0..3eff6de 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectLoader.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectLoader.java @@ -1,155 +1,155 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.leshan.core.model.json.ObjectModelDeserializer; -import org.eclipse.leshan.core.model.json.ResourceModelDeserializer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class ObjectLoader { - - private static final Logger LOG = LoggerFactory.getLogger(ObjectLoader.class); - - private static final Gson GSON; - - static { - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(ObjectModel.class, new ObjectModelDeserializer()); - gsonBuilder.registerTypeAdapter(ResourceModel.class, new ResourceModelDeserializer()); - GSON = gsonBuilder.create(); - } - - /** - * Load the default LWM2M objects - */ - public static List loadDefault() { - List models = new ArrayList<>(); - - // standard objects - LOG.debug("Loading OMA standard object models"); - InputStream input = ObjectLoader.class.getResourceAsStream("/oma-objects-spec.json"); - if (input != null) { - try (Reader reader = new InputStreamReader(input)) { - models.addAll(loadJsonStream(input)); - } catch (IOException e) { - LOG.error("Unable to load object models", e); - } - } - - // custom objects (environment variable) - String modelsFolderEnvVar = System.getenv("MODELS_FOLDER"); - if (modelsFolderEnvVar != null) { - models.addAll(loadObjectsFromDir(new File(modelsFolderEnvVar))); - } - - return models; - } - - /** - * Load object definitions from DDF or JSON files. - * - * @param modelDir the directory containing the object definition files. - */ - public static List load(File modelDir) { - return loadObjectsFromDir(modelDir); - } - - /** - * Load object definition from DDF file. - * - * @param input An inputStream to a DFF file. - * @param streamName A name for the stream used for logging only - */ - public static ObjectModel loadDdfFile(InputStream input, String streamName) { - DDFFileParser ddfFileParser = new DDFFileParser(); - return ddfFileParser.parse(input, streamName); - } - - /** - * Load object definitions from JSON stream. - * - * @param input An inputStream to a JSON stream. - */ - public static List loadJsonStream(InputStream input) { - List models = new ArrayList<>(); - Reader reader = new InputStreamReader(input); - ObjectModel[] objectModels = GSON.fromJson(reader, ObjectModel[].class); - for (ObjectModel objectModel : objectModels) { - models.add(objectModel); - } - return models; - } - - /* - * Load object definitions from files - */ - private static List loadObjectsFromDir(File modelsDir) { - List models = new ArrayList<>(); - - // check if the folder is usable - if (!modelsDir.isDirectory() || !modelsDir.canRead()) { - LOG.error(MessageFormat.format( - "Models folder {0} is not a directory or you are not allowed to list its content", - modelsDir.getPath())); - } else { - // get all files - for (File file : modelsDir.listFiles()) { - if (!file.canRead()) - continue; - - if (file.getName().endsWith(".xml")) { - // from DDF file - LOG.debug("Loading object models from DDF file {}", file.getAbsolutePath()); - try (FileInputStream input = new FileInputStream(file)) { - ObjectModel objectModel = loadDdfFile(input, file.getName()); - if (objectModel != null) { - models.add(objectModel); - } - } catch (IOException e) { - LOG.warn(MessageFormat.format("Unable to load object models for {0}", file.getAbsolutePath()), - e); - } - - } else if (file.getName().endsWith(".json")) { - // from JSON file - LOG.debug("Loading object models from JSON file {}", file.getAbsolutePath()); - try (FileInputStream input = new FileInputStream(file)) { - models.addAll(loadJsonStream(input)); - } catch (IOException e) { - LOG.warn(MessageFormat.format("Unable to load object models for {0}", file.getAbsolutePath()), - e); - } - } - } - } - return models; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.leshan.core.model.json.ObjectModelDeserializer; +import org.eclipse.leshan.core.model.json.ResourceModelDeserializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class ObjectLoader { + + private static final Logger LOG = LoggerFactory.getLogger(ObjectLoader.class); + + private static final Gson GSON; + + static { + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeAdapter(ObjectModel.class, new ObjectModelDeserializer()); + gsonBuilder.registerTypeAdapter(ResourceModel.class, new ResourceModelDeserializer()); + GSON = gsonBuilder.create(); + } + + /** + * Load the default LWM2M objects + */ + public static List loadDefault() { + List models = new ArrayList<>(); + + // standard objects + LOG.debug("Loading OMA standard object models"); + InputStream input = ObjectLoader.class.getResourceAsStream("/oma-objects-spec.json"); + if (input != null) { + try (Reader reader = new InputStreamReader(input)) { + models.addAll(loadJsonStream(input)); + } catch (IOException e) { + LOG.error("Unable to load object models", e); + } + } + + // custom objects (environment variable) + String modelsFolderEnvVar = System.getenv("MODELS_FOLDER"); + if (modelsFolderEnvVar != null) { + models.addAll(loadObjectsFromDir(new File(modelsFolderEnvVar))); + } + + return models; + } + + /** + * Load object definitions from DDF or JSON files. + * + * @param modelDir the directory containing the object definition files. + */ + public static List load(File modelDir) { + return loadObjectsFromDir(modelDir); + } + + /** + * Load object definition from DDF file. + * + * @param input An inputStream to a DFF file. + * @param streamName A name for the stream used for logging only + */ + public static ObjectModel loadDdfFile(InputStream input, String streamName) { + DDFFileParser ddfFileParser = new DDFFileParser(); + return ddfFileParser.parse(input, streamName); + } + + /** + * Load object definitions from JSON stream. + * + * @param input An inputStream to a JSON stream. + */ + public static List loadJsonStream(InputStream input) { + List models = new ArrayList<>(); + Reader reader = new InputStreamReader(input); + ObjectModel[] objectModels = GSON.fromJson(reader, ObjectModel[].class); + for (ObjectModel objectModel : objectModels) { + models.add(objectModel); + } + return models; + } + + /* + * Load object definitions from files + */ + private static List loadObjectsFromDir(File modelsDir) { + List models = new ArrayList<>(); + + // check if the folder is usable + if (!modelsDir.isDirectory() || !modelsDir.canRead()) { + LOG.error(MessageFormat.format( + "Models folder {0} is not a directory or you are not allowed to list its content", + modelsDir.getPath())); + } else { + // get all files + for (File file : modelsDir.listFiles()) { + if (!file.canRead()) + continue; + + if (file.getName().endsWith(".xml")) { + // from DDF file + LOG.debug("Loading object models from DDF file {}", file.getAbsolutePath()); + try (FileInputStream input = new FileInputStream(file)) { + ObjectModel objectModel = loadDdfFile(input, file.getName()); + if (objectModel != null) { + models.add(objectModel); + } + } catch (IOException e) { + LOG.warn(MessageFormat.format("Unable to load object models for {0}", file.getAbsolutePath()), + e); + } + + } else if (file.getName().endsWith(".json")) { + // from JSON file + LOG.debug("Loading object models from JSON file {}", file.getAbsolutePath()); + try (FileInputStream input = new FileInputStream(file)) { + models.addAll(loadJsonStream(input)); + } catch (IOException e) { + LOG.warn(MessageFormat.format("Unable to load object models for {0}", file.getAbsolutePath()), + e); + } + } + } + } + return models; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectModel.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectModel.java index a77b79e..bf3dd9d 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectModel.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ObjectModel.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * An object description - */ -public class ObjectModel { - - private static final Logger LOG = LoggerFactory.getLogger(ObjectModel.class); - - public final int id; - public final String name; - public final String description; - public final boolean multiple; - public final boolean mandatory; - - public final Map resources; // resources by ID - - public ObjectModel(int id, String name, String description, boolean multiple, boolean mandatory, - ResourceModel... resources) { - this(id, name, description, multiple, mandatory, Arrays.asList(resources)); - } - - public ObjectModel(int id, String name, String description, boolean multiple, boolean mandatory, - Collection resources) { - this.id = id; - this.name = name; - this.description = description; - this.multiple = multiple; - this.mandatory = mandatory; - - Map resourcesMap = new HashMap<>(resources.size()); - for (ResourceModel resource : resources) { - ResourceModel old = resourcesMap.put(resource.id, resource); - if (old != null) { - LOG.debug("Model already exists for resource {} of object {}. Overriding it.", resource.id, id); - } - resourcesMap.put(resource.id, resource); - } - this.resources = Collections.unmodifiableMap(resourcesMap); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ObjectModel [id=").append(id).append(", name=").append(name).append(", description=") - .append(description).append(", multiple=").append(multiple).append(", mandatory=").append(mandatory) - .append(", resources=").append(resources).append("]"); - return builder.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * An object description + */ +public class ObjectModel { + + private static final Logger LOG = LoggerFactory.getLogger(ObjectModel.class); + + public final int id; + public final String name; + public final String description; + public final boolean multiple; + public final boolean mandatory; + + public final Map resources; // resources by ID + + public ObjectModel(int id, String name, String description, boolean multiple, boolean mandatory, + ResourceModel... resources) { + this(id, name, description, multiple, mandatory, Arrays.asList(resources)); + } + + public ObjectModel(int id, String name, String description, boolean multiple, boolean mandatory, + Collection resources) { + this.id = id; + this.name = name; + this.description = description; + this.multiple = multiple; + this.mandatory = mandatory; + + Map resourcesMap = new HashMap<>(resources.size()); + for (ResourceModel resource : resources) { + ResourceModel old = resourcesMap.put(resource.id, resource); + if (old != null) { + LOG.debug("Model already exists for resource {} of object {}. Overriding it.", resource.id, id); + } + resourcesMap.put(resource.id, resource); + } + this.resources = Collections.unmodifiableMap(resourcesMap); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ObjectModel [id=").append(id).append(", name=").append(name).append(", description=") + .append(description).append(", multiple=").append(multiple).append(", mandatory=").append(mandatory) + .append(", resources=").append(resources).append("]"); + return builder.toString(); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ResourceModel.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ResourceModel.java index 143b5c9..37580eb 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ResourceModel.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/ResourceModel.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model; - -/** - * A resource description - */ -public class ResourceModel { - - public enum Operations { - NONE, R, W, RW, E, RE, WE, RWE; - - public boolean isReadable() { - return this == R || this == RW || this == RE || this == RWE; - } - - public boolean isWritable() { - return this == W || this == RW || this == WE || this == RWE; - } - - public boolean isExecutable() { - return this == E || this == RE || this == WE || this == RWE; - } - } - - public enum Type { - STRING, INTEGER, FLOAT, BOOLEAN, OPAQUE, TIME - } - - public final int id; - public final String name; - public final Operations operations; - public final boolean multiple; - public final boolean mandatory; - public final Type type; - public final String rangeEnumeration; - public final String units; - public final String description; - - public ResourceModel(int id, String name, Operations operations, boolean multiple, boolean mandatory, Type type, - String rangeEnumeration, String units, String description) { - this.id = id; - this.name = name; - this.operations = operations; - this.multiple = multiple; - this.mandatory = mandatory; - this.type = type; - this.rangeEnumeration = rangeEnumeration; - this.units = units; - this.description = description; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ResourceDesc [id=").append(id).append(", name=").append(name).append(", operations=") - .append(operations).append(", multiple=").append(multiple).append(", mandatory=").append(mandatory) - .append(", type=").append(type).append(", rangeEnumeration=").append(rangeEnumeration) - .append(", units=").append(units).append(", description=").append(description).append("]"); - return builder.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model; + +/** + * A resource description + */ +public class ResourceModel { + + public enum Operations { + NONE, R, W, RW, E, RE, WE, RWE; + + public boolean isReadable() { + return this == R || this == RW || this == RE || this == RWE; + } + + public boolean isWritable() { + return this == W || this == RW || this == WE || this == RWE; + } + + public boolean isExecutable() { + return this == E || this == RE || this == WE || this == RWE; + } + } + + public enum Type { + STRING, INTEGER, FLOAT, BOOLEAN, OPAQUE, TIME + } + + public final int id; + public final String name; + public final Operations operations; + public final boolean multiple; + public final boolean mandatory; + public final Type type; + public final String rangeEnumeration; + public final String units; + public final String description; + + public ResourceModel(int id, String name, Operations operations, boolean multiple, boolean mandatory, Type type, + String rangeEnumeration, String units, String description) { + this.id = id; + this.name = name; + this.operations = operations; + this.multiple = multiple; + this.mandatory = mandatory; + this.type = type; + this.rangeEnumeration = rangeEnumeration; + this.units = units; + this.description = description; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ResourceDesc [id=").append(id).append(", name=").append(name).append(", operations=") + .append(operations).append(", multiple=").append(multiple).append(", mandatory=").append(mandatory) + .append(", type=").append(type).append(", rangeEnumeration=").append(rangeEnumeration) + .append(", units=").append(units).append(", description=").append(description).append("]"); + return builder.toString(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelDeserializer.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelDeserializer.java index d19b1ad..d745674 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelDeserializer.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelDeserializer.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model.json; - -import java.lang.reflect.Type; - -import org.eclipse.leshan.core.model.ObjectModel; -import org.eclipse.leshan.core.model.ResourceModel; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -public class ObjectModelDeserializer implements JsonDeserializer { - - @Override - public ObjectModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - if (json == null) - return null; - - if (!json.isJsonObject()) - return null; - - JsonObject jsonObject = json.getAsJsonObject(); - if (!jsonObject.has("id")) - return null; - - int id = jsonObject.get("id").getAsInt(); - String name = jsonObject.get("name").getAsString(); - String instancetype = jsonObject.get("instancetype").getAsString(); - boolean mandatory = jsonObject.get("mandatory").getAsBoolean(); - String description = jsonObject.get("description").getAsString(); - ResourceModel[] resourceSpecs = context.deserialize(jsonObject.get("resourcedefs"), ResourceModel[].class); - - return new ObjectModel(id, name, description, "multiple".equals(instancetype), mandatory, resourceSpecs); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model.json; + +import java.lang.reflect.Type; + +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +public class ObjectModelDeserializer implements JsonDeserializer { + + @Override + public ObjectModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + if (json == null) + return null; + + if (!json.isJsonObject()) + return null; + + JsonObject jsonObject = json.getAsJsonObject(); + if (!jsonObject.has("id")) + return null; + + int id = jsonObject.get("id").getAsInt(); + String name = jsonObject.get("name").getAsString(); + String instancetype = jsonObject.get("instancetype").getAsString(); + boolean mandatory = jsonObject.get("mandatory").getAsBoolean(); + String description = jsonObject.get("description").getAsString(); + ResourceModel[] resourceSpecs = context.deserialize(jsonObject.get("resourcedefs"), ResourceModel[].class); + + return new ObjectModel(id, name, description, "multiple".equals(instancetype), mandatory, resourceSpecs); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelSerializer.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelSerializer.java index 02e4ebc..d2a6980 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelSerializer.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ObjectModelSerializer.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model.json; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.eclipse.leshan.core.model.ObjectModel; -import org.eclipse.leshan.core.model.ResourceModel; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -public class ObjectModelSerializer implements JsonSerializer { - - @Override - public JsonElement serialize(ObjectModel object, Type typeOfSrc, JsonSerializationContext context) { - JsonObject element = new JsonObject(); - - // sort resources value - List resourceSpecs = new ArrayList(object.resources.values()); - Collections.sort(resourceSpecs, new Comparator() { - @Override - public int compare(ResourceModel r1, ResourceModel r2) { - return r1.id - r2.id; - } - }); - - // serialize fields - element.addProperty("name", object.name); - element.addProperty("id", object.id); - element.addProperty("instancetype", object.multiple ? "multiple" : "single"); - element.addProperty("mandatory", object.mandatory); - element.addProperty("description", object.description); - element.add("resourcedefs", context.serialize(resourceSpecs)); - - return element; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model.json; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +public class ObjectModelSerializer implements JsonSerializer { + + @Override + public JsonElement serialize(ObjectModel object, Type typeOfSrc, JsonSerializationContext context) { + JsonObject element = new JsonObject(); + + // sort resources value + List resourceSpecs = new ArrayList(object.resources.values()); + Collections.sort(resourceSpecs, new Comparator() { + @Override + public int compare(ResourceModel r1, ResourceModel r2) { + return r1.id - r2.id; + } + }); + + // serialize fields + element.addProperty("name", object.name); + element.addProperty("id", object.id); + element.addProperty("instancetype", object.multiple ? "multiple" : "single"); + element.addProperty("mandatory", object.mandatory); + element.addProperty("description", object.description); + element.add("resourcedefs", context.serialize(resourceSpecs)); + + return element; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelDeserializer.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelDeserializer.java index adadbf1..bdfe835 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelDeserializer.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelDeserializer.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model.json; - -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Operations; -import org.eclipse.leshan.core.model.ResourceModel.Type; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -public class ResourceModelDeserializer implements JsonDeserializer { - - @Override - public ResourceModel deserialize(JsonElement json, java.lang.reflect.Type typeOfT, - JsonDeserializationContext context) throws JsonParseException { - if (json == null) - return null; - - if (!json.isJsonObject()) - return null; - - JsonObject jsonObject = json.getAsJsonObject(); - if (!jsonObject.has("id")) - return null; - - int id = jsonObject.get("id").getAsInt(); - String name = jsonObject.get("name").getAsString(); - Operations operations = Operations.valueOf(jsonObject.get("operations").getAsString()); - String instancetype = jsonObject.get("instancetype").getAsString(); - boolean mandatory = jsonObject.get("mandatory").getAsBoolean(); - Type type = Type.valueOf(jsonObject.get("type").getAsString().toUpperCase()); - String range = jsonObject.get("range").getAsString(); - String units = jsonObject.get("units").getAsString(); - String description = jsonObject.get("description").getAsString(); - - return new ResourceModel(id, name, operations, "multiple".equals(instancetype), mandatory, type, range, units, - description); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model.json; + +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Operations; +import org.eclipse.leshan.core.model.ResourceModel.Type; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +public class ResourceModelDeserializer implements JsonDeserializer { + + @Override + public ResourceModel deserialize(JsonElement json, java.lang.reflect.Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + if (json == null) + return null; + + if (!json.isJsonObject()) + return null; + + JsonObject jsonObject = json.getAsJsonObject(); + if (!jsonObject.has("id")) + return null; + + int id = jsonObject.get("id").getAsInt(); + String name = jsonObject.get("name").getAsString(); + Operations operations = Operations.valueOf(jsonObject.get("operations").getAsString()); + String instancetype = jsonObject.get("instancetype").getAsString(); + boolean mandatory = jsonObject.get("mandatory").getAsBoolean(); + Type type = Type.valueOf(jsonObject.get("type").getAsString().toUpperCase()); + String range = jsonObject.get("range").getAsString(); + String units = jsonObject.get("units").getAsString(); + String description = jsonObject.get("description").getAsString(); + + return new ResourceModel(id, name, operations, "multiple".equals(instancetype), mandatory, type, range, units, + description); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelSerializer.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelSerializer.java index fa2fe29..baed667 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelSerializer.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/model/json/ResourceModelSerializer.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.model.json; - -import java.lang.reflect.Type; - -import org.eclipse.leshan.core.model.ResourceModel; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -public class ResourceModelSerializer implements JsonSerializer { - - @Override - public JsonElement serialize(ResourceModel resource, Type typeOfSrc, JsonSerializationContext context) { - JsonObject element = new JsonObject(); - - element.addProperty("id", resource.id); - element.addProperty("name", resource.name); - element.addProperty("operations", resource.operations.toString()); - element.addProperty("instancetype", resource.multiple ? "multiple" : "single"); - element.addProperty("mandatory", resource.mandatory); - element.addProperty("type", resource.type.toString().toLowerCase()); - element.addProperty("range", resource.rangeEnumeration); - element.addProperty("units", resource.units); - element.addProperty("description", resource.description); - - return element; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.model.json; + +import java.lang.reflect.Type; + +import org.eclipse.leshan.core.model.ResourceModel; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +public class ResourceModelSerializer implements JsonSerializer { + + @Override + public JsonElement serialize(ResourceModel resource, Type typeOfSrc, JsonSerializationContext context) { + JsonObject element = new JsonObject(); + + element.addProperty("id", resource.id); + element.addProperty("name", resource.name); + element.addProperty("operations", resource.operations.toString()); + element.addProperty("instancetype", resource.multiple ? "multiple" : "single"); + element.addProperty("mandatory", resource.mandatory); + element.addProperty("type", resource.type.toString().toLowerCase()); + element.addProperty("range", resource.rangeEnumeration); + element.addProperty("units", resource.units); + element.addProperty("description", resource.description); + + return element; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mMultipleResource.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mMultipleResource.java index 796c87c..0284ead 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mMultipleResource.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mMultipleResource.java @@ -1,255 +1,255 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import java.util.AbstractMap; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.Objects; - -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.util.Validate; - -/** - * A resource which contains several resource instances. - * - * A resource instance is defined by a numeric identifier and a value. There are accessible via {@link #getValues()} - */ -public class LwM2mMultipleResource implements LwM2mResource { - - private final int id; - - private final Map values; - - private final Type type; - - protected LwM2mMultipleResource(int id, Map values, Type type) { - this.id = id; - this.values = Collections.unmodifiableMap(new HashMap(values)); - this.type = type; - } - - public static LwM2mMultipleResource newResource(int id, Map values, Type type) { - switch (type) { - case INTEGER: - Validate.allElementsOfType(values.values(), Long.class); - break; - case FLOAT: - Validate.allElementsOfType(values.values(), Double.class); - break; - case BOOLEAN: - Validate.allElementsOfType(values.values(), Boolean.class); - break; - case OPAQUE: - Validate.allElementsOfType(values.values(), byte[].class); - break; - case STRING: - Validate.allElementsOfType(values.values(), String.class); - break; - case TIME: - Validate.allElementsOfType(values.values(), Date.class); - break; - default: - throw new IllegalArgumentException(String.format("Type %s is not supported", type.name())); - } - return new LwM2mMultipleResource(id, values, type); - } - - public static LwM2mMultipleResource newStringResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.STRING); - } - - public static LwM2mMultipleResource newIntegerResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.INTEGER); - } - - public static LwM2mMultipleResource newBooleanResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.BOOLEAN); - } - - public static LwM2mMultipleResource newFloatResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.FLOAT); - } - - public static LwM2mMultipleResource newDateResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.TIME); - } - - public static LwM2mMultipleResource newBinaryResource(int id, Map values) { - Validate.noNullElements(values.values()); - return new LwM2mMultipleResource(id, values, Type.OPAQUE); - } - - /** - * {@inheritDoc} - */ - @Override - public int getId() { - return id; - } - - /** - * {@inheritDoc} - */ - @Override - public Type getType() { - return type; - } - - /** - * @exception raise a {@link NoSuchElementException} - */ - @Override - public Object getValue() { - throw new NoSuchElementException("There is no 'value' on multiple resources, use getValues() instead."); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getValues() { - return values; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getValue(int id) { - return values.get(id); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isMultiInstances() { - return true; - } - - @Override - public void accept(LwM2mNodeVisitor visitor) { - visitor.visit(this); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + id; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((values == null) ? 0 : internalHashCode(values)); - return result; - } - - /** - * This is a copy of {@link AbstractMap#hashCode()} with custom code to handle byte array equality - */ - private int internalHashCode(Map m) { - int h = 0; - Iterator i = m.entrySet().iterator(); - if (type == Type.OPAQUE) { - // Custom hashcode to handle byte arrays - while (i.hasNext()) { - Entry e = (Entry) i.next(); - h += Objects.hashCode(e.getKey()) ^ Arrays.hashCode((byte[]) e.getValue()); - } - } else { - while (i.hasNext()) { - Entry e = (Entry) i.next(); - h += Objects.hashCode(e.getKey()) ^ Objects.hashCode(e.getValue()); - } - } - return h; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LwM2mMultipleResource other = (LwM2mMultipleResource) obj; - if (id != other.id) - return false; - if (type != other.type) - return false; - if (values == null) { - if (other.values != null) - return false; - // Custom equals to handle byte arrays - } else if (!internalMapEquals(values, other.values)) - return false; - return true; - } - - /** - * This is a copy of {@link AbstractMap#equals(Object)} with custom code to handle byte array equality - */ - private boolean internalMapEquals(Map m1, Object o2) { - if (o2 == this) - return true; - - if (!(o2 instanceof Map)) - return false; - Map m2 = (Map) o2; - if (m2.size() != m1.size()) - return false; - - try { - Iterator i = m1.entrySet().iterator(); - while (i.hasNext()) { - Entry e = (Entry) i.next(); - Object key = e.getKey(); - Object value = e.getValue(); - if (value == null) { - if (!(m2.get(key) == null && m2.containsKey(key))) - return false; - } else { - // Custom equals to handle byte arrays - return type == Type.OPAQUE ? Arrays.equals((byte[]) value, (byte[]) m2.get(key)) : value.equals(m2 - .get(key)); - } - } - } catch (ClassCastException unused) { - return false; - } catch (NullPointerException unused) { - return false; - } - - return true; - } - - @Override - public String toString() { - return String.format("LwM2mMultipleResource [id=%s, values=%s, type=%s]", id, values, type); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import java.util.AbstractMap; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.Objects; + +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.util.Validate; + +/** + * A resource which contains several resource instances. + * + * A resource instance is defined by a numeric identifier and a value. There are accessible via {@link #getValues()} + */ +public class LwM2mMultipleResource implements LwM2mResource { + + private final int id; + + private final Map values; + + private final Type type; + + protected LwM2mMultipleResource(int id, Map values, Type type) { + this.id = id; + this.values = Collections.unmodifiableMap(new HashMap(values)); + this.type = type; + } + + public static LwM2mMultipleResource newResource(int id, Map values, Type type) { + switch (type) { + case INTEGER: + Validate.allElementsOfType(values.values(), Long.class); + break; + case FLOAT: + Validate.allElementsOfType(values.values(), Double.class); + break; + case BOOLEAN: + Validate.allElementsOfType(values.values(), Boolean.class); + break; + case OPAQUE: + Validate.allElementsOfType(values.values(), byte[].class); + break; + case STRING: + Validate.allElementsOfType(values.values(), String.class); + break; + case TIME: + Validate.allElementsOfType(values.values(), Date.class); + break; + default: + throw new IllegalArgumentException(String.format("Type %s is not supported", type.name())); + } + return new LwM2mMultipleResource(id, values, type); + } + + public static LwM2mMultipleResource newStringResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.STRING); + } + + public static LwM2mMultipleResource newIntegerResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.INTEGER); + } + + public static LwM2mMultipleResource newBooleanResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.BOOLEAN); + } + + public static LwM2mMultipleResource newFloatResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.FLOAT); + } + + public static LwM2mMultipleResource newDateResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.TIME); + } + + public static LwM2mMultipleResource newBinaryResource(int id, Map values) { + Validate.noNullElements(values.values()); + return new LwM2mMultipleResource(id, values, Type.OPAQUE); + } + + /** + * {@inheritDoc} + */ + @Override + public int getId() { + return id; + } + + /** + * {@inheritDoc} + */ + @Override + public Type getType() { + return type; + } + + /** + * @exception raise a {@link NoSuchElementException} + */ + @Override + public Object getValue() { + throw new NoSuchElementException("There is no 'value' on multiple resources, use getValues() instead."); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getValues() { + return values; + } + + /** + * {@inheritDoc} + */ + @Override + public Object getValue(int id) { + return values.get(id); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isMultiInstances() { + return true; + } + + @Override + public void accept(LwM2mNodeVisitor visitor) { + visitor.visit(this); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((values == null) ? 0 : internalHashCode(values)); + return result; + } + + /** + * This is a copy of {@link AbstractMap#hashCode()} with custom code to handle byte array equality + */ + private int internalHashCode(Map m) { + int h = 0; + Iterator i = m.entrySet().iterator(); + if (type == Type.OPAQUE) { + // Custom hashcode to handle byte arrays + while (i.hasNext()) { + Entry e = (Entry) i.next(); + h += Objects.hashCode(e.getKey()) ^ Arrays.hashCode((byte[]) e.getValue()); + } + } else { + while (i.hasNext()) { + Entry e = (Entry) i.next(); + h += Objects.hashCode(e.getKey()) ^ Objects.hashCode(e.getValue()); + } + } + return h; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + LwM2mMultipleResource other = (LwM2mMultipleResource) obj; + if (id != other.id) + return false; + if (type != other.type) + return false; + if (values == null) { + if (other.values != null) + return false; + // Custom equals to handle byte arrays + } else if (!internalMapEquals(values, other.values)) + return false; + return true; + } + + /** + * This is a copy of {@link AbstractMap#equals(Object)} with custom code to handle byte array equality + */ + private boolean internalMapEquals(Map m1, Object o2) { + if (o2 == this) + return true; + + if (!(o2 instanceof Map)) + return false; + Map m2 = (Map) o2; + if (m2.size() != m1.size()) + return false; + + try { + Iterator i = m1.entrySet().iterator(); + while (i.hasNext()) { + Entry e = (Entry) i.next(); + Object key = e.getKey(); + Object value = e.getValue(); + if (value == null) { + if (!(m2.get(key) == null && m2.containsKey(key))) + return false; + } else { + // Custom equals to handle byte arrays + return type == Type.OPAQUE ? Arrays.equals((byte[]) value, (byte[]) m2.get(key)) : value.equals(m2 + .get(key)); + } + } + } catch (ClassCastException unused) { + return false; + } catch (NullPointerException unused) { + return false; + } + + return true; + } + + @Override + public String toString() { + return String.format("LwM2mMultipleResource [id=%s, values=%s, type=%s]", id, values, type); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNode.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNode.java index 05b9af0..a69fcfa 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNode.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNode.java @@ -1,33 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -/** - * A node in the LWM2M resource tree: Objects, Object instances and Resources. - */ -public interface LwM2mNode { - - /** - * @return the node identifier - */ - int getId(); - - /** - * Accept a visitor for this node. - */ - void accept(LwM2mNodeVisitor visitor); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +/** + * A node in the LWM2M resource tree: Objects, Object instances and Resources. + */ +public interface LwM2mNode { + + /** + * @return the node identifier + */ + int getId(); + + /** + * Accept a visitor for this node. + */ + void accept(LwM2mNodeVisitor visitor); + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNodeVisitor.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNodeVisitor.java index 84af26a..e442a0e 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNodeVisitor.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mNodeVisitor.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -/** - * A visitor to visit an object, an object instance, or a resource. - */ -public interface LwM2mNodeVisitor { - - void visit(LwM2mObject object); - - void visit(LwM2mObjectInstance instance); - - void visit(LwM2mResource resource); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +/** + * A visitor to visit an object, an object instance, or a resource. + */ +public interface LwM2mNodeVisitor { + + void visit(LwM2mObject object); + + void visit(LwM2mObjectInstance instance); + + void visit(LwM2mResource resource); + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObject.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObject.java index 99e834a..6e76f8b 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObject.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObject.java @@ -1,121 +1,121 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.leshan.util.Validate; - -/** - * The top level element in the LWM2M resource tree. - *

- * An Objects defines a grouping of Resources and may consist of multiple instances. - *

- */ -public class LwM2mObject implements LwM2mNode { - - private int id; - - private final Map instances; - - public LwM2mObject(int id, Collection instances) { - Validate.notNull(instances); - - this.id = id; - HashMap instancesMap = new HashMap<>(instances.size()); - for (LwM2mObjectInstance instance : instances) { - instancesMap.put(instance.getId(), instance); - } - this.instances = Collections.unmodifiableMap(instancesMap); - } - - public LwM2mObject(int id, LwM2mObjectInstance... instances) { - this(id, Arrays.asList(instances)); - } - - @Override - public void accept(LwM2mNodeVisitor visitor) { - visitor.visit(this); - } - - /** - * {@inheritDoc} - */ - @Override - public int getId() { - return id; - } - - /** - * Returns a map of object instances by id. - * - * @return the instances - */ - public Map getInstances() { - return instances; - } - - /** - * @return the object instance with the given id or {@code null} if there is no instance for this id. - */ - public LwM2mObjectInstance getInstance(int id) { - return instances.get(id); - } - - @Override - public String toString() { - return String.format("LwM2mObject [id=%s, instances=%s]", id, instances); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + id; - result = prime * result + ((instances == null) ? 0 : instances.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LwM2mObject other = (LwM2mObject) obj; - if (id != other.id) { - return false; - } - if (instances == null) { - if (other.instances != null) { - return false; - } - } else if (!instances.equals(other.instances)) { - return false; - } - return true; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.leshan.util.Validate; + +/** + * The top level element in the LWM2M resource tree. + *

+ * An Objects defines a grouping of Resources and may consist of multiple instances. + *

+ */ +public class LwM2mObject implements LwM2mNode { + + private int id; + + private final Map instances; + + public LwM2mObject(int id, Collection instances) { + Validate.notNull(instances); + + this.id = id; + HashMap instancesMap = new HashMap<>(instances.size()); + for (LwM2mObjectInstance instance : instances) { + instancesMap.put(instance.getId(), instance); + } + this.instances = Collections.unmodifiableMap(instancesMap); + } + + public LwM2mObject(int id, LwM2mObjectInstance... instances) { + this(id, Arrays.asList(instances)); + } + + @Override + public void accept(LwM2mNodeVisitor visitor) { + visitor.visit(this); + } + + /** + * {@inheritDoc} + */ + @Override + public int getId() { + return id; + } + + /** + * Returns a map of object instances by id. + * + * @return the instances + */ + public Map getInstances() { + return instances; + } + + /** + * @return the object instance with the given id or {@code null} if there is no instance for this id. + */ + public LwM2mObjectInstance getInstance(int id) { + return instances.get(id); + } + + @Override + public String toString() { + return String.format("LwM2mObject [id=%s, instances=%s]", id, instances); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((instances == null) ? 0 : instances.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + LwM2mObject other = (LwM2mObject) obj; + if (id != other.id) { + return false; + } + if (instances == null) { + if (other.instances != null) { + return false; + } + } else if (!instances.equals(other.instances)) { + return false; + } + return true; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObjectInstance.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObjectInstance.java index ba80b45..a31f896 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObjectInstance.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mObjectInstance.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.leshan.util.Validate; - -/** - * An instance of {@link LwM2mObject}. - */ -public class LwM2mObjectInstance implements LwM2mNode { - - /** Undefined instance Id */ - public static final int UNDEFINED = -1; - - private final int id; - - private final Map resources; - - public LwM2mObjectInstance(int id, Collection resources) { - Validate.notNull(resources); - - this.id = id; - Map resourcesMap = new HashMap<>(resources.size()); - for (LwM2mResource resource : resources) { - resourcesMap.put(resource.getId(), resource); - } - this.resources = Collections.unmodifiableMap(resourcesMap); - } - - public LwM2mObjectInstance(int id, LwM2mResource... resources) { - this(id, Arrays.asList(resources)); - } - - @Override - public void accept(LwM2mNodeVisitor visitor) { - visitor.visit(this); - } - - /** - * {@inheritDoc} - */ - @Override - public int getId() { - return id; - } - - /** - * Returns a map of resources by id. - * - * @return the resources - */ - public Map getResources() { - return resources; - } - - /** - * @return the resource with the given id or {@code null} if there is no resource for this id. - */ - public LwM2mResource getResource(int id) { - return resources.get(id); - } - - @Override - public String toString() { - return String.format("LwM2mObjectInstance [id=%s, resources=%s]", id, resources); - } - - public String prettyPrint() { - StringBuilder builder = new StringBuilder(); - builder.append("LwM2mObjectInstance [id=").append(id).append("]"); - for (LwM2mResource r : resources.values()) { - builder.append("\n\t").append(r); - } - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + id; - result = prime * result + ((resources == null) ? 0 : resources.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LwM2mObjectInstance other = (LwM2mObjectInstance) obj; - if (id != other.id) { - return false; - } - if (resources == null) { - if (other.resources != null) { - return false; - } - } else if (!resources.equals(other.resources)) { - return false; - } - return true; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.leshan.util.Validate; + +/** + * An instance of {@link LwM2mObject}. + */ +public class LwM2mObjectInstance implements LwM2mNode { + + /** Undefined instance Id */ + public static final int UNDEFINED = -1; + + private final int id; + + private final Map resources; + + public LwM2mObjectInstance(int id, Collection resources) { + Validate.notNull(resources); + + this.id = id; + Map resourcesMap = new HashMap<>(resources.size()); + for (LwM2mResource resource : resources) { + resourcesMap.put(resource.getId(), resource); + } + this.resources = Collections.unmodifiableMap(resourcesMap); + } + + public LwM2mObjectInstance(int id, LwM2mResource... resources) { + this(id, Arrays.asList(resources)); + } + + @Override + public void accept(LwM2mNodeVisitor visitor) { + visitor.visit(this); + } + + /** + * {@inheritDoc} + */ + @Override + public int getId() { + return id; + } + + /** + * Returns a map of resources by id. + * + * @return the resources + */ + public Map getResources() { + return resources; + } + + /** + * @return the resource with the given id or {@code null} if there is no resource for this id. + */ + public LwM2mResource getResource(int id) { + return resources.get(id); + } + + @Override + public String toString() { + return String.format("LwM2mObjectInstance [id=%s, resources=%s]", id, resources); + } + + public String prettyPrint() { + StringBuilder builder = new StringBuilder(); + builder.append("LwM2mObjectInstance [id=").append(id).append("]"); + for (LwM2mResource r : resources.values()) { + builder.append("\n\t").append(r); + } + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((resources == null) ? 0 : resources.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + LwM2mObjectInstance other = (LwM2mObjectInstance) obj; + if (id != other.id) { + return false; + } + if (resources == null) { + if (other.resources != null) { + return false; + } + } else if (!resources.equals(other.resources)) { + return false; + } + return true; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mPath.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mPath.java index 55904b9..03e9db1 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mPath.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mPath.java @@ -1,281 +1,281 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import org.eclipse.leshan.util.Validate; - -/** - * A path pointing to a LwM2M node (root, object, object instance, resource or resource instance). - */ -public class LwM2mPath { - - private final Integer objectId; - private final Integer objectInstanceId; - private final Integer resourceId; - private final Integer resourceInstanceId; - - public final static LwM2mPath ROOTPATH = new LwM2mPath(); - - private LwM2mPath() { - this.objectId = null; - this.objectInstanceId = null; - this.resourceId = null; - this.resourceInstanceId = null; - } - - /** - * Create a path to an object - * - * @param objectId the object identifier - */ - public LwM2mPath(int objectId) { - this.objectId = objectId; - this.objectInstanceId = null; - this.resourceId = null; - this.resourceInstanceId = null; - } - - /** - * Create a path to an object instance - * - * @param objectId the object identifier - * @param objectInstanceId the instance identifier - */ - public LwM2mPath(int objectId, int objectInstanceId) { - this.objectId = objectId; - this.objectInstanceId = objectInstanceId; - this.resourceId = null; - this.resourceInstanceId = null; - } - - /** - * Create a path to a resource of a given object instance - * - * @param objectId the object identifier - * @param objectInstanceId the instance identifier - * @param resourceId the resource identifier - */ - public LwM2mPath(int objectId, int objectInstanceId, int resourceId) { - this.objectId = objectId; - this.objectInstanceId = objectInstanceId; - this.resourceId = resourceId; - this.resourceInstanceId = null; - } - - /** - * Create a path to a resource instance of a given resource - * - * @param objectId the object identifier - * @param objectInstanceId the instance identifier - * @param resourceId the resource identifier - * @param resourceInstanceId the resource instance identifier - */ - public LwM2mPath(int objectId, int objectInstanceId, int resourceId, int resourceInstanceId) { - this.objectId = objectId; - this.objectInstanceId = objectInstanceId; - this.resourceId = resourceId; - this.resourceInstanceId = resourceInstanceId; - } - - /** - * Constructs a {@link LwM2mPath} from a string representation - * - * @param path the path (e.g. "/3/0/1" or "/3") - */ - public LwM2mPath(String path) { - Validate.notNull(path); - if (path.startsWith("/")) { - path = path.substring(1); - } - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - String[] p = path.split("/"); - if (0 > p.length || p.length > 4) { - throw new IllegalArgumentException("Invalid length for path: " + path); - } - try { - this.objectId = (p.length >= 1 && !p[0].isEmpty()) ? Integer.valueOf(p[0]) : null; - this.objectInstanceId = (p.length >= 2) ? Integer.valueOf(p[1]) : null; - this.resourceId = (p.length >= 3) ? Integer.valueOf(p[2]) : null; - this.resourceInstanceId = (p.length == 4) ? Integer.valueOf(p[3]) : null; - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid elements in path: " + path, e); - } - } - - /** - * @param path the end of the new path - * @return a new path which is the concatenation of this path and the given one in parameter. - */ - public LwM2mPath append(String path) { - LwM2mPath pathToAdd = new LwM2mPath(path); - if (isRoot()) { - return pathToAdd; - } else { - return new LwM2mPath(this.toString() + pathToAdd.toString()); - } - } - - /** - * Returns the object ID in the path. - * - * @return the object ID. Can be null when this is an root path. - */ - public Integer getObjectId() { - return objectId; - } - - /** - * Returns the object instance ID in the path. - * - * @return the object instance ID. Can be null when this is an root/object path. - */ - public Integer getObjectInstanceId() { - return objectInstanceId; - } - - /** - * Returns the resource ID in the request path. - * - * @return the resource ID. Can be null when this is a root/object/object instance path. - */ - public Integer getResourceId() { - return resourceId; - } - - /** - * Returns the resource instance ID in the request path. - * - * @return the resource instance ID. Can be null when this is a root/object/object instance/resource - * path. - */ - public Integer getResourceInstanceId() { - return resourceInstanceId; - } - - /** - * @return true if this is the root path ("/"). - */ - public boolean isRoot() { - return objectId == null && objectInstanceId == null && resourceId == null && resourceInstanceId == null; - } - - /** - * @return true if this is an Object path. - */ - public boolean isObject() { - return objectId != null && objectInstanceId == null && resourceId == null && resourceInstanceId == null; - } - - /** - * @return true if this is an ObjectInstance path. - */ - public boolean isObjectInstance() { - return objectId != null && objectInstanceId != null && resourceId == null && resourceInstanceId == null; - } - - /** - * @return true if this is a Resource path. - */ - public boolean isResource() { - return objectId != null && objectInstanceId != null && resourceId != null && resourceInstanceId == null; - } - - /** - * @return true if this is a Resource instance path. - */ - public boolean isResourceInstance() { - return objectId != null && objectInstanceId != null && resourceId != null && resourceInstanceId != null; - } - - /** - * The string representation of the path: /{Object ID}/{ObjectInstance ID}/{Resource ID}/{ResourceInstance ID} - */ - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - b.append("/"); - if (getObjectId() != null) { - b.append(getObjectId()); - if (getObjectInstanceId() != null) { - b.append("/").append(getObjectInstanceId()); - if (getResourceId() != null) { - b.append("/").append(getResourceId()); - if (getResourceInstanceId() != null) { - b.append("/").append(getResourceInstanceId()); - } - } - } - } - return b.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + objectId; - result = prime * result + ((objectInstanceId == null) ? 0 : objectInstanceId.hashCode()); - result = prime * result + ((resourceId == null) ? 0 : resourceId.hashCode()); - result = prime * result + ((resourceInstanceId == null) ? 0 : resourceInstanceId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LwM2mPath other = (LwM2mPath) obj; - if (objectId == null) { - if (other.objectId != null) { - return false; - } - } else if (!objectId.equals(other.objectId)) { - return false; - } - if (objectInstanceId == null) { - if (other.objectInstanceId != null) { - return false; - } - } else if (!objectInstanceId.equals(other.objectInstanceId)) { - return false; - } - if (resourceId == null) { - if (other.resourceId != null) { - return false; - } - } else if (!resourceId.equals(other.resourceId)) { - return false; - } - if (resourceInstanceId == null) { - if (other.resourceInstanceId != null) { - return false; - } - } else if (!resourceInstanceId.equals(other.resourceInstanceId)) { - return false; - } - return true; - } - +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import org.eclipse.leshan.util.Validate; + +/** + * A path pointing to a LwM2M node (root, object, object instance, resource or resource instance). + */ +public class LwM2mPath { + + private final Integer objectId; + private final Integer objectInstanceId; + private final Integer resourceId; + private final Integer resourceInstanceId; + + public final static LwM2mPath ROOTPATH = new LwM2mPath(); + + private LwM2mPath() { + this.objectId = null; + this.objectInstanceId = null; + this.resourceId = null; + this.resourceInstanceId = null; + } + + /** + * Create a path to an object + * + * @param objectId the object identifier + */ + public LwM2mPath(int objectId) { + this.objectId = objectId; + this.objectInstanceId = null; + this.resourceId = null; + this.resourceInstanceId = null; + } + + /** + * Create a path to an object instance + * + * @param objectId the object identifier + * @param objectInstanceId the instance identifier + */ + public LwM2mPath(int objectId, int objectInstanceId) { + this.objectId = objectId; + this.objectInstanceId = objectInstanceId; + this.resourceId = null; + this.resourceInstanceId = null; + } + + /** + * Create a path to a resource of a given object instance + * + * @param objectId the object identifier + * @param objectInstanceId the instance identifier + * @param resourceId the resource identifier + */ + public LwM2mPath(int objectId, int objectInstanceId, int resourceId) { + this.objectId = objectId; + this.objectInstanceId = objectInstanceId; + this.resourceId = resourceId; + this.resourceInstanceId = null; + } + + /** + * Create a path to a resource instance of a given resource + * + * @param objectId the object identifier + * @param objectInstanceId the instance identifier + * @param resourceId the resource identifier + * @param resourceInstanceId the resource instance identifier + */ + public LwM2mPath(int objectId, int objectInstanceId, int resourceId, int resourceInstanceId) { + this.objectId = objectId; + this.objectInstanceId = objectInstanceId; + this.resourceId = resourceId; + this.resourceInstanceId = resourceInstanceId; + } + + /** + * Constructs a {@link LwM2mPath} from a string representation + * + * @param path the path (e.g. "/3/0/1" or "/3") + */ + public LwM2mPath(String path) { + Validate.notNull(path); + if (path.startsWith("/")) { + path = path.substring(1); + } + if (path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + String[] p = path.split("/"); + if (0 > p.length || p.length > 4) { + throw new IllegalArgumentException("Invalid length for path: " + path); + } + try { + this.objectId = (p.length >= 1 && !p[0].isEmpty()) ? Integer.valueOf(p[0]) : null; + this.objectInstanceId = (p.length >= 2) ? Integer.valueOf(p[1]) : null; + this.resourceId = (p.length >= 3) ? Integer.valueOf(p[2]) : null; + this.resourceInstanceId = (p.length == 4) ? Integer.valueOf(p[3]) : null; + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Invalid elements in path: " + path, e); + } + } + + /** + * @param path the end of the new path + * @return a new path which is the concatenation of this path and the given one in parameter. + */ + public LwM2mPath append(String path) { + LwM2mPath pathToAdd = new LwM2mPath(path); + if (isRoot()) { + return pathToAdd; + } else { + return new LwM2mPath(this.toString() + pathToAdd.toString()); + } + } + + /** + * Returns the object ID in the path. + * + * @return the object ID. Can be null when this is an root path. + */ + public Integer getObjectId() { + return objectId; + } + + /** + * Returns the object instance ID in the path. + * + * @return the object instance ID. Can be null when this is an root/object path. + */ + public Integer getObjectInstanceId() { + return objectInstanceId; + } + + /** + * Returns the resource ID in the request path. + * + * @return the resource ID. Can be null when this is a root/object/object instance path. + */ + public Integer getResourceId() { + return resourceId; + } + + /** + * Returns the resource instance ID in the request path. + * + * @return the resource instance ID. Can be null when this is a root/object/object instance/resource + * path. + */ + public Integer getResourceInstanceId() { + return resourceInstanceId; + } + + /** + * @return true if this is the root path ("/"). + */ + public boolean isRoot() { + return objectId == null && objectInstanceId == null && resourceId == null && resourceInstanceId == null; + } + + /** + * @return true if this is an Object path. + */ + public boolean isObject() { + return objectId != null && objectInstanceId == null && resourceId == null && resourceInstanceId == null; + } + + /** + * @return true if this is an ObjectInstance path. + */ + public boolean isObjectInstance() { + return objectId != null && objectInstanceId != null && resourceId == null && resourceInstanceId == null; + } + + /** + * @return true if this is a Resource path. + */ + public boolean isResource() { + return objectId != null && objectInstanceId != null && resourceId != null && resourceInstanceId == null; + } + + /** + * @return true if this is a Resource instance path. + */ + public boolean isResourceInstance() { + return objectId != null && objectInstanceId != null && resourceId != null && resourceInstanceId != null; + } + + /** + * The string representation of the path: /{Object ID}/{ObjectInstance ID}/{Resource ID}/{ResourceInstance ID} + */ + @Override + public String toString() { + StringBuilder b = new StringBuilder(); + b.append("/"); + if (getObjectId() != null) { + b.append(getObjectId()); + if (getObjectInstanceId() != null) { + b.append("/").append(getObjectInstanceId()); + if (getResourceId() != null) { + b.append("/").append(getResourceId()); + if (getResourceInstanceId() != null) { + b.append("/").append(getResourceInstanceId()); + } + } + } + } + return b.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + objectId; + result = prime * result + ((objectInstanceId == null) ? 0 : objectInstanceId.hashCode()); + result = prime * result + ((resourceId == null) ? 0 : resourceId.hashCode()); + result = prime * result + ((resourceInstanceId == null) ? 0 : resourceInstanceId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + LwM2mPath other = (LwM2mPath) obj; + if (objectId == null) { + if (other.objectId != null) { + return false; + } + } else if (!objectId.equals(other.objectId)) { + return false; + } + if (objectInstanceId == null) { + if (other.objectInstanceId != null) { + return false; + } + } else if (!objectInstanceId.equals(other.objectInstanceId)) { + return false; + } + if (resourceId == null) { + if (other.resourceId != null) { + return false; + } + } else if (!resourceId.equals(other.resourceId)) { + return false; + } + if (resourceInstanceId == null) { + if (other.resourceInstanceId != null) { + return false; + } + } else if (!resourceInstanceId.equals(other.resourceInstanceId)) { + return false; + } + return true; + } + } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mResource.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mResource.java index 991e6aa..328adb1 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mResource.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mResource.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import java.util.Date; -import java.util.Map; - -import org.eclipse.leshan.core.model.ResourceModel.Type; - -/** - * A resource is an information made available by the LWM2M Client. - *

- * A resource could be a {@link LwM2mSingleResource} or a {@link LwM2mMultipleResource}. - *

- */ -public interface LwM2mResource extends LwM2mNode { - - /** - * @return the type of the resource. - */ - Type getType(); - - /** - * @return true if this resource contains severals resources instances. - */ - boolean isMultiInstances(); - - /** - * This method is only available if {@link #isMultiInstances()} return false. - * - * The type of the returned value depends on the {@link #getType()} method. - * - * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
- * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
- * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
- * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
- * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
- * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
- * - * @return the value of the resource. - */ - Object getValue(); - - /** - * This method is only available if {@link #isMultiInstances()} return true. - * - * The type of the right part of the returned map depends on the {@link #getType()} method. - * - * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
- * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
- * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
- * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
- * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
- * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
- * - * @return the values of each resource instances (key is the resource instance identifier). - */ - Map getValues(); - - /** - * This method is only available if {@link #isMultiInstances()} return true. - * - * The type of the returned value depends on the {@link #getType()} method. - * - * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
- * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
- * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
- * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
- * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
- * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
- * - * @return the value a resource instance with the given identifier. - */ - Object getValue(int id); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import java.util.Date; +import java.util.Map; + +import org.eclipse.leshan.core.model.ResourceModel.Type; + +/** + * A resource is an information made available by the LWM2M Client. + *

+ * A resource could be a {@link LwM2mSingleResource} or a {@link LwM2mMultipleResource}. + *

+ */ +public interface LwM2mResource extends LwM2mNode { + + /** + * @return the type of the resource. + */ + Type getType(); + + /** + * @return true if this resource contains severals resources instances. + */ + boolean isMultiInstances(); + + /** + * This method is only available if {@link #isMultiInstances()} return false. + * + * The type of the returned value depends on the {@link #getType()} method. + * + * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
+ * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
+ * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
+ * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
+ * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
+ * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
+ * + * @return the value of the resource. + */ + Object getValue(); + + /** + * This method is only available if {@link #isMultiInstances()} return true. + * + * The type of the right part of the returned map depends on the {@link #getType()} method. + * + * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
+ * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
+ * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
+ * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
+ * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
+ * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
+ * + * @return the values of each resource instances (key is the resource instance identifier). + */ + Map getValues(); + + /** + * This method is only available if {@link #isMultiInstances()} return true. + * + * The type of the returned value depends on the {@link #getType()} method. + * + * If {@link #getType()} returns {@link Type#BOOLEAN}, the value is a {@link Boolean}.
+ * If {@link #getType()} returns {@link Type#STRING}, the value is a {@link String}.
+ * If {@link #getType()} returns {@link Type#OPAQUE}, the value is a byte array.
+ * If {@link #getType()} returns {@link Type#TIME}, the value is a {@link Date}.
+ * If {@link #getType()} returns {@link Type#INTEGER}, the value is a {@link Long}.
+ * If {@link #getType()} returns {@link Type#FLOAT}, the value is a {@link Double}.
+ * + * @return the value a resource instance with the given identifier. + */ + Object getValue(int id); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mSingleResource.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mSingleResource.java index 0253f40..2c4af80 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mSingleResource.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/LwM2mSingleResource.java @@ -1,192 +1,192 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import java.util.Arrays; -import java.util.Date; -import java.util.Map; -import java.util.NoSuchElementException; - -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.util.Validate; - -/** - * A resource with a single value. - */ -public class LwM2mSingleResource implements LwM2mResource { - - private final int id; - - private final Object value; - - private final Type type; - - protected LwM2mSingleResource(int id, Object value, Type type) { - Validate.notNull(value); - this.id = id; - this.value = value; - this.type = type; - } - - public static LwM2mSingleResource newResource(int id, Object value, Type type) { - switch (type) { - case INTEGER: - if (value instanceof Long) - break; - case FLOAT: - if (value instanceof Double) - break; - case BOOLEAN: - if (value instanceof Boolean) - break; - case OPAQUE: - if (value instanceof byte[]) - break; - case STRING: - if (value instanceof String) - break; - case TIME: - if (value instanceof Date) - break; - throw new IllegalArgumentException("Value does not match the given datatype"); - default: - throw new IllegalArgumentException(String.format("Type %s is not supported", type.name())); - } - return new LwM2mSingleResource(id, value, type); - } - - public static LwM2mSingleResource newStringResource(int id, String value) { - return new LwM2mSingleResource(id, value, Type.STRING); - } - - public static LwM2mSingleResource newIntegerResource(int id, long value) { - return new LwM2mSingleResource(id, value, Type.INTEGER); - } - - public static LwM2mSingleResource newBooleanResource(int id, boolean value) { - return new LwM2mSingleResource(id, value, Type.BOOLEAN); - } - - public static LwM2mSingleResource newFloatResource(int id, double value) { - return new LwM2mSingleResource(id, value, Type.FLOAT); - } - - public static LwM2mSingleResource newDateResource(int id, Date value) { - return new LwM2mSingleResource(id, value, Type.TIME); - } - - public static LwM2mSingleResource newBinaryResource(int id, byte[] value) { - return new LwM2mSingleResource(id, value, Type.OPAQUE); - } - - /** - * {@inheritDoc} - */ - @Override - public int getId() { - return id; - } - - /** - * {@inheritDoc} - */ - @Override - public Type getType() { - return type; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getValue() { - return value; - } - - /** - * @exception raise a {@link NoSuchElementException} - */ - @Override - public Map getValues() { - throw new NoSuchElementException("There is no 'values' on single resources, use getValue() instead."); - } - - /** - * @exception raise a {@link NoSuchElementException} - */ - @Override - public Object getValue(int id) { - throw new NoSuchElementException("There is no 'values' on single resources, use getValue() instead."); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isMultiInstances() { - return false; - } - - @Override - public void accept(LwM2mNodeVisitor visitor) { - visitor.visit(this); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + id; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - if (type == Type.OPAQUE) { - // Custom hashcode to handle byte arrays - result = prime * result + ((value == null) ? 0 : Arrays.hashCode((byte[]) value)); - } else { - result = prime * result + ((value == null) ? 0 : value.hashCode()); - } - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LwM2mSingleResource other = (LwM2mSingleResource) obj; - if (id != other.id) - return false; - if (type != other.type) - return false; - if (value == null) { - if (other.value != null) - return false; - } else { - // Custom equals to handle byte arrays - return type == Type.OPAQUE ? Arrays.equals((byte[]) value, (byte[]) other.value) : value - .equals(other.value); - } - return true; - } - - @Override - public String toString() { - return String.format("LwM2mSingleResource [id=%s, value=%s, type=%s]", id, value, type); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import java.util.Arrays; +import java.util.Date; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.util.Validate; + +/** + * A resource with a single value. + */ +public class LwM2mSingleResource implements LwM2mResource { + + private final int id; + + private final Object value; + + private final Type type; + + protected LwM2mSingleResource(int id, Object value, Type type) { + Validate.notNull(value); + this.id = id; + this.value = value; + this.type = type; + } + + public static LwM2mSingleResource newResource(int id, Object value, Type type) { + switch (type) { + case INTEGER: + if (value instanceof Long) + break; + case FLOAT: + if (value instanceof Double) + break; + case BOOLEAN: + if (value instanceof Boolean) + break; + case OPAQUE: + if (value instanceof byte[]) + break; + case STRING: + if (value instanceof String) + break; + case TIME: + if (value instanceof Date) + break; + throw new IllegalArgumentException("Value does not match the given datatype"); + default: + throw new IllegalArgumentException(String.format("Type %s is not supported", type.name())); + } + return new LwM2mSingleResource(id, value, type); + } + + public static LwM2mSingleResource newStringResource(int id, String value) { + return new LwM2mSingleResource(id, value, Type.STRING); + } + + public static LwM2mSingleResource newIntegerResource(int id, long value) { + return new LwM2mSingleResource(id, value, Type.INTEGER); + } + + public static LwM2mSingleResource newBooleanResource(int id, boolean value) { + return new LwM2mSingleResource(id, value, Type.BOOLEAN); + } + + public static LwM2mSingleResource newFloatResource(int id, double value) { + return new LwM2mSingleResource(id, value, Type.FLOAT); + } + + public static LwM2mSingleResource newDateResource(int id, Date value) { + return new LwM2mSingleResource(id, value, Type.TIME); + } + + public static LwM2mSingleResource newBinaryResource(int id, byte[] value) { + return new LwM2mSingleResource(id, value, Type.OPAQUE); + } + + /** + * {@inheritDoc} + */ + @Override + public int getId() { + return id; + } + + /** + * {@inheritDoc} + */ + @Override + public Type getType() { + return type; + } + + /** + * {@inheritDoc} + */ + @Override + public Object getValue() { + return value; + } + + /** + * @exception raise a {@link NoSuchElementException} + */ + @Override + public Map getValues() { + throw new NoSuchElementException("There is no 'values' on single resources, use getValue() instead."); + } + + /** + * @exception raise a {@link NoSuchElementException} + */ + @Override + public Object getValue(int id) { + throw new NoSuchElementException("There is no 'values' on single resources, use getValue() instead."); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isMultiInstances() { + return false; + } + + @Override + public void accept(LwM2mNodeVisitor visitor) { + visitor.visit(this); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + if (type == Type.OPAQUE) { + // Custom hashcode to handle byte arrays + result = prime * result + ((value == null) ? 0 : Arrays.hashCode((byte[]) value)); + } else { + result = prime * result + ((value == null) ? 0 : value.hashCode()); + } + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + LwM2mSingleResource other = (LwM2mSingleResource) obj; + if (id != other.id) + return false; + if (type != other.type) + return false; + if (value == null) { + if (other.value != null) + return false; + } else { + // Custom equals to handle byte arrays + return type == Type.OPAQUE ? Arrays.equals((byte[]) value, (byte[]) other.value) : value + .equals(other.value); + } + return true; + } + + @Override + public String toString() { + return String.format("LwM2mSingleResource [id=%s, value=%s, type=%s]", id, value, type); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/TimestampedLwM2mNode.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/TimestampedLwM2mNode.java index 2d9f64c..abc1572 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/TimestampedLwM2mNode.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/TimestampedLwM2mNode.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node; - -import org.eclipse.leshan.util.Validate; - -public class TimestampedLwM2mNode { - - private final Long timestamp; - - private final LwM2mNode node; - - public TimestampedLwM2mNode(Long timestamp, LwM2mNode node) { - Validate.notNull(node); - this.timestamp = timestamp; - this.node = node; - } - - public Long getTimestamp() { - return timestamp; - } - - public LwM2mNode getNode() { - return node; - } - - public boolean isTimespamped() { - return timestamp != null && timestamp >= 0; - } -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node; + +import org.eclipse.leshan.util.Validate; + +public class TimestampedLwM2mNode { + + private final Long timestamp; + + private final LwM2mNode node; + + public TimestampedLwM2mNode(Long timestamp, LwM2mNode node) { + Validate.notNull(node); + this.timestamp = timestamp; + this.node = node; + } + + public Long getTimestamp() { + return timestamp; + } + + public LwM2mNode getNode() { + return node; + } + + public boolean isTimespamped() { + return timestamp != null && timestamp >= 0; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeDecoder.java index d748db1..5e0a92c 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeDecoder.java @@ -1,129 +1,129 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.node.codec.json.LwM2mNodeJsonDecoder; -import org.eclipse.leshan.core.node.codec.opaque.LwM2mNodeOpaqueDecoder; -import org.eclipse.leshan.core.node.codec.text.LwM2mNodeTextDecoder; -import org.eclipse.leshan.core.node.codec.tlv.LwM2mNodeTlvDecoder; -import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultLwM2mNodeDecoder implements LwM2mNodeDecoder { - - private static final Logger LOG = LoggerFactory.getLogger(DefaultLwM2mNodeDecoder.class); - - @Override - public LwM2mNode decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model) - throws InvalidValueException { - return decode(content, format, path, model, nodeClassFromPath(path)); - } - - @Override - @SuppressWarnings("unchecked") - public T decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model, - Class nodeClass) throws InvalidValueException { - - LOG.debug("Decoding value for path {} and format {}: {}", path, format, content); - Validate.notNull(path); - Validate.notNull(format); - - // Decode content. - switch (format.getCode()) { - case ContentFormat.TEXT_CODE: - return (T) LwM2mNodeTextDecoder.decode(content, path, model); - case ContentFormat.TLV_CODE: - return LwM2mNodeTlvDecoder.decode(content, path, model, nodeClass); - case ContentFormat.OPAQUE_CODE: - return (T) LwM2mNodeOpaqueDecoder.decode(content, path, model); - case ContentFormat.JSON_CODE: - return LwM2mNodeJsonDecoder.decode(content, path, model, nodeClass); - case ContentFormat.LINK_CODE: - throw new UnsupportedOperationException("Content format " + format + " not yet implemented '" + path + "'"); - } - return null; - } - - @Override - public List decodeTimestampedData(byte[] content, ContentFormat format, LwM2mPath path, - LwM2mModel model) throws InvalidValueException { - LOG.debug("Decoding value for path {} and format {}: {}", path, format, content); - Validate.notNull(path); - Validate.notNull(format); - - // Decode content. - switch (format.getCode()) { - case ContentFormat.TEXT_CODE: - return toTimestampedNodes(LwM2mNodeTextDecoder.decode(content, path, model)); - case ContentFormat.TLV_CODE: - return toTimestampedNodes(LwM2mNodeTlvDecoder.decode(content, path, model, nodeClassFromPath(path))); - case ContentFormat.OPAQUE_CODE: - return toTimestampedNodes(LwM2mNodeOpaqueDecoder.decode(content, path, model)); - case ContentFormat.JSON_CODE: - return LwM2mNodeJsonDecoder.decodeTimestamped(content, path, model, nodeClassFromPath(path)); - case ContentFormat.LINK_CODE: - throw new UnsupportedOperationException("Content format " + format + " not yet implemented '" + path + "'"); - } - return null; - } - - private static List toTimestampedNodes(LwM2mNode node) { - if (node == null) - return Collections.emptyList(); - - ArrayList timestampedNodes = new ArrayList<>(1); - timestampedNodes.add(new TimestampedLwM2mNode(null, node)); - return Collections.unmodifiableList(timestampedNodes); - } - - public static Class nodeClassFromPath(LwM2mPath path) { - if (path.isObject()) { - return LwM2mObject.class; - } else if (path.isObjectInstance()) { - return LwM2mObjectInstance.class; - } else if (path.isResource()) { - return LwM2mResource.class; - } - throw new IllegalArgumentException("invalid path level: " + path); - } - - @Override - public boolean isSupported(ContentFormat format) { - switch (format.getCode()) { - case ContentFormat.TEXT_CODE: - case ContentFormat.TLV_CODE: - case ContentFormat.OPAQUE_CODE: - case ContentFormat.JSON_CODE: - return true; - default: - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.node.codec.json.LwM2mNodeJsonDecoder; +import org.eclipse.leshan.core.node.codec.opaque.LwM2mNodeOpaqueDecoder; +import org.eclipse.leshan.core.node.codec.text.LwM2mNodeTextDecoder; +import org.eclipse.leshan.core.node.codec.tlv.LwM2mNodeTlvDecoder; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DefaultLwM2mNodeDecoder implements LwM2mNodeDecoder { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultLwM2mNodeDecoder.class); + + @Override + public LwM2mNode decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model) + throws InvalidValueException { + return decode(content, format, path, model, nodeClassFromPath(path)); + } + + @Override + @SuppressWarnings("unchecked") + public T decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model, + Class nodeClass) throws InvalidValueException { + + LOG.debug("Decoding value for path {} and format {}: {}", path, format, content); + Validate.notNull(path); + Validate.notNull(format); + + // Decode content. + switch (format.getCode()) { + case ContentFormat.TEXT_CODE: + return (T) LwM2mNodeTextDecoder.decode(content, path, model); + case ContentFormat.TLV_CODE: + return LwM2mNodeTlvDecoder.decode(content, path, model, nodeClass); + case ContentFormat.OPAQUE_CODE: + return (T) LwM2mNodeOpaqueDecoder.decode(content, path, model); + case ContentFormat.JSON_CODE: + return LwM2mNodeJsonDecoder.decode(content, path, model, nodeClass); + case ContentFormat.LINK_CODE: + throw new UnsupportedOperationException("Content format " + format + " not yet implemented '" + path + "'"); + } + return null; + } + + @Override + public List decodeTimestampedData(byte[] content, ContentFormat format, LwM2mPath path, + LwM2mModel model) throws InvalidValueException { + LOG.debug("Decoding value for path {} and format {}: {}", path, format, content); + Validate.notNull(path); + Validate.notNull(format); + + // Decode content. + switch (format.getCode()) { + case ContentFormat.TEXT_CODE: + return toTimestampedNodes(LwM2mNodeTextDecoder.decode(content, path, model)); + case ContentFormat.TLV_CODE: + return toTimestampedNodes(LwM2mNodeTlvDecoder.decode(content, path, model, nodeClassFromPath(path))); + case ContentFormat.OPAQUE_CODE: + return toTimestampedNodes(LwM2mNodeOpaqueDecoder.decode(content, path, model)); + case ContentFormat.JSON_CODE: + return LwM2mNodeJsonDecoder.decodeTimestamped(content, path, model, nodeClassFromPath(path)); + case ContentFormat.LINK_CODE: + throw new UnsupportedOperationException("Content format " + format + " not yet implemented '" + path + "'"); + } + return null; + } + + private static List toTimestampedNodes(LwM2mNode node) { + if (node == null) + return Collections.emptyList(); + + ArrayList timestampedNodes = new ArrayList<>(1); + timestampedNodes.add(new TimestampedLwM2mNode(null, node)); + return Collections.unmodifiableList(timestampedNodes); + } + + public static Class nodeClassFromPath(LwM2mPath path) { + if (path.isObject()) { + return LwM2mObject.class; + } else if (path.isObjectInstance()) { + return LwM2mObjectInstance.class; + } else if (path.isResource()) { + return LwM2mResource.class; + } + throw new IllegalArgumentException("invalid path level: " + path); + } + + @Override + public boolean isSupported(ContentFormat format) { + switch (format.getCode()) { + case ContentFormat.TEXT_CODE: + case ContentFormat.TLV_CODE: + case ContentFormat.OPAQUE_CODE: + case ContentFormat.JSON_CODE: + return true; + default: + return false; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeEncoder.java index 8e3682e..4b180ba 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/DefaultLwM2mNodeEncoder.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import java.util.Arrays; -import java.util.List; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.node.codec.json.LwM2mNodeJsonEncoder; -import org.eclipse.leshan.core.node.codec.opaque.LwM2mNodeOpaqueEncoder; -import org.eclipse.leshan.core.node.codec.text.LwM2mNodeTextEncoder; -import org.eclipse.leshan.core.node.codec.tlv.LwM2mNodeTlvEncoder; -import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultLwM2mNodeEncoder implements LwM2mNodeEncoder { - - private static final Logger LOG = LoggerFactory.getLogger(DefaultLwM2mNodeEncoder.class); - - @Override - public byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model) { - Validate.notNull(node); - Validate.notNull(format); - - LOG.debug("Encoding node {} for path {} and format {}", node, path, format); - - byte[] encoded = null; - switch (format.getCode()) { - case ContentFormat.TLV_CODE: - encoded = LwM2mNodeTlvEncoder.encode(node, path, model); - break; - case ContentFormat.TEXT_CODE: - encoded = LwM2mNodeTextEncoder.encode(node, path, model); - break; - case ContentFormat.OPAQUE_CODE: - encoded = LwM2mNodeOpaqueEncoder.encode(node, path, model); - break; - case ContentFormat.JSON_CODE: - encoded = LwM2mNodeJsonEncoder.encode(node, path, model); - break; - default: - throw new IllegalArgumentException("Cannot encode " + node + " with format " + format); - } - - LOG.trace("Encoded node {}: {}", node, Arrays.toString(encoded)); - return encoded; - } - - @Override - public byte[] encodeTimestampedData(List timestampedNodes, ContentFormat format, - LwM2mPath path, LwM2mModel model) { - Validate.notEmpty(timestampedNodes); - Validate.notNull(format); - - LOG.debug("Encoding time-stamped nodes for path {} and format {}", timestampedNodes, path, format); - - byte[] encoded = null; - switch (format.getCode()) { - case ContentFormat.JSON_CODE: - encoded = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, path, model); - break; - default: - throw new IllegalArgumentException("Cannot encode timestampedNode with format " + format); - } - - LOG.trace("Encoded node timestampedNode: {}", timestampedNodes, Arrays.toString(encoded)); - return encoded; - } - - @Override - public boolean isSupported(ContentFormat format) { - switch (format.getCode()) { - case ContentFormat.TEXT_CODE: - case ContentFormat.TLV_CODE: - case ContentFormat.OPAQUE_CODE: - case ContentFormat.JSON_CODE: - return true; - default: - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.node.codec.json.LwM2mNodeJsonEncoder; +import org.eclipse.leshan.core.node.codec.opaque.LwM2mNodeOpaqueEncoder; +import org.eclipse.leshan.core.node.codec.text.LwM2mNodeTextEncoder; +import org.eclipse.leshan.core.node.codec.tlv.LwM2mNodeTlvEncoder; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DefaultLwM2mNodeEncoder implements LwM2mNodeEncoder { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultLwM2mNodeEncoder.class); + + @Override + public byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model) { + Validate.notNull(node); + Validate.notNull(format); + + LOG.debug("Encoding node {} for path {} and format {}", node, path, format); + + byte[] encoded = null; + switch (format.getCode()) { + case ContentFormat.TLV_CODE: + encoded = LwM2mNodeTlvEncoder.encode(node, path, model); + break; + case ContentFormat.TEXT_CODE: + encoded = LwM2mNodeTextEncoder.encode(node, path, model); + break; + case ContentFormat.OPAQUE_CODE: + encoded = LwM2mNodeOpaqueEncoder.encode(node, path, model); + break; + case ContentFormat.JSON_CODE: + encoded = LwM2mNodeJsonEncoder.encode(node, path, model); + break; + default: + throw new IllegalArgumentException("Cannot encode " + node + " with format " + format); + } + + LOG.trace("Encoded node {}: {}", node, Arrays.toString(encoded)); + return encoded; + } + + @Override + public byte[] encodeTimestampedData(List timestampedNodes, ContentFormat format, + LwM2mPath path, LwM2mModel model) { + Validate.notEmpty(timestampedNodes); + Validate.notNull(format); + + LOG.debug("Encoding time-stamped nodes for path {} and format {}", timestampedNodes, path, format); + + byte[] encoded = null; + switch (format.getCode()) { + case ContentFormat.JSON_CODE: + encoded = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, path, model); + break; + default: + throw new IllegalArgumentException("Cannot encode timestampedNode with format " + format); + } + + LOG.trace("Encoded node timestampedNode: {}", timestampedNodes, Arrays.toString(encoded)); + return encoded; + } + + @Override + public boolean isSupported(ContentFormat format) { + switch (format.getCode()) { + case ContentFormat.TEXT_CODE: + case ContentFormat.TLV_CODE: + case ContentFormat.OPAQUE_CODE: + case ContentFormat.JSON_CODE: + return true; + default: + return false; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/InvalidValueException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/InvalidValueException.java index 3294b70..ed52cf1 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/InvalidValueException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/InvalidValueException.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import org.eclipse.leshan.core.node.LwM2mPath; - -public class InvalidValueException extends Exception { - - private static final long serialVersionUID = 1L; - - private final LwM2mPath path; - - public InvalidValueException(String message, LwM2mPath path) { - super(message); - this.path = path; - } - - public InvalidValueException(String message, LwM2mPath path, Exception e) { - super(message, e); - this.path = path; - } - - /** - * @return the path of the resource with an invalid value - */ - public LwM2mPath getPath() { - return path; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import org.eclipse.leshan.core.node.LwM2mPath; + +public class InvalidValueException extends Exception { + + private static final long serialVersionUID = 1L; + + private final LwM2mPath path; + + public InvalidValueException(String message, LwM2mPath path) { + super(message); + this.path = path; + } + + public InvalidValueException(String message, LwM2mPath path, Exception e) { + super(message, e); + this.path = path; + } + + /** + * @return the path of the resource with an invalid value + */ + public LwM2mPath getPath() { + return path; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeDecoder.java index d2db321..0acf746 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeDecoder.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import java.util.List; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.request.ContentFormat; - -public interface LwM2mNodeDecoder { - - /** - * Deserializes a binary content into a {@link LwM2mNode}. - * - * The type of the returned node depends on the path argument. - * - * @param content the content - * @param format the content format - * @param path the path of the node to build - * @param model the collection of supported object models - * @return the resulting node - * @throws InvalidValueException - */ - LwM2mNode decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model) - throws InvalidValueException; - - /** - * Deserializes a binary content into a {@link LwM2mNode} of the expected type. - * - * @param content the content - * @param format the content format - * @param path the path of the node to build - * @param model the collection of supported object models - * @param nodeClass the class of the {@link LwM2mNode} to decode - * @return the resulting node - * @throws InvalidValueException - */ - T decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model, - Class nodeClass) throws InvalidValueException; - - /** - * Deserializes a binary content into a list of time-stamped {@link LwM2mNode} ordering by time-stamp. - * - * @param content the content - * @param format the content format - * @param path the path of the node to build - * @param model the collection of supported object models - * @param nodeClass the class of the {@link LwM2mNode} to decode - * @return the resulting list of time-stamped {@link LwM2mNode} ordering by time-stamp - * @throws InvalidValueException - */ - List decodeTimestampedData(byte[] content, ContentFormat format, LwM2mPath path, - LwM2mModel model) throws InvalidValueException; - - /** - * return true is the given {@link ContentFormat} is supported - */ - boolean isSupported(ContentFormat format); - -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import java.util.List; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.request.ContentFormat; + +public interface LwM2mNodeDecoder { + + /** + * Deserializes a binary content into a {@link LwM2mNode}. + * + * The type of the returned node depends on the path argument. + * + * @param content the content + * @param format the content format + * @param path the path of the node to build + * @param model the collection of supported object models + * @return the resulting node + * @throws InvalidValueException + */ + LwM2mNode decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model) + throws InvalidValueException; + + /** + * Deserializes a binary content into a {@link LwM2mNode} of the expected type. + * + * @param content the content + * @param format the content format + * @param path the path of the node to build + * @param model the collection of supported object models + * @param nodeClass the class of the {@link LwM2mNode} to decode + * @return the resulting node + * @throws InvalidValueException + */ + T decode(byte[] content, ContentFormat format, LwM2mPath path, LwM2mModel model, + Class nodeClass) throws InvalidValueException; + + /** + * Deserializes a binary content into a list of time-stamped {@link LwM2mNode} ordering by time-stamp. + * + * @param content the content + * @param format the content format + * @param path the path of the node to build + * @param model the collection of supported object models + * @param nodeClass the class of the {@link LwM2mNode} to decode + * @return the resulting list of time-stamped {@link LwM2mNode} ordering by time-stamp + * @throws InvalidValueException + */ + List decodeTimestampedData(byte[] content, ContentFormat format, LwM2mPath path, + LwM2mModel model) throws InvalidValueException; + + /** + * return true is the given {@link ContentFormat} is supported + */ + boolean isSupported(ContentFormat format); + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeEncoder.java index 8be2f92..6232319 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/LwM2mNodeEncoder.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2016 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import java.util.List; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.request.ContentFormat; - -public interface LwM2mNodeEncoder { - - /** - * Serializes a {@link LwM2mNode} with the given content format. - * - * @param node the object/instance/resource to serialize - * @param format the content format - * @param path the path of the node to serialize - * @param model the collection of supported object models - * @return the encoded node as a byte array - */ - byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model); - - /** - * Serializes a list of time-stamped {@link LwM2mNode} with the given content format. - * - * @param timestampedNodes the list of time-stamped object/instance/resource to serialize - * @param format the content format - * @param path the path of the node to serialize - * @param model the collection of supported object models - * @return the encoded node as a byte array - */ - byte[] encodeTimestampedData(List timestampedNodes, ContentFormat format, LwM2mPath path, - LwM2mModel model); - - /** - * return true is the given {@link ContentFormat} is supported - */ - boolean isSupported(ContentFormat format); -} +/******************************************************************************* + * Copyright (c) 2016 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import java.util.List; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.request.ContentFormat; + +public interface LwM2mNodeEncoder { + + /** + * Serializes a {@link LwM2mNode} with the given content format. + * + * @param node the object/instance/resource to serialize + * @param format the content format + * @param path the path of the node to serialize + * @param model the collection of supported object models + * @return the encoded node as a byte array + */ + byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model); + + /** + * Serializes a list of time-stamped {@link LwM2mNode} with the given content format. + * + * @param timestampedNodes the list of time-stamped object/instance/resource to serialize + * @param format the content format + * @param path the path of the node to serialize + * @param model the collection of supported object models + * @return the encoded node as a byte array + */ + byte[] encodeTimestampedData(List timestampedNodes, ContentFormat format, LwM2mPath path, + LwM2mModel model); + + /** + * return true is the given {@link ContentFormat} is supported + */ + boolean isSupported(ContentFormat format); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/Lwm2mNodeEncoderUtil.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/Lwm2mNodeEncoderUtil.java index 2183623..d4e9ee0 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/Lwm2mNodeEncoderUtil.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/Lwm2mNodeEncoderUtil.java @@ -1,150 +1,150 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Kai Hudalla (Bosch Software Innovations GmbH) - remove dependency on - * javax.xml.bind.DatatypeConverter - * which is not available on Android - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec; - -import java.util.Date; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.util.Hex; -import org.eclipse.leshan.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Helper for all the LwM2mNode encoders. - */ -public class Lwm2mNodeEncoderUtil { - private static final Logger LOG = LoggerFactory.getLogger(Lwm2mNodeEncoderUtil.class); - - private Lwm2mNodeEncoderUtil() { - } - - /** - * Convert the given value to the expected type given in parameter. - * - * @throws IllegalArgumentException the value is not convertible. - */ - public static Object convertValue(Object value, Type currentType, Type expectedType) { - if (expectedType == null) { - // unknown resource, trusted value - return value; - } - - if (currentType == expectedType) { - // expected type - return value; - } - - // We received a value with an unexpected type. - // Let's do some magic to try to convert this value... - - switch (expectedType) { - case INTEGER: - switch (currentType) { - case FLOAT: - LOG.debug("Trying to convert float value {} to integer", value); - Long longValue = ((Double) value).longValue(); - if ((double) value == longValue.doubleValue()) { - return longValue; - } - default: - break; - } - break; - case FLOAT: - switch (currentType) { - case INTEGER: - LOG.debug("Trying to convert integer value {} to float", value); - Double floatValue = ((Long) value).doubleValue(); - if ((long) value == floatValue.longValue()) { - return floatValue; - } - default: - break; - } - break; - case BOOLEAN: - switch (currentType) { - case STRING: - LOG.debug("Trying to convert string value {} to boolean", value); - if (StringUtils.equalsIgnoreCase((String) value, "true")) { - return true; - } else if (StringUtils.equalsIgnoreCase((String) value, "false")) { - return false; - } - case INTEGER: - LOG.debug("Trying to convert int value {} to boolean", value); - Long val = (Long) value; - if (val == 1) { - return true; - } else if (val == 0) { - return false; - } - default: - break; - } - break; - case TIME: - switch (currentType) { - case INTEGER: - LOG.debug("Trying to convert long value {} to date", value); - // let's assume we received the millisecond since 1970/1/1 - return new Date((Long) value); - case STRING: - LOG.debug("Trying to convert string value {} to date", value); - // let's assume we received an ISO 8601 format date - try { - DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); - XMLGregorianCalendar cal = datatypeFactory.newXMLGregorianCalendar((String) value); - return cal.toGregorianCalendar().getTime(); - } catch (DatatypeConfigurationException e) { - LOG.debug("Unable to convert string to date", e); - } - default: - break; - } - break; - case STRING: - switch (currentType) { - case BOOLEAN: - case INTEGER: - case FLOAT: - return String.valueOf(value); - default: - break; - } - break; - case OPAQUE: - if (currentType == Type.STRING) { - // let's assume we received an hexadecimal string - LOG.debug("Trying to convert hexadecimal string {} to byte array", value); - // TODO: check if we shouldn't instead assume that the string contains Base64 encoded data - return Hex.decodeHex(((String) value).toCharArray()); - } - break; - default: - } - - throw new IllegalArgumentException("Invalid value type, expected " + expectedType + ", got " + currentType); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Kai Hudalla (Bosch Software Innovations GmbH) - remove dependency on + * javax.xml.bind.DatatypeConverter + * which is not available on Android + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec; + +import java.util.Date; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.util.Hex; +import org.eclipse.leshan.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Helper for all the LwM2mNode encoders. + */ +public class Lwm2mNodeEncoderUtil { + private static final Logger LOG = LoggerFactory.getLogger(Lwm2mNodeEncoderUtil.class); + + private Lwm2mNodeEncoderUtil() { + } + + /** + * Convert the given value to the expected type given in parameter. + * + * @throws IllegalArgumentException the value is not convertible. + */ + public static Object convertValue(Object value, Type currentType, Type expectedType) { + if (expectedType == null) { + // unknown resource, trusted value + return value; + } + + if (currentType == expectedType) { + // expected type + return value; + } + + // We received a value with an unexpected type. + // Let's do some magic to try to convert this value... + + switch (expectedType) { + case INTEGER: + switch (currentType) { + case FLOAT: + LOG.debug("Trying to convert float value {} to integer", value); + Long longValue = ((Double) value).longValue(); + if ((double) value == longValue.doubleValue()) { + return longValue; + } + default: + break; + } + break; + case FLOAT: + switch (currentType) { + case INTEGER: + LOG.debug("Trying to convert integer value {} to float", value); + Double floatValue = ((Long) value).doubleValue(); + if ((long) value == floatValue.longValue()) { + return floatValue; + } + default: + break; + } + break; + case BOOLEAN: + switch (currentType) { + case STRING: + LOG.debug("Trying to convert string value {} to boolean", value); + if (StringUtils.equalsIgnoreCase((String) value, "true")) { + return true; + } else if (StringUtils.equalsIgnoreCase((String) value, "false")) { + return false; + } + case INTEGER: + LOG.debug("Trying to convert int value {} to boolean", value); + Long val = (Long) value; + if (val == 1) { + return true; + } else if (val == 0) { + return false; + } + default: + break; + } + break; + case TIME: + switch (currentType) { + case INTEGER: + LOG.debug("Trying to convert long value {} to date", value); + // let's assume we received the millisecond since 1970/1/1 + return new Date((Long) value); + case STRING: + LOG.debug("Trying to convert string value {} to date", value); + // let's assume we received an ISO 8601 format date + try { + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + XMLGregorianCalendar cal = datatypeFactory.newXMLGregorianCalendar((String) value); + return cal.toGregorianCalendar().getTime(); + } catch (DatatypeConfigurationException e) { + LOG.debug("Unable to convert string to date", e); + } + default: + break; + } + break; + case STRING: + switch (currentType) { + case BOOLEAN: + case INTEGER: + case FLOAT: + return String.valueOf(value); + default: + break; + } + break; + case OPAQUE: + if (currentType == Type.STRING) { + // let's assume we received an hexadecimal string + LOG.debug("Trying to convert hexadecimal string {} to byte array", value); + // TODO: check if we shouldn't instead assume that the string contains Base64 encoded data + return Hex.decodeHex(((String) value).toCharArray()); + } + break; + default: + } + + throw new IllegalArgumentException("Invalid value type, expected " + expectedType + ", got " + currentType); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonDecoder.java index f8b3afc..f8d687d 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonDecoder.java @@ -1,379 +1,379 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.json; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.node.codec.InvalidValueException; -import org.eclipse.leshan.json.JsonArrayEntry; -import org.eclipse.leshan.json.JsonRootObject; -import org.eclipse.leshan.json.LwM2mJson; -import org.eclipse.leshan.json.LwM2mJsonException; -import org.eclipse.leshan.util.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeJsonDecoder { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeJsonDecoder.class); - - @SuppressWarnings("unchecked") - public static T decode(byte[] content, LwM2mPath path, LwM2mModel model, Class nodeClass) - throws InvalidValueException { - try { - String jsonStrValue = new String(content); - JsonRootObject json = LwM2mJson.fromJsonLwM2m(jsonStrValue); - List timestampedNodes = parseJSON(json, path, model, nodeClass); - if (timestampedNodes.size() == 0) { - return null; - } else { - // return the most recent value - return (T) timestampedNodes.get(0).getNode(); - } - } catch (LwM2mJsonException e) { - throw new InvalidValueException("Unable to deSerialize json", path, e); - } - } - - public static List decodeTimestamped(byte[] content, LwM2mPath path, LwM2mModel model, - Class nodeClass) throws InvalidValueException { - try { - String jsonStrValue = new String(content); - JsonRootObject json = LwM2mJson.fromJsonLwM2m(jsonStrValue); - return parseJSON(json, path, model, nodeClass); - } catch (LwM2mJsonException e) { - throw new InvalidValueException("Unable to deSerialize json", path, e); - } - } - - private static List parseJSON(JsonRootObject jsonObject, LwM2mPath path, LwM2mModel model, - Class nodeClass) throws InvalidValueException { - - LOG.trace("Parsing JSON content for path {}: {}", path, jsonObject); - - // Group JSON entry by time-stamp - Map> jsonEntryByTimestamp = groupJsonEntryByTimestamp(jsonObject); - - // Extract baseName - LwM2mPath baseName = extractAndValidateBaseName(jsonObject, path); - if (baseName == null) - baseName = path; // if no base name, use request path as base name - - // fill time-stamped nodes collection - List timestampedNodes = new ArrayList<>(); - for (Entry> entryByTimestamp : jsonEntryByTimestamp.entrySet()) { - - // Group JSON entry by instance - Map> jsonEntryByInstanceId = groupJsonEntryByInstanceId( - entryByTimestamp.getValue(), baseName); - - // Create lwm2m node - LwM2mNode node = null; - if (nodeClass == LwM2mObject.class) { - Collection instances = new ArrayList<>(); - for (Entry> entryByInstanceId : jsonEntryByInstanceId.entrySet()) { - Map resourcesMap = extractLwM2mResources(entryByInstanceId.getValue(), - baseName, model); - - instances.add(new LwM2mObjectInstance(entryByInstanceId.getKey(), resourcesMap.values())); - } - - node = new LwM2mObject(baseName.getObjectId(), instances); - } else if (nodeClass == LwM2mObjectInstance.class) { - // validate we have resources for only 1 instance - if (jsonEntryByInstanceId.size() > 1) - throw new InvalidValueException("Only one instance expected in the payload", path); - - // Extract resources - Entry> instanceEntry = jsonEntryByInstanceId.entrySet().iterator() - .next(); - Map resourcesMap = extractLwM2mResources(instanceEntry.getValue(), baseName, - model); - - // Create instance - node = new LwM2mObjectInstance(instanceEntry.getKey(), resourcesMap.values()); - } else if (nodeClass == LwM2mResource.class) { - // validate we have resources for only 1 instance - if (jsonEntryByInstanceId.size() > 1) - throw new InvalidValueException("Only one instance expected in the payload", path); - - // Extract resources - Map resourcesMap = extractLwM2mResources(jsonEntryByInstanceId.values() - .iterator().next(), baseName, model); - - // validate there is only 1 resource - if (resourcesMap.size() != 1) - throw new InvalidValueException("Only one resource should be present in the payload", path); - - node = resourcesMap.values().iterator().next(); - } else { - throw new IllegalArgumentException("invalid node class: " + nodeClass); - } - - // compute time-stamp - Long timestamp = computeTimestamp(jsonObject.getBaseTime(), entryByTimestamp.getKey()); - - // add time-stamped node - timestampedNodes.add(new TimestampedLwM2mNode(timestamp, node)); - } - - return timestampedNodes; - - } - - private static Long computeTimestamp(Long baseTime, Long time) { - Long timestamp; - if (baseTime != null) { - if (time != null) { - timestamp = baseTime + time; - } else { - timestamp = baseTime; - } - } else { - if (time != null) { - timestamp = time; - } else { - timestamp = null; - } - } - return timestamp; - } - - /** - * Group all JsonArrayEntry by time-stamp - * - * @return a map (relativeTimestamp => collection of JsonArrayEntry) - */ - private static SortedMap> groupJsonEntryByTimestamp(JsonRootObject jsonObject) { - SortedMap> result = new TreeMap<>(new Comparator() { - @Override - public int compare(Long o1, Long o2) { - // comparator which - // - supports null (time null means 0 if there is a base time) - // - reverses natural order (most recent value in first) - return Long.compare(o2 == null ? 0 : o2, o1 == null ? 0 : o1); - } - }); - - for (JsonArrayEntry e : jsonObject.getResourceList()) { - // Get time for this entry - Long time = e.getTime(); - - // Get jsonArray for this time-stamp - Collection jsonArray = result.get(time); - if (jsonArray == null) { - jsonArray = new ArrayList(); - result.put(time, jsonArray); - } - - // Add it to the list - jsonArray.add(e); - } - - return result; - } - - /** - * Group all JsonArrayEntry by instanceId - * - * @param requestPath - * @param baseName - * @param jsonEntries - * - * @return a map (instanceId => collection of JsonArrayEntry) - */ - private static Map> groupJsonEntryByInstanceId( - Collection jsonEntries, LwM2mPath baseName) throws InvalidValueException { - Map> result = new HashMap<>(); - - for (JsonArrayEntry e : jsonEntries) { - // Build resource path - LwM2mPath nodePath = baseName.append(e.getName()); - - // Validate path - if (!nodePath.isResourceInstance() && !nodePath.isResource()) { - throw new InvalidValueException( - "Invalid path for resource, it should be a resource or a resource instance path", nodePath); - } - - // Get jsonArray for this instance - Collection jsonArray = result.get(nodePath.getObjectInstanceId()); - if (jsonArray == null) { - jsonArray = new ArrayList<>(); - result.put(nodePath.getObjectInstanceId(), jsonArray); - } - - // Add it to the list - jsonArray.add(e); - } - - return result; - } - - private static LwM2mPath extractAndValidateBaseName(JsonRootObject jsonObject, LwM2mPath requestPath) - throws InvalidValueException { - // Check baseName is valid - if (jsonObject.getBaseName() != null && !jsonObject.getBaseName().isEmpty()) { - LwM2mPath bnPath = new LwM2mPath(jsonObject.getBaseName()); - - // check returned base name path is under requested path - if (requestPath.getObjectId() != null && bnPath.getObjectId() != null) { - if (!bnPath.getObjectId().equals(requestPath.getObjectId())) { - throw new InvalidValueException("Basename path does not match requested path.", bnPath); - } - if (requestPath.getObjectInstanceId() != null && bnPath.getObjectInstanceId() != null) { - if (!bnPath.getObjectInstanceId().equals(requestPath.getObjectInstanceId())) { - throw new InvalidValueException("Basename path does not match requested path.", bnPath); - } - if (requestPath.getResourceId() != null && bnPath.getResourceId() != null) { - if (!bnPath.getResourceId().equals(requestPath.getResourceId())) { - throw new InvalidValueException("Basename path does not match requested path.", bnPath); - } - } - } - } - return bnPath; - } - return null; - - } - - private static Map extractLwM2mResources(Collection jsonArrayEntries, - LwM2mPath baseName, LwM2mModel model) throws InvalidValueException { - if (jsonArrayEntries == null) - return Collections.emptyMap(); - - // Extract LWM2M resources from JSON resource list - Map lwM2mResourceMap = new HashMap<>(); - Map> multiResourceMap = new HashMap<>(); - for (JsonArrayEntry resourceElt : jsonArrayEntries) { - - // Build resource path - LwM2mPath nodePath = baseName.append(resourceElt.getName()); - - // handle LWM2M resources - if (nodePath.isResourceInstance()) { - // Multi-instance resource - // Store multi-instance resource values in a map - // we will deal with it later - LwM2mPath resourcePath = new LwM2mPath(nodePath.getObjectId(), nodePath.getObjectInstanceId(), - nodePath.getResourceId()); - Map multiResource = multiResourceMap.get(resourcePath); - if (multiResource == null) { - multiResource = new HashMap<>(); - multiResourceMap.put(resourcePath, multiResource); - } - multiResource.put(nodePath.getResourceInstanceId(), resourceElt); - } else if (nodePath.isResource()) { - // Single resource - Type expectedType = getResourceType(nodePath, model, resourceElt); - LwM2mResource res = LwM2mSingleResource.newResource(nodePath.getResourceId(), - parseJsonValue(resourceElt.getResourceValue(), expectedType, nodePath), expectedType); - lwM2mResourceMap.put(nodePath.getResourceId(), res); - } else { - throw new InvalidValueException( - "Invalid path for resource, it should be a resource or a resource instance path", nodePath); - } - } - - // Handle multi-instance resource. - for (Map.Entry> entry : multiResourceMap.entrySet()) { - LwM2mPath resourcePath = entry.getKey(); - Map jsonEntries = entry.getValue(); - - if (jsonEntries != null && !jsonEntries.isEmpty()) { - Type expectedType = getResourceType(resourcePath, model, jsonEntries.values().iterator().next()); - Map values = new HashMap<>(); - for (Entry e : jsonEntries.entrySet()) { - Integer resourceInstanceId = e.getKey(); - values.put(resourceInstanceId, - parseJsonValue(e.getValue().getResourceValue(), expectedType, resourcePath)); - } - LwM2mResource resource = LwM2mMultipleResource.newResource(resourcePath.getResourceId(), values, - expectedType); - lwM2mResourceMap.put(resourcePath.getResourceId(), resource); - } - } - return lwM2mResourceMap; - } - - private static Object parseJsonValue(Object value, Type expectedType, LwM2mPath path) throws InvalidValueException { - - LOG.trace("JSON value for path {} and expected type {}: {}", path, expectedType, value); - - try { - switch (expectedType) { - case INTEGER: - // JSON format specs said v = integer or float - return ((Number) value).longValue(); - case BOOLEAN: - return value; - case FLOAT: - // JSON format specs said v = integer or float - return ((Number) value).doubleValue(); - case TIME: - // TODO Specs page 44, Resource 13 (current time) of device object represented as Float value - return new Date(((Number) value).longValue() * 1000L); - case OPAQUE: - // If the Resource data type is opaque the string value - // holds the Base64 encoded representation of the Resource - return Base64.decodeBase64((String) value); - case STRING: - return value; - default: - throw new InvalidValueException("Unsupported type " + expectedType, path); - } - } catch (Exception e) { - throw new InvalidValueException("Invalid content for type " + expectedType, path, e); - } - } - - public static Type getResourceType(LwM2mPath rscPath, LwM2mModel model, JsonArrayEntry resourceElt) - throws InvalidValueException { - ResourceModel rscDesc = model.getResourceModel(rscPath.getObjectId(), rscPath.getResourceId()); - if (rscDesc == null || rscDesc.type == null) { - Type type = resourceElt.getType(); - if (type != null) - return type; - - LOG.trace("unknown type for resource use string as default: {}", rscPath); - return Type.STRING; - } else { - return rscDesc.type; - } - } +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.json; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.node.codec.InvalidValueException; +import org.eclipse.leshan.json.JsonArrayEntry; +import org.eclipse.leshan.json.JsonRootObject; +import org.eclipse.leshan.json.LwM2mJson; +import org.eclipse.leshan.json.LwM2mJsonException; +import org.eclipse.leshan.util.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeJsonDecoder { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeJsonDecoder.class); + + @SuppressWarnings("unchecked") + public static T decode(byte[] content, LwM2mPath path, LwM2mModel model, Class nodeClass) + throws InvalidValueException { + try { + String jsonStrValue = new String(content); + JsonRootObject json = LwM2mJson.fromJsonLwM2m(jsonStrValue); + List timestampedNodes = parseJSON(json, path, model, nodeClass); + if (timestampedNodes.size() == 0) { + return null; + } else { + // return the most recent value + return (T) timestampedNodes.get(0).getNode(); + } + } catch (LwM2mJsonException e) { + throw new InvalidValueException("Unable to deSerialize json", path, e); + } + } + + public static List decodeTimestamped(byte[] content, LwM2mPath path, LwM2mModel model, + Class nodeClass) throws InvalidValueException { + try { + String jsonStrValue = new String(content); + JsonRootObject json = LwM2mJson.fromJsonLwM2m(jsonStrValue); + return parseJSON(json, path, model, nodeClass); + } catch (LwM2mJsonException e) { + throw new InvalidValueException("Unable to deSerialize json", path, e); + } + } + + private static List parseJSON(JsonRootObject jsonObject, LwM2mPath path, LwM2mModel model, + Class nodeClass) throws InvalidValueException { + + LOG.trace("Parsing JSON content for path {}: {}", path, jsonObject); + + // Group JSON entry by time-stamp + Map> jsonEntryByTimestamp = groupJsonEntryByTimestamp(jsonObject); + + // Extract baseName + LwM2mPath baseName = extractAndValidateBaseName(jsonObject, path); + if (baseName == null) + baseName = path; // if no base name, use request path as base name + + // fill time-stamped nodes collection + List timestampedNodes = new ArrayList<>(); + for (Entry> entryByTimestamp : jsonEntryByTimestamp.entrySet()) { + + // Group JSON entry by instance + Map> jsonEntryByInstanceId = groupJsonEntryByInstanceId( + entryByTimestamp.getValue(), baseName); + + // Create lwm2m node + LwM2mNode node = null; + if (nodeClass == LwM2mObject.class) { + Collection instances = new ArrayList<>(); + for (Entry> entryByInstanceId : jsonEntryByInstanceId.entrySet()) { + Map resourcesMap = extractLwM2mResources(entryByInstanceId.getValue(), + baseName, model); + + instances.add(new LwM2mObjectInstance(entryByInstanceId.getKey(), resourcesMap.values())); + } + + node = new LwM2mObject(baseName.getObjectId(), instances); + } else if (nodeClass == LwM2mObjectInstance.class) { + // validate we have resources for only 1 instance + if (jsonEntryByInstanceId.size() > 1) + throw new InvalidValueException("Only one instance expected in the payload", path); + + // Extract resources + Entry> instanceEntry = jsonEntryByInstanceId.entrySet().iterator() + .next(); + Map resourcesMap = extractLwM2mResources(instanceEntry.getValue(), baseName, + model); + + // Create instance + node = new LwM2mObjectInstance(instanceEntry.getKey(), resourcesMap.values()); + } else if (nodeClass == LwM2mResource.class) { + // validate we have resources for only 1 instance + if (jsonEntryByInstanceId.size() > 1) + throw new InvalidValueException("Only one instance expected in the payload", path); + + // Extract resources + Map resourcesMap = extractLwM2mResources(jsonEntryByInstanceId.values() + .iterator().next(), baseName, model); + + // validate there is only 1 resource + if (resourcesMap.size() != 1) + throw new InvalidValueException("Only one resource should be present in the payload", path); + + node = resourcesMap.values().iterator().next(); + } else { + throw new IllegalArgumentException("invalid node class: " + nodeClass); + } + + // compute time-stamp + Long timestamp = computeTimestamp(jsonObject.getBaseTime(), entryByTimestamp.getKey()); + + // add time-stamped node + timestampedNodes.add(new TimestampedLwM2mNode(timestamp, node)); + } + + return timestampedNodes; + + } + + private static Long computeTimestamp(Long baseTime, Long time) { + Long timestamp; + if (baseTime != null) { + if (time != null) { + timestamp = baseTime + time; + } else { + timestamp = baseTime; + } + } else { + if (time != null) { + timestamp = time; + } else { + timestamp = null; + } + } + return timestamp; + } + + /** + * Group all JsonArrayEntry by time-stamp + * + * @return a map (relativeTimestamp => collection of JsonArrayEntry) + */ + private static SortedMap> groupJsonEntryByTimestamp(JsonRootObject jsonObject) { + SortedMap> result = new TreeMap<>(new Comparator() { + @Override + public int compare(Long o1, Long o2) { + // comparator which + // - supports null (time null means 0 if there is a base time) + // - reverses natural order (most recent value in first) + return Long.compare(o2 == null ? 0 : o2, o1 == null ? 0 : o1); + } + }); + + for (JsonArrayEntry e : jsonObject.getResourceList()) { + // Get time for this entry + Long time = e.getTime(); + + // Get jsonArray for this time-stamp + Collection jsonArray = result.get(time); + if (jsonArray == null) { + jsonArray = new ArrayList(); + result.put(time, jsonArray); + } + + // Add it to the list + jsonArray.add(e); + } + + return result; + } + + /** + * Group all JsonArrayEntry by instanceId + * + * @param requestPath + * @param baseName + * @param jsonEntries + * + * @return a map (instanceId => collection of JsonArrayEntry) + */ + private static Map> groupJsonEntryByInstanceId( + Collection jsonEntries, LwM2mPath baseName) throws InvalidValueException { + Map> result = new HashMap<>(); + + for (JsonArrayEntry e : jsonEntries) { + // Build resource path + LwM2mPath nodePath = baseName.append(e.getName()); + + // Validate path + if (!nodePath.isResourceInstance() && !nodePath.isResource()) { + throw new InvalidValueException( + "Invalid path for resource, it should be a resource or a resource instance path", nodePath); + } + + // Get jsonArray for this instance + Collection jsonArray = result.get(nodePath.getObjectInstanceId()); + if (jsonArray == null) { + jsonArray = new ArrayList<>(); + result.put(nodePath.getObjectInstanceId(), jsonArray); + } + + // Add it to the list + jsonArray.add(e); + } + + return result; + } + + private static LwM2mPath extractAndValidateBaseName(JsonRootObject jsonObject, LwM2mPath requestPath) + throws InvalidValueException { + // Check baseName is valid + if (jsonObject.getBaseName() != null && !jsonObject.getBaseName().isEmpty()) { + LwM2mPath bnPath = new LwM2mPath(jsonObject.getBaseName()); + + // check returned base name path is under requested path + if (requestPath.getObjectId() != null && bnPath.getObjectId() != null) { + if (!bnPath.getObjectId().equals(requestPath.getObjectId())) { + throw new InvalidValueException("Basename path does not match requested path.", bnPath); + } + if (requestPath.getObjectInstanceId() != null && bnPath.getObjectInstanceId() != null) { + if (!bnPath.getObjectInstanceId().equals(requestPath.getObjectInstanceId())) { + throw new InvalidValueException("Basename path does not match requested path.", bnPath); + } + if (requestPath.getResourceId() != null && bnPath.getResourceId() != null) { + if (!bnPath.getResourceId().equals(requestPath.getResourceId())) { + throw new InvalidValueException("Basename path does not match requested path.", bnPath); + } + } + } + } + return bnPath; + } + return null; + + } + + private static Map extractLwM2mResources(Collection jsonArrayEntries, + LwM2mPath baseName, LwM2mModel model) throws InvalidValueException { + if (jsonArrayEntries == null) + return Collections.emptyMap(); + + // Extract LWM2M resources from JSON resource list + Map lwM2mResourceMap = new HashMap<>(); + Map> multiResourceMap = new HashMap<>(); + for (JsonArrayEntry resourceElt : jsonArrayEntries) { + + // Build resource path + LwM2mPath nodePath = baseName.append(resourceElt.getName()); + + // handle LWM2M resources + if (nodePath.isResourceInstance()) { + // Multi-instance resource + // Store multi-instance resource values in a map + // we will deal with it later + LwM2mPath resourcePath = new LwM2mPath(nodePath.getObjectId(), nodePath.getObjectInstanceId(), + nodePath.getResourceId()); + Map multiResource = multiResourceMap.get(resourcePath); + if (multiResource == null) { + multiResource = new HashMap<>(); + multiResourceMap.put(resourcePath, multiResource); + } + multiResource.put(nodePath.getResourceInstanceId(), resourceElt); + } else if (nodePath.isResource()) { + // Single resource + Type expectedType = getResourceType(nodePath, model, resourceElt); + LwM2mResource res = LwM2mSingleResource.newResource(nodePath.getResourceId(), + parseJsonValue(resourceElt.getResourceValue(), expectedType, nodePath), expectedType); + lwM2mResourceMap.put(nodePath.getResourceId(), res); + } else { + throw new InvalidValueException( + "Invalid path for resource, it should be a resource or a resource instance path", nodePath); + } + } + + // Handle multi-instance resource. + for (Map.Entry> entry : multiResourceMap.entrySet()) { + LwM2mPath resourcePath = entry.getKey(); + Map jsonEntries = entry.getValue(); + + if (jsonEntries != null && !jsonEntries.isEmpty()) { + Type expectedType = getResourceType(resourcePath, model, jsonEntries.values().iterator().next()); + Map values = new HashMap<>(); + for (Entry e : jsonEntries.entrySet()) { + Integer resourceInstanceId = e.getKey(); + values.put(resourceInstanceId, + parseJsonValue(e.getValue().getResourceValue(), expectedType, resourcePath)); + } + LwM2mResource resource = LwM2mMultipleResource.newResource(resourcePath.getResourceId(), values, + expectedType); + lwM2mResourceMap.put(resourcePath.getResourceId(), resource); + } + } + return lwM2mResourceMap; + } + + private static Object parseJsonValue(Object value, Type expectedType, LwM2mPath path) throws InvalidValueException { + + LOG.trace("JSON value for path {} and expected type {}: {}", path, expectedType, value); + + try { + switch (expectedType) { + case INTEGER: + // JSON format specs said v = integer or float + return ((Number) value).longValue(); + case BOOLEAN: + return value; + case FLOAT: + // JSON format specs said v = integer or float + return ((Number) value).doubleValue(); + case TIME: + // TODO Specs page 44, Resource 13 (current time) of device object represented as Float value + return new Date(((Number) value).longValue() * 1000L); + case OPAQUE: + // If the Resource data type is opaque the string value + // holds the Base64 encoded representation of the Resource + return Base64.decodeBase64((String) value); + case STRING: + return value; + default: + throw new InvalidValueException("Unsupported type " + expectedType, path); + } + } catch (Exception e) { + throw new InvalidValueException("Invalid content for type " + expectedType, path, e); + } + } + + public static Type getResourceType(LwM2mPath rscPath, LwM2mModel model, JsonArrayEntry resourceElt) + throws InvalidValueException { + ResourceModel rscDesc = model.getResourceModel(rscPath.getObjectId(), rscPath.getResourceId()); + if (rscDesc == null || rscDesc.type == null) { + Type type = resourceElt.getType(); + if (type != null) + return type; + + LOG.trace("unknown type for resource use string as default: {}", rscPath); + return Type.STRING; + } else { + return rscDesc.type; + } + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonEncoder.java index 63d38f9..d95124e 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonEncoder.java @@ -1,210 +1,210 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.json; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map.Entry; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mNodeVisitor; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.TimestampedLwM2mNode; -import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; -import org.eclipse.leshan.json.JsonArrayEntry; -import org.eclipse.leshan.json.JsonRootObject; -import org.eclipse.leshan.json.LwM2mJson; -import org.eclipse.leshan.util.Base64; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeJsonEncoder { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeJsonEncoder.class); - - public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { - Validate.notNull(node); - Validate.notNull(path); - Validate.notNull(model); - - InternalEncoder internalEncoder = new InternalEncoder(); - internalEncoder.objectId = path.getObjectId(); - internalEncoder.model = model; - internalEncoder.requestPath = path; - node.accept(internalEncoder); - JsonRootObject jsonObject = new JsonRootObject(internalEncoder.resourceList); - return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); - } - - public static byte[] encodeTimestampedData(List timestampedNodes, LwM2mPath path, - LwM2mModel model) { - Validate.notNull(timestampedNodes); - Validate.notNull(path); - Validate.notNull(model); - - InternalEncoder internalEncoder = new InternalEncoder(); - ArrayList entries = new ArrayList<>(); - for (TimestampedLwM2mNode timestampedLwM2mNode : timestampedNodes) { - internalEncoder.objectId = path.getObjectId(); - internalEncoder.model = model; - internalEncoder.requestPath = path; - internalEncoder.resourceList = null; - internalEncoder.timestamp = timestampedLwM2mNode.getTimestamp(); - timestampedLwM2mNode.getNode().accept(internalEncoder); - entries.addAll(internalEncoder.resourceList); - } - JsonRootObject jsonObject = new JsonRootObject(entries); - - return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); - } - - private static class InternalEncoder implements LwM2mNodeVisitor { - // visitor inputs - private int objectId; - private LwM2mModel model; - private LwM2mPath requestPath; - private Long timestamp; - - // visitor output - private ArrayList resourceList = null; - - @Override - public void visit(LwM2mObject object) { - LOG.trace("Encoding Object {} into JSON", object); - // Validate request path - if (!requestPath.isObject()) { - throw new IllegalArgumentException("Invalid request path for JSON object encoding"); - } - - // Create resources - resourceList = new ArrayList<>(); - for (LwM2mObjectInstance instance : object.getInstances().values()) { - for (LwM2mResource resource : instance.getResources().values()) { - String prefixPath = Integer.toString(instance.getId()) + "/" + Integer.toString(resource.getId()); - resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); - } - } - } - - @Override - public void visit(LwM2mObjectInstance instance) { - LOG.trace("Encoding object instance {} into JSON", instance); - resourceList = new ArrayList<>(); - for (LwM2mResource resource : instance.getResources().values()) { - // Validate request path & compute resource path - String prefixPath = null; - if (requestPath.isObject()) { - prefixPath = instance.getId() + "/" + resource.getId(); - } else if (requestPath.isObjectInstance()) { - prefixPath = Integer.toString(resource.getId()); - } else { - throw new IllegalArgumentException("Invalid request path for JSON instance encoding"); - } - // Create resources - resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); - } - } - - @Override - public void visit(LwM2mResource resource) { - LOG.trace("Encoding resource {} into JSON", resource); - if (!requestPath.isResource()) { - throw new IllegalArgumentException("Invalid request path for JSON resource encoding"); - } - - resourceList = lwM2mResourceToJsonArrayEntry("", timestamp, resource); - } - - private ArrayList lwM2mResourceToJsonArrayEntry(String resourcePath, Long timestamp, - LwM2mResource resource) { - // get type for this resource - ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); - Type expectedType = rSpec != null ? rSpec.type : resource.getType(); - ArrayList resourcesList = new ArrayList<>(); - - // create JSON resource element - if (resource.isMultiInstances()) { - for (Entry entry : resource.getValues().entrySet()) { - // Create resource element - JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); - if (resourcePath == null || resourcePath.isEmpty()) { - jsonResourceElt.setName(Integer.toString(entry.getKey())); - } else { - jsonResourceElt.setName(resourcePath + "/" + entry.getKey()); - } - jsonResourceElt.setTime(timestamp); - - // Convert value using expected type - Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(entry.getValue(), resource.getType(), - expectedType); - this.setResourceValue(convertedValue, expectedType, jsonResourceElt); - - // Add it to the List - resourcesList.add(jsonResourceElt); - } - } else { - // Create resource element - JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); - jsonResourceElt.setName(resourcePath); - jsonResourceElt.setTime(timestamp); - - // Convert value using expected type - this.setResourceValue( - Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), expectedType), - expectedType, jsonResourceElt); - - // Add it to the List - resourcesList.add(jsonResourceElt); - } - return resourcesList; - } - - private void setResourceValue(Object value, Type type, JsonArrayEntry jsonResource) { - LOG.trace("Encoding value {} in JSON", value); - // Following table 20 in the Specs - switch (type) { - case STRING: - jsonResource.setStringValue((String) value); - break; - case INTEGER: - case FLOAT: - jsonResource.setFloatValue((Number) value); - break; - case BOOLEAN: - jsonResource.setBooleanValue((Boolean) value); - break; - case TIME: - // Specs device object example page 44, rec 13 is Time - // represented as float? - jsonResource.setFloatValue((((Date) value).getTime() / 1000L)); - break; - case OPAQUE: - jsonResource.setStringValue(Base64.encodeBase64String((byte[]) value)); - break; - default: - throw new IllegalArgumentException("Invalid value type: " + type); - } - } - } +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.json; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map.Entry; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mNodeVisitor; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.TimestampedLwM2mNode; +import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; +import org.eclipse.leshan.json.JsonArrayEntry; +import org.eclipse.leshan.json.JsonRootObject; +import org.eclipse.leshan.json.LwM2mJson; +import org.eclipse.leshan.util.Base64; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeJsonEncoder { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeJsonEncoder.class); + + public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { + Validate.notNull(node); + Validate.notNull(path); + Validate.notNull(model); + + InternalEncoder internalEncoder = new InternalEncoder(); + internalEncoder.objectId = path.getObjectId(); + internalEncoder.model = model; + internalEncoder.requestPath = path; + node.accept(internalEncoder); + JsonRootObject jsonObject = new JsonRootObject(internalEncoder.resourceList); + return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); + } + + public static byte[] encodeTimestampedData(List timestampedNodes, LwM2mPath path, + LwM2mModel model) { + Validate.notNull(timestampedNodes); + Validate.notNull(path); + Validate.notNull(model); + + InternalEncoder internalEncoder = new InternalEncoder(); + ArrayList entries = new ArrayList<>(); + for (TimestampedLwM2mNode timestampedLwM2mNode : timestampedNodes) { + internalEncoder.objectId = path.getObjectId(); + internalEncoder.model = model; + internalEncoder.requestPath = path; + internalEncoder.resourceList = null; + internalEncoder.timestamp = timestampedLwM2mNode.getTimestamp(); + timestampedLwM2mNode.getNode().accept(internalEncoder); + entries.addAll(internalEncoder.resourceList); + } + JsonRootObject jsonObject = new JsonRootObject(entries); + + return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); + } + + private static class InternalEncoder implements LwM2mNodeVisitor { + // visitor inputs + private int objectId; + private LwM2mModel model; + private LwM2mPath requestPath; + private Long timestamp; + + // visitor output + private ArrayList resourceList = null; + + @Override + public void visit(LwM2mObject object) { + LOG.trace("Encoding Object {} into JSON", object); + // Validate request path + if (!requestPath.isObject()) { + throw new IllegalArgumentException("Invalid request path for JSON object encoding"); + } + + // Create resources + resourceList = new ArrayList<>(); + for (LwM2mObjectInstance instance : object.getInstances().values()) { + for (LwM2mResource resource : instance.getResources().values()) { + String prefixPath = Integer.toString(instance.getId()) + "/" + Integer.toString(resource.getId()); + resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); + } + } + } + + @Override + public void visit(LwM2mObjectInstance instance) { + LOG.trace("Encoding object instance {} into JSON", instance); + resourceList = new ArrayList<>(); + for (LwM2mResource resource : instance.getResources().values()) { + // Validate request path & compute resource path + String prefixPath = null; + if (requestPath.isObject()) { + prefixPath = instance.getId() + "/" + resource.getId(); + } else if (requestPath.isObjectInstance()) { + prefixPath = Integer.toString(resource.getId()); + } else { + throw new IllegalArgumentException("Invalid request path for JSON instance encoding"); + } + // Create resources + resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); + } + } + + @Override + public void visit(LwM2mResource resource) { + LOG.trace("Encoding resource {} into JSON", resource); + if (!requestPath.isResource()) { + throw new IllegalArgumentException("Invalid request path for JSON resource encoding"); + } + + resourceList = lwM2mResourceToJsonArrayEntry("", timestamp, resource); + } + + private ArrayList lwM2mResourceToJsonArrayEntry(String resourcePath, Long timestamp, + LwM2mResource resource) { + // get type for this resource + ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); + Type expectedType = rSpec != null ? rSpec.type : resource.getType(); + ArrayList resourcesList = new ArrayList<>(); + + // create JSON resource element + if (resource.isMultiInstances()) { + for (Entry entry : resource.getValues().entrySet()) { + // Create resource element + JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); + if (resourcePath == null || resourcePath.isEmpty()) { + jsonResourceElt.setName(Integer.toString(entry.getKey())); + } else { + jsonResourceElt.setName(resourcePath + "/" + entry.getKey()); + } + jsonResourceElt.setTime(timestamp); + + // Convert value using expected type + Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(entry.getValue(), resource.getType(), + expectedType); + this.setResourceValue(convertedValue, expectedType, jsonResourceElt); + + // Add it to the List + resourcesList.add(jsonResourceElt); + } + } else { + // Create resource element + JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); + jsonResourceElt.setName(resourcePath); + jsonResourceElt.setTime(timestamp); + + // Convert value using expected type + this.setResourceValue( + Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), expectedType), + expectedType, jsonResourceElt); + + // Add it to the List + resourcesList.add(jsonResourceElt); + } + return resourcesList; + } + + private void setResourceValue(Object value, Type type, JsonArrayEntry jsonResource) { + LOG.trace("Encoding value {} in JSON", value); + // Following table 20 in the Specs + switch (type) { + case STRING: + jsonResource.setStringValue((String) value); + break; + case INTEGER: + case FLOAT: + jsonResource.setFloatValue((Number) value); + break; + case BOOLEAN: + jsonResource.setBooleanValue((Boolean) value); + break; + case TIME: + // Specs device object example page 44, rec 13 is Time + // represented as float? + jsonResource.setFloatValue((((Date) value).getTime() / 1000L)); + break; + case OPAQUE: + jsonResource.setStringValue(Base64.encodeBase64String((byte[]) value)); + break; + default: + throw new IllegalArgumentException("Invalid value type: " + type); + } + } + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueDecoder.java index 0f10aba..c060db8 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueDecoder.java @@ -1,40 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.opaque; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.codec.InvalidValueException; -import org.eclipse.leshan.util.Validate; - -public class LwM2mNodeOpaqueDecoder { - - public static LwM2mNode decode(byte[] content, LwM2mPath path, LwM2mModel model) throws InvalidValueException { - // single resource value - Validate.notNull(path.getResourceId()); - ResourceModel desc = model.getResourceModel(path.getObjectId(), path.getResourceId()); - if (desc != null && desc.type != Type.OPAQUE) { - throw new InvalidValueException( - "Invalid content format, OPAQUE can only be used for single OPAQUE resource", path); - } - return LwM2mSingleResource.newBinaryResource(path.getResourceId(), content); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.opaque; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.node.codec.InvalidValueException; +import org.eclipse.leshan.util.Validate; + +public class LwM2mNodeOpaqueDecoder { + + public static LwM2mNode decode(byte[] content, LwM2mPath path, LwM2mModel model) throws InvalidValueException { + // single resource value + Validate.notNull(path.getResourceId()); + ResourceModel desc = model.getResourceModel(path.getObjectId(), path.getResourceId()); + if (desc != null && desc.type != Type.OPAQUE) { + throw new InvalidValueException( + "Invalid content format, OPAQUE can only be used for single OPAQUE resource", path); + } + return LwM2mSingleResource.newBinaryResource(path.getResourceId(), content); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueEncoder.java index 0cd9063..12f21dd 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/opaque/LwM2mNodeOpaqueEncoder.java @@ -1,78 +1,78 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.opaque; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mNodeVisitor; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeOpaqueEncoder { - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeOpaqueEncoder.class); - - public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { - Validate.notNull(node); - Validate.notNull(path); - Validate.notNull(model); - - InternalEncoder internalEncoder = new InternalEncoder(); - internalEncoder.objectId = path.getObjectId(); - internalEncoder.model = model; - node.accept(internalEncoder); - return internalEncoder.encoded; - } - - private static class InternalEncoder implements LwM2mNodeVisitor { - - int objectId; - LwM2mModel model; - - byte[] encoded = null; - - @Override - public void visit(LwM2mObject object) { - throw new IllegalArgumentException("Object cannot be encoded in opaque format"); - } - - @Override - public void visit(LwM2mObjectInstance instance) { - throw new IllegalArgumentException("Object instance cannot be encoded in opaque format"); - } - - @Override - public void visit(LwM2mResource resource) { - if (resource.isMultiInstances()) { - throw new IllegalArgumentException("Mulitple instances resource cannot be encoded in opaque format"); - } - ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); - if (rSpec != null && rSpec.type != Type.OPAQUE) { - throw new IllegalArgumentException("Only single opaque resource can be encoded in opaque format"); - } - LOG.trace("Encoding resource {} into text", resource); - Object value = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), Type.OPAQUE); - encoded = (byte[]) value; - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.opaque; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mNodeVisitor; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeOpaqueEncoder { + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeOpaqueEncoder.class); + + public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { + Validate.notNull(node); + Validate.notNull(path); + Validate.notNull(model); + + InternalEncoder internalEncoder = new InternalEncoder(); + internalEncoder.objectId = path.getObjectId(); + internalEncoder.model = model; + node.accept(internalEncoder); + return internalEncoder.encoded; + } + + private static class InternalEncoder implements LwM2mNodeVisitor { + + int objectId; + LwM2mModel model; + + byte[] encoded = null; + + @Override + public void visit(LwM2mObject object) { + throw new IllegalArgumentException("Object cannot be encoded in opaque format"); + } + + @Override + public void visit(LwM2mObjectInstance instance) { + throw new IllegalArgumentException("Object instance cannot be encoded in opaque format"); + } + + @Override + public void visit(LwM2mResource resource) { + if (resource.isMultiInstances()) { + throw new IllegalArgumentException("Mulitple instances resource cannot be encoded in opaque format"); + } + ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); + if (rSpec != null && rSpec.type != Type.OPAQUE) { + throw new IllegalArgumentException("Only single opaque resource can be encoded in opaque format"); + } + LOG.trace("Encoding resource {} into text", resource); + Object value = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), Type.OPAQUE); + encoded = (byte[]) value; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextDecoder.java index af9afd2..979c03a 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextDecoder.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.text; - -import java.util.Date; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.codec.InvalidValueException; -import org.eclipse.leshan.util.Charsets; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeTextDecoder { - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTextDecoder.class); - - public static LwM2mNode decode(byte[] content, LwM2mPath path, LwM2mModel model) throws InvalidValueException { - // single resource value - Validate.notNull(path.getResourceId()); - ResourceModel rDesc = model.getResourceModel(path.getObjectId(), path.getResourceId()); - - String strValue = new String(content, Charsets.UTF_8); - if (rDesc != null && rDesc.type != null) { - return LwM2mSingleResource.newResource(path.getResourceId(), parseTextValue(strValue, rDesc.type, path), - rDesc.type); - } else { - // unknown resource, returning a default string value - return LwM2mSingleResource.newStringResource(path.getResourceId(), strValue); - } - - } - - private static Object parseTextValue(String value, Type type, LwM2mPath path) throws InvalidValueException { - LOG.trace("TEXT value for path {} and expected type {}: {}", path, type, value); - - try { - switch (type) { - case STRING: - return value; - case INTEGER: - try { - return Long.valueOf(value); - } catch (NumberFormatException e) { - throw new InvalidValueException("Invalid value for integer resource: " + value, path); - } - case BOOLEAN: - switch (value) { - case "0": - return false; - case "1": - return true; - default: - throw new InvalidValueException("Invalid value for boolean resource: " + value, path); - } - case FLOAT: - try { - return Double.valueOf(value); - } catch (NumberFormatException e) { - throw new InvalidValueException("Invalid value for float resource: " + value, path); - } - case TIME: - // number of seconds since 1970/1/1 - return new Date(Long.valueOf(value) * 1000L); - case OPAQUE: - // not specified - default: - throw new InvalidValueException("Could not parse opaque value with content format " + type, path); - } - } catch (NumberFormatException e) { - throw new InvalidValueException("Invalid numeric value: " + value, path, e); - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.text; + +import java.util.Date; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.node.codec.InvalidValueException; +import org.eclipse.leshan.util.Charsets; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeTextDecoder { + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTextDecoder.class); + + public static LwM2mNode decode(byte[] content, LwM2mPath path, LwM2mModel model) throws InvalidValueException { + // single resource value + Validate.notNull(path.getResourceId()); + ResourceModel rDesc = model.getResourceModel(path.getObjectId(), path.getResourceId()); + + String strValue = new String(content, Charsets.UTF_8); + if (rDesc != null && rDesc.type != null) { + return LwM2mSingleResource.newResource(path.getResourceId(), parseTextValue(strValue, rDesc.type, path), + rDesc.type); + } else { + // unknown resource, returning a default string value + return LwM2mSingleResource.newStringResource(path.getResourceId(), strValue); + } + + } + + private static Object parseTextValue(String value, Type type, LwM2mPath path) throws InvalidValueException { + LOG.trace("TEXT value for path {} and expected type {}: {}", path, type, value); + + try { + switch (type) { + case STRING: + return value; + case INTEGER: + try { + return Long.valueOf(value); + } catch (NumberFormatException e) { + throw new InvalidValueException("Invalid value for integer resource: " + value, path); + } + case BOOLEAN: + switch (value) { + case "0": + return false; + case "1": + return true; + default: + throw new InvalidValueException("Invalid value for boolean resource: " + value, path); + } + case FLOAT: + try { + return Double.valueOf(value); + } catch (NumberFormatException e) { + throw new InvalidValueException("Invalid value for float resource: " + value, path); + } + case TIME: + // number of seconds since 1970/1/1 + return new Date(Long.valueOf(value) * 1000L); + case OPAQUE: + // not specified + default: + throw new InvalidValueException("Could not parse opaque value with content format " + type, path); + } + } catch (NumberFormatException e) { + throw new InvalidValueException("Invalid numeric value: " + value, path, e); + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextEncoder.java index 7318140..d554cd7 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/text/LwM2mNodeTextEncoder.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.text; - -import java.util.Date; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mNodeVisitor; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; -import org.eclipse.leshan.util.Charsets; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeTextEncoder { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTextEncoder.class); - - public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { - Validate.notNull(node); - Validate.notNull(path); - Validate.notNull(model); - - InternalEncoder internalEncoder = new InternalEncoder(); - internalEncoder.objectId = path.getObjectId(); - internalEncoder.model = model; - node.accept(internalEncoder); - return internalEncoder.encoded; - } - - private static class InternalEncoder implements LwM2mNodeVisitor { - // visitor inputs - private int objectId; - private LwM2mModel model; - - // visitor output - private byte[] encoded = null; - - @Override - public void visit(LwM2mObject object) { - throw new IllegalArgumentException("Object cannot be encoded in text format"); - } - - @Override - public void visit(LwM2mObjectInstance instance) { - throw new IllegalArgumentException("Object instance cannot be encoded in text format"); - } - - @Override - public void visit(LwM2mResource resource) { - if (resource.isMultiInstances()) { - throw new IllegalArgumentException("Mulitple instances resource cannot be encoded in text format"); - } - LOG.trace("Encoding resource {} into text", resource); - - ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); - Type expectedType = rSpec != null ? rSpec.type : resource.getType(); - Object val = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), expectedType); - - String strValue = null; - switch (expectedType) { - case INTEGER: - case FLOAT: - case STRING: - strValue = String.valueOf(val); - break; - case BOOLEAN: - strValue = ((Boolean) val) ? "1" : "0"; - break; - case TIME: - // number of seconds since 1970/1/1 - strValue = String.valueOf(((Date) val).getTime() / 1000L); - break; - default: - throw new IllegalArgumentException("Cannot encode " + val + " in text format"); - } - - encoded = strValue.getBytes(Charsets.UTF_8); - } - } +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.text; + +import java.util.Date; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mNodeVisitor; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; +import org.eclipse.leshan.util.Charsets; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeTextEncoder { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTextEncoder.class); + + public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { + Validate.notNull(node); + Validate.notNull(path); + Validate.notNull(model); + + InternalEncoder internalEncoder = new InternalEncoder(); + internalEncoder.objectId = path.getObjectId(); + internalEncoder.model = model; + node.accept(internalEncoder); + return internalEncoder.encoded; + } + + private static class InternalEncoder implements LwM2mNodeVisitor { + // visitor inputs + private int objectId; + private LwM2mModel model; + + // visitor output + private byte[] encoded = null; + + @Override + public void visit(LwM2mObject object) { + throw new IllegalArgumentException("Object cannot be encoded in text format"); + } + + @Override + public void visit(LwM2mObjectInstance instance) { + throw new IllegalArgumentException("Object instance cannot be encoded in text format"); + } + + @Override + public void visit(LwM2mResource resource) { + if (resource.isMultiInstances()) { + throw new IllegalArgumentException("Mulitple instances resource cannot be encoded in text format"); + } + LOG.trace("Encoding resource {} into text", resource); + + ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); + Type expectedType = rSpec != null ? rSpec.type : resource.getType(); + Object val = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), expectedType); + + String strValue = null; + switch (expectedType) { + case INTEGER: + case FLOAT: + case STRING: + strValue = String.valueOf(val); + break; + case BOOLEAN: + strValue = ((Boolean) val) ? "1" : "0"; + break; + case TIME: + // number of seconds since 1970/1/1 + strValue = String.valueOf(((Date) val).getTime() / 1000L); + break; + default: + throw new IllegalArgumentException("Cannot encode " + val + " in text format"); + } + + encoded = strValue.getBytes(Charsets.UTF_8); + } + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvDecoder.java index ebfe2a5..1d8a079 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvDecoder.java @@ -1,217 +1,217 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.tlv; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ObjectModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.codec.InvalidValueException; -import org.eclipse.leshan.tlv.Tlv; -import org.eclipse.leshan.tlv.Tlv.TlvType; -import org.eclipse.leshan.tlv.TlvDecoder; -import org.eclipse.leshan.tlv.TlvException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LwM2mNodeTlvDecoder { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTlvDecoder.class); - - public static T decode(byte[] content, LwM2mPath path, LwM2mModel model, Class nodeClass) - throws InvalidValueException { - try { - Tlv[] tlvs = TlvDecoder.decode(ByteBuffer.wrap(content)); - return parseTlv(tlvs, path, model, nodeClass); - } catch (TlvException e) { - throw new InvalidValueException("Unable to decode tlv.", path, e); - } - } - - @SuppressWarnings("unchecked") - private static T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class nodeClass) - throws InvalidValueException { - LOG.trace("Parsing TLV content for path {}: {}", path, tlvs); - - // Object - if (nodeClass == LwM2mObject.class) { - final List instances = new ArrayList<>(); - - // is it an array of TLV resources? - if (tlvs.length > 0 && // - (tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) { - - ObjectModel oModel = model.getObjectModel(path.getObjectId()); - if (oModel == null) { - LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object", - path.getObjectId()); - instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); - } else if (!oModel.multiple) { - instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); - } else { - throw new InvalidValueException("Object instance TLV is mandatory for multiple instances object", - path); - } - - } else { - for (int i = 0; i < tlvs.length; i++) { - if (tlvs[i].getType() != TlvType.OBJECT_INSTANCE) - throw new InvalidValueException(String.format( - "Expected TLV of type OBJECT_INSTANCE but was %s", tlvs[i].getType().name()), path); - - instances.add(parseObjectInstanceTlv(tlvs[i].getChildren(), path.getObjectId(), - tlvs[i].getIdentifier(), model)); - } - } - return (T) new LwM2mObject(path.getObjectId(), instances); - } - - // Object instance - else if (nodeClass == LwM2mObjectInstance.class) { - - if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) { - if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) { - throw new InvalidValueException("Id conflict between path and instance TLV", path); - } - // object instance TLV - return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(), - model); - } else { - // array of TLV resources - // try to retrieve the instanceId from the path or the model - Integer instanceId = path.getObjectInstanceId(); - if (instanceId == null) { - // single instance object? - ObjectModel oModel = model.getObjectModel(path.getObjectId()); - if (oModel != null && !oModel.multiple) { - instanceId = 0; - } else { - instanceId = LwM2mObjectInstance.UNDEFINED; - } - } - return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model); - } - } - - // Resource - else if (nodeClass == LwM2mResource.class) { - - if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) { - if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) { - throw new InvalidValueException("Id conflict between path and resource TLV", path); - } - return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model); - } else { - Type expectedRscType = getResourceType(path, model); - return (T) LwM2mMultipleResource.newResource(path.getResourceId(), - parseTlvValues(tlvs, expectedRscType, path), expectedRscType); - } - } else { - throw new IllegalArgumentException("invalid node class: " + nodeClass); - } - - } - - private static LwM2mObjectInstance parseObjectInstanceTlv(Tlv[] rscTlvs, int objectId, int instanceId, - LwM2mModel model) throws InvalidValueException { - // read resources - List resources = new ArrayList<>(rscTlvs.length); - for (int i = 0; i < rscTlvs.length; i++) { - resources.add(parseResourceTlv(rscTlvs[i], objectId, instanceId, model)); - } - return new LwM2mObjectInstance(instanceId, resources); - } - - private static LwM2mResource parseResourceTlv(Tlv tlv, int objectId, int objectInstanceId, LwM2mModel model) - throws InvalidValueException { - LwM2mPath resourcePath = new LwM2mPath(objectId, objectInstanceId, tlv.getIdentifier()); - Type expectedType = getResourceType(resourcePath, model); - Integer resourceId = tlv.getIdentifier(); - switch (tlv.getType()) { - case MULTIPLE_RESOURCE: - return LwM2mMultipleResource.newResource(resourceId, - parseTlvValues(tlv.getChildren(), expectedType, resourcePath), expectedType); - case RESOURCE_VALUE: - return LwM2mSingleResource.newResource(resourceId, - parseTlvValue(tlv.getValue(), expectedType, resourcePath), expectedType); - default: - throw new InvalidValueException("Invalid TLV value", resourcePath); - } - } - - private static Map parseTlvValues(Tlv[] tlvs, Type expectedType, LwM2mPath path) - throws InvalidValueException { - Map values = new HashMap(); - for (int j = 0; j < tlvs.length; j++) { - Tlv tlvChild = tlvs[j]; - - if (tlvChild.getType() != TlvType.RESOURCE_INSTANCE) - throw new InvalidValueException(String.format("Expected TLV of type RESOURCE_INSTANCE but was %s", - tlvChild.getType().name()), path); - - values.put(tlvChild.getIdentifier(), parseTlvValue(tlvChild.getValue(), expectedType, path)); - } - return values; - } - - private static Object parseTlvValue(byte[] value, Type expectedType, LwM2mPath path) throws InvalidValueException { - try { - LOG.trace("TLV value for path {} and expected type {}: {}", path, expectedType, value); - switch (expectedType) { - case STRING: - return TlvDecoder.decodeString(value); - case INTEGER: - return TlvDecoder.decodeInteger(value).longValue(); - case FLOAT: - return TlvDecoder.decodeFloat(value).doubleValue(); - case BOOLEAN: - return TlvDecoder.decodeBoolean(value); - case TIME: - return TlvDecoder.decodeDate(value); - case OPAQUE: - return value; - default: - throw new InvalidValueException("Unsupported type " + expectedType, path); - } - } catch (TlvException e) { - throw new InvalidValueException("Invalid content for type " + expectedType, path, e); - } - } - - public static Type getResourceType(LwM2mPath rscPath, LwM2mModel model) throws InvalidValueException { - ResourceModel rscDesc = model.getResourceModel(rscPath.getObjectId(), rscPath.getResourceId()); - if (rscDesc == null || rscDesc.type == null) { - LOG.trace("unknown type for resource : {}", rscPath); - // no resource description... opaque - return Type.OPAQUE; - } else { - return rscDesc.type; - } - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.tlv; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.node.codec.InvalidValueException; +import org.eclipse.leshan.tlv.Tlv; +import org.eclipse.leshan.tlv.Tlv.TlvType; +import org.eclipse.leshan.tlv.TlvDecoder; +import org.eclipse.leshan.tlv.TlvException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LwM2mNodeTlvDecoder { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTlvDecoder.class); + + public static T decode(byte[] content, LwM2mPath path, LwM2mModel model, Class nodeClass) + throws InvalidValueException { + try { + Tlv[] tlvs = TlvDecoder.decode(ByteBuffer.wrap(content)); + return parseTlv(tlvs, path, model, nodeClass); + } catch (TlvException e) { + throw new InvalidValueException("Unable to decode tlv.", path, e); + } + } + + @SuppressWarnings("unchecked") + private static T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class nodeClass) + throws InvalidValueException { + LOG.trace("Parsing TLV content for path {}: {}", path, tlvs); + + // Object + if (nodeClass == LwM2mObject.class) { + final List instances = new ArrayList<>(); + + // is it an array of TLV resources? + if (tlvs.length > 0 && // + (tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) { + + ObjectModel oModel = model.getObjectModel(path.getObjectId()); + if (oModel == null) { + LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object", + path.getObjectId()); + instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); + } else if (!oModel.multiple) { + instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); + } else { + throw new InvalidValueException("Object instance TLV is mandatory for multiple instances object", + path); + } + + } else { + for (int i = 0; i < tlvs.length; i++) { + if (tlvs[i].getType() != TlvType.OBJECT_INSTANCE) + throw new InvalidValueException(String.format( + "Expected TLV of type OBJECT_INSTANCE but was %s", tlvs[i].getType().name()), path); + + instances.add(parseObjectInstanceTlv(tlvs[i].getChildren(), path.getObjectId(), + tlvs[i].getIdentifier(), model)); + } + } + return (T) new LwM2mObject(path.getObjectId(), instances); + } + + // Object instance + else if (nodeClass == LwM2mObjectInstance.class) { + + if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) { + if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) { + throw new InvalidValueException("Id conflict between path and instance TLV", path); + } + // object instance TLV + return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(), + model); + } else { + // array of TLV resources + // try to retrieve the instanceId from the path or the model + Integer instanceId = path.getObjectInstanceId(); + if (instanceId == null) { + // single instance object? + ObjectModel oModel = model.getObjectModel(path.getObjectId()); + if (oModel != null && !oModel.multiple) { + instanceId = 0; + } else { + instanceId = LwM2mObjectInstance.UNDEFINED; + } + } + return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model); + } + } + + // Resource + else if (nodeClass == LwM2mResource.class) { + + if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) { + if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) { + throw new InvalidValueException("Id conflict between path and resource TLV", path); + } + return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model); + } else { + Type expectedRscType = getResourceType(path, model); + return (T) LwM2mMultipleResource.newResource(path.getResourceId(), + parseTlvValues(tlvs, expectedRscType, path), expectedRscType); + } + } else { + throw new IllegalArgumentException("invalid node class: " + nodeClass); + } + + } + + private static LwM2mObjectInstance parseObjectInstanceTlv(Tlv[] rscTlvs, int objectId, int instanceId, + LwM2mModel model) throws InvalidValueException { + // read resources + List resources = new ArrayList<>(rscTlvs.length); + for (int i = 0; i < rscTlvs.length; i++) { + resources.add(parseResourceTlv(rscTlvs[i], objectId, instanceId, model)); + } + return new LwM2mObjectInstance(instanceId, resources); + } + + private static LwM2mResource parseResourceTlv(Tlv tlv, int objectId, int objectInstanceId, LwM2mModel model) + throws InvalidValueException { + LwM2mPath resourcePath = new LwM2mPath(objectId, objectInstanceId, tlv.getIdentifier()); + Type expectedType = getResourceType(resourcePath, model); + Integer resourceId = tlv.getIdentifier(); + switch (tlv.getType()) { + case MULTIPLE_RESOURCE: + return LwM2mMultipleResource.newResource(resourceId, + parseTlvValues(tlv.getChildren(), expectedType, resourcePath), expectedType); + case RESOURCE_VALUE: + return LwM2mSingleResource.newResource(resourceId, + parseTlvValue(tlv.getValue(), expectedType, resourcePath), expectedType); + default: + throw new InvalidValueException("Invalid TLV value", resourcePath); + } + } + + private static Map parseTlvValues(Tlv[] tlvs, Type expectedType, LwM2mPath path) + throws InvalidValueException { + Map values = new HashMap(); + for (int j = 0; j < tlvs.length; j++) { + Tlv tlvChild = tlvs[j]; + + if (tlvChild.getType() != TlvType.RESOURCE_INSTANCE) + throw new InvalidValueException(String.format("Expected TLV of type RESOURCE_INSTANCE but was %s", + tlvChild.getType().name()), path); + + values.put(tlvChild.getIdentifier(), parseTlvValue(tlvChild.getValue(), expectedType, path)); + } + return values; + } + + private static Object parseTlvValue(byte[] value, Type expectedType, LwM2mPath path) throws InvalidValueException { + try { + LOG.trace("TLV value for path {} and expected type {}: {}", path, expectedType, value); + switch (expectedType) { + case STRING: + return TlvDecoder.decodeString(value); + case INTEGER: + return TlvDecoder.decodeInteger(value).longValue(); + case FLOAT: + return TlvDecoder.decodeFloat(value).doubleValue(); + case BOOLEAN: + return TlvDecoder.decodeBoolean(value); + case TIME: + return TlvDecoder.decodeDate(value); + case OPAQUE: + return value; + default: + throw new InvalidValueException("Unsupported type " + expectedType, path); + } + } catch (TlvException e) { + throw new InvalidValueException("Invalid content for type " + expectedType, path, e); + } + } + + public static Type getResourceType(LwM2mPath rscPath, LwM2mModel model) throws InvalidValueException { + ResourceModel rscDesc = model.getResourceModel(rscPath.getObjectId(), rscPath.getResourceId()); + if (rscDesc == null || rscDesc.type == null) { + LOG.trace("unknown type for resource : {}", rscPath); + // no resource description... opaque + return Type.OPAQUE; + } else { + return rscDesc.type; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvEncoder.java index 5f3294e..daf041f 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/tlv/LwM2mNodeTlvEncoder.java @@ -1,189 +1,189 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.node.codec.tlv; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Collection; -import java.util.Date; -import java.util.Map.Entry; - -import org.eclipse.leshan.core.model.LwM2mModel; -import org.eclipse.leshan.core.model.ObjectModel; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mNodeVisitor; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; -import org.eclipse.leshan.tlv.Tlv; -import org.eclipse.leshan.tlv.Tlv.TlvType; -import org.eclipse.leshan.tlv.TlvEncoder; -import org.eclipse.leshan.util.Validate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * TLV encoder for {@link LwM2mNode}. - */ -public class LwM2mNodeTlvEncoder { - - private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTlvEncoder.class); - - public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { - Validate.notNull(node); - Validate.notNull(path); - Validate.notNull(model); - - InternalEncoder internalEncoder = new InternalEncoder(); - internalEncoder.path = path; - internalEncoder.model = model; - node.accept(internalEncoder); - return internalEncoder.out.toByteArray(); - } - - private static class InternalEncoder implements LwM2mNodeVisitor { - - // visitor inputs - private LwM2mPath path; - private LwM2mModel model; - - // visitor output - private ByteArrayOutputStream out = new ByteArrayOutputStream(); - - @Override - public void visit(LwM2mObject object) { - LOG.trace("Encoding object {} into TLV", object); - - Tlv[] tlvs = null; - - ObjectModel objectModel = model.getObjectModel(object.getId()); - if (objectModel != null && !objectModel.multiple) { - // single instance object, the instance is level is not needed - tlvs = encodeResources(object.getInstance(0).getResources().values()); - } else { - // encoded as an array of instances - tlvs = new Tlv[object.getInstances().size()]; - int i = 0; - for (Entry instance : object.getInstances().entrySet()) { - Tlv[] resources = encodeResources(instance.getValue().getResources().values()); - tlvs[i] = new Tlv(TlvType.OBJECT_INSTANCE, resources, null, instance.getKey()); - i++; - } - } - - try { - out.write(TlvEncoder.encode(tlvs).array()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void visit(LwM2mObjectInstance instance) { - LOG.trace("Encoding object instance {} into TLV", instance); - - Tlv[] tlvs; - if (path.isObjectInstance() || instance.getId() == LwM2mObjectInstance.UNDEFINED) { - // the instanceId is part of the request path or is undefined - // so the instance TLV layer is not needed. - // encoded as an array of resource TLVs - tlvs = encodeResources(instance.getResources().values()); - } else { - // encoded as an instance TLV - Tlv[] resources = encodeResources(instance.getResources().values()); - tlvs = new Tlv[] { new Tlv(TlvType.OBJECT_INSTANCE, resources, null, instance.getId()) }; - } - - try { - out.write(TlvEncoder.encode(tlvs).array()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void visit(LwM2mResource resource) { - LOG.trace("Encoding resource {} into TLV", resource); - - Tlv rTlv = encodeResource(resource); - - try { - out.write(TlvEncoder.encode(new Tlv[] { rTlv }).array()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private Tlv[] encodeResources(Collection resources) { - Tlv[] rTlvs = new Tlv[resources.size()]; - int i = 0; - for (LwM2mResource resource : resources) { - rTlvs[i] = encodeResource(resource); - i++; - } - return rTlvs; - } - - private Tlv encodeResource(LwM2mResource resource) { - ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); - Type expectedType = rSpec != null ? rSpec.type : resource.getType(); - - Tlv rTlv = null; - if (resource.isMultiInstances()) { - Tlv[] instances = new Tlv[resource.getValues().size()]; - int i = 0; - for (Entry entry : resource.getValues().entrySet()) { - Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(entry.getValue(), resource.getType(), - expectedType); - instances[i] = new Tlv(TlvType.RESOURCE_INSTANCE, null, this.encodeTlvValue(convertedValue, - expectedType), entry.getKey()); - i++; - } - rTlv = new Tlv(TlvType.MULTIPLE_RESOURCE, instances, null, resource.getId()); - } else { - Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), - expectedType); - rTlv = new Tlv(TlvType.RESOURCE_VALUE, null, this.encodeTlvValue(convertedValue, expectedType), - resource.getId()); - } - return rTlv; - } - - private byte[] encodeTlvValue(Object value, Type type) { - LOG.trace("Encoding value {} in TLV", value); - switch (type) { - case STRING: - return TlvEncoder.encodeString((String) value); - case INTEGER: - return TlvEncoder.encodeInteger((Number) value); - case FLOAT: - return TlvEncoder.encodeFloat((Number) value); - case BOOLEAN: - return TlvEncoder.encodeBoolean((Boolean) value); - case TIME: - return TlvEncoder.encodeDate((Date) value); - case OPAQUE: - return (byte[]) value; - default: - throw new IllegalArgumentException("Invalid value type: " + type); - } - } - } +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.node.codec.tlv; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Collection; +import java.util.Date; +import java.util.Map.Entry; + +import org.eclipse.leshan.core.model.LwM2mModel; +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mNodeVisitor; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; +import org.eclipse.leshan.tlv.Tlv; +import org.eclipse.leshan.tlv.Tlv.TlvType; +import org.eclipse.leshan.tlv.TlvEncoder; +import org.eclipse.leshan.util.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * TLV encoder for {@link LwM2mNode}. + */ +public class LwM2mNodeTlvEncoder { + + private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeTlvEncoder.class); + + public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { + Validate.notNull(node); + Validate.notNull(path); + Validate.notNull(model); + + InternalEncoder internalEncoder = new InternalEncoder(); + internalEncoder.path = path; + internalEncoder.model = model; + node.accept(internalEncoder); + return internalEncoder.out.toByteArray(); + } + + private static class InternalEncoder implements LwM2mNodeVisitor { + + // visitor inputs + private LwM2mPath path; + private LwM2mModel model; + + // visitor output + private ByteArrayOutputStream out = new ByteArrayOutputStream(); + + @Override + public void visit(LwM2mObject object) { + LOG.trace("Encoding object {} into TLV", object); + + Tlv[] tlvs = null; + + ObjectModel objectModel = model.getObjectModel(object.getId()); + if (objectModel != null && !objectModel.multiple) { + // single instance object, the instance is level is not needed + tlvs = encodeResources(object.getInstance(0).getResources().values()); + } else { + // encoded as an array of instances + tlvs = new Tlv[object.getInstances().size()]; + int i = 0; + for (Entry instance : object.getInstances().entrySet()) { + Tlv[] resources = encodeResources(instance.getValue().getResources().values()); + tlvs[i] = new Tlv(TlvType.OBJECT_INSTANCE, resources, null, instance.getKey()); + i++; + } + } + + try { + out.write(TlvEncoder.encode(tlvs).array()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void visit(LwM2mObjectInstance instance) { + LOG.trace("Encoding object instance {} into TLV", instance); + + Tlv[] tlvs; + if (path.isObjectInstance() || instance.getId() == LwM2mObjectInstance.UNDEFINED) { + // the instanceId is part of the request path or is undefined + // so the instance TLV layer is not needed. + // encoded as an array of resource TLVs + tlvs = encodeResources(instance.getResources().values()); + } else { + // encoded as an instance TLV + Tlv[] resources = encodeResources(instance.getResources().values()); + tlvs = new Tlv[] { new Tlv(TlvType.OBJECT_INSTANCE, resources, null, instance.getId()) }; + } + + try { + out.write(TlvEncoder.encode(tlvs).array()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void visit(LwM2mResource resource) { + LOG.trace("Encoding resource {} into TLV", resource); + + Tlv rTlv = encodeResource(resource); + + try { + out.write(TlvEncoder.encode(new Tlv[] { rTlv }).array()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private Tlv[] encodeResources(Collection resources) { + Tlv[] rTlvs = new Tlv[resources.size()]; + int i = 0; + for (LwM2mResource resource : resources) { + rTlvs[i] = encodeResource(resource); + i++; + } + return rTlvs; + } + + private Tlv encodeResource(LwM2mResource resource) { + ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); + Type expectedType = rSpec != null ? rSpec.type : resource.getType(); + + Tlv rTlv = null; + if (resource.isMultiInstances()) { + Tlv[] instances = new Tlv[resource.getValues().size()]; + int i = 0; + for (Entry entry : resource.getValues().entrySet()) { + Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(entry.getValue(), resource.getType(), + expectedType); + instances[i] = new Tlv(TlvType.RESOURCE_INSTANCE, null, this.encodeTlvValue(convertedValue, + expectedType), entry.getKey()); + i++; + } + rTlv = new Tlv(TlvType.MULTIPLE_RESOURCE, instances, null, resource.getId()); + } else { + Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), + expectedType); + rTlv = new Tlv(TlvType.RESOURCE_VALUE, null, this.encodeTlvValue(convertedValue, expectedType), + resource.getId()); + } + return rTlv; + } + + private byte[] encodeTlvValue(Object value, Type type) { + LOG.trace("Encoding value {} in TLV", value); + switch (type) { + case STRING: + return TlvEncoder.encodeString((String) value); + case INTEGER: + return TlvEncoder.encodeInteger((Number) value); + case FLOAT: + return TlvEncoder.encodeFloat((Number) value); + case BOOLEAN: + return TlvEncoder.encodeBoolean((Boolean) value); + case TIME: + return TlvEncoder.encodeDate((Date) value); + case OPAQUE: + return (byte[]) value; + default: + throw new IllegalArgumentException("Invalid value type: " + type); + } + } + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/observation/Observation.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/observation/Observation.java index 763b210..67bc599 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/observation/Observation.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/observation/Observation.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.observation; - -import org.eclipse.leshan.core.node.LwM2mPath; - -/** - * An observation of a resource provided by a LWM2M Client. - * - */ -public class Observation { - - private byte[] id; - private LwM2mPath path; - private String registrationId; - - public Observation(byte[] id, String registrationId, LwM2mPath path) { - super(); - this.id = id; - this.path = path; - this.registrationId = registrationId; - } - - /** - * Get the id of this observation. - * - */ - public byte[] getId() { - return id; - } - - /** - * Get the registration ID link to this observation. - * - * @return the registration ID - */ - public String getRegistrationId() { - return registrationId; - } - - /** - * Gets the observed resource path. - * - * @return the resource path - */ - public LwM2mPath getPath() { - return path; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.observation; + +import org.eclipse.leshan.core.node.LwM2mPath; + +/** + * An observation of a resource provided by a LWM2M Client. + * + */ +public class Observation { + + private byte[] id; + private LwM2mPath path; + private String registrationId; + + public Observation(byte[] id, String registrationId, LwM2mPath path) { + super(); + this.id = id; + this.path = path; + this.registrationId = registrationId; + } + + /** + * Get the id of this observation. + * + */ + public byte[] getId() { + return id; + } + + /** + * Get the registration ID link to this observation. + * + * @return the registration ID + */ + public String getRegistrationId() { + return registrationId; + } + + /** + * Gets the observed resource path. + * + * @return the resource path + */ + public LwM2mPath getPath() { + return path; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/AbstractDownlinkRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/AbstractDownlinkRequest.java index ea8e80e..ce60ffe 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/AbstractDownlinkRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/AbstractDownlinkRequest.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A base class for concrete LWM2M Downlink request types. - * - * Provides generic support for specifying the target client and the resource path. - */ -public abstract class AbstractDownlinkRequest implements DownlinkRequest { - - private final LwM2mPath path; - - protected AbstractDownlinkRequest(final LwM2mPath path) { - Validate.notNull(path); - if (path.isRoot()) { - throw new IllegalArgumentException("downlink request cannot target root path: " + path.toString()); - } - if (path.isResourceInstance()) { - throw new IllegalArgumentException( - "downlink request cannot target resource instance path: " + path.toString()); - } - this.path = path; - } - - /** - * {@inheritDoc} - */ - @Override - public LwM2mPath getPath() { - return this.path; - } - +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A base class for concrete LWM2M Downlink request types. + * + * Provides generic support for specifying the target client and the resource path. + */ +public abstract class AbstractDownlinkRequest implements DownlinkRequest { + + private final LwM2mPath path; + + protected AbstractDownlinkRequest(final LwM2mPath path) { + Validate.notNull(path); + if (path.isRoot()) { + throw new IllegalArgumentException("downlink request cannot target root path: " + path.toString()); + } + if (path.isResourceInstance()) { + throw new IllegalArgumentException( + "downlink request cannot target resource instance path: " + path.toString()); + } + this.path = path; + } + + /** + * {@inheritDoc} + */ + @Override + public LwM2mPath getPath() { + return this.path; + } + } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BindingMode.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BindingMode.java index 1a979c2..c4e4da4 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BindingMode.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BindingMode.java @@ -1,40 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -/** - * Transport binding and Queue Mode - */ -public enum BindingMode { - - /** UDP */ - U, - - /** UDP with Queue Mode */ - UQ, - - /** SMS */ - S, - - /** SMS with Queue Mode */ - SQ, - - /** UDP and SMS */ - US, - - /** UDP with Queue Mode and SMS */ - UQS -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +/** + * Transport binding and Queue Mode + */ +public enum BindingMode { + + /** UDP */ + U, + + /** UDP with Queue Mode */ + UQ, + + /** SMS */ + S, + + /** SMS with Queue Mode */ + SQ, + + /** UDP and SMS */ + US, + + /** UDP with Queue Mode and SMS */ + UQS +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapDeleteRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapDeleteRequest.java index 99bf88a..4514e59 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapDeleteRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapDeleteRequest.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.BootstrapDeleteResponse; - -/** - * A LWM2M request for deleting object instances during the bootstrap phase. - */ -public class BootstrapDeleteRequest implements DownlinkRequest { - - @Override - public LwM2mPath getPath() { - // not targeting a node. - return null; - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.BootstrapDeleteResponse; + +/** + * A LWM2M request for deleting object instances during the bootstrap phase. + */ +public class BootstrapDeleteRequest implements DownlinkRequest { + + @Override + public LwM2mPath getPath() { + // not targeting a node. + return null; + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapFinishRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapFinishRequest.java index e44ec99..6422927 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapFinishRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapFinishRequest.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.BootstrapFinishResponse; - -/** - * Request sent when bootstrap session is finished - */ -public class BootstrapFinishRequest implements DownlinkRequest { - - @Override - public LwM2mPath getPath() { - // not targeting a node. - return null; - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.BootstrapFinishResponse; + +/** + * Request sent when bootstrap session is finished + */ +public class BootstrapFinishRequest implements DownlinkRequest { + + @Override + public LwM2mPath getPath() { + // not targeting a node. + return null; + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapRequest.java index a5cb4f9..5e267ab 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapRequest.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.response.BootstrapResponse; -import org.eclipse.leshan.util.Validate; - -/** - * The request to send to start a bootstrap session - */ -public class BootstrapRequest implements UplinkRequest { - - private final String endpointName; - - public BootstrapRequest(String endpointName) { - Validate.notEmpty(endpointName); - this.endpointName = endpointName; - } - - public String getEndpointName() { - return endpointName; - } - - @Override - public void accept(UplinkRequestVisitor visitor) { - visitor.visit(this); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.response.BootstrapResponse; +import org.eclipse.leshan.util.Validate; + +/** + * The request to send to start a bootstrap session + */ +public class BootstrapRequest implements UplinkRequest { + + private final String endpointName; + + public BootstrapRequest(String endpointName) { + Validate.notEmpty(endpointName); + this.endpointName = endpointName; + } + + public String getEndpointName() { + return endpointName; + } + + @Override + public void accept(UplinkRequestVisitor visitor) { + visitor.visit(this); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapWriteRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapWriteRequest.java index d60f8e9..468991c 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapWriteRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/BootstrapWriteRequest.java @@ -1,105 +1,105 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.response.BootstrapWriteResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A LWM2M request for writing object instances during the bootstrap phase. - */ -public class BootstrapWriteRequest extends AbstractDownlinkRequest { - - private final LwM2mNode node; - private final ContentFormat contentFormat; - - public BootstrapWriteRequest(final LwM2mPath target, final LwM2mNode node, ContentFormat format) { - super(target); - Validate.notNull(node); - - // Validate node and path coherence - if (getPath().isResource()) { - if (!(node instanceof LwM2mResource)) { - throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", - target.toString(), node.getClass().getSimpleName())); - } - } else if (getPath().isObjectInstance()) { - if (!(node instanceof LwM2mObjectInstance)) { - throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", - target.toString(), node.getClass().getSimpleName())); - } - } else if (getPath().isObject()) { - if (!(node instanceof LwM2mObject)) { - throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", - target.toString(), node.getClass().getSimpleName())); - } - } - - // Validate content format - if (ContentFormat.TEXT == format || ContentFormat.OPAQUE == format) { - if (!getPath().isResource()) { - throw new IllegalArgumentException( - String.format("%s format must be used only for single resources", format.toString())); - } else { - LwM2mResource resource = (LwM2mResource) node; - if (resource.isMultiInstances()) { - throw new IllegalArgumentException( - String.format("%s format must be used only for single resources", format.toString())); - } else { - if (resource.getType() == Type.OPAQUE && format == ContentFormat.TEXT) { - throw new IllegalArgumentException( - "TEXT format must not be used for byte array single resources"); - } else if (resource.getType() != Type.OPAQUE && format == ContentFormat.OPAQUE) { - throw new IllegalArgumentException( - "OPAQUE format must be used only for byte array single resources"); - } - } - } - } - - this.node = node; - if (format == null) { - this.contentFormat = ContentFormat.TLV; // use TLV as default content type - } else { - this.contentFormat = format; - } - } - - public LwM2mNode getNode() { - return node; - } - - public ContentFormat getContentFormat() { - return contentFormat; - } - - @Override - public void accept(final DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - @Override - public String toString() { - return String.format("BootstrapWriteRequest [node=%s, contentFormat=%s]", node, contentFormat); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.response.BootstrapWriteResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A LWM2M request for writing object instances during the bootstrap phase. + */ +public class BootstrapWriteRequest extends AbstractDownlinkRequest { + + private final LwM2mNode node; + private final ContentFormat contentFormat; + + public BootstrapWriteRequest(final LwM2mPath target, final LwM2mNode node, ContentFormat format) { + super(target); + Validate.notNull(node); + + // Validate node and path coherence + if (getPath().isResource()) { + if (!(node instanceof LwM2mResource)) { + throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", + target.toString(), node.getClass().getSimpleName())); + } + } else if (getPath().isObjectInstance()) { + if (!(node instanceof LwM2mObjectInstance)) { + throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", + target.toString(), node.getClass().getSimpleName())); + } + } else if (getPath().isObject()) { + if (!(node instanceof LwM2mObject)) { + throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", + target.toString(), node.getClass().getSimpleName())); + } + } + + // Validate content format + if (ContentFormat.TEXT == format || ContentFormat.OPAQUE == format) { + if (!getPath().isResource()) { + throw new IllegalArgumentException( + String.format("%s format must be used only for single resources", format.toString())); + } else { + LwM2mResource resource = (LwM2mResource) node; + if (resource.isMultiInstances()) { + throw new IllegalArgumentException( + String.format("%s format must be used only for single resources", format.toString())); + } else { + if (resource.getType() == Type.OPAQUE && format == ContentFormat.TEXT) { + throw new IllegalArgumentException( + "TEXT format must not be used for byte array single resources"); + } else if (resource.getType() != Type.OPAQUE && format == ContentFormat.OPAQUE) { + throw new IllegalArgumentException( + "OPAQUE format must be used only for byte array single resources"); + } + } + } + } + + this.node = node; + if (format == null) { + this.contentFormat = ContentFormat.TLV; // use TLV as default content type + } else { + this.contentFormat = format; + } + } + + public LwM2mNode getNode() { + return node; + } + + public ContentFormat getContentFormat() { + return contentFormat; + } + + @Override + public void accept(final DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + @Override + public String toString() { + return String.format("BootstrapWriteRequest [node=%s, contentFormat=%s]", node, contentFormat); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ContentFormat.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ContentFormat.java index 0f618c6..eb42f97 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ContentFormat.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ContentFormat.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -/** - * Data format defined by the LWM2M specification - */ -public class ContentFormat { - public static final int TLV_CODE = 1542; - public static final int JSON_CODE = 1543; - public static final int TEXT_CODE = 0; - public static final int OPAQUE_CODE = 42; - public static final int LINK_CODE = 40; - - public static final ContentFormat TLV = new ContentFormat("TLV", "application/vnd.oma.lwm2m+tlv", TLV_CODE); - public static final ContentFormat JSON = new ContentFormat("JSON", "application/vnd.oma.lwm2m+json", JSON_CODE); - public static final ContentFormat TEXT = new ContentFormat("TEXT", "text/plain", TEXT_CODE); - public static final ContentFormat OPAQUE = new ContentFormat("OPAQUE", "application/octet-stream", OPAQUE_CODE); - public static final ContentFormat LINK = new ContentFormat("LINK", "application/link-format", LINK_CODE); - - private static final ContentFormat knownContentFormat[] = new ContentFormat[] { TLV, JSON, TEXT, OPAQUE, LINK }; - - private final String name; - private final String mediaType; - private final int code; - - public ContentFormat(String name, String mediaType, int code) { - this.name = name; - this.mediaType = mediaType; - this.code = code; - } - - public ContentFormat(int code) { - this.name = "UNKNOWN"; - this.mediaType = "unknown/unknown"; - this.code = code; - } - - public String getName() { - return this.name; - } - - public String getMediaType() { - return this.mediaType; - } - - public int getCode() { - return this.code; - } - - /** - * Find the {@link ContentFormat} for the given media type (null if not found) - */ - public static ContentFormat fromMediaType(String mediaType) { - for (ContentFormat t : knownContentFormat) { - if (t.getMediaType().equals(mediaType)) { - return t; - } - } - return null; - } - - /** - * Finds the {@link ContentFormat} for a given media type code. - * - * @return the media type or null if the given code is unknown - */ - public static ContentFormat fromCode(int code) { - for (ContentFormat t : knownContentFormat) { - if (t.getCode() == code) { - return t; - } - } - return new ContentFormat(code); - } - - /** - * Finds the {@link ContentFormat} by name. - * - * @return the media type or null if the given code is unknown - */ - public static ContentFormat fromName(String name) { - for (ContentFormat t : knownContentFormat) { - if (t.getName().equals(name)) { - return t; - } - } - return null; - } - - @Override - public String toString() { - return String.format("ContentFormat [name=%s, code=%s]", name, code); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + code; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ContentFormat other = (ContentFormat) obj; - if (code != other.code) - return false; - return true; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +/** + * Data format defined by the LWM2M specification + */ +public class ContentFormat { + public static final int TLV_CODE = 1542; + public static final int JSON_CODE = 1543; + public static final int TEXT_CODE = 0; + public static final int OPAQUE_CODE = 42; + public static final int LINK_CODE = 40; + + public static final ContentFormat TLV = new ContentFormat("TLV", "application/vnd.oma.lwm2m+tlv", TLV_CODE); + public static final ContentFormat JSON = new ContentFormat("JSON", "application/vnd.oma.lwm2m+json", JSON_CODE); + public static final ContentFormat TEXT = new ContentFormat("TEXT", "text/plain", TEXT_CODE); + public static final ContentFormat OPAQUE = new ContentFormat("OPAQUE", "application/octet-stream", OPAQUE_CODE); + public static final ContentFormat LINK = new ContentFormat("LINK", "application/link-format", LINK_CODE); + + private static final ContentFormat knownContentFormat[] = new ContentFormat[] { TLV, JSON, TEXT, OPAQUE, LINK }; + + private final String name; + private final String mediaType; + private final int code; + + public ContentFormat(String name, String mediaType, int code) { + this.name = name; + this.mediaType = mediaType; + this.code = code; + } + + public ContentFormat(int code) { + this.name = "UNKNOWN"; + this.mediaType = "unknown/unknown"; + this.code = code; + } + + public String getName() { + return this.name; + } + + public String getMediaType() { + return this.mediaType; + } + + public int getCode() { + return this.code; + } + + /** + * Find the {@link ContentFormat} for the given media type (null if not found) + */ + public static ContentFormat fromMediaType(String mediaType) { + for (ContentFormat t : knownContentFormat) { + if (t.getMediaType().equals(mediaType)) { + return t; + } + } + return null; + } + + /** + * Finds the {@link ContentFormat} for a given media type code. + * + * @return the media type or null if the given code is unknown + */ + public static ContentFormat fromCode(int code) { + for (ContentFormat t : knownContentFormat) { + if (t.getCode() == code) { + return t; + } + } + return new ContentFormat(code); + } + + /** + * Finds the {@link ContentFormat} by name. + * + * @return the media type or null if the given code is unknown + */ + public static ContentFormat fromName(String name) { + for (ContentFormat t : knownContentFormat) { + if (t.getName().equals(name)) { + return t; + } + } + return null; + } + + @Override + public String toString() { + return String.format("ContentFormat [name=%s, code=%s]", name, code); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + code; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ContentFormat other = (ContentFormat) obj; + if (code != other.code) + return false; + return true; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/CreateRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/CreateRequest.java index c520393..836f947 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/CreateRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/CreateRequest.java @@ -1,244 +1,244 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.response.CreateResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for creating Object Instance(s) within the LWM2M Client. - */ -public class CreateRequest extends AbstractDownlinkRequest { - - private final Integer instanceId; - private final List resources; - private final ContentFormat contentFormat; - - // ***************** constructors without object instance id ******************* / - - /** - * Creates a request for creating an instance of a particular object without specifying the id of this new instance. - * The id will be chosen by the client and accessible in the CreateResponse. - * - * @param contentFormat the payload format - * @param objectId the object id - * @param resources the resource values for the new instance - */ - public CreateRequest(ContentFormat contentFormat, int objectId, LwM2mResource... resources) { - this(contentFormat, new LwM2mPath(objectId), null, resources); - } - - /** - * Creates a request for creating an instance of a particular object without specifying the id of this new instance - * and using the TLV content format. The id will be chosen by the client and accessible in the CreateResponse. - * - * @param objectId the object id - * @param resources the resource values for the new instance - */ - public CreateRequest(int objectId, LwM2mResource... resources) { - this(null, new LwM2mPath(objectId), null, resources); - } - - /** - * Creates a request for creating an instance of a particular object without specifying the id of this new instance. - * The id will be chosen by the client and accessible in the CreateResponse. - * - * @param contentFormat the payload format - * @param objectId the object id - * @param resources the resource values for the new instance - */ - public CreateRequest(ContentFormat contentFormat, int objectId, Collection resources) { - this(contentFormat, objectId, resources.toArray(new LwM2mResource[resources.size()])); - } - - /** - * Creates a request for creating an instance of a particular object without specifying the id of this new instance - * and using the TLV content format. The id will be chosen by the client and accessible in the CreateResponse. - * - * @param objectId the object id - * @param resources the resource values for the new instance - */ - public CreateRequest(int objectId, Collection resources) { - this(objectId, resources.toArray(new LwM2mResource[resources.size()])); - } - - // ***************** constructor with object instance ******************* / - - /** - * Creates a request for creating an instance of a particular object. - * - * @param contentFormat the payload format - * @param objectId the object id - * @param instance the object instance - */ - public CreateRequest(ContentFormat contentFormat, int objectId, LwM2mObjectInstance instance) { - this(contentFormat, new LwM2mPath(objectId), instance.getId(), - instance.getResources().values().toArray(new LwM2mResource[0])); - } - - /** - * Creates a request for creating an instance of a particular object using the TLV content format. - * - * @param objectId the object id - * @param instance the object instance - */ - public CreateRequest(int objectId, LwM2mObjectInstance instance) { - this(null, objectId, instance); - } - - // ***************** string path constructor ******************* / - /** - * Creates a request for creating an instance of a particular object using the default TLV content format.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param path the target path (object or object instance) - * @param resources the resource values for the new instance - */ - public CreateRequest(String path, Collection resources) { - this(path, resources.toArray(new LwM2mResource[resources.size()])); - } - - /** - * Creates a request for creating an instance of a particular object.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param contentFormat the payload format (TLV or JSON) - * @param path the target path (object or object instance) - * @param resources the resource values for the new instance - */ - public CreateRequest(ContentFormat contentFormat, String path, Collection resources) { - this(contentFormat, path, resources.toArray(new LwM2mResource[resources.size()])); - } - - /** - * Creates a request for creating an instance of a particular object using the default TLV content format.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param path the target path (object or object instance) - * @param resources the resource values for the new instance - */ - public CreateRequest(String path, LwM2mResource... resources) { - this(null, new LwM2mPath(path), null, resources); - } - - /** - * Creates a request for creating an instance of a particular object.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param contentFormat the payload format (TLV or JSON) - * @param path the target path (object or object instance) - * @param resources the resource values for the new instance - */ - public CreateRequest(ContentFormat contentFormat, String path, LwM2mResource... resources) { - this(contentFormat, new LwM2mPath(path), null, resources); - } - - /** - * Creates a request for creating an instance of a particular object.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param path the target path (object or object instance) - * @param instance the object instance - */ - public CreateRequest(String path, LwM2mObjectInstance instance) { - this(null, new LwM2mPath(path), instance.getId(), - instance.getResources().values().toArray((new LwM2mResource[instance.getResources().size()]))); - } - - /** - * Creates a request for creating an instance of a particular object.
- * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. - * To choose instance id at server side, the path must be an object instance path. - * - * @param contentFormat the payload format (TLV or JSON) - * @param path the target path (object or object instance) - * @param instance the object instance - */ - public CreateRequest(ContentFormat contentFormat, String path, LwM2mObjectInstance instance) { - this(contentFormat, new LwM2mPath(path), instance.getId(), - instance.getResources().values().toArray((new LwM2mResource[instance.getResources().size()]))); - } - - // ***************** generic constructor ******************* / - private CreateRequest(ContentFormat format, LwM2mPath target, Integer instanceId, LwM2mResource[] resources) { - super(target); - - // accept only object and object instance path - if (!target.isObject() && !target.isObjectInstance()) { - throw new IllegalArgumentException("Create request must target an object or object instance"); - } - - // validate instance id - if (instanceId != null && instanceId == LwM2mObjectInstance.UNDEFINED) { - instanceId = null; - } - if (target.isObjectInstance()) { - if (instanceId == null) { - instanceId = target.getObjectInstanceId(); - } else { - if (instanceId != target.getObjectInstanceId()) { - throw new IllegalArgumentException("Conflict between path instance id and node instance id"); - } - } - } - Validate.isTrue(instanceId == null || instanceId >= 0, "Invalid instance id: " + instanceId); - - // store attributes - this.instanceId = instanceId; - this.resources = Collections.unmodifiableList(Arrays.asList(resources)); - this.contentFormat = format != null ? format : ContentFormat.TLV; // default to TLV - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - public List getResources() { - return resources; - } - - /** - * @return the id of the new instance. null if not assigned by the server. - */ - public Integer getInstanceId() { - return instanceId; - } - - public ContentFormat getContentFormat() { - return contentFormat; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("CreateRequest [").append(getPath()).append("]"); - return builder.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.response.CreateResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for creating Object Instance(s) within the LWM2M Client. + */ +public class CreateRequest extends AbstractDownlinkRequest { + + private final Integer instanceId; + private final List resources; + private final ContentFormat contentFormat; + + // ***************** constructors without object instance id ******************* / + + /** + * Creates a request for creating an instance of a particular object without specifying the id of this new instance. + * The id will be chosen by the client and accessible in the CreateResponse. + * + * @param contentFormat the payload format + * @param objectId the object id + * @param resources the resource values for the new instance + */ + public CreateRequest(ContentFormat contentFormat, int objectId, LwM2mResource... resources) { + this(contentFormat, new LwM2mPath(objectId), null, resources); + } + + /** + * Creates a request for creating an instance of a particular object without specifying the id of this new instance + * and using the TLV content format. The id will be chosen by the client and accessible in the CreateResponse. + * + * @param objectId the object id + * @param resources the resource values for the new instance + */ + public CreateRequest(int objectId, LwM2mResource... resources) { + this(null, new LwM2mPath(objectId), null, resources); + } + + /** + * Creates a request for creating an instance of a particular object without specifying the id of this new instance. + * The id will be chosen by the client and accessible in the CreateResponse. + * + * @param contentFormat the payload format + * @param objectId the object id + * @param resources the resource values for the new instance + */ + public CreateRequest(ContentFormat contentFormat, int objectId, Collection resources) { + this(contentFormat, objectId, resources.toArray(new LwM2mResource[resources.size()])); + } + + /** + * Creates a request for creating an instance of a particular object without specifying the id of this new instance + * and using the TLV content format. The id will be chosen by the client and accessible in the CreateResponse. + * + * @param objectId the object id + * @param resources the resource values for the new instance + */ + public CreateRequest(int objectId, Collection resources) { + this(objectId, resources.toArray(new LwM2mResource[resources.size()])); + } + + // ***************** constructor with object instance ******************* / + + /** + * Creates a request for creating an instance of a particular object. + * + * @param contentFormat the payload format + * @param objectId the object id + * @param instance the object instance + */ + public CreateRequest(ContentFormat contentFormat, int objectId, LwM2mObjectInstance instance) { + this(contentFormat, new LwM2mPath(objectId), instance.getId(), + instance.getResources().values().toArray(new LwM2mResource[0])); + } + + /** + * Creates a request for creating an instance of a particular object using the TLV content format. + * + * @param objectId the object id + * @param instance the object instance + */ + public CreateRequest(int objectId, LwM2mObjectInstance instance) { + this(null, objectId, instance); + } + + // ***************** string path constructor ******************* / + /** + * Creates a request for creating an instance of a particular object using the default TLV content format.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param path the target path (object or object instance) + * @param resources the resource values for the new instance + */ + public CreateRequest(String path, Collection resources) { + this(path, resources.toArray(new LwM2mResource[resources.size()])); + } + + /** + * Creates a request for creating an instance of a particular object.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param contentFormat the payload format (TLV or JSON) + * @param path the target path (object or object instance) + * @param resources the resource values for the new instance + */ + public CreateRequest(ContentFormat contentFormat, String path, Collection resources) { + this(contentFormat, path, resources.toArray(new LwM2mResource[resources.size()])); + } + + /** + * Creates a request for creating an instance of a particular object using the default TLV content format.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param path the target path (object or object instance) + * @param resources the resource values for the new instance + */ + public CreateRequest(String path, LwM2mResource... resources) { + this(null, new LwM2mPath(path), null, resources); + } + + /** + * Creates a request for creating an instance of a particular object.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param contentFormat the payload format (TLV or JSON) + * @param path the target path (object or object instance) + * @param resources the resource values for the new instance + */ + public CreateRequest(ContentFormat contentFormat, String path, LwM2mResource... resources) { + this(contentFormat, new LwM2mPath(path), null, resources); + } + + /** + * Creates a request for creating an instance of a particular object.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param path the target path (object or object instance) + * @param instance the object instance + */ + public CreateRequest(String path, LwM2mObjectInstance instance) { + this(null, new LwM2mPath(path), instance.getId(), + instance.getResources().values().toArray((new LwM2mResource[instance.getResources().size()]))); + } + + /** + * Creates a request for creating an instance of a particular object.
+ * If the path is an object path, the instance id will be chosen by the client and accessible in the CreateResponse. + * To choose instance id at server side, the path must be an object instance path. + * + * @param contentFormat the payload format (TLV or JSON) + * @param path the target path (object or object instance) + * @param instance the object instance + */ + public CreateRequest(ContentFormat contentFormat, String path, LwM2mObjectInstance instance) { + this(contentFormat, new LwM2mPath(path), instance.getId(), + instance.getResources().values().toArray((new LwM2mResource[instance.getResources().size()]))); + } + + // ***************** generic constructor ******************* / + private CreateRequest(ContentFormat format, LwM2mPath target, Integer instanceId, LwM2mResource[] resources) { + super(target); + + // accept only object and object instance path + if (!target.isObject() && !target.isObjectInstance()) { + throw new IllegalArgumentException("Create request must target an object or object instance"); + } + + // validate instance id + if (instanceId != null && instanceId == LwM2mObjectInstance.UNDEFINED) { + instanceId = null; + } + if (target.isObjectInstance()) { + if (instanceId == null) { + instanceId = target.getObjectInstanceId(); + } else { + if (instanceId != target.getObjectInstanceId()) { + throw new IllegalArgumentException("Conflict between path instance id and node instance id"); + } + } + } + Validate.isTrue(instanceId == null || instanceId >= 0, "Invalid instance id: " + instanceId); + + // store attributes + this.instanceId = instanceId; + this.resources = Collections.unmodifiableList(Arrays.asList(resources)); + this.contentFormat = format != null ? format : ContentFormat.TLV; // default to TLV + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + public List getResources() { + return resources; + } + + /** + * @return the id of the new instance. null if not assigned by the server. + */ + public Integer getInstanceId() { + return instanceId; + } + + public ContentFormat getContentFormat() { + return contentFormat; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("CreateRequest [").append(getPath()).append("]"); + return builder.toString(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeleteRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeleteRequest.java index 0d004f8..d3346ba 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeleteRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeleteRequest.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.DeleteResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for deleting an Object Instance within the LWM2M Client. - */ -public class DeleteRequest extends AbstractDownlinkRequest { - - /** - * Creates a request for deleting a particular object instance implemented by a client. - * - * @param objectId the object type - * @param objectInstanceId the object instance - */ - public DeleteRequest(final int objectId, final int objectInstanceId) { - this(new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for deleting a particular object instance implemented by a client. - * - * @param path the path of the instance to delete - * @throw IllegalArgumentException if the path is not valid - */ - public DeleteRequest(final String path) { - super(new LwM2mPath(path)); - } - - private DeleteRequest(final LwM2mPath target) { - super(target); - Validate.isTrue(target.isObjectInstance(), "Only object instance can be delete."); - } - - @Override - public void accept(final DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - @Override - public final String toString() { - return String.format("DeleteRequest [%s]", getPath()); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.DeleteResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for deleting an Object Instance within the LWM2M Client. + */ +public class DeleteRequest extends AbstractDownlinkRequest { + + /** + * Creates a request for deleting a particular object instance implemented by a client. + * + * @param objectId the object type + * @param objectInstanceId the object instance + */ + public DeleteRequest(final int objectId, final int objectInstanceId) { + this(new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for deleting a particular object instance implemented by a client. + * + * @param path the path of the instance to delete + * @throw IllegalArgumentException if the path is not valid + */ + public DeleteRequest(final String path) { + super(new LwM2mPath(path)); + } + + private DeleteRequest(final LwM2mPath target) { + super(target); + Validate.isTrue(target.isObjectInstance(), "Only object instance can be delete."); + } + + @Override + public void accept(final DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + @Override + public final String toString() { + return String.format("DeleteRequest [%s]", getPath()); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeregisterRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeregisterRequest.java index 79a59a5..861766e 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeregisterRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DeregisterRequest.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.response.DeregisterResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for removing the registration information from the LWM2M Server. - */ -public class DeregisterRequest implements UplinkRequest { - - private String registrationID = null; - - /** - * Creates a request for removing the registration information from the LWM2M Server. - * - * @param registrationID the registration ID to remove - */ - public DeregisterRequest(String registrationID) { - Validate.notNull(registrationID); - this.registrationID = registrationID; - } - - public String getRegistrationID() { - return registrationID; - } - - @Override - public void accept(UplinkRequestVisitor visitor) { - visitor.visit(this); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.response.DeregisterResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for removing the registration information from the LWM2M Server. + */ +public class DeregisterRequest implements UplinkRequest { + + private String registrationID = null; + + /** + * Creates a request for removing the registration information from the LWM2M Server. + * + * @param registrationID the registration ID to remove + */ + public DeregisterRequest(String registrationID) { + Validate.notNull(registrationID); + this.registrationID = registrationID; + } + + public String getRegistrationID() { + return registrationID; + } + + @Override + public void accept(UplinkRequestVisitor visitor) { + visitor.visit(this); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DiscoverRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DiscoverRequest.java index dd17e61..31eb411 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DiscoverRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DiscoverRequest.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.DiscoverResponse; - -/** - * A Lightweight M2M request for discovering LWM2M Attributes attached to an Object, Object Instances, and Resources. - */ -public class DiscoverRequest extends AbstractDownlinkRequest { - - /** - * Creates a request for discovering the resources implemented by a client for a particular object type. - * - * @param objectId the object type - */ - public DiscoverRequest(int objectId) { - this(new LwM2mPath(objectId)); - } - - /** - * Creates a request for discovering the resources implemented by a client for a particular object instance. - * - * @param objectId the object type - * @param objectInstanceId the object instance - */ - public DiscoverRequest(int objectId, int objectInstanceId) { - this(new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for discovering the attributes of a particular resource implemented by a client. - * - * @param objectId the object type - * @param objectInstanceId the object instance - * @param resourceId the resource - */ - public DiscoverRequest(int objectId, int objectInstanceId, int resourceId) { - this(new LwM2mPath(objectId, objectInstanceId, resourceId)); - } - - /** - * Create a request for discovering the attributes of a particular object/instance/resource targeted by a specific - * path. - * - * @param path the path of the LWM2M node to discover - * @throw IllegalArgumentException if the path is not valid - */ - public DiscoverRequest(String path) { - super(new LwM2mPath(path)); - } - - private DiscoverRequest(LwM2mPath target) { - super(target); - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - @Override - public final String toString() { - return String.format("DiscoverRequest [%s]", getPath()); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.DiscoverResponse; + +/** + * A Lightweight M2M request for discovering LWM2M Attributes attached to an Object, Object Instances, and Resources. + */ +public class DiscoverRequest extends AbstractDownlinkRequest { + + /** + * Creates a request for discovering the resources implemented by a client for a particular object type. + * + * @param objectId the object type + */ + public DiscoverRequest(int objectId) { + this(new LwM2mPath(objectId)); + } + + /** + * Creates a request for discovering the resources implemented by a client for a particular object instance. + * + * @param objectId the object type + * @param objectInstanceId the object instance + */ + public DiscoverRequest(int objectId, int objectInstanceId) { + this(new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for discovering the attributes of a particular resource implemented by a client. + * + * @param objectId the object type + * @param objectInstanceId the object instance + * @param resourceId the resource + */ + public DiscoverRequest(int objectId, int objectInstanceId, int resourceId) { + this(new LwM2mPath(objectId, objectInstanceId, resourceId)); + } + + /** + * Create a request for discovering the attributes of a particular object/instance/resource targeted by a specific + * path. + * + * @param path the path of the LWM2M node to discover + * @throw IllegalArgumentException if the path is not valid + */ + public DiscoverRequest(String path) { + super(new LwM2mPath(path)); + } + + private DiscoverRequest(LwM2mPath target) { + super(target); + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + @Override + public final String toString() { + return String.format("DiscoverRequest [%s]", getPath()); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequest.java index 71fe93c..bcac8a2 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequest.java @@ -1,39 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * A Downlink Lightweight M2M request.
- * This is a request sent from server to client to interact with the client resource tree. - */ -public interface DownlinkRequest extends LwM2mRequest { - - /** - * Gets the requested resource path. - * - * @return the request path - */ - LwM2mPath getPath(); - - /** - * Accept a visitor for this request. - */ - void accept(DownlinkRequestVisitor visitor); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * A Downlink Lightweight M2M request.
+ * This is a request sent from server to client to interact with the client resource tree. + */ +public interface DownlinkRequest extends LwM2mRequest { + + /** + * Gets the requested resource path. + * + * @return the request path + */ + LwM2mPath getPath(); + + /** + * Accept a visitor for this request. + */ + void accept(DownlinkRequestVisitor visitor); + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequestVisitor.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequestVisitor.java index 9bc9301..d8f74f5 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequestVisitor.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/DownlinkRequestVisitor.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -/** - * A visitor to visit a Downlink Lightweight M2M request. - */ -public interface DownlinkRequestVisitor { - void visit(ReadRequest request); - - void visit(DiscoverRequest request); - - void visit(WriteRequest request); - - void visit(WriteAttributesRequest request); - - void visit(ExecuteRequest request); - - void visit(CreateRequest request); - - void visit(DeleteRequest request); - - void visit(ObserveRequest request); - - void visit(BootstrapWriteRequest request); - - void visit(BootstrapDeleteRequest request); - - void visit(BootstrapFinishRequest request); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +/** + * A visitor to visit a Downlink Lightweight M2M request. + */ +public interface DownlinkRequestVisitor { + void visit(ReadRequest request); + + void visit(DiscoverRequest request); + + void visit(WriteRequest request); + + void visit(WriteAttributesRequest request); + + void visit(ExecuteRequest request); + + void visit(CreateRequest request); + + void visit(DeleteRequest request); + + void visit(ObserveRequest request); + + void visit(BootstrapWriteRequest request); + + void visit(BootstrapDeleteRequest request); + + void visit(BootstrapFinishRequest request); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ExecuteRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ExecuteRequest.java index 92afd22..c6ea515 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ExecuteRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ExecuteRequest.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.ExecuteResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for initiate some action, it can only be performed on individual Resources. - */ -public class ExecuteRequest extends AbstractDownlinkRequest { - - private final String parameters; - - /** - * Creates a new execute request for a resource that does not require any parameters. - * - * @param path the path of the resource to execute - * @throw IllegalArgumentException if the path is not valid - */ - public ExecuteRequest(final String path) { - this(new LwM2mPath(path), null); - } - - /** - * Creates a new execute request for a resource accepting parameters encoded as plain text. - * - * @param path the path of the resource to execute - * @param parameters the parameters - * @throw IllegalArgumentException if the path is not valid - */ - public ExecuteRequest(final String path, final String parameters) { - this(new LwM2mPath(path), parameters); - } - - /** - * Creates a new execute request for a resource that does not require any parameters. - * - * @param objectId the resource's object ID - * @param objectInstanceId the resource's object instance ID - * @param resourceId the resource's ID - */ - public ExecuteRequest(final int objectId, final int objectInstanceId, final int resourceId) { - this(new LwM2mPath(objectId, objectInstanceId, resourceId), null); - } - - /** - * Creates a new execute request for a resource accepting parameters encoded as plain text. - * - * @param objectId the resource's object ID - * @param objectInstanceId the resource's object instance ID - * @param resourceId the resource's ID - * @param parameters the parameters - */ - public ExecuteRequest(final int objectId, final int objectInstanceId, final int resourceId, - final String parameters) { - this(new LwM2mPath(objectId, objectInstanceId, resourceId), parameters); - } - - private ExecuteRequest(final LwM2mPath path, final String parameters) { - super(path); - Validate.isTrue(path.isResource(), "Only resource can be executed."); - this.parameters = parameters; - } - - @Override - public String toString() { - return String.format("ExecuteRequest [%s]", getPath()); - } - - @Override - public void accept(final DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - public String getParameters() { - return parameters; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for initiate some action, it can only be performed on individual Resources. + */ +public class ExecuteRequest extends AbstractDownlinkRequest { + + private final String parameters; + + /** + * Creates a new execute request for a resource that does not require any parameters. + * + * @param path the path of the resource to execute + * @throw IllegalArgumentException if the path is not valid + */ + public ExecuteRequest(final String path) { + this(new LwM2mPath(path), null); + } + + /** + * Creates a new execute request for a resource accepting parameters encoded as plain text. + * + * @param path the path of the resource to execute + * @param parameters the parameters + * @throw IllegalArgumentException if the path is not valid + */ + public ExecuteRequest(final String path, final String parameters) { + this(new LwM2mPath(path), parameters); + } + + /** + * Creates a new execute request for a resource that does not require any parameters. + * + * @param objectId the resource's object ID + * @param objectInstanceId the resource's object instance ID + * @param resourceId the resource's ID + */ + public ExecuteRequest(final int objectId, final int objectInstanceId, final int resourceId) { + this(new LwM2mPath(objectId, objectInstanceId, resourceId), null); + } + + /** + * Creates a new execute request for a resource accepting parameters encoded as plain text. + * + * @param objectId the resource's object ID + * @param objectInstanceId the resource's object instance ID + * @param resourceId the resource's ID + * @param parameters the parameters + */ + public ExecuteRequest(final int objectId, final int objectInstanceId, final int resourceId, + final String parameters) { + this(new LwM2mPath(objectId, objectInstanceId, resourceId), parameters); + } + + private ExecuteRequest(final LwM2mPath path, final String parameters) { + super(path); + Validate.isTrue(path.isResource(), "Only resource can be executed."); + this.parameters = parameters; + } + + @Override + public String toString() { + return String.format("ExecuteRequest [%s]", getPath()); + } + + @Override + public void accept(final DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + public String getParameters() { + return parameters; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/Identity.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/Identity.java index 18a7980..aa2ab87 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/Identity.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/Identity.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Achim Kraus (Bosch Software Innovations GmbH) - add protected constructor for sub-classing - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import java.net.InetSocketAddress; -import java.security.PublicKey; - -import org.eclipse.leshan.util.Validate; - -/** - * A request sender identity. - */ -public class Identity { - - private final InetSocketAddress peerAddress; - private final String pskIdentity; - private final PublicKey rawPublicKey; - private final String x509CommonName; - - private Identity(InetSocketAddress peerAddress, String pskIdentity, PublicKey rawPublicKey, String x509CommonName) { - Validate.notNull(peerAddress); - this.peerAddress = peerAddress; - this.pskIdentity = pskIdentity; - this.rawPublicKey = rawPublicKey; - this.x509CommonName = x509CommonName; - } - - protected Identity(Identity identity) { - this.peerAddress = identity.peerAddress; - this.pskIdentity = identity.pskIdentity; - this.rawPublicKey = identity.rawPublicKey; - this.x509CommonName = identity.x509CommonName; - } - - public InetSocketAddress getPeerAddress() { - return peerAddress; - } - - public String getPskIdentity() { - return pskIdentity; - } - - public PublicKey getRawPublicKey() { - return rawPublicKey; - } - - public String getX509CommonName() { - return x509CommonName; - } - - public boolean isPSK() { - return pskIdentity != null && !pskIdentity.isEmpty(); - } - - public boolean isRPK() { - return rawPublicKey != null; - } - - public boolean isX509() { - return x509CommonName != null && !x509CommonName.isEmpty(); - } - - public boolean isSecure() { - return isPSK() || isRPK() || isX509(); - } - - public static Identity unsecure(InetSocketAddress peerAddress) { - return new Identity(peerAddress, null, null, null); - } - - public static Identity psk(InetSocketAddress peerAddress, String identity) { - return new Identity(peerAddress, identity, null, null); - } - - public static Identity rpk(InetSocketAddress peerAddress, PublicKey publicKey) { - return new Identity(peerAddress, null, publicKey, null); - } - - public static Identity x509(InetSocketAddress peerAddress, String commonName) { - return new Identity(peerAddress, null, null, commonName); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Achim Kraus (Bosch Software Innovations GmbH) - add protected constructor for sub-classing + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import java.net.InetSocketAddress; +import java.security.PublicKey; + +import org.eclipse.leshan.util.Validate; + +/** + * A request sender identity. + */ +public class Identity { + + private final InetSocketAddress peerAddress; + private final String pskIdentity; + private final PublicKey rawPublicKey; + private final String x509CommonName; + + private Identity(InetSocketAddress peerAddress, String pskIdentity, PublicKey rawPublicKey, String x509CommonName) { + Validate.notNull(peerAddress); + this.peerAddress = peerAddress; + this.pskIdentity = pskIdentity; + this.rawPublicKey = rawPublicKey; + this.x509CommonName = x509CommonName; + } + + protected Identity(Identity identity) { + this.peerAddress = identity.peerAddress; + this.pskIdentity = identity.pskIdentity; + this.rawPublicKey = identity.rawPublicKey; + this.x509CommonName = identity.x509CommonName; + } + + public InetSocketAddress getPeerAddress() { + return peerAddress; + } + + public String getPskIdentity() { + return pskIdentity; + } + + public PublicKey getRawPublicKey() { + return rawPublicKey; + } + + public String getX509CommonName() { + return x509CommonName; + } + + public boolean isPSK() { + return pskIdentity != null && !pskIdentity.isEmpty(); + } + + public boolean isRPK() { + return rawPublicKey != null; + } + + public boolean isX509() { + return x509CommonName != null && !x509CommonName.isEmpty(); + } + + public boolean isSecure() { + return isPSK() || isRPK() || isX509(); + } + + public static Identity unsecure(InetSocketAddress peerAddress) { + return new Identity(peerAddress, null, null, null); + } + + public static Identity psk(InetSocketAddress peerAddress, String identity) { + return new Identity(peerAddress, identity, null, null); + } + + public static Identity rpk(InetSocketAddress peerAddress, PublicKey publicKey) { + return new Identity(peerAddress, null, publicKey, null); + } + + public static Identity x509(InetSocketAddress peerAddress, String commonName) { + return new Identity(peerAddress, null, null, commonName); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/LwM2mRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/LwM2mRequest.java index 3ea2ddf..afdddde 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/LwM2mRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/LwM2mRequest.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * A Lightweight M2M request. - */ -public interface LwM2mRequest { -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * A Lightweight M2M request. + */ +public interface LwM2mRequest { +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ObserveRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ObserveRequest.java index 2bd7fba..8a54a15 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ObserveRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ObserveRequest.java @@ -1,135 +1,135 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.ObserveResponse; - -/** - * A Lightweight M2M request for observing changes of a specific Resource, Resources within an Object Instance or for - * all the Object Instances of an Object within the LWM2M Client. - */ -public class ObserveRequest extends AbstractDownlinkRequest { - - private ContentFormat format; - - /** - * Creates a request for observing future changes of all instances of a particular object of a client. - * - * @param objectId the object ID of the resource - */ - public ObserveRequest(int objectId) { - this(null, new LwM2mPath(objectId)); - } - - /** - * Creates a request for observing future changes of all instances of a particular object of a client. - * - * @param format the desired format for the response (TLV or JSON) - * @param objectId the object ID of the resource - */ - public ObserveRequest(ContentFormat format, int objectId) { - this(format, new LwM2mPath(objectId)); - } - - /** - * Creates a request for observing future changes of a particular object instance of a client. - * - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - */ - public ObserveRequest(int objectId, int objectInstanceId) { - this(null, new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for observing future changes of a particular object instance of a client. - * - * @param format the desired format for the response (TLV or JSON) - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - */ - public ObserveRequest(ContentFormat format, int objectId, int objectInstanceId) { - this(format, new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for observing future changes of a specific resource of a client. - * - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - * @param resourceId the (individual) resource's ID - */ - public ObserveRequest(int objectId, int objectInstanceId, int resourceId) { - this(null, new LwM2mPath(objectId, objectInstanceId, resourceId)); - } - - /** - * Creates a request for observing future changes of a specific resource of a client. - * - * @param format the desired format for the response (TLV, JSON, TEXT or OPAQUE) - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - * @param resourceId the (individual) resource's ID - */ - public ObserveRequest(ContentFormat format, int objectId, int objectInstanceId, int resourceId) { - this(format, new LwM2mPath(objectId, objectInstanceId, resourceId)); - } - - /** - * Creates a request for observing future changes of a particular LWM2M node (object, object instance or resource). - * - * @param path the path to the LWM2M node to observe - * @throw IllegalArgumentException if the path is not valid - */ - public ObserveRequest(String path) { - this(null, new LwM2mPath(path)); - } - - /** - * Creates a request for observing future changes of a particular LWM2M node (object, object instance or resource). - * - * @param format the desired format for the response - * @param path the path to the LWM2M node to observe - * @throw IllegalArgumentException if the path is not valid - */ - public ObserveRequest(ContentFormat format, String path) { - this(format, new LwM2mPath(path)); - } - - private ObserveRequest(ContentFormat format, LwM2mPath target) { - super(target); - this.format = format; - } - - /** - * @return the desired format of the resource to read - */ - public ContentFormat getFormat() { - return format; - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - @Override - public final String toString() { - return String.format("ObserveRequest [path=%s format=%s]", getPath(), format); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.ObserveResponse; + +/** + * A Lightweight M2M request for observing changes of a specific Resource, Resources within an Object Instance or for + * all the Object Instances of an Object within the LWM2M Client. + */ +public class ObserveRequest extends AbstractDownlinkRequest { + + private ContentFormat format; + + /** + * Creates a request for observing future changes of all instances of a particular object of a client. + * + * @param objectId the object ID of the resource + */ + public ObserveRequest(int objectId) { + this(null, new LwM2mPath(objectId)); + } + + /** + * Creates a request for observing future changes of all instances of a particular object of a client. + * + * @param format the desired format for the response (TLV or JSON) + * @param objectId the object ID of the resource + */ + public ObserveRequest(ContentFormat format, int objectId) { + this(format, new LwM2mPath(objectId)); + } + + /** + * Creates a request for observing future changes of a particular object instance of a client. + * + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + */ + public ObserveRequest(int objectId, int objectInstanceId) { + this(null, new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for observing future changes of a particular object instance of a client. + * + * @param format the desired format for the response (TLV or JSON) + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + */ + public ObserveRequest(ContentFormat format, int objectId, int objectInstanceId) { + this(format, new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for observing future changes of a specific resource of a client. + * + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + * @param resourceId the (individual) resource's ID + */ + public ObserveRequest(int objectId, int objectInstanceId, int resourceId) { + this(null, new LwM2mPath(objectId, objectInstanceId, resourceId)); + } + + /** + * Creates a request for observing future changes of a specific resource of a client. + * + * @param format the desired format for the response (TLV, JSON, TEXT or OPAQUE) + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + * @param resourceId the (individual) resource's ID + */ + public ObserveRequest(ContentFormat format, int objectId, int objectInstanceId, int resourceId) { + this(format, new LwM2mPath(objectId, objectInstanceId, resourceId)); + } + + /** + * Creates a request for observing future changes of a particular LWM2M node (object, object instance or resource). + * + * @param path the path to the LWM2M node to observe + * @throw IllegalArgumentException if the path is not valid + */ + public ObserveRequest(String path) { + this(null, new LwM2mPath(path)); + } + + /** + * Creates a request for observing future changes of a particular LWM2M node (object, object instance or resource). + * + * @param format the desired format for the response + * @param path the path to the LWM2M node to observe + * @throw IllegalArgumentException if the path is not valid + */ + public ObserveRequest(ContentFormat format, String path) { + this(format, new LwM2mPath(path)); + } + + private ObserveRequest(ContentFormat format, LwM2mPath target) { + super(target); + this.format = format; + } + + /** + * @return the desired format of the resource to read + */ + public ContentFormat getFormat() { + return format; + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + @Override + public final String toString() { + return String.format("ObserveRequest [path=%s format=%s]", getPath(), format); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ReadRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ReadRequest.java index 1ec56be..b780b11 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ReadRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/ReadRequest.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.ReadResponse; - -/** - * A Lightweight M2M request for retrieving the values of resources from a LWM2M Client. - * - * The request can be used to retrieve the value(s) of one or all attributes of one particular or all instances of a - * particular object type. - */ -public class ReadRequest extends AbstractDownlinkRequest { - - private ContentFormat format; - - /** - * Creates a request for reading all instances of a particular object from a client. - * - * @param objectId the object ID of the resource - */ - public ReadRequest(int objectId) { - this(null, new LwM2mPath(objectId)); - } - - /** - * Creates a request for reading all instances of a particular object from a client. - * - * @param format the desired format for the response (TLV or JSON) - * @param objectId the object ID of the resource - */ - public ReadRequest(ContentFormat format, int objectId) { - this(format, new LwM2mPath(objectId)); - } - - /** - * Creates a request for reading a particular object instance from a client. - * - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - */ - public ReadRequest(int objectId, int objectInstanceId) { - this(null, new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for reading a particular object instance from a client. - * - * @param format the desired format for the response (TLV or JSON) - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - */ - public ReadRequest(ContentFormat format, int objectId, int objectInstanceId) { - this(format, new LwM2mPath(objectId, objectInstanceId)); - } - - /** - * Creates a request for reading a specific resource from a client. - * - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - * @param resourceId the (individual) resource's ID - */ - public ReadRequest(int objectId, int objectInstanceId, int resourceId) { - this(null, new LwM2mPath(objectId, objectInstanceId, resourceId)); - } - - /** - * Creates a request for reading a specific resource from a client. - * - * @param format the desired format for the response (TLV, JSON, TEXT or OPAQUE) - * @param objectId the object ID of the resource - * @param objectInstanceId the object instance ID - * @param resourceId the (individual) resource's ID - */ - public ReadRequest(ContentFormat format, int objectId, int objectInstanceId, int resourceId) { - this(format, new LwM2mPath(objectId, objectInstanceId, resourceId)); - } - - /** - * Create a request for reading an object/instance/resource targeted by a specific path. - * - * @param path the path to the LWM2M node to read - * @throws IllegalArgumentException if the target path is not valid - */ - public ReadRequest(String path) { - this(null, new LwM2mPath(path)); - } - - /** - * Create a request for reading an object/instance/resource targeted by a specific path. - * - * @param format the desired format for the response - * @param path the path to the LWM2M node to read - * @throws IllegalArgumentException if the target path is not valid - */ - public ReadRequest(ContentFormat format, String path) { - this(format, new LwM2mPath(path)); - } - - private ReadRequest(ContentFormat format, LwM2mPath target) { - super(target); - this.format = format; - } - - /** - * @return the desired format of the resource to read - */ - public ContentFormat getFormat() { - return format; - } - - @Override - public final String toString() { - return String.format("ReadRequest [path=%s format=%s]", getPath(), format); - } - - @Override - public void accept(DownlinkRequestVisitor visitor) { - visitor.visit(this); - - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.ReadResponse; + +/** + * A Lightweight M2M request for retrieving the values of resources from a LWM2M Client. + * + * The request can be used to retrieve the value(s) of one or all attributes of one particular or all instances of a + * particular object type. + */ +public class ReadRequest extends AbstractDownlinkRequest { + + private ContentFormat format; + + /** + * Creates a request for reading all instances of a particular object from a client. + * + * @param objectId the object ID of the resource + */ + public ReadRequest(int objectId) { + this(null, new LwM2mPath(objectId)); + } + + /** + * Creates a request for reading all instances of a particular object from a client. + * + * @param format the desired format for the response (TLV or JSON) + * @param objectId the object ID of the resource + */ + public ReadRequest(ContentFormat format, int objectId) { + this(format, new LwM2mPath(objectId)); + } + + /** + * Creates a request for reading a particular object instance from a client. + * + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + */ + public ReadRequest(int objectId, int objectInstanceId) { + this(null, new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for reading a particular object instance from a client. + * + * @param format the desired format for the response (TLV or JSON) + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + */ + public ReadRequest(ContentFormat format, int objectId, int objectInstanceId) { + this(format, new LwM2mPath(objectId, objectInstanceId)); + } + + /** + * Creates a request for reading a specific resource from a client. + * + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + * @param resourceId the (individual) resource's ID + */ + public ReadRequest(int objectId, int objectInstanceId, int resourceId) { + this(null, new LwM2mPath(objectId, objectInstanceId, resourceId)); + } + + /** + * Creates a request for reading a specific resource from a client. + * + * @param format the desired format for the response (TLV, JSON, TEXT or OPAQUE) + * @param objectId the object ID of the resource + * @param objectInstanceId the object instance ID + * @param resourceId the (individual) resource's ID + */ + public ReadRequest(ContentFormat format, int objectId, int objectInstanceId, int resourceId) { + this(format, new LwM2mPath(objectId, objectInstanceId, resourceId)); + } + + /** + * Create a request for reading an object/instance/resource targeted by a specific path. + * + * @param path the path to the LWM2M node to read + * @throws IllegalArgumentException if the target path is not valid + */ + public ReadRequest(String path) { + this(null, new LwM2mPath(path)); + } + + /** + * Create a request for reading an object/instance/resource targeted by a specific path. + * + * @param format the desired format for the response + * @param path the path to the LWM2M node to read + * @throws IllegalArgumentException if the target path is not valid + */ + public ReadRequest(ContentFormat format, String path) { + this(format, new LwM2mPath(path)); + } + + private ReadRequest(ContentFormat format, LwM2mPath target) { + super(target); + this.format = format; + } + + /** + * @return the desired format of the resource to read + */ + public ContentFormat getFormat() { + return format; + } + + @Override + public final String toString() { + return String.format("ReadRequest [path=%s format=%s]", getPath(), format); + } + + @Override + public void accept(DownlinkRequestVisitor visitor) { + visitor.visit(this); + + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/RegisterRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/RegisterRequest.java index 45dedd6..d859b98 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/RegisterRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/RegisterRequest.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.core.response.RegisterResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for sending the LWM2M Client properties required by the LWM2M Server to contact the LWM2M - * Client. - */ -public class RegisterRequest implements UplinkRequest { - - private final String endpointName; - private final Long lifetime; - private final String lwVersion; - private final BindingMode bindingMode; - private final String smsNumber; - private final LinkObject[] objectLinks; - private final Map additionalAttributes; - - public RegisterRequest(String endpointName, Long lifetime, String lwVersion, BindingMode bindingMode, - String smsNumber, LinkObject[] objectLinks, Map additionalAttributes) { - - Validate.notNull(endpointName); - Validate.noNullElements(objectLinks); - - this.endpointName = endpointName; - this.lifetime = lifetime; - this.lwVersion = lwVersion; - this.bindingMode = bindingMode; - this.smsNumber = smsNumber; - this.objectLinks = objectLinks; - if (additionalAttributes == null) - this.additionalAttributes = Collections.unmodifiableMap(new HashMap()); - else - this.additionalAttributes = Collections.unmodifiableMap(additionalAttributes); - } - - public String getEndpointName() { - return endpointName; - } - - public Long getLifetime() { - return lifetime; - } - - public String getLwVersion() { - return lwVersion; - } - - public BindingMode getBindingMode() { - return bindingMode; - } - - public String getSmsNumber() { - return smsNumber; - } - - public LinkObject[] getObjectLinks() { - return objectLinks; - } - - public Map getAdditionalAttributes() { - return additionalAttributes; - } - - @Override - public void accept(UplinkRequestVisitor visitor) { - visitor.visit(this); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.core.response.RegisterResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for sending the LWM2M Client properties required by the LWM2M Server to contact the LWM2M + * Client. + */ +public class RegisterRequest implements UplinkRequest { + + private final String endpointName; + private final Long lifetime; + private final String lwVersion; + private final BindingMode bindingMode; + private final String smsNumber; + private final LinkObject[] objectLinks; + private final Map additionalAttributes; + + public RegisterRequest(String endpointName, Long lifetime, String lwVersion, BindingMode bindingMode, + String smsNumber, LinkObject[] objectLinks, Map additionalAttributes) { + + Validate.notNull(endpointName); + Validate.noNullElements(objectLinks); + + this.endpointName = endpointName; + this.lifetime = lifetime; + this.lwVersion = lwVersion; + this.bindingMode = bindingMode; + this.smsNumber = smsNumber; + this.objectLinks = objectLinks; + if (additionalAttributes == null) + this.additionalAttributes = Collections.unmodifiableMap(new HashMap()); + else + this.additionalAttributes = Collections.unmodifiableMap(additionalAttributes); + } + + public String getEndpointName() { + return endpointName; + } + + public Long getLifetime() { + return lifetime; + } + + public String getLwVersion() { + return lwVersion; + } + + public BindingMode getBindingMode() { + return bindingMode; + } + + public String getSmsNumber() { + return smsNumber; + } + + public LinkObject[] getObjectLinks() { + return objectLinks; + } + + public Map getAdditionalAttributes() { + return additionalAttributes; + } + + @Override + public void accept(UplinkRequestVisitor visitor) { + visitor.visit(this); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UpdateRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UpdateRequest.java index d489d51..8006ac9 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UpdateRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UpdateRequest.java @@ -1,79 +1,79 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.core.response.UpdateResponse; -import org.eclipse.leshan.util.Validate; - -/** - * A Lightweight M2M request for updating the LWM2M Client properties required by the LWM2M Server to contact the LWM2M - * Client. - */ -public class UpdateRequest implements UplinkRequest { - - private final Long lifeTimeInSec; - private final String smsNumber; - private final BindingMode bindingMode; - private final String registrationId; - private final LinkObject[] objectLinks; - - /** - * Sets all fields. - * - * @param registrationId the ID under which the client is registered - * @param lifetime the number of seconds the client would like its registration to be valid - * @param smsNumber the SMS number the client can receive messages under - * @param binding the binding mode(s) the client supports - * @param objectLinks the objects and object instances the client hosts/supports - * @throws NullPointerException if the registration ID is null - */ - public UpdateRequest(String registrationId, Long lifetime, String smsNumber, BindingMode binding, - LinkObject[] objectLinks) { - - Validate.notNull(registrationId); - this.registrationId = registrationId; - this.objectLinks = objectLinks; - this.lifeTimeInSec = lifetime; - this.bindingMode = binding; - this.smsNumber = smsNumber; - } - - public String getRegistrationId() { - return registrationId; - } - - public LinkObject[] getObjectLinks() { - return objectLinks; - } - - public Long getLifeTimeInSec() { - return lifeTimeInSec; - } - - public String getSmsNumber() { - return smsNumber; - } - - public BindingMode getBindingMode() { - return bindingMode; - } - - @Override - public void accept(UplinkRequestVisitor visitor) { - visitor.visit(this); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.core.response.UpdateResponse; +import org.eclipse.leshan.util.Validate; + +/** + * A Lightweight M2M request for updating the LWM2M Client properties required by the LWM2M Server to contact the LWM2M + * Client. + */ +public class UpdateRequest implements UplinkRequest { + + private final Long lifeTimeInSec; + private final String smsNumber; + private final BindingMode bindingMode; + private final String registrationId; + private final LinkObject[] objectLinks; + + /** + * Sets all fields. + * + * @param registrationId the ID under which the client is registered + * @param lifetime the number of seconds the client would like its registration to be valid + * @param smsNumber the SMS number the client can receive messages under + * @param binding the binding mode(s) the client supports + * @param objectLinks the objects and object instances the client hosts/supports + * @throws NullPointerException if the registration ID is null + */ + public UpdateRequest(String registrationId, Long lifetime, String smsNumber, BindingMode binding, + LinkObject[] objectLinks) { + + Validate.notNull(registrationId); + this.registrationId = registrationId; + this.objectLinks = objectLinks; + this.lifeTimeInSec = lifetime; + this.bindingMode = binding; + this.smsNumber = smsNumber; + } + + public String getRegistrationId() { + return registrationId; + } + + public LinkObject[] getObjectLinks() { + return objectLinks; + } + + public Long getLifeTimeInSec() { + return lifeTimeInSec; + } + + public String getSmsNumber() { + return smsNumber; + } + + public BindingMode getBindingMode() { + return bindingMode; + } + + @Override + public void accept(UplinkRequestVisitor visitor) { + visitor.visit(this); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequest.java index 5aaa361..11c637c 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequest.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.core.response.LwM2mResponse; - -/** - * A Uplink Lightweight M2M request.
- * This is a request sent from client to server. - */ -public interface UplinkRequest extends LwM2mRequest { - - /** - * Accept a visitor for this request. - */ - void accept(UplinkRequestVisitor visitor); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.core.response.LwM2mResponse; + +/** + * A Uplink Lightweight M2M request.
+ * This is a request sent from client to server. + */ +public interface UplinkRequest extends LwM2mRequest { + + /** + * Accept a visitor for this request. + */ + void accept(UplinkRequestVisitor visitor); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequestVisitor.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequestVisitor.java index f41d059..a74e5d3 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequestVisitor.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/UplinkRequestVisitor.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -/** - * A visitor to visit an Uplink Lightweight M2M request. - */ -public interface UplinkRequestVisitor { - void visit(RegisterRequest request); - - void visit(UpdateRequest request); - - void visit(DeregisterRequest request); - - void visit(BootstrapRequest request); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +/** + * A visitor to visit an Uplink Lightweight M2M request. + */ +public interface UplinkRequestVisitor { + void visit(RegisterRequest request); + + void visit(UpdateRequest request); + + void visit(DeregisterRequest request); + + void visit(BootstrapRequest request); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteAttributesRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteAttributesRequest.java index c2aad17..6647499 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteAttributesRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteAttributesRequest.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import org.eclipse.leshan.ObserveSpec; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.response.WriteAttributesResponse; -import org.eclipse.leshan.util.Validate; - -public class WriteAttributesRequest extends AbstractDownlinkRequest { - - private final ObserveSpec observeSpec; - - public WriteAttributesRequest(final int objectId, final ObserveSpec observeSpec) { - this(new LwM2mPath(objectId), observeSpec); - } - - public WriteAttributesRequest(final int objectId, final int objectInstanceId, final ObserveSpec observeSpec) { - this(new LwM2mPath(objectId, objectInstanceId), observeSpec); - } - - public WriteAttributesRequest(final int objectId, final int objectInstanceId, final int resourceId, - final ObserveSpec observeSpec) { - this(new LwM2mPath(objectId, objectInstanceId, resourceId), observeSpec); - } - - public WriteAttributesRequest(final String path, final ObserveSpec observeSpec) { - this(new LwM2mPath(path), observeSpec); - } - - private WriteAttributesRequest(final LwM2mPath path, final ObserveSpec observeSpec) { - super(path); - Validate.notNull(observeSpec); - this.observeSpec = observeSpec; - } - - @Override - public void accept(final DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - public ObserveSpec getObserveSpec() { - return this.observeSpec; - } - - @Override - public String toString() { - return String.format("WriteAttributesRequest [%s, attributes=%s]", getPath(), getObserveSpec()); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import org.eclipse.leshan.ObserveSpec; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.response.WriteAttributesResponse; +import org.eclipse.leshan.util.Validate; + +public class WriteAttributesRequest extends AbstractDownlinkRequest { + + private final ObserveSpec observeSpec; + + public WriteAttributesRequest(final int objectId, final ObserveSpec observeSpec) { + this(new LwM2mPath(objectId), observeSpec); + } + + public WriteAttributesRequest(final int objectId, final int objectInstanceId, final ObserveSpec observeSpec) { + this(new LwM2mPath(objectId, objectInstanceId), observeSpec); + } + + public WriteAttributesRequest(final int objectId, final int objectInstanceId, final int resourceId, + final ObserveSpec observeSpec) { + this(new LwM2mPath(objectId, objectInstanceId, resourceId), observeSpec); + } + + public WriteAttributesRequest(final String path, final ObserveSpec observeSpec) { + this(new LwM2mPath(path), observeSpec); + } + + private WriteAttributesRequest(final LwM2mPath path, final ObserveSpec observeSpec) { + super(path); + Validate.notNull(observeSpec); + this.observeSpec = observeSpec; + } + + @Override + public void accept(final DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + public ObserveSpec getObserveSpec() { + return this.observeSpec; + } + + @Override + public String toString() { + return String.format("WriteAttributesRequest [%s, attributes=%s]", getPath(), getObserveSpec()); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteRequest.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteRequest.java index 23ef589..dd68ff7 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteRequest.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/WriteRequest.java @@ -1,350 +1,350 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request; - -import java.util.Collection; -import java.util.Date; -import java.util.Map; - -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mPath; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.response.WriteResponse; -import org.eclipse.leshan.util.Validate; - -/** - * The request to change the value of a Resource, an array of Resources Instances or multiple Resources from an Object - * Instance. - */ -public class WriteRequest extends AbstractDownlinkRequest { - - /** - * Define the behavior of a write request. - */ - public enum Mode { - /** - * Replaces the Object Instance or the Resource(s) with the new value provided in the “Write” operation. (see - * section 5.3.3 of the LW M2M spec). - */ - REPLACE, - /** - * Adds or updates Resources provided in the new value and leaves other existing Resources unchanged. (see - * section 5.3.3 of the LW M2M spec). - */ - UPDATE - } - - private final LwM2mNode node; - private final ContentFormat contentFormat; - private final Mode mode; - - // ***************** write instance ****************** // - - /** - * Request to write an Object Instance. - * - * @param mode the mode of the request : replace or update. - * @param contentFormat Format of the payload (TLV or JSON). - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resources the list of resources to write. - */ - public WriteRequest(final Mode mode, final ContentFormat contentFormat, final int objectId, - final int objectInstanceId, final Collection resources) { - this(mode, contentFormat, new LwM2mPath(objectId, objectInstanceId), - new LwM2mObjectInstance(objectId, resources)); - } - - /** - * Request to write an Object Instance using the TLV content format. - * - * @param mode the mode of the request : replace or update. - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resources the list of resources to write. - */ - public WriteRequest(final Mode mode, final int objectId, final int objectInstanceId, - final Collection resources) { - this(mode, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId), - new LwM2mObjectInstance(objectId, resources)); - } - - /** - * Request to write an Object Instance. - * - * @param mode the mode of the request : replace or update. - * @param contentFormat Format of the payload (TLV or JSON). - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resources the list of resources to write. - */ - public WriteRequest(final Mode mode, final ContentFormat contentFormat, final int objectId, - final int objectInstanceId, final LwM2mResource... resources) { - this(mode, contentFormat, new LwM2mPath(objectId, objectInstanceId), - new LwM2mObjectInstance(objectId, resources)); - } - - /** - * Request to write an Object Instance using the TLV content format. - * - * @param mode the mode of the request : replace or update. - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resources the list of resources to write. - */ - public WriteRequest(final Mode mode, final int objectId, final int objectInstanceId, - final LwM2mResource... resources) { - this(mode, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId), - new LwM2mObjectInstance(objectId, resources)); - } - - // ***************** write single value resource ****************** // - /** - * Request to write a String Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, String value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a String Single-Instance Resource using the given content format (TEXT, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, String value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newStringResource(resourceId, value)); - } - - /** - * Request to write a Boolean Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, boolean value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a Boolean Single-Instance Resource using the given content format (TEXT, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, boolean value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newBooleanResource(resourceId, value)); - } - - /** - * Request to write a Integer Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, long value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a Integer Single-Instance Resource using the given content format (TEXT, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, long value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newIntegerResource(resourceId, value)); - } - - /** - * Request to write a Float Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, double value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a Float Single-Instance Resource using the given content format (TEXT, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, double value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newFloatResource(resourceId, value)); - } - - /** - * Request to write a Date Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, Date value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a Date Single-Instance Resource using the given content format (TEXT, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, Date value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newDateResource(resourceId, value)); - } - - /** - * Request to write a Binary Single-Instance Resource using the TLV content format. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, byte[] value) { - this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); - } - - /** - * Request to write a Binary Single-Instance Resource using the given content format (OPAQUE, TLV, JSON). - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, byte[] value) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mSingleResource.newBinaryResource(resourceId, value)); - } - - // ***************** write multi instance resource ****************** // - /** - * Request to write a Multi-Instance Resource. - * - * @param contentFormat Format of the payload (TLV or JSON). - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resourceId the id of the resource to write. - * @param values the list of resource instance (id->value) to write. - * @param type the data type of the resource. - */ - public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, - final int resourceId, final Map values, Type type) { - this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mMultipleResource.newResource(resourceId, values, type)); - } - - /** - * Request to write a Multi-Instance Resource using the TLV content format. - * - * @param objectId the id of the object to write. - * @param objectInstanceId the id of the object instance to write. - * @param resourceId the id of the resource to write. - * @param values the list of resource instance (id->value) to write. - * @param type the data type of the resource. - */ - public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, - final Map values, Type type) { - this(Mode.REPLACE, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId, resourceId), - LwM2mMultipleResource.newResource(resourceId, values, type)); - } - - // ***************** generic constructor ****************** // - /** - * A generic constructor to write request. - * - * @param mode the mode of the request : replace or update. - * @param contentFormat Format of the payload (TLV,JSON,TEXT,OPAQUE ..). - * @param path the path of the LWM2M node to write (object instance or resource). - * @param node the {@link LwM2mNode} to write. - */ - public WriteRequest(final Mode mode, final ContentFormat contentFormat, final String path, final LwM2mNode node) { - this(mode, contentFormat, new LwM2mPath(path), node); - } - - private WriteRequest(final Mode mode, ContentFormat format, final LwM2mPath target, final LwM2mNode node) { - super(target); - Validate.notNull(mode); - Validate.notNull(node); - - // Validate Mode - if (getPath().isResource() && mode == Mode.UPDATE) { - throw new IllegalArgumentException( - String.format("Invalid mode for '%s': update is not allowed on resource", target.toString())); - } - - // Validate node and path coherence - if (getPath().isResource()) { - if (!(node instanceof LwM2mResource)) { - throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", - target.toString(), node.getClass().getSimpleName())); - } - } else if (getPath().isObjectInstance()) { - if (!(node instanceof LwM2mObjectInstance)) { - throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", - target.toString(), node.getClass().getSimpleName())); - } - } else if (getPath().isObject()) { - throw new IllegalArgumentException("write request cannot target an object: " + target.toString()); - } - - // Validate content format - if (ContentFormat.TEXT == format || ContentFormat.OPAQUE == format) { - if (!getPath().isResource()) { - throw new IllegalArgumentException( - String.format("%s format must be used only for single resources", format.toString())); - } else { - LwM2mResource resource = (LwM2mResource) node; - if (resource.isMultiInstances()) { - throw new IllegalArgumentException( - String.format("%s format must be used only for single resources", format.toString())); - } else { - if (resource.getType() == Type.OPAQUE && format == ContentFormat.TEXT) { - throw new IllegalArgumentException( - "TEXT format must not be used for byte array single resources"); - } else if (resource.getType() != Type.OPAQUE && format == ContentFormat.OPAQUE) { - throw new IllegalArgumentException( - "OPAQUE format must be used only for byte array single resources"); - } - } - } - } - - this.node = node; - if (format == null) { - this.contentFormat = ContentFormat.TLV; // use TLV as default content type - } else { - this.contentFormat = format; - } - this.mode = mode; - } - - /** - * @return true if all resources are to be replaced (see section 5.3.3 of the LW M2M spec). - */ - public boolean isReplaceRequest() { - return mode == Mode.REPLACE; - } - - /** - * @return true if this is a partial update request (see section 5.3.3 of the LW M2M spec). - */ - public boolean isPartialUpdateRequest() { - return mode == Mode.UPDATE; - } - - public LwM2mNode getNode() { - return node; - } - - public ContentFormat getContentFormat() { - return contentFormat; - } - - @Override - public void accept(final DownlinkRequestVisitor visitor) { - visitor.visit(this); - } - - @Override - public String toString() { - return String.format("WriteRequest [mode=%s, path=%s, format=%s, node=%s]", mode, getPath(), contentFormat, - node); - } - +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; + +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.response.WriteResponse; +import org.eclipse.leshan.util.Validate; + +/** + * The request to change the value of a Resource, an array of Resources Instances or multiple Resources from an Object + * Instance. + */ +public class WriteRequest extends AbstractDownlinkRequest { + + /** + * Define the behavior of a write request. + */ + public enum Mode { + /** + * Replaces the Object Instance or the Resource(s) with the new value provided in the “Write” operation. (see + * section 5.3.3 of the LW M2M spec). + */ + REPLACE, + /** + * Adds or updates Resources provided in the new value and leaves other existing Resources unchanged. (see + * section 5.3.3 of the LW M2M spec). + */ + UPDATE + } + + private final LwM2mNode node; + private final ContentFormat contentFormat; + private final Mode mode; + + // ***************** write instance ****************** // + + /** + * Request to write an Object Instance. + * + * @param mode the mode of the request : replace or update. + * @param contentFormat Format of the payload (TLV or JSON). + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resources the list of resources to write. + */ + public WriteRequest(final Mode mode, final ContentFormat contentFormat, final int objectId, + final int objectInstanceId, final Collection resources) { + this(mode, contentFormat, new LwM2mPath(objectId, objectInstanceId), + new LwM2mObjectInstance(objectId, resources)); + } + + /** + * Request to write an Object Instance using the TLV content format. + * + * @param mode the mode of the request : replace or update. + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resources the list of resources to write. + */ + public WriteRequest(final Mode mode, final int objectId, final int objectInstanceId, + final Collection resources) { + this(mode, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId), + new LwM2mObjectInstance(objectId, resources)); + } + + /** + * Request to write an Object Instance. + * + * @param mode the mode of the request : replace or update. + * @param contentFormat Format of the payload (TLV or JSON). + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resources the list of resources to write. + */ + public WriteRequest(final Mode mode, final ContentFormat contentFormat, final int objectId, + final int objectInstanceId, final LwM2mResource... resources) { + this(mode, contentFormat, new LwM2mPath(objectId, objectInstanceId), + new LwM2mObjectInstance(objectId, resources)); + } + + /** + * Request to write an Object Instance using the TLV content format. + * + * @param mode the mode of the request : replace or update. + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resources the list of resources to write. + */ + public WriteRequest(final Mode mode, final int objectId, final int objectInstanceId, + final LwM2mResource... resources) { + this(mode, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId), + new LwM2mObjectInstance(objectId, resources)); + } + + // ***************** write single value resource ****************** // + /** + * Request to write a String Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, String value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a String Single-Instance Resource using the given content format (TEXT, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, String value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newStringResource(resourceId, value)); + } + + /** + * Request to write a Boolean Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, boolean value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a Boolean Single-Instance Resource using the given content format (TEXT, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, boolean value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newBooleanResource(resourceId, value)); + } + + /** + * Request to write a Integer Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, long value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a Integer Single-Instance Resource using the given content format (TEXT, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, long value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newIntegerResource(resourceId, value)); + } + + /** + * Request to write a Float Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, double value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a Float Single-Instance Resource using the given content format (TEXT, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, double value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newFloatResource(resourceId, value)); + } + + /** + * Request to write a Date Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, Date value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a Date Single-Instance Resource using the given content format (TEXT, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, Date value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newDateResource(resourceId, value)); + } + + /** + * Request to write a Binary Single-Instance Resource using the TLV content format. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, byte[] value) { + this(ContentFormat.TLV, objectId, objectInstanceId, resourceId, value); + } + + /** + * Request to write a Binary Single-Instance Resource using the given content format (OPAQUE, TLV, JSON). + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, byte[] value) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mSingleResource.newBinaryResource(resourceId, value)); + } + + // ***************** write multi instance resource ****************** // + /** + * Request to write a Multi-Instance Resource. + * + * @param contentFormat Format of the payload (TLV or JSON). + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resourceId the id of the resource to write. + * @param values the list of resource instance (id->value) to write. + * @param type the data type of the resource. + */ + public WriteRequest(final ContentFormat contentFormat, final int objectId, final int objectInstanceId, + final int resourceId, final Map values, Type type) { + this(Mode.REPLACE, contentFormat, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mMultipleResource.newResource(resourceId, values, type)); + } + + /** + * Request to write a Multi-Instance Resource using the TLV content format. + * + * @param objectId the id of the object to write. + * @param objectInstanceId the id of the object instance to write. + * @param resourceId the id of the resource to write. + * @param values the list of resource instance (id->value) to write. + * @param type the data type of the resource. + */ + public WriteRequest(final int objectId, final int objectInstanceId, final int resourceId, + final Map values, Type type) { + this(Mode.REPLACE, ContentFormat.TLV, new LwM2mPath(objectId, objectInstanceId, resourceId), + LwM2mMultipleResource.newResource(resourceId, values, type)); + } + + // ***************** generic constructor ****************** // + /** + * A generic constructor to write request. + * + * @param mode the mode of the request : replace or update. + * @param contentFormat Format of the payload (TLV,JSON,TEXT,OPAQUE ..). + * @param path the path of the LWM2M node to write (object instance or resource). + * @param node the {@link LwM2mNode} to write. + */ + public WriteRequest(final Mode mode, final ContentFormat contentFormat, final String path, final LwM2mNode node) { + this(mode, contentFormat, new LwM2mPath(path), node); + } + + private WriteRequest(final Mode mode, ContentFormat format, final LwM2mPath target, final LwM2mNode node) { + super(target); + Validate.notNull(mode); + Validate.notNull(node); + + // Validate Mode + if (getPath().isResource() && mode == Mode.UPDATE) { + throw new IllegalArgumentException( + String.format("Invalid mode for '%s': update is not allowed on resource", target.toString())); + } + + // Validate node and path coherence + if (getPath().isResource()) { + if (!(node instanceof LwM2mResource)) { + throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", + target.toString(), node.getClass().getSimpleName())); + } + } else if (getPath().isObjectInstance()) { + if (!(node instanceof LwM2mObjectInstance)) { + throw new IllegalArgumentException(String.format("path '%s' and node type '%s' does not match", + target.toString(), node.getClass().getSimpleName())); + } + } else if (getPath().isObject()) { + throw new IllegalArgumentException("write request cannot target an object: " + target.toString()); + } + + // Validate content format + if (ContentFormat.TEXT == format || ContentFormat.OPAQUE == format) { + if (!getPath().isResource()) { + throw new IllegalArgumentException( + String.format("%s format must be used only for single resources", format.toString())); + } else { + LwM2mResource resource = (LwM2mResource) node; + if (resource.isMultiInstances()) { + throw new IllegalArgumentException( + String.format("%s format must be used only for single resources", format.toString())); + } else { + if (resource.getType() == Type.OPAQUE && format == ContentFormat.TEXT) { + throw new IllegalArgumentException( + "TEXT format must not be used for byte array single resources"); + } else if (resource.getType() != Type.OPAQUE && format == ContentFormat.OPAQUE) { + throw new IllegalArgumentException( + "OPAQUE format must be used only for byte array single resources"); + } + } + } + } + + this.node = node; + if (format == null) { + this.contentFormat = ContentFormat.TLV; // use TLV as default content type + } else { + this.contentFormat = format; + } + this.mode = mode; + } + + /** + * @return true if all resources are to be replaced (see section 5.3.3 of the LW M2M spec). + */ + public boolean isReplaceRequest() { + return mode == Mode.REPLACE; + } + + /** + * @return true if this is a partial update request (see section 5.3.3 of the LW M2M spec). + */ + public boolean isPartialUpdateRequest() { + return mode == Mode.UPDATE; + } + + public LwM2mNode getNode() { + return node; + } + + public ContentFormat getContentFormat() { + return contentFormat; + } + + @Override + public void accept(final DownlinkRequestVisitor visitor) { + visitor.visit(this); + } + + @Override + public String toString() { + return String.format("WriteRequest [mode=%s, path=%s, format=%s, node=%s]", mode, getPath(), contentFormat, + node); + } + } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/RequestFailedException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/RequestFailedException.java index 0d7f0db..7868d76 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/RequestFailedException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/RequestFailedException.java @@ -1,33 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request.exception; - -/** - * Generic exception for all unexpected errors (e.g. rejected request at CoAP level). - */ -public class RequestFailedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public RequestFailedException() { - super(); - } - - public RequestFailedException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request.exception; + +/** + * Generic exception for all unexpected errors (e.g. rejected request at CoAP level). + */ +public class RequestFailedException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public RequestFailedException() { + super(); + } + + public RequestFailedException(String message) { + super(message); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/ResourceAccessException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/ResourceAccessException.java index 9375724..035b3b5 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/ResourceAccessException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/ResourceAccessException.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request.exception; - - -/** - * An exception indicating a problem while accessing a resource on a LWM2M Client (invalid error code, invalid resource - * value...). - */ -public class ResourceAccessException extends RuntimeException { - - private static final long serialVersionUID = 1L; - private final String uri; - - /** - * Initializes all fields. - * - * @param uri the URI of the accessed resource - * @param message the message returned by the server or null if the server did not return a message - * @throws NullPointerException if the uri is null - */ - public ResourceAccessException(String uri, String message) { - this(uri, message, null); - } - - /** - * Initializes all fields. - * - * @param uri the URI of the accessed resource - * @param message the message returned by the server or null if the server did not return a message - * @param cause the root cause of the access problem - * @throws NullPointerException if the uri is null - */ - public ResourceAccessException(String uri, String message, Throwable cause) { - super(message, cause); - if (uri == null) { - throw new NullPointerException("Request URI must not be null"); - } - this.uri = uri; - } - - /** - * Gets the URI of the accessed resource. - * - * @return the URI - */ - public String getUri() { - return this.uri; - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request.exception; + + +/** + * An exception indicating a problem while accessing a resource on a LWM2M Client (invalid error code, invalid resource + * value...). + */ +public class ResourceAccessException extends RuntimeException { + + private static final long serialVersionUID = 1L; + private final String uri; + + /** + * Initializes all fields. + * + * @param uri the URI of the accessed resource + * @param message the message returned by the server or null if the server did not return a message + * @throws NullPointerException if the uri is null + */ + public ResourceAccessException(String uri, String message) { + this(uri, message, null); + } + + /** + * Initializes all fields. + * + * @param uri the URI of the accessed resource + * @param message the message returned by the server or null if the server did not return a message + * @param cause the root cause of the access problem + * @throws NullPointerException if the uri is null + */ + public ResourceAccessException(String uri, String message, Throwable cause) { + super(message, cause); + if (uri == null) { + throw new NullPointerException("Request URI must not be null"); + } + this.uri = uri; + } + + /** + * Gets the URI of the accessed resource. + * + * @return the URI + */ + public String getUri() { + return this.uri; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/TimeoutException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/TimeoutException.java index 9e070fa..1f66d8f 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/TimeoutException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/request/exception/TimeoutException.java @@ -1,26 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.request.exception; - -public class TimeoutException extends Exception { - - private static final long serialVersionUID = -8966041387554358975L; - - public TimeoutException() { - super("Request timed out after all CoAP retransmission attempts"); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.request.exception; + +public class TimeoutException extends Exception { + + private static final long serialVersionUID = -8966041387554358975L; + + public TimeoutException() { + super("Request timed out after all CoAP retransmission attempts"); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/AbstractLwM2mResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/AbstractLwM2mResponse.java index 4ea9164..0833562 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/AbstractLwM2mResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/AbstractLwM2mResponse.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; -import org.eclipse.leshan.util.Validate; - -/** - * A base class for concrete LWM2M response. - */ -public abstract class AbstractLwM2mResponse implements LwM2mResponse { - - protected final ResponseCode code; - protected final String errorMessage; - - public AbstractLwM2mResponse(final ResponseCode code, final String errorMessage) { - Validate.notNull(code); - if (errorMessage != null) - Validate.isTrue(code.isError(), "Only error response could have an error message."); - this.code = code; - this.errorMessage = errorMessage; - } - - @Override - public final ResponseCode getCode() { - return this.code; - } - - @Override - public String getErrorMessage() { - return errorMessage; - } - - @Override - public boolean isFailure() { - return !isSuccess(); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; +import org.eclipse.leshan.util.Validate; + +/** + * A base class for concrete LWM2M response. + */ +public abstract class AbstractLwM2mResponse implements LwM2mResponse { + + protected final ResponseCode code; + protected final String errorMessage; + + public AbstractLwM2mResponse(final ResponseCode code, final String errorMessage) { + Validate.notNull(code); + if (errorMessage != null) + Validate.isTrue(code.isError(), "Only error response could have an error message."); + this.code = code; + this.errorMessage = errorMessage; + } + + @Override + public final ResponseCode getCode() { + return this.code; + } + + @Override + public String getErrorMessage() { + return errorMessage; + } + + @Override + public boolean isFailure() { + return !isSuccess(); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapDeleteResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapDeleteResponse.java index b71fd74..f7be35d 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapDeleteResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapDeleteResponse.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * Response to a delete request from the bootstrap server. - */ -public class BootstrapDeleteResponse extends AbstractLwM2mResponse { - - public BootstrapDeleteResponse(ResponseCode code, String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.DELETED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("BootstrapDeleteResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("BootstrapDeleteResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static BootstrapDeleteResponse success() { - return new BootstrapDeleteResponse(ResponseCode.DELETED, null); - } - - public static BootstrapDeleteResponse badRequest(String errorMessage) { - return new BootstrapDeleteResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static BootstrapDeleteResponse internalServerError(String errorMessage) { - return new BootstrapDeleteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * Response to a delete request from the bootstrap server. + */ +public class BootstrapDeleteResponse extends AbstractLwM2mResponse { + + public BootstrapDeleteResponse(ResponseCode code, String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.DELETED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("BootstrapDeleteResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("BootstrapDeleteResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static BootstrapDeleteResponse success() { + return new BootstrapDeleteResponse(ResponseCode.DELETED, null); + } + + public static BootstrapDeleteResponse badRequest(String errorMessage) { + return new BootstrapDeleteResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static BootstrapDeleteResponse internalServerError(String errorMessage) { + return new BootstrapDeleteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapFinishResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapFinishResponse.java index f10e0c2..f494c65 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapFinishResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapFinishResponse.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * Response to a bootstrap finish request from the bootstrap server. - */ -public class BootstrapFinishResponse extends AbstractLwM2mResponse { - - public BootstrapFinishResponse(ResponseCode code, String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("BootstrapFinishResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("BootstrapFinishResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static BootstrapFinishResponse success() { - return new BootstrapFinishResponse(ResponseCode.CHANGED, null); - } - - public static BootstrapFinishResponse badRequest(String errorMessage) { - return new BootstrapFinishResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static BootstrapFinishResponse internalServerError(String errorMessage) { - return new BootstrapFinishResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * Response to a bootstrap finish request from the bootstrap server. + */ +public class BootstrapFinishResponse extends AbstractLwM2mResponse { + + public BootstrapFinishResponse(ResponseCode code, String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("BootstrapFinishResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("BootstrapFinishResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static BootstrapFinishResponse success() { + return new BootstrapFinishResponse(ResponseCode.CHANGED, null); + } + + public static BootstrapFinishResponse badRequest(String errorMessage) { + return new BootstrapFinishResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static BootstrapFinishResponse internalServerError(String errorMessage) { + return new BootstrapFinishResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapResponse.java index 1b834e5..e071549 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapResponse.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * The response to a client bootstrap request. - */ -public class BootstrapResponse extends AbstractLwM2mResponse { - - public BootstrapResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("BootstrapResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("BootstrapResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static BootstrapResponse success() { - return new BootstrapResponse(ResponseCode.CHANGED, null); - } - - public static BootstrapResponse badRequest(String errorMessage) { - return new BootstrapResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static BootstrapResponse internalServerError(String errorMessage) { - return new BootstrapResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * The response to a client bootstrap request. + */ +public class BootstrapResponse extends AbstractLwM2mResponse { + + public BootstrapResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("BootstrapResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("BootstrapResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static BootstrapResponse success() { + return new BootstrapResponse(ResponseCode.CHANGED, null); + } + + public static BootstrapResponse badRequest(String errorMessage) { + return new BootstrapResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static BootstrapResponse internalServerError(String errorMessage) { + return new BootstrapResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapWriteResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapWriteResponse.java index 50574d1..8b46730 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapWriteResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/BootstrapWriteResponse.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * Response to a write request from the bootstrap server. - */ -public class BootstrapWriteResponse extends AbstractLwM2mResponse { - - public BootstrapWriteResponse(ResponseCode code, String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("BootstrapWriteResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("BootstrapWriteResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static BootstrapWriteResponse success() { - return new BootstrapWriteResponse(ResponseCode.CHANGED, null); - } - - public static BootstrapWriteResponse unsupportedContentFormat() { - return new BootstrapWriteResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null); - } - - public static BootstrapWriteResponse badRequest(String errorMessage) { - return new BootstrapWriteResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static BootstrapWriteResponse internalServerError(String errorMessage) { - return new BootstrapWriteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } - -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * Response to a write request from the bootstrap server. + */ +public class BootstrapWriteResponse extends AbstractLwM2mResponse { + + public BootstrapWriteResponse(ResponseCode code, String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("BootstrapWriteResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("BootstrapWriteResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static BootstrapWriteResponse success() { + return new BootstrapWriteResponse(ResponseCode.CHANGED, null); + } + + public static BootstrapWriteResponse unsupportedContentFormat() { + return new BootstrapWriteResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null); + } + + public static BootstrapWriteResponse badRequest(String errorMessage) { + return new BootstrapWriteResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static BootstrapWriteResponse internalServerError(String errorMessage) { + return new BootstrapWriteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/CreateResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/CreateResponse.java index 800bd6a..71f50af 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/CreateResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/CreateResponse.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class CreateResponse extends AbstractLwM2mResponse { - - private String location; - - public CreateResponse(ResponseCode code, String location, String errorMessage) { - super(code, errorMessage); - this.location = location; - } - - public String getLocation() { - return location; - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CREATED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("CreateResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("CreateResponse [code=%s, location=%s]", code, location); - } - - // Syntactic sugar static constructors : - - public static CreateResponse success(String location) { - return new CreateResponse(ResponseCode.CREATED, location, null); - } - - public static CreateResponse badRequest(String errorMessage) { - return new CreateResponse(ResponseCode.BAD_REQUEST, null, errorMessage); - } - - public static CreateResponse notFound() { - return new CreateResponse(ResponseCode.NOT_FOUND, null, null); - } - - public static CreateResponse unauthorized() { - return new CreateResponse(ResponseCode.UNAUTHORIZED, null, null); - } - - public static CreateResponse methodNotAllowed() { - return new CreateResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); - } - - public static CreateResponse unsupportedContentFormat() { - return new CreateResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null, null); - } - - public static CreateResponse internalServerError(String errorMessage) { - return new CreateResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class CreateResponse extends AbstractLwM2mResponse { + + private String location; + + public CreateResponse(ResponseCode code, String location, String errorMessage) { + super(code, errorMessage); + this.location = location; + } + + public String getLocation() { + return location; + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CREATED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("CreateResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("CreateResponse [code=%s, location=%s]", code, location); + } + + // Syntactic sugar static constructors : + + public static CreateResponse success(String location) { + return new CreateResponse(ResponseCode.CREATED, location, null); + } + + public static CreateResponse badRequest(String errorMessage) { + return new CreateResponse(ResponseCode.BAD_REQUEST, null, errorMessage); + } + + public static CreateResponse notFound() { + return new CreateResponse(ResponseCode.NOT_FOUND, null, null); + } + + public static CreateResponse unauthorized() { + return new CreateResponse(ResponseCode.UNAUTHORIZED, null, null); + } + + public static CreateResponse methodNotAllowed() { + return new CreateResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); + } + + public static CreateResponse unsupportedContentFormat() { + return new CreateResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null, null); + } + + public static CreateResponse internalServerError(String errorMessage) { + return new CreateResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeleteResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeleteResponse.java index c73630d..0212a51 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeleteResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeleteResponse.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class DeleteResponse extends AbstractLwM2mResponse { - - public DeleteResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.DELETED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("DeleteResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("DeleteResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static DeleteResponse success() { - return new DeleteResponse(ResponseCode.DELETED, null); - } - - public static DeleteResponse badRequest(String errorMessage) { - return new DeleteResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static DeleteResponse notFound() { - return new DeleteResponse(ResponseCode.NOT_FOUND, null); - } - - public static DeleteResponse unauthorized() { - return new DeleteResponse(ResponseCode.UNAUTHORIZED, null); - } - - public static DeleteResponse methodNotAllowed() { - return new DeleteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); - } - - public static DeleteResponse internalServerError(String errorMessage) { - return new DeleteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class DeleteResponse extends AbstractLwM2mResponse { + + public DeleteResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.DELETED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("DeleteResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("DeleteResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static DeleteResponse success() { + return new DeleteResponse(ResponseCode.DELETED, null); + } + + public static DeleteResponse badRequest(String errorMessage) { + return new DeleteResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static DeleteResponse notFound() { + return new DeleteResponse(ResponseCode.NOT_FOUND, null); + } + + public static DeleteResponse unauthorized() { + return new DeleteResponse(ResponseCode.UNAUTHORIZED, null); + } + + public static DeleteResponse methodNotAllowed() { + return new DeleteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); + } + + public static DeleteResponse internalServerError(String errorMessage) { + return new DeleteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeregisterResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeregisterResponse.java index 320d941..986fa20 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeregisterResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DeregisterResponse.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class DeregisterResponse extends AbstractLwM2mResponse { - - public DeregisterResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.DELETED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("DeregisterResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("DeregisterResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static DeregisterResponse success() { - return new DeregisterResponse(ResponseCode.DELETED, null); - } - - public static DeregisterResponse badRequest(String errorMessage) { - return new DeregisterResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static DeregisterResponse notFound() { - return new DeregisterResponse(ResponseCode.NOT_FOUND, null); - } - - public static DeregisterResponse internalServerError(String errorMessage) { - return new DeregisterResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class DeregisterResponse extends AbstractLwM2mResponse { + + public DeregisterResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.DELETED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("DeregisterResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("DeregisterResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static DeregisterResponse success() { + return new DeregisterResponse(ResponseCode.DELETED, null); + } + + public static DeregisterResponse badRequest(String errorMessage) { + return new DeregisterResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static DeregisterResponse notFound() { + return new DeregisterResponse(ResponseCode.NOT_FOUND, null); + } + + public static DeregisterResponse internalServerError(String errorMessage) { + return new DeregisterResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DiscoverResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DiscoverResponse.java index cda8cbd..3294518 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DiscoverResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/DiscoverResponse.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import java.util.Arrays; - -import org.eclipse.leshan.LinkObject; -import org.eclipse.leshan.ResponseCode; -import org.eclipse.leshan.util.Validate; - -public class DiscoverResponse extends AbstractLwM2mResponse { - - private final LinkObject[] links; - - public DiscoverResponse(ResponseCode code, LinkObject[] links, String errorMessage) { - super(code, errorMessage); - if (ResponseCode.CONTENT.equals(code)) { - Validate.notNull(links); - this.links = Arrays.copyOf(links, links.length); - } else { - this.links = null; - } - } - - /** - * Get the list of {@link LinkObject} returned as response payload. - * - * @return the object links or null if the client returned an error response. - */ - public LinkObject[] getObjectLinks() { - return links != null ? links.clone() : null; - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CONTENT; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("DiscoverResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("DiscoverResponse [code=%s, location=%s]", code, Arrays.toString(links)); - } - - // Syntactic sugar static constructors : - - public static DiscoverResponse success(LinkObject[] links) { - return new DiscoverResponse(ResponseCode.CONTENT, links, null); - } - - public static DiscoverResponse badRequest(String errorMessage) { - return new DiscoverResponse(ResponseCode.BAD_REQUEST, null, errorMessage); - } - - public static DiscoverResponse notFound() { - return new DiscoverResponse(ResponseCode.NOT_FOUND, null, null); - } - - public static DiscoverResponse unauthorized() { - return new DiscoverResponse(ResponseCode.UNAUTHORIZED, null, null); - } - - public static DiscoverResponse methodNotAllowed() { - return new DiscoverResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); - } - - public static DiscoverResponse internalServerError(String errorMessage) { - return new DiscoverResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import java.util.Arrays; + +import org.eclipse.leshan.LinkObject; +import org.eclipse.leshan.ResponseCode; +import org.eclipse.leshan.util.Validate; + +public class DiscoverResponse extends AbstractLwM2mResponse { + + private final LinkObject[] links; + + public DiscoverResponse(ResponseCode code, LinkObject[] links, String errorMessage) { + super(code, errorMessage); + if (ResponseCode.CONTENT.equals(code)) { + Validate.notNull(links); + this.links = Arrays.copyOf(links, links.length); + } else { + this.links = null; + } + } + + /** + * Get the list of {@link LinkObject} returned as response payload. + * + * @return the object links or null if the client returned an error response. + */ + public LinkObject[] getObjectLinks() { + return links != null ? links.clone() : null; + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CONTENT; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("DiscoverResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("DiscoverResponse [code=%s, location=%s]", code, Arrays.toString(links)); + } + + // Syntactic sugar static constructors : + + public static DiscoverResponse success(LinkObject[] links) { + return new DiscoverResponse(ResponseCode.CONTENT, links, null); + } + + public static DiscoverResponse badRequest(String errorMessage) { + return new DiscoverResponse(ResponseCode.BAD_REQUEST, null, errorMessage); + } + + public static DiscoverResponse notFound() { + return new DiscoverResponse(ResponseCode.NOT_FOUND, null, null); + } + + public static DiscoverResponse unauthorized() { + return new DiscoverResponse(ResponseCode.UNAUTHORIZED, null, null); + } + + public static DiscoverResponse methodNotAllowed() { + return new DiscoverResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); + } + + public static DiscoverResponse internalServerError(String errorMessage) { + return new DiscoverResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ErrorCallback.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ErrorCallback.java index bb56bbb..702ec10 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ErrorCallback.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ErrorCallback.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -/** - * On error callback for LWM2M request. - */ -public interface ErrorCallback { - // We should keep this as a 1 method interface to be java 8 lambda compatible. - - /** - * Called when the request failed - */ - void onError(Exception e); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +/** + * On error callback for LWM2M request. + */ +public interface ErrorCallback { + // We should keep this as a 1 method interface to be java 8 lambda compatible. + + /** + * Called when the request failed + */ + void onError(Exception e); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ExecuteResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ExecuteResponse.java index 878f8f3..a618f99 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ExecuteResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ExecuteResponse.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class ExecuteResponse extends AbstractLwM2mResponse { - - public ExecuteResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("ExecuteResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("ExecuteResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static ExecuteResponse success() { - return new ExecuteResponse(ResponseCode.CHANGED, null); - } - - public static ExecuteResponse badRequest(String errorMessage) { - return new ExecuteResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static ExecuteResponse notFound() { - return new ExecuteResponse(ResponseCode.NOT_FOUND, null); - } - - public static ExecuteResponse unauthorized() { - return new ExecuteResponse(ResponseCode.UNAUTHORIZED, null); - } - - public static ExecuteResponse methodNotAllowed() { - return new ExecuteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); - } - - public static ExecuteResponse internalServerError(String errorMessage) { - return new ExecuteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class ExecuteResponse extends AbstractLwM2mResponse { + + public ExecuteResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("ExecuteResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("ExecuteResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static ExecuteResponse success() { + return new ExecuteResponse(ResponseCode.CHANGED, null); + } + + public static ExecuteResponse badRequest(String errorMessage) { + return new ExecuteResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static ExecuteResponse notFound() { + return new ExecuteResponse(ResponseCode.NOT_FOUND, null); + } + + public static ExecuteResponse unauthorized() { + return new ExecuteResponse(ResponseCode.UNAUTHORIZED, null); + } + + public static ExecuteResponse methodNotAllowed() { + return new ExecuteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); + } + + public static ExecuteResponse internalServerError(String errorMessage) { + return new ExecuteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/LwM2mResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/LwM2mResponse.java index e6ba163..2a9588f 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/LwM2mResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/LwM2mResponse.java @@ -1,49 +1,49 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * A response to Lightweight M2M request. - */ -public interface LwM2mResponse { - - /** - * Gets the response code. - * - * @return the code - */ - ResponseCode getCode(); - - /** - * Gets the error Message. The message is similar to the Reason-Phrase on an HTTP status line. It is not intended - * for end users but for software engineers that during debugging need to interpret it. - * - * @return the error message - */ - String getErrorMessage(); - - /** - * @return true if the request was successfully done. - */ - boolean isSuccess(); - - /** - * @return true if we get an error or unexpected code. - */ - boolean isFailure(); -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * A response to Lightweight M2M request. + */ +public interface LwM2mResponse { + + /** + * Gets the response code. + * + * @return the code + */ + ResponseCode getCode(); + + /** + * Gets the error Message. The message is similar to the Reason-Phrase on an HTTP status line. It is not intended + * for end users but for software engineers that during debugging need to interpret it. + * + * @return the error message + */ + String getErrorMessage(); + + /** + * @return true if the request was successfully done. + */ + boolean isSuccess(); + + /** + * @return true if we get an error or unexpected code. + */ + boolean isFailure(); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ObserveResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ObserveResponse.java index 583f350..f10dc33 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ObserveResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ObserveResponse.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.observation.Observation; - -/** - * Specialized ReadResponse to a Observe request, with the corresponding Observation. - * - * This can be useful to listen to updates on the specific Observation. - */ -public class ObserveResponse extends ReadResponse { - - private Observation observation; - - public ObserveResponse(ResponseCode code, LwM2mNode content, Observation observation, String errorMessage) { - super(code, content, errorMessage); - this.observation = observation; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("ObserveResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("ObserveResponse [code=%s, content=%s, observation=%s]", code, content, observation); - } - - public Observation getObservation() { - return observation; - } - - // Syntactic sugar static constructors : - - public static ObserveResponse success(LwM2mNode content) { - return new ObserveResponse(ResponseCode.CONTENT, content, null, null); - } - - public static ObserveResponse badRequest(String errorMessage) { - return new ObserveResponse(ResponseCode.BAD_REQUEST, null, null, errorMessage); - } - - public static ObserveResponse notFound() { - return new ObserveResponse(ResponseCode.NOT_FOUND, null, null, null); - } - - public static ObserveResponse unauthorized() { - return new ObserveResponse(ResponseCode.UNAUTHORIZED, null, null, null); - } - - public static ObserveResponse methodNotAllowed() { - return new ObserveResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null, null); - } - - public static ObserveResponse notAcceptable() { - return new ObserveResponse(ResponseCode.NOT_ACCEPTABLE, null, null, null); - } - - public static ObserveResponse internalServerError(String errorMessage) { - return new ObserveResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, null, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.observation.Observation; + +/** + * Specialized ReadResponse to a Observe request, with the corresponding Observation. + * + * This can be useful to listen to updates on the specific Observation. + */ +public class ObserveResponse extends ReadResponse { + + private Observation observation; + + public ObserveResponse(ResponseCode code, LwM2mNode content, Observation observation, String errorMessage) { + super(code, content, errorMessage); + this.observation = observation; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("ObserveResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("ObserveResponse [code=%s, content=%s, observation=%s]", code, content, observation); + } + + public Observation getObservation() { + return observation; + } + + // Syntactic sugar static constructors : + + public static ObserveResponse success(LwM2mNode content) { + return new ObserveResponse(ResponseCode.CONTENT, content, null, null); + } + + public static ObserveResponse badRequest(String errorMessage) { + return new ObserveResponse(ResponseCode.BAD_REQUEST, null, null, errorMessage); + } + + public static ObserveResponse notFound() { + return new ObserveResponse(ResponseCode.NOT_FOUND, null, null, null); + } + + public static ObserveResponse unauthorized() { + return new ObserveResponse(ResponseCode.UNAUTHORIZED, null, null, null); + } + + public static ObserveResponse methodNotAllowed() { + return new ObserveResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null, null); + } + + public static ObserveResponse notAcceptable() { + return new ObserveResponse(ResponseCode.NOT_ACCEPTABLE, null, null, null); + } + + public static ObserveResponse internalServerError(String errorMessage) { + return new ObserveResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, null, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ReadResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ReadResponse.java index 1b2aa55..7cfd683 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ReadResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ReadResponse.java @@ -1,120 +1,120 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import java.util.Date; -import java.util.Map; - -import org.eclipse.leshan.ResponseCode; -import org.eclipse.leshan.core.model.ResourceModel.Type; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; -import org.eclipse.leshan.core.node.LwM2mNode; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.util.Validate; - -public class ReadResponse extends AbstractLwM2mResponse { - - protected final LwM2mNode content; - - public ReadResponse(ResponseCode code, LwM2mNode content, String errorMessage) { - super(code, errorMessage); - - if (ResponseCode.CONTENT.equals(code)) { - Validate.notNull(content); - } - this.content = content; - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CONTENT; - } - - /** - * Get the {@link LwM2mNode} value returned as response payload. - * - * @return the value or null if the client returned an error response. - */ - public LwM2mNode getContent() { - return content; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("ReadResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("ReadResponse [code=%s, content=%s]", code, content); - } - - // Syntactic sugar static constructors : - - public static ReadResponse success(LwM2mNode content) { - return new ReadResponse(ResponseCode.CONTENT, content, null); - } - - public static ReadResponse success(int resourceId, String value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newStringResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, Date value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newDateResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, long value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newIntegerResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, double value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newFloatResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, boolean value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newBooleanResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, byte[] value) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newBinaryResource(resourceId, value), null); - } - - public static ReadResponse success(int resourceId, Map value, Type type) { - return new ReadResponse(ResponseCode.CONTENT, LwM2mMultipleResource.newResource(resourceId, value, type), null); - } - - public static ReadResponse notFound() { - return new ReadResponse(ResponseCode.NOT_FOUND, null, null); - } - - public static ReadResponse unauthorized() { - return new ReadResponse(ResponseCode.UNAUTHORIZED, null, null); - } - - public static ReadResponse methodNotAllowed() { - return new ReadResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); - } - - public static ReadResponse notAcceptable() { - return new ReadResponse(ResponseCode.NOT_ACCEPTABLE, null, null); - } - - public static ReadResponse badRequest(String errorMessage) { - return new ReadResponse(ResponseCode.BAD_REQUEST, null, errorMessage); - } - - public static ReadResponse internalServerError(String errorMessage) { - return new ReadResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import java.util.Date; +import java.util.Map; + +import org.eclipse.leshan.ResponseCode; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.util.Validate; + +public class ReadResponse extends AbstractLwM2mResponse { + + protected final LwM2mNode content; + + public ReadResponse(ResponseCode code, LwM2mNode content, String errorMessage) { + super(code, errorMessage); + + if (ResponseCode.CONTENT.equals(code)) { + Validate.notNull(content); + } + this.content = content; + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CONTENT; + } + + /** + * Get the {@link LwM2mNode} value returned as response payload. + * + * @return the value or null if the client returned an error response. + */ + public LwM2mNode getContent() { + return content; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("ReadResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("ReadResponse [code=%s, content=%s]", code, content); + } + + // Syntactic sugar static constructors : + + public static ReadResponse success(LwM2mNode content) { + return new ReadResponse(ResponseCode.CONTENT, content, null); + } + + public static ReadResponse success(int resourceId, String value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newStringResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, Date value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newDateResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, long value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newIntegerResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, double value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newFloatResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, boolean value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newBooleanResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, byte[] value) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mSingleResource.newBinaryResource(resourceId, value), null); + } + + public static ReadResponse success(int resourceId, Map value, Type type) { + return new ReadResponse(ResponseCode.CONTENT, LwM2mMultipleResource.newResource(resourceId, value, type), null); + } + + public static ReadResponse notFound() { + return new ReadResponse(ResponseCode.NOT_FOUND, null, null); + } + + public static ReadResponse unauthorized() { + return new ReadResponse(ResponseCode.UNAUTHORIZED, null, null); + } + + public static ReadResponse methodNotAllowed() { + return new ReadResponse(ResponseCode.METHOD_NOT_ALLOWED, null, null); + } + + public static ReadResponse notAcceptable() { + return new ReadResponse(ResponseCode.NOT_ACCEPTABLE, null, null); + } + + public static ReadResponse badRequest(String errorMessage) { + return new ReadResponse(ResponseCode.BAD_REQUEST, null, errorMessage); + } + + public static ReadResponse internalServerError(String errorMessage) { + return new ReadResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/RegisterResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/RegisterResponse.java index a29ed8e..59dfd03 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/RegisterResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/RegisterResponse.java @@ -1,66 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -/** - * Response to a client registration request - */ -public class RegisterResponse extends AbstractLwM2mResponse { - - private final String registrationID; - - public RegisterResponse(ResponseCode code, String registrationID, String errorMessage) { - super(code, errorMessage); - this.registrationID = registrationID; - } - - public String getRegistrationID() { - return registrationID; - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CREATED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("RegisterResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("RegisterResponse [code=%s, registrationID=%s]", code, registrationID); - } - - // Syntactic sugar static constructors : - - public static RegisterResponse success(String registrationID) { - return new RegisterResponse(ResponseCode.CREATED, registrationID, null); - } - - public static RegisterResponse badRequest(String errorMessage) { - return new RegisterResponse(ResponseCode.BAD_REQUEST, null, errorMessage); - } - - public static RegisterResponse forbidden(String errorMessage) { - return new RegisterResponse(ResponseCode.FORBIDDEN, null, errorMessage); - } - - public static RegisterResponse internalServerError(String errorMessage) { - return new RegisterResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +/** + * Response to a client registration request + */ +public class RegisterResponse extends AbstractLwM2mResponse { + + private final String registrationID; + + public RegisterResponse(ResponseCode code, String registrationID, String errorMessage) { + super(code, errorMessage); + this.registrationID = registrationID; + } + + public String getRegistrationID() { + return registrationID; + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CREATED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("RegisterResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("RegisterResponse [code=%s, registrationID=%s]", code, registrationID); + } + + // Syntactic sugar static constructors : + + public static RegisterResponse success(String registrationID) { + return new RegisterResponse(ResponseCode.CREATED, registrationID, null); + } + + public static RegisterResponse badRequest(String errorMessage) { + return new RegisterResponse(ResponseCode.BAD_REQUEST, null, errorMessage); + } + + public static RegisterResponse forbidden(String errorMessage) { + return new RegisterResponse(ResponseCode.FORBIDDEN, null, errorMessage); + } + + public static RegisterResponse internalServerError(String errorMessage) { + return new RegisterResponse(ResponseCode.INTERNAL_SERVER_ERROR, null, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ResponseCallback.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ResponseCallback.java index 9779ed7..fd3286c 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ResponseCallback.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/ResponseCallback.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -/** - * On success callback for LWM2M request. - */ -public interface ResponseCallback { - // We should keep this as a 1 method interface to be java 8 lambda compatible. - - /** - * Called when the request succeed. - */ - void onResponse(T response); - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +/** + * On success callback for LWM2M request. + */ +public interface ResponseCallback { + // We should keep this as a 1 method interface to be java 8 lambda compatible. + + /** + * Called when the request succeed. + */ + void onResponse(T response); + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/UpdateResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/UpdateResponse.java index bebcdfd..52f76ce 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/UpdateResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/UpdateResponse.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class UpdateResponse extends AbstractLwM2mResponse { - - public UpdateResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("UpdateResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("UpdateResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static UpdateResponse success() { - return new UpdateResponse(ResponseCode.CHANGED, null); - } - - public static UpdateResponse badRequest(String errorMessage) { - return new UpdateResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static UpdateResponse notFound() { - return new UpdateResponse(ResponseCode.NOT_FOUND, null); - } - - public static UpdateResponse internalServerError(String errorMessage) { - return new UpdateResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class UpdateResponse extends AbstractLwM2mResponse { + + public UpdateResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("UpdateResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("UpdateResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static UpdateResponse success() { + return new UpdateResponse(ResponseCode.CHANGED, null); + } + + public static UpdateResponse badRequest(String errorMessage) { + return new UpdateResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static UpdateResponse notFound() { + return new UpdateResponse(ResponseCode.NOT_FOUND, null); + } + + public static UpdateResponse internalServerError(String errorMessage) { + return new UpdateResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteAttributesResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteAttributesResponse.java index c7da56f..d8643bb 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteAttributesResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteAttributesResponse.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class WriteAttributesResponse extends AbstractLwM2mResponse { - - public WriteAttributesResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("WriteAttributesResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("WriteAttributesResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static WriteAttributesResponse success() { - return new WriteAttributesResponse(ResponseCode.CHANGED, null); - } - - public static WriteAttributesResponse badRequest(String errorMessage) { - return new WriteAttributesResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static WriteAttributesResponse notFound() { - return new WriteAttributesResponse(ResponseCode.NOT_FOUND, null); - } - - public static WriteAttributesResponse unauthorized() { - return new WriteAttributesResponse(ResponseCode.UNAUTHORIZED, null); - } - - public static WriteAttributesResponse methodNotAllowed() { - return new WriteAttributesResponse(ResponseCode.METHOD_NOT_ALLOWED, null); - } - - public static WriteAttributesResponse internalServerError(String errorMessage) { - return new WriteAttributesResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class WriteAttributesResponse extends AbstractLwM2mResponse { + + public WriteAttributesResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("WriteAttributesResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("WriteAttributesResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static WriteAttributesResponse success() { + return new WriteAttributesResponse(ResponseCode.CHANGED, null); + } + + public static WriteAttributesResponse badRequest(String errorMessage) { + return new WriteAttributesResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static WriteAttributesResponse notFound() { + return new WriteAttributesResponse(ResponseCode.NOT_FOUND, null); + } + + public static WriteAttributesResponse unauthorized() { + return new WriteAttributesResponse(ResponseCode.UNAUTHORIZED, null); + } + + public static WriteAttributesResponse methodNotAllowed() { + return new WriteAttributesResponse(ResponseCode.METHOD_NOT_ALLOWED, null); + } + + public static WriteAttributesResponse internalServerError(String errorMessage) { + return new WriteAttributesResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteResponse.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteResponse.java index 5acd702..defcd9e 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteResponse.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/response/WriteResponse.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.core.response; - -import org.eclipse.leshan.ResponseCode; - -public class WriteResponse extends AbstractLwM2mResponse { - - public WriteResponse(final ResponseCode code, final String errorMessage) { - super(code, errorMessage); - } - - @Override - public boolean isSuccess() { - return getCode() == ResponseCode.CHANGED; - } - - @Override - public String toString() { - if (errorMessage != null) - return String.format("WriteResponse [code=%s, errormessage=%s]", code, errorMessage); - else - return String.format("WriteResponse [code=%s]", code); - } - - // Syntactic sugar static constructors : - - public static WriteResponse success() { - return new WriteResponse(ResponseCode.CHANGED, null); - } - - public static WriteResponse badRequest(String errorMessage) { - return new WriteResponse(ResponseCode.BAD_REQUEST, errorMessage); - } - - public static WriteResponse notFound() { - return new WriteResponse(ResponseCode.NOT_FOUND, null); - } - - public static WriteResponse unauthorized() { - return new WriteResponse(ResponseCode.UNAUTHORIZED, null); - } - - public static WriteResponse methodNotAllowed() { - return new WriteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); - } - - public static WriteResponse unsupportedContentFormat() { - return new WriteResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null); - } - - public static WriteResponse internalServerError(String errorMessage) { - return new WriteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); - } -} +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.core.response; + +import org.eclipse.leshan.ResponseCode; + +public class WriteResponse extends AbstractLwM2mResponse { + + public WriteResponse(final ResponseCode code, final String errorMessage) { + super(code, errorMessage); + } + + @Override + public boolean isSuccess() { + return getCode() == ResponseCode.CHANGED; + } + + @Override + public String toString() { + if (errorMessage != null) + return String.format("WriteResponse [code=%s, errormessage=%s]", code, errorMessage); + else + return String.format("WriteResponse [code=%s]", code); + } + + // Syntactic sugar static constructors : + + public static WriteResponse success() { + return new WriteResponse(ResponseCode.CHANGED, null); + } + + public static WriteResponse badRequest(String errorMessage) { + return new WriteResponse(ResponseCode.BAD_REQUEST, errorMessage); + } + + public static WriteResponse notFound() { + return new WriteResponse(ResponseCode.NOT_FOUND, null); + } + + public static WriteResponse unauthorized() { + return new WriteResponse(ResponseCode.UNAUTHORIZED, null); + } + + public static WriteResponse methodNotAllowed() { + return new WriteResponse(ResponseCode.METHOD_NOT_ALLOWED, null); + } + + public static WriteResponse unsupportedContentFormat() { + return new WriteResponse(ResponseCode.UNSUPPORTED_CONTENT_FORMAT, null); + } + + public static WriteResponse internalServerError(String errorMessage) { + return new WriteResponse(ResponseCode.INTERNAL_SERVER_ERROR, errorMessage); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonArrayEntry.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonArrayEntry.java index 2a8bfd1..e576401 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonArrayEntry.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonArrayEntry.java @@ -1,170 +1,170 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ - -package org.eclipse.leshan.json; - -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.model.ResourceModel.Type; - -import com.google.gson.annotations.SerializedName; - -public class JsonArrayEntry { - - @SerializedName("n") - private String name; - - @SerializedName("v") - private Number floatValue; - - @SerializedName("bv") - private Boolean booleanValue; - - @SerializedName("ov") - private String objectLinkValue; - - @SerializedName("sv") - private String stringValue; - - @SerializedName("t") - private Long time; - - public ResourceModel.Type getType() { - if (booleanValue != null) { - return Type.BOOLEAN; - } - if (floatValue != null) { - return Type.FLOAT; - } - if (objectLinkValue != null) { - // TODO handle object link or not .. - return null; - } - if (stringValue != null) { - return Type.STRING; - } - return null; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getTime() { - return time; - } - - public void setTime(Long time) { - this.time = time; - } - - public void setFloatValue(Number floatValue) { - this.floatValue = floatValue; - } - - public void setBooleanValue(Boolean booleanValue) { - this.booleanValue = booleanValue; - } - - public void setObjectLinkValue(String objectLinkValue) { - this.objectLinkValue = objectLinkValue; - } - - public void setStringValue(String stringValue) { - this.stringValue = stringValue; - } - - public Object getResourceValue() { - - if (booleanValue != null) { - return booleanValue; - } - if (floatValue != null) { - return floatValue; - } - if (objectLinkValue != null) { - return objectLinkValue; - } - if (stringValue != null) { - return stringValue; - } - return null; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((booleanValue == null) ? 0 : booleanValue.hashCode()); - result = prime * result + ((floatValue == null) ? 0 : floatValue.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((objectLinkValue == null) ? 0 : objectLinkValue.hashCode()); - result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); - result = prime * result + ((time == null) ? 0 : time.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - JsonArrayEntry other = (JsonArrayEntry) obj; - if (booleanValue == null) { - if (other.booleanValue != null) - return false; - } else if (!booleanValue.equals(other.booleanValue)) - return false; - if (floatValue == null) { - if (other.floatValue != null) - return false; - } else if (!floatValue.equals(other.floatValue)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (objectLinkValue == null) { - if (other.objectLinkValue != null) - return false; - } else if (!objectLinkValue.equals(other.objectLinkValue)) - return false; - if (stringValue == null) { - if (other.stringValue != null) - return false; - } else if (!stringValue.equals(other.stringValue)) - return false; - if (time != other.time) - return false; - return true; - } - - @Override - public String toString() { - return String.format( - "JsonArrayElement [name=%s, floatValue=%s, booleanValue=%s, objectLinkValue=%s, stringValue=%s, time=%s]", - name, floatValue, booleanValue, objectLinkValue, stringValue, time); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ + +package org.eclipse.leshan.json; + +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; + +import com.google.gson.annotations.SerializedName; + +public class JsonArrayEntry { + + @SerializedName("n") + private String name; + + @SerializedName("v") + private Number floatValue; + + @SerializedName("bv") + private Boolean booleanValue; + + @SerializedName("ov") + private String objectLinkValue; + + @SerializedName("sv") + private String stringValue; + + @SerializedName("t") + private Long time; + + public ResourceModel.Type getType() { + if (booleanValue != null) { + return Type.BOOLEAN; + } + if (floatValue != null) { + return Type.FLOAT; + } + if (objectLinkValue != null) { + // TODO handle object link or not .. + return null; + } + if (stringValue != null) { + return Type.STRING; + } + return null; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } + + public void setFloatValue(Number floatValue) { + this.floatValue = floatValue; + } + + public void setBooleanValue(Boolean booleanValue) { + this.booleanValue = booleanValue; + } + + public void setObjectLinkValue(String objectLinkValue) { + this.objectLinkValue = objectLinkValue; + } + + public void setStringValue(String stringValue) { + this.stringValue = stringValue; + } + + public Object getResourceValue() { + + if (booleanValue != null) { + return booleanValue; + } + if (floatValue != null) { + return floatValue; + } + if (objectLinkValue != null) { + return objectLinkValue; + } + if (stringValue != null) { + return stringValue; + } + return null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((booleanValue == null) ? 0 : booleanValue.hashCode()); + result = prime * result + ((floatValue == null) ? 0 : floatValue.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((objectLinkValue == null) ? 0 : objectLinkValue.hashCode()); + result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); + result = prime * result + ((time == null) ? 0 : time.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JsonArrayEntry other = (JsonArrayEntry) obj; + if (booleanValue == null) { + if (other.booleanValue != null) + return false; + } else if (!booleanValue.equals(other.booleanValue)) + return false; + if (floatValue == null) { + if (other.floatValue != null) + return false; + } else if (!floatValue.equals(other.floatValue)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (objectLinkValue == null) { + if (other.objectLinkValue != null) + return false; + } else if (!objectLinkValue.equals(other.objectLinkValue)) + return false; + if (stringValue == null) { + if (other.stringValue != null) + return false; + } else if (!stringValue.equals(other.stringValue)) + return false; + if (time != other.time) + return false; + return true; + } + + @Override + public String toString() { + return String.format( + "JsonArrayElement [name=%s, floatValue=%s, booleanValue=%s, objectLinkValue=%s, stringValue=%s, time=%s]", + name, floatValue, booleanValue, objectLinkValue, stringValue, time); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonRootObject.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonRootObject.java index bd1d41a..be6f552 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonRootObject.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/JsonRootObject.java @@ -1,105 +1,105 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ - -package org.eclipse.leshan.json; - -import java.util.ArrayList; - -import com.google.gson.annotations.SerializedName; - -/** - * The class representing the JSON format of LWM2M - */ -public class JsonRootObject { - - @SerializedName("bn") - private String baseName = null; - - @SerializedName("e") - private final ArrayList jsonArray; - - @SerializedName("bt") - private Long baseTime; - - public JsonRootObject(ArrayList jsonArray) { - this.jsonArray = jsonArray; - } - - public String getBaseName() { - return baseName; - } - - public void setBaseName(String baseName) { - this.baseName = baseName; - } - - public Long getBaseTime() { - return baseTime; - } - - public void setBaseTime(Long baseTime) { - this.baseTime = baseTime; - } - - public ArrayList getResourceList() { - return jsonArray; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((baseName == null) ? 0 : baseName.hashCode()); - result = prime * result + ((baseTime == null) ? 0 : baseTime.hashCode()); - result = prime * result + ((jsonArray == null) ? 0 : jsonArray.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - JsonRootObject other = (JsonRootObject) obj; - if (baseName == null) { - if (other.baseName != null) - return false; - } else if (!baseName.equals(other.baseName)) - return false; - if (baseTime == null) { - if (other.baseTime != null) - return false; - } else if (!baseTime.equals(other.baseTime)) - return false; - if (jsonArray == null) { - if (other.jsonArray != null) - return false; - } else if (!jsonArray.equals(other.jsonArray)) - return false; - return true; - } - - @Override - public String toString() { - return String.format("LwM2mJsonElement [baseName=%s, baseTime=%d, resourceList=%s]", baseName, baseTime, - jsonArray); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ + +package org.eclipse.leshan.json; + +import java.util.ArrayList; + +import com.google.gson.annotations.SerializedName; + +/** + * The class representing the JSON format of LWM2M + */ +public class JsonRootObject { + + @SerializedName("bn") + private String baseName = null; + + @SerializedName("e") + private final ArrayList jsonArray; + + @SerializedName("bt") + private Long baseTime; + + public JsonRootObject(ArrayList jsonArray) { + this.jsonArray = jsonArray; + } + + public String getBaseName() { + return baseName; + } + + public void setBaseName(String baseName) { + this.baseName = baseName; + } + + public Long getBaseTime() { + return baseTime; + } + + public void setBaseTime(Long baseTime) { + this.baseTime = baseTime; + } + + public ArrayList getResourceList() { + return jsonArray; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((baseName == null) ? 0 : baseName.hashCode()); + result = prime * result + ((baseTime == null) ? 0 : baseTime.hashCode()); + result = prime * result + ((jsonArray == null) ? 0 : jsonArray.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JsonRootObject other = (JsonRootObject) obj; + if (baseName == null) { + if (other.baseName != null) + return false; + } else if (!baseName.equals(other.baseName)) + return false; + if (baseTime == null) { + if (other.baseTime != null) + return false; + } else if (!baseTime.equals(other.baseTime)) + return false; + if (jsonArray == null) { + if (other.jsonArray != null) + return false; + } else if (!jsonArray.equals(other.jsonArray)) + return false; + return true; + } + + @Override + public String toString() { + return String.format("LwM2mJsonElement [baseName=%s, baseTime=%d, resourceList=%s]", baseName, baseTime, + jsonArray); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJson.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJson.java index 9f538f1..fdf1466 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJson.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJson.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ - -package org.eclipse.leshan.json; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; - -/** - * Helper for encoding/decoding LWM2M JSON format - */ -public class LwM2mJson { - - private static final Gson gson = new GsonBuilder().create(); - - public static String toJsonLwM2m(JsonRootObject lwM2mJsonElement) { - String json = gson.toJson(lwM2mJsonElement); - return json; - } - - public static JsonRootObject fromJsonLwM2m(String jsonString) throws LwM2mJsonException { - try { - JsonRootObject element = gson.fromJson(jsonString, JsonRootObject.class); - return element; - } catch (JsonSyntaxException e) { - throw new LwM2mJsonException("Unable to deserialize JSON String to JsonRootObject ", e); - } - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ + +package org.eclipse.leshan.json; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; + +/** + * Helper for encoding/decoding LWM2M JSON format + */ +public class LwM2mJson { + + private static final Gson gson = new GsonBuilder().create(); + + public static String toJsonLwM2m(JsonRootObject lwM2mJsonElement) { + String json = gson.toJson(lwM2mJsonElement); + return json; + } + + public static JsonRootObject fromJsonLwM2m(String jsonString) throws LwM2mJsonException { + try { + JsonRootObject element = gson.fromJson(jsonString, JsonRootObject.class); + return element; + } catch (JsonSyntaxException e) { + throw new LwM2mJsonException("Unable to deserialize JSON String to JsonRootObject ", e); + } + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJsonException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJsonException.java index aed9780..71faff1 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJsonException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/json/LwM2mJsonException.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - * Gemalto M2M GmbH - *******************************************************************************/ -package org.eclipse.leshan.json; - -/** - * Exception thrown in case of JSON parsing error - */ -public class LwM2mJsonException extends Exception { - - private static final long serialVersionUID = 1L; - - public LwM2mJsonException(String message) { - super(message); - } - - public LwM2mJsonException(String message, Exception cause) { - super(message, cause); - } - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Gemalto M2M GmbH + *******************************************************************************/ +package org.eclipse.leshan.json; + +/** + * Exception thrown in case of JSON parsing error + */ +public class LwM2mJsonException extends Exception { + + private static final long serialVersionUID = 1L; + + public LwM2mJsonException(String message) { + super(message); + } + + public LwM2mJsonException(String message, Exception cause) { + super(message, cause); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/Tlv.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/Tlv.java index e7d9e44..9effdff 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/Tlv.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/Tlv.java @@ -1,140 +1,140 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.tlv; - -import java.util.Arrays; - -/** - * A Type-Length-Value container, can contain multiple TLV entries. - */ -public class Tlv { - - // type of TLV, indicate if it's containing a value or TLV containing more TLV or values - private TlvType type; - - // if of type OBJECT_INSTANCE,MULTIPLE_RESOURCE or null - private Tlv[] children; - - // if type RESOURCE_VALUE or RESOURCE_INSTANCE => null - private byte[] value; - - private int identifier; - - /** - * Creates a TLV container. - * - * @param type the type of TLV - * @param children the list of children TLV (must be null for type {@link TlvType#RESOURCE_VALUE} - * @param value the raw contained value, only for type {@link TlvType#RESOURCE_VALUE} null for the - * other types - * @param identifier the TLV identifier (resource id, instance id,..) - */ - public Tlv(TlvType type, Tlv[] children, byte[] value, int identifier) { - this.type = type; - this.children = children; - this.value = value; - this.identifier = identifier; - - if (type == TlvType.RESOURCE_VALUE || type == TlvType.RESOURCE_INSTANCE) { - if (value == null) { - throw new IllegalArgumentException("a " + type.name() + " must have a value"); - } else if (children != null) { - throw new IllegalArgumentException("a " + type.name() + " can't have children"); - } - } else { - if (value != null) { - throw new IllegalArgumentException("a " + type.name() + " can't have a value"); - } else if (children == null) { - throw new IllegalArgumentException("a " + type.name() + " must have children"); - } - } - } - - public TlvType getType() { - return type; - } - - public void setType(TlvType type) { - this.type = type; - } - - public Tlv[] getChildren() { - return children; - } - - public void setChildren(Tlv[] children) { - this.children = children; - } - - public byte[] getValue() { - return value; - } - - public void setValue(byte[] value) { - this.value = value; - } - - public int getIdentifier() { - return identifier; - } - - public void setIdentifier(int identifier) { - this.identifier = identifier; - } - - public enum TlvType { - OBJECT_INSTANCE, RESOURCE_INSTANCE, MULTIPLE_RESOURCE, RESOURCE_VALUE; - } - - @Override - public String toString() { - return String.format( - "Tlv [type=%s, children=%s, value=%s, identifier=%s]", - new Object[] { type.name(), Arrays.toString(children), Arrays.toString(value), - Integer.toString(identifier) }); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(children); - result = prime * result + identifier; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + Arrays.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Tlv other = (Tlv) obj; - if (!Arrays.equals(children, other.children)) - return false; - if (identifier != other.identifier) - return false; - if (type != other.type) - return false; - if (!Arrays.equals(value, other.value)) - return false; - return true; - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.tlv; + +import java.util.Arrays; + +/** + * A Type-Length-Value container, can contain multiple TLV entries. + */ +public class Tlv { + + // type of TLV, indicate if it's containing a value or TLV containing more TLV or values + private TlvType type; + + // if of type OBJECT_INSTANCE,MULTIPLE_RESOURCE or null + private Tlv[] children; + + // if type RESOURCE_VALUE or RESOURCE_INSTANCE => null + private byte[] value; + + private int identifier; + + /** + * Creates a TLV container. + * + * @param type the type of TLV + * @param children the list of children TLV (must be null for type {@link TlvType#RESOURCE_VALUE} + * @param value the raw contained value, only for type {@link TlvType#RESOURCE_VALUE} null for the + * other types + * @param identifier the TLV identifier (resource id, instance id,..) + */ + public Tlv(TlvType type, Tlv[] children, byte[] value, int identifier) { + this.type = type; + this.children = children; + this.value = value; + this.identifier = identifier; + + if (type == TlvType.RESOURCE_VALUE || type == TlvType.RESOURCE_INSTANCE) { + if (value == null) { + throw new IllegalArgumentException("a " + type.name() + " must have a value"); + } else if (children != null) { + throw new IllegalArgumentException("a " + type.name() + " can't have children"); + } + } else { + if (value != null) { + throw new IllegalArgumentException("a " + type.name() + " can't have a value"); + } else if (children == null) { + throw new IllegalArgumentException("a " + type.name() + " must have children"); + } + } + } + + public TlvType getType() { + return type; + } + + public void setType(TlvType type) { + this.type = type; + } + + public Tlv[] getChildren() { + return children; + } + + public void setChildren(Tlv[] children) { + this.children = children; + } + + public byte[] getValue() { + return value; + } + + public void setValue(byte[] value) { + this.value = value; + } + + public int getIdentifier() { + return identifier; + } + + public void setIdentifier(int identifier) { + this.identifier = identifier; + } + + public enum TlvType { + OBJECT_INSTANCE, RESOURCE_INSTANCE, MULTIPLE_RESOURCE, RESOURCE_VALUE; + } + + @Override + public String toString() { + return String.format( + "Tlv [type=%s, children=%s, value=%s, identifier=%s]", + new Object[] { type.name(), Arrays.toString(children), Arrays.toString(value), + Integer.toString(identifier) }); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(children); + result = prime * result + identifier; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + Arrays.hashCode(value); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Tlv other = (Tlv) obj; + if (!Arrays.equals(children, other.children)) + return false; + if (identifier != other.identifier) + return false; + if (type != other.type) + return false; + if (!Arrays.equals(value, other.value)) + return false; + return true; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvDecoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvDecoder.java index 792d745..9cd6554 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvDecoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvDecoder.java @@ -1,218 +1,218 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.tlv; - -import java.math.BigInteger; -import java.nio.BufferOverflowException; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.eclipse.leshan.tlv.Tlv.TlvType; -import org.eclipse.leshan.util.Charsets; -import org.eclipse.leshan.util.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TlvDecoder { - - private static final Logger LOG = LoggerFactory.getLogger(TlvDecoder.class); - - public static Tlv[] decode(ByteBuffer input) throws TlvException { - - try { - List tlvs = new ArrayList<>(); - - while (input.remaining() > 0) { - input.order(ByteOrder.BIG_ENDIAN); - - // decode type - int typeByte = input.get() & 0xFF; - TlvType type; - switch (typeByte & 0b1100_0000) { - case 0b0000_0000: - type = TlvType.OBJECT_INSTANCE; - break; - case 0b0100_0000: - type = TlvType.RESOURCE_INSTANCE; - break; - case 0b1000_0000: - type = TlvType.MULTIPLE_RESOURCE; - break; - case 0b1100_0000: - type = TlvType.RESOURCE_VALUE; - break; - default: - throw new TlvException("unknown type: " + (typeByte & 0b1100_0000)); - } - - // decode identifier - int identifier; - try { - if ((typeByte & 0b0010_0000) == 0) { - identifier = input.get() & 0xFF; - } else { - identifier = input.getShort() & 0xFFFF; - } - } catch (BufferUnderflowException e) { - throw new TlvException("Invalid 'identifier' length", e); - } - LOG.trace("decoding {} {}", type, identifier); - - // decode length - int length; - int lengthType = typeByte & 0b0001_1000; - try { - switch (lengthType) { - case 0b0000_0000: - // 2 bit length - length = typeByte & 0b0000_0111; - break; - case 0b0000_1000: - // 8 bit length - length = input.get() & 0xFF; - break; - case 0b0001_0000: - // 16 bit length - length = input.getShort() & 0xFFFF; - break; - case 0b0001_1000: - // 24 bit length - int b = input.get() & 0x000000FF; - int s = input.getShort() & 0x0000FFFF; - length = (b << 16) | s; - break; - default: - throw new TlvException("unknown length type: " + (typeByte & 0b0001_1000)); - } - } catch (BufferUnderflowException e) { - throw new TlvException("Invalid 'length' length", e); - } - LOG.trace("length: {} (length type: {})", length, lengthType); - - // decode value - if (type == TlvType.RESOURCE_VALUE || type == TlvType.RESOURCE_INSTANCE) { - try { - byte[] payload = new byte[length]; - input.get(payload); - tlvs.add(new Tlv(type, null, payload, identifier)); - - if (LOG.isTraceEnabled()) { - LOG.trace("payload value: {}", Hex.encodeHexString(payload)); - } - } catch (BufferOverflowException e) { - throw new TlvException("Invalid 'value' length", e); - } - } else { - try { - // create a view of the contained TLVs - ByteBuffer slice = input.slice(); - slice.limit(length); - - Tlv[] children = decode(slice); - - // skip the children, it will be decoded by the view - input.position(input.position() + length); - - Tlv tlv = new Tlv(type, children, null, identifier); - tlvs.add(tlv); - } catch (IllegalArgumentException e) { - throw new TlvException("Invalid 'value' length", e); - } - } - } - - return tlvs.toArray(new Tlv[] {}); - } catch (TlvException ex) { - String printHexBinary = Hex.encodeHexString(input.array()); - throw new TlvException("Impossible to parse TLV: \n" + printHexBinary, ex); - } catch (RuntimeException ex) { - String printHexBinary = Hex.encodeHexString(input.array()); - throw new TlvException("Unexpected TLV parse error: \n" + printHexBinary, ex); - } - } - - /** - * Decodes a byte array into string value. - */ - public static String decodeString(byte[] value) { - return new String(value, Charsets.UTF_8); - } - - /** - * Decodes a byte array into a boolean value. - */ - public static boolean decodeBoolean(byte[] value) throws TlvException { - if (value.length == 1) { - if (value[0] == 0) { - return false; - } else if (value[0] == 1) { - return true; - } else { - LOG.warn("Boolean value should be encoded as integer with value 0 or 1, not {}", value[0]); - return false; - } - } - throw new TlvException("Invalid length for a boolean value: " + value.length); - } - - /** - * Decodes a byte array into a date value. - */ - public static Date decodeDate(byte[] value) throws TlvException { - BigInteger bi = new BigInteger(value); - if (value.length <= 8) { - return new Date(bi.longValue() * 1000L); - } else { - throw new TlvException("Invalid length for a time value: " + value.length); - } - } - - /** - * Decodes a byte array into an integer value. - */ - public static Number decodeInteger(byte[] value) throws TlvException { - BigInteger bi = new BigInteger(value); - if (value.length == 1) { - return bi.byteValue(); - } else if (value.length <= 2) { - return bi.shortValue(); - } else if (value.length <= 4) { - return bi.intValue(); - } else if (value.length <= 8) { - return bi.longValue(); - } else { - throw new TlvException("Invalid length for an integer value: " + value.length); - } - } - - /** - * Decodes a byte array into a float value. - */ - public static Number decodeFloat(byte[] value) throws TlvException { - ByteBuffer floatBb = ByteBuffer.wrap(value); - if (value.length == 4) { - return floatBb.getFloat(); - } else if (value.length == 8) { - return floatBb.getDouble(); - } else { - throw new TlvException("Invalid length for a float value: " + value.length); - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.tlv; + +import java.math.BigInteger; +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.eclipse.leshan.tlv.Tlv.TlvType; +import org.eclipse.leshan.util.Charsets; +import org.eclipse.leshan.util.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TlvDecoder { + + private static final Logger LOG = LoggerFactory.getLogger(TlvDecoder.class); + + public static Tlv[] decode(ByteBuffer input) throws TlvException { + + try { + List tlvs = new ArrayList<>(); + + while (input.remaining() > 0) { + input.order(ByteOrder.BIG_ENDIAN); + + // decode type + int typeByte = input.get() & 0xFF; + TlvType type; + switch (typeByte & 0b1100_0000) { + case 0b0000_0000: + type = TlvType.OBJECT_INSTANCE; + break; + case 0b0100_0000: + type = TlvType.RESOURCE_INSTANCE; + break; + case 0b1000_0000: + type = TlvType.MULTIPLE_RESOURCE; + break; + case 0b1100_0000: + type = TlvType.RESOURCE_VALUE; + break; + default: + throw new TlvException("unknown type: " + (typeByte & 0b1100_0000)); + } + + // decode identifier + int identifier; + try { + if ((typeByte & 0b0010_0000) == 0) { + identifier = input.get() & 0xFF; + } else { + identifier = input.getShort() & 0xFFFF; + } + } catch (BufferUnderflowException e) { + throw new TlvException("Invalid 'identifier' length", e); + } + LOG.trace("decoding {} {}", type, identifier); + + // decode length + int length; + int lengthType = typeByte & 0b0001_1000; + try { + switch (lengthType) { + case 0b0000_0000: + // 2 bit length + length = typeByte & 0b0000_0111; + break; + case 0b0000_1000: + // 8 bit length + length = input.get() & 0xFF; + break; + case 0b0001_0000: + // 16 bit length + length = input.getShort() & 0xFFFF; + break; + case 0b0001_1000: + // 24 bit length + int b = input.get() & 0x000000FF; + int s = input.getShort() & 0x0000FFFF; + length = (b << 16) | s; + break; + default: + throw new TlvException("unknown length type: " + (typeByte & 0b0001_1000)); + } + } catch (BufferUnderflowException e) { + throw new TlvException("Invalid 'length' length", e); + } + LOG.trace("length: {} (length type: {})", length, lengthType); + + // decode value + if (type == TlvType.RESOURCE_VALUE || type == TlvType.RESOURCE_INSTANCE) { + try { + byte[] payload = new byte[length]; + input.get(payload); + tlvs.add(new Tlv(type, null, payload, identifier)); + + if (LOG.isTraceEnabled()) { + LOG.trace("payload value: {}", Hex.encodeHexString(payload)); + } + } catch (BufferOverflowException e) { + throw new TlvException("Invalid 'value' length", e); + } + } else { + try { + // create a view of the contained TLVs + ByteBuffer slice = input.slice(); + slice.limit(length); + + Tlv[] children = decode(slice); + + // skip the children, it will be decoded by the view + input.position(input.position() + length); + + Tlv tlv = new Tlv(type, children, null, identifier); + tlvs.add(tlv); + } catch (IllegalArgumentException e) { + throw new TlvException("Invalid 'value' length", e); + } + } + } + + return tlvs.toArray(new Tlv[] {}); + } catch (TlvException ex) { + String printHexBinary = Hex.encodeHexString(input.array()); + throw new TlvException("Impossible to parse TLV: \n" + printHexBinary, ex); + } catch (RuntimeException ex) { + String printHexBinary = Hex.encodeHexString(input.array()); + throw new TlvException("Unexpected TLV parse error: \n" + printHexBinary, ex); + } + } + + /** + * Decodes a byte array into string value. + */ + public static String decodeString(byte[] value) { + return new String(value, Charsets.UTF_8); + } + + /** + * Decodes a byte array into a boolean value. + */ + public static boolean decodeBoolean(byte[] value) throws TlvException { + if (value.length == 1) { + if (value[0] == 0) { + return false; + } else if (value[0] == 1) { + return true; + } else { + LOG.warn("Boolean value should be encoded as integer with value 0 or 1, not {}", value[0]); + return false; + } + } + throw new TlvException("Invalid length for a boolean value: " + value.length); + } + + /** + * Decodes a byte array into a date value. + */ + public static Date decodeDate(byte[] value) throws TlvException { + BigInteger bi = new BigInteger(value); + if (value.length <= 8) { + return new Date(bi.longValue() * 1000L); + } else { + throw new TlvException("Invalid length for a time value: " + value.length); + } + } + + /** + * Decodes a byte array into an integer value. + */ + public static Number decodeInteger(byte[] value) throws TlvException { + BigInteger bi = new BigInteger(value); + if (value.length == 1) { + return bi.byteValue(); + } else if (value.length <= 2) { + return bi.shortValue(); + } else if (value.length <= 4) { + return bi.intValue(); + } else if (value.length <= 8) { + return bi.longValue(); + } else { + throw new TlvException("Invalid length for an integer value: " + value.length); + } + } + + /** + * Decodes a byte array into a float value. + */ + public static Number decodeFloat(byte[] value) throws TlvException { + ByteBuffer floatBb = ByteBuffer.wrap(value); + if (value.length == 4) { + return floatBb.getFloat(); + } else if (value.length == 8) { + return floatBb.getDouble(); + } else { + throw new TlvException("Invalid length for a float value: " + value.length); + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvEncoder.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvEncoder.java index da5f14f..ba7d474 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvEncoder.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvEncoder.java @@ -1,227 +1,227 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.tlv; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Date; - -import org.eclipse.leshan.util.Charsets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TlvEncoder { - - private static final Logger LOG = LoggerFactory.getLogger(TlvEncoder.class); - - private static final int MAX_LENGTH_8BIT = 256; - private static final int MAX_LENGTH_16BIT = 65_536; - private static final int MAX_LENGTH_24BIT = 16_777_216; - - /** - * Encodes an array of TLV. - */ - public static ByteBuffer encode(Tlv[] tlvs) { - int size = 0; - - LOG.trace("start"); - for (Tlv tlv : tlvs) { - - int length = tlvEncodedLength(tlv); - size += tlvEncodedSize(tlv, length); - LOG.trace("tlv size : {}", size); - } - LOG.trace("done, size : {}", size); - ByteBuffer b = ByteBuffer.allocate(size); - b.order(ByteOrder.BIG_ENDIAN); - for (Tlv tlv : tlvs) { - encode(tlv, b); - } - b.flip(); - return b; - } - - /** - * Encodes an integer value. - */ - public static byte[] encodeInteger(Number number) { - ByteBuffer iBuf = null; - long lValue = number.longValue(); - if (lValue >= Byte.MIN_VALUE && lValue <= Byte.MAX_VALUE) { - iBuf = ByteBuffer.allocate(1); - iBuf.put((byte) lValue); - } else if (lValue >= Short.MIN_VALUE && lValue <= Short.MAX_VALUE) { - iBuf = ByteBuffer.allocate(2); - iBuf.putShort((short) lValue); - } else if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) { - iBuf = ByteBuffer.allocate(4); - iBuf.putInt((int) lValue); - } else { - iBuf = ByteBuffer.allocate(8); - iBuf.putLong(lValue); - } - return iBuf.array(); - } - - /** - * Encodes a floating point value. - */ - public static byte[] encodeFloat(Number number) { - ByteBuffer fBuf = null; - if (number instanceof Float) { - fBuf = ByteBuffer.allocate(4); - fBuf.putFloat(number.floatValue()); - } else { - fBuf = ByteBuffer.allocate(8); - fBuf.putDouble(number.doubleValue()); - } - return fBuf.array(); - } - - /** - * Encodes a boolean value. - */ - public static byte[] encodeBoolean(boolean value) { - return value ? new byte[] { 1 } : new byte[] { 0 }; - } - - /** - * Encodes a string value. - */ - public static byte[] encodeString(String value) { - return value.getBytes(Charsets.UTF_8); - } - - /** - * Encodes a date value. - */ - public static byte[] encodeDate(Date value) { - ByteBuffer tBuf = ByteBuffer.allocate(4); - tBuf.putInt((int) (value.getTime() / 1000L)); - return tBuf.array(); - } - - private static int tlvEncodedSize(Tlv tlv, int length) { - int size = 1 /* HEADER */; - size += (tlv.getIdentifier() < MAX_LENGTH_8BIT) ? 1 : 2; /* 8 bits or 16 bits identifiers */ - - if (length < 8) { - size += 0; - } else if (length < MAX_LENGTH_8BIT) { - size += 1; - } else if (length < MAX_LENGTH_16BIT) { - size += 2; - } else if (length < MAX_LENGTH_24BIT) { - size += 3; - } else { - throw new IllegalArgumentException("length should fit in max 24bits"); - } - - size += length; - return size; - } - - private static int tlvEncodedLength(Tlv tlv) { - int length; - switch (tlv.getType()) { - case RESOURCE_VALUE: - case RESOURCE_INSTANCE: - length = tlv.getValue().length; - break; - default: - length = 0; - for (Tlv child : tlv.getChildren()) { - int subLength = tlvEncodedLength(child); - length += tlvEncodedSize(child, subLength); - } - } - - return length; - } - - private static void encode(Tlv tlv, ByteBuffer b) { - int length; - length = tlvEncodedLength(tlv); - int typeByte; - - switch (tlv.getType()) { - case OBJECT_INSTANCE: - typeByte = 0b00_000000; - break; - case RESOURCE_INSTANCE: - typeByte = 0b01_000000; - break; - case MULTIPLE_RESOURCE: - typeByte = 0b10_000000; - break; - case RESOURCE_VALUE: - // encode the value - typeByte = 0b11_000000; - break; - default: - throw new IllegalArgumentException("unknown TLV type : '" + tlv.getType() + "'"); - } - - // encode identifier length - typeByte |= (tlv.getIdentifier() < MAX_LENGTH_8BIT) ? 0b00_0000 : 0b10_0000; - - // type of length - if (length < 8) { - typeByte |= length; - } else if (length < MAX_LENGTH_8BIT) { - typeByte |= 0b0000_1000; - } else if (length < MAX_LENGTH_16BIT) { - typeByte |= 0b0001_0000; - } else { - typeByte |= 0b0001_1000; - } - - // fill the buffer - b.put((byte) typeByte); - if (tlv.getIdentifier() < MAX_LENGTH_8BIT) { - b.put((byte) tlv.getIdentifier()); - } else { - b.putShort((short) tlv.getIdentifier()); - } - - // write length - - if (length >= 8) { - if (length < MAX_LENGTH_8BIT) { - b.put((byte) length); - } else if (length < MAX_LENGTH_16BIT) { - b.putShort((short) length); - } else { - int msb = (length & 0xFF_00_00) >> 16; - b.put((byte) msb); - b.putShort((short) (length & 0xFF_FF)); - typeByte |= 0b0001_1000; - } - } - - switch (tlv.getType()) { - case RESOURCE_VALUE: - case RESOURCE_INSTANCE: - b.put(tlv.getValue()); - break; - default: - for (Tlv child : tlv.getChildren()) { - encode(child, b); - } - break; - } - } -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.tlv; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Date; + +import org.eclipse.leshan.util.Charsets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TlvEncoder { + + private static final Logger LOG = LoggerFactory.getLogger(TlvEncoder.class); + + private static final int MAX_LENGTH_8BIT = 256; + private static final int MAX_LENGTH_16BIT = 65_536; + private static final int MAX_LENGTH_24BIT = 16_777_216; + + /** + * Encodes an array of TLV. + */ + public static ByteBuffer encode(Tlv[] tlvs) { + int size = 0; + + LOG.trace("start"); + for (Tlv tlv : tlvs) { + + int length = tlvEncodedLength(tlv); + size += tlvEncodedSize(tlv, length); + LOG.trace("tlv size : {}", size); + } + LOG.trace("done, size : {}", size); + ByteBuffer b = ByteBuffer.allocate(size); + b.order(ByteOrder.BIG_ENDIAN); + for (Tlv tlv : tlvs) { + encode(tlv, b); + } + b.flip(); + return b; + } + + /** + * Encodes an integer value. + */ + public static byte[] encodeInteger(Number number) { + ByteBuffer iBuf = null; + long lValue = number.longValue(); + if (lValue >= Byte.MIN_VALUE && lValue <= Byte.MAX_VALUE) { + iBuf = ByteBuffer.allocate(1); + iBuf.put((byte) lValue); + } else if (lValue >= Short.MIN_VALUE && lValue <= Short.MAX_VALUE) { + iBuf = ByteBuffer.allocate(2); + iBuf.putShort((short) lValue); + } else if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) { + iBuf = ByteBuffer.allocate(4); + iBuf.putInt((int) lValue); + } else { + iBuf = ByteBuffer.allocate(8); + iBuf.putLong(lValue); + } + return iBuf.array(); + } + + /** + * Encodes a floating point value. + */ + public static byte[] encodeFloat(Number number) { + ByteBuffer fBuf = null; + if (number instanceof Float) { + fBuf = ByteBuffer.allocate(4); + fBuf.putFloat(number.floatValue()); + } else { + fBuf = ByteBuffer.allocate(8); + fBuf.putDouble(number.doubleValue()); + } + return fBuf.array(); + } + + /** + * Encodes a boolean value. + */ + public static byte[] encodeBoolean(boolean value) { + return value ? new byte[] { 1 } : new byte[] { 0 }; + } + + /** + * Encodes a string value. + */ + public static byte[] encodeString(String value) { + return value.getBytes(Charsets.UTF_8); + } + + /** + * Encodes a date value. + */ + public static byte[] encodeDate(Date value) { + ByteBuffer tBuf = ByteBuffer.allocate(4); + tBuf.putInt((int) (value.getTime() / 1000L)); + return tBuf.array(); + } + + private static int tlvEncodedSize(Tlv tlv, int length) { + int size = 1 /* HEADER */; + size += (tlv.getIdentifier() < MAX_LENGTH_8BIT) ? 1 : 2; /* 8 bits or 16 bits identifiers */ + + if (length < 8) { + size += 0; + } else if (length < MAX_LENGTH_8BIT) { + size += 1; + } else if (length < MAX_LENGTH_16BIT) { + size += 2; + } else if (length < MAX_LENGTH_24BIT) { + size += 3; + } else { + throw new IllegalArgumentException("length should fit in max 24bits"); + } + + size += length; + return size; + } + + private static int tlvEncodedLength(Tlv tlv) { + int length; + switch (tlv.getType()) { + case RESOURCE_VALUE: + case RESOURCE_INSTANCE: + length = tlv.getValue().length; + break; + default: + length = 0; + for (Tlv child : tlv.getChildren()) { + int subLength = tlvEncodedLength(child); + length += tlvEncodedSize(child, subLength); + } + } + + return length; + } + + private static void encode(Tlv tlv, ByteBuffer b) { + int length; + length = tlvEncodedLength(tlv); + int typeByte; + + switch (tlv.getType()) { + case OBJECT_INSTANCE: + typeByte = 0b00_000000; + break; + case RESOURCE_INSTANCE: + typeByte = 0b01_000000; + break; + case MULTIPLE_RESOURCE: + typeByte = 0b10_000000; + break; + case RESOURCE_VALUE: + // encode the value + typeByte = 0b11_000000; + break; + default: + throw new IllegalArgumentException("unknown TLV type : '" + tlv.getType() + "'"); + } + + // encode identifier length + typeByte |= (tlv.getIdentifier() < MAX_LENGTH_8BIT) ? 0b00_0000 : 0b10_0000; + + // type of length + if (length < 8) { + typeByte |= length; + } else if (length < MAX_LENGTH_8BIT) { + typeByte |= 0b0000_1000; + } else if (length < MAX_LENGTH_16BIT) { + typeByte |= 0b0001_0000; + } else { + typeByte |= 0b0001_1000; + } + + // fill the buffer + b.put((byte) typeByte); + if (tlv.getIdentifier() < MAX_LENGTH_8BIT) { + b.put((byte) tlv.getIdentifier()); + } else { + b.putShort((short) tlv.getIdentifier()); + } + + // write length + + if (length >= 8) { + if (length < MAX_LENGTH_8BIT) { + b.put((byte) length); + } else if (length < MAX_LENGTH_16BIT) { + b.putShort((short) length); + } else { + int msb = (length & 0xFF_00_00) >> 16; + b.put((byte) msb); + b.putShort((short) (length & 0xFF_FF)); + typeByte |= 0b0001_1000; + } + } + + switch (tlv.getType()) { + case RESOURCE_VALUE: + case RESOURCE_INSTANCE: + b.put(tlv.getValue()); + break; + default: + for (Tlv child : tlv.getChildren()) { + encode(child, b); + } + break; + } + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvException.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvException.java index a2d5a50..962ee38 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvException.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/tlv/TlvException.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 Sierra Wireless and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Sierra Wireless - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.tlv; - -public class TlvException extends Exception { - - public TlvException(String message) { - super(message); - } - - public TlvException(String message, Exception cause) { - super(message, cause); - } - - private static final long serialVersionUID = 9017593873541376092L; - -} +/******************************************************************************* + * Copyright (c) 2013-2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.tlv; + +public class TlvException extends Exception { + + public TlvException(String message) { + super(message); + } + + public TlvException(String message, Exception cause) { + super(message, cause); + } + + private static final long serialVersionUID = 9017593873541376092L; + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Base64.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Base64.java index 6f019a2..048c6bc 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Base64.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Base64.java @@ -1,784 +1,784 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.eclipse.leshan.util; - -import java.math.BigInteger; - -/** - * Provides Base64 encoding and decoding as defined by RFC 2045. - * - *

- * This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 Multipurpose - * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies by Freed and Borenstein. - *

- *

- * The class can be parameterized in the following manner with various constructors: - *

- *
    - *
  • URL-safe mode: Default off.
  • - *
  • Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of - * 4 in the encoded data. - *
  • Line separator: Default is CRLF ("\r\n")
  • - *
- *

- * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes. - *

- *

- * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only - * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, - * UTF-8, etc). - *

- *

- * This class is thread-safe. - *

- * - * @see RFC 2045 - * @since 1.0 - * @version $Id: Base64.java 1635986 2014-11-01 16:27:52Z tn $ - */ -public class Base64 extends BaseNCodec { - - /** - * BASE32 characters are 6 bits in length. - * They are formed by taking a block of 3 octets to form a 24-bit string, - * which is converted into 4 BASE64 characters. - */ - private static final int BITS_PER_ENCODED_BYTE = 6; - private static final int BYTES_PER_UNENCODED_BLOCK = 3; - private static final int BYTES_PER_ENCODED_BLOCK = 4; - - /** - * Chunk separator per RFC 2045 section 2.1. - * - *

- * N.B. The next major release may break compatibility and make this field private. - *

- * - * @see RFC 2045 section 2.1 - */ - static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; - - /** - * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" - * equivalents as specified in Table 1 of RFC 2045. - * - * Thanks to "commons" project in ws.apache.org for this code. - * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ - */ - private static final byte[] STANDARD_ENCODE_TABLE = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' - }; - - /** - * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / - * changed to - and _ to make the encoded Base64 results more URL-SAFE. - * This table is only used when the Base64's mode is set to URL-SAFE. - */ - private static final byte[] URL_SAFE_ENCODE_TABLE = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' - }; - - /** - * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified - * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 - * alphabet but fall within the bounds of the array are translated to -1. - * - * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both - * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit). - * - * Thanks to "commons" project in ws.apache.org for this code. - * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ - */ - private static final byte[] DECODE_TABLE = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, - 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, 63, -1, 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 - }; - - /** - * Base64 uses 6-bit fields. - */ - /** Mask used to extract 6 bits, used when encoding */ - private static final int MASK_6BITS = 0x3f; - - // The static final fields above are used for the original static byte[] methods on Base64. - // The private member fields below are used with the new streaming approach, which requires - // some state be preserved between calls of encode() and decode(). - - /** - * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able - * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch - * between the two modes. - */ - private final byte[] encodeTable; - - // Only one decode table currently; keep for consistency with Base32 code - private final byte[] decodeTable = DECODE_TABLE; - - /** - * Line separator for encoding. Not used when decoding. Only used if lineLength > 0. - */ - private final byte[] lineSeparator; - - /** - * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. - * decodeSize = 3 + lineSeparator.length; - */ - private final int decodeSize; - - /** - * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. - * encodeSize = 4 + lineSeparator.length; - */ - private final int encodeSize; - - /** - * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. - *

- * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. - *

- * - *

- * When decoding all variants are supported. - *

- */ - public Base64() { - this(0); - } - - /** - * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode. - *

- * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE. - *

- * - *

- * When decoding all variants are supported. - *

- * - * @param urlSafe - * if true, URL-safe encoding is used. In most cases this should be set to - * false. - * @since 1.4 - */ - public Base64(final boolean urlSafe) { - this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe); - } - - /** - * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. - *

- * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is - * STANDARD_ENCODE_TABLE. - *

- *

- * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. - *

- *

- * When decoding all variants are supported. - *

- * - * @param lineLength - * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of - * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when - * decoding. - * @since 1.4 - */ - public Base64(final int lineLength) { - this(lineLength, CHUNK_SEPARATOR); - } - - /** - * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. - *

- * When encoding the line length and line separator are given in the constructor, and the encoding table is - * STANDARD_ENCODE_TABLE. - *

- *

- * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. - *

- *

- * When decoding all variants are supported. - *

- * - * @param lineLength - * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of - * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when - * decoding. - * @param lineSeparator - * Each line of encoded data will end with this sequence of bytes. - * @throws IllegalArgumentException - * Thrown when the provided lineSeparator included some base64 characters. - * @since 1.4 - */ - public Base64(final int lineLength, final byte[] lineSeparator) { - this(lineLength, lineSeparator, false); - } - - /** - * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. - *

- * When encoding the line length and line separator are given in the constructor, and the encoding table is - * STANDARD_ENCODE_TABLE. - *

- *

- * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. - *

- *

- * When decoding all variants are supported. - *

- * - * @param lineLength - * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of - * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when - * decoding. - * @param lineSeparator - * Each line of encoded data will end with this sequence of bytes. - * @param urlSafe - * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode - * operations. Decoding seamlessly handles both modes. - * Note: no padding is added when using the URL-safe alphabet. - * @throws IllegalArgumentException - * The provided lineSeparator included some base64 characters. That's not going to work! - * @since 1.4 - */ - public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) { - super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, - lineLength, - lineSeparator == null ? 0 : lineSeparator.length); - // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0 - // @see test case Base64Test.testConstructors() - if (lineSeparator != null) { - if (containsAlphabetOrPad(lineSeparator)) { - final String sep = StringUtils.newStringUtf8(lineSeparator); - throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]"); - } - if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE - this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; - this.lineSeparator = new byte[lineSeparator.length]; - System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); - } else { - this.encodeSize = BYTES_PER_ENCODED_BLOCK; - this.lineSeparator = null; - } - } else { - this.encodeSize = BYTES_PER_ENCODED_BLOCK; - this.lineSeparator = null; - } - this.decodeSize = this.encodeSize - 1; - this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE; - } - - /** - * Returns our current encode mode. True if we're URL-SAFE, false otherwise. - * - * @return true if we're in URL-SAFE mode, false otherwise. - * @since 1.4 - */ - public boolean isUrlSafe() { - return this.encodeTable == URL_SAFE_ENCODE_TABLE; - } - - /** - *

- * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with - * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last - * remaining bytes (if not multiple of 3). - *

- *

Note: no padding is added when encoding using the URL-safe alphabet.

- *

- * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. - * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ - *

- * - * @param in - * byte[] array of binary data to base64 encode. - * @param inPos - * Position to start reading data from. - * @param inAvail - * Amount of bytes available from input for encoding. - * @param context - * the context to be used - */ - @Override - void encode(final byte[] in, int inPos, final int inAvail, final Context context) { - if (context.eof) { - return; - } - // inAvail < 0 is how we're informed of EOF in the underlying data we're - // encoding. - if (inAvail < 0) { - context.eof = true; - if (0 == context.modulus && lineLength == 0) { - return; // no leftovers to process and not using chunking - } - final byte[] buffer = ensureBufferSize(encodeSize, context); - final int savedPos = context.pos; - switch (context.modulus) { // 0-2 - case 0 : // nothing to do here - break; - case 1 : // 8 bits = 6 + 2 - // top 6 bits: - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS]; - // remaining 2: - buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS]; - // URL-SAFE skips the padding to further reduce size. - if (encodeTable == STANDARD_ENCODE_TABLE) { - buffer[context.pos++] = pad; - buffer[context.pos++] = pad; - } - break; - - case 2 : // 16 bits = 6 + 6 + 4 - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS]; - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS]; - buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS]; - // URL-SAFE skips the padding to further reduce size. - if (encodeTable == STANDARD_ENCODE_TABLE) { - buffer[context.pos++] = pad; - } - break; - default: - throw new IllegalStateException("Impossible modulus "+context.modulus); - } - context.currentLinePos += context.pos - savedPos; // keep track of current line position - // if currentPos == 0 we are at the start of a line, so don't add CRLF - if (lineLength > 0 && context.currentLinePos > 0) { - System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); - context.pos += lineSeparator.length; - } - } else { - for (int i = 0; i < inAvail; i++) { - final byte[] buffer = ensureBufferSize(encodeSize, context); - context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; - int b = in[inPos++]; - if (b < 0) { - b += 256; - } - context.ibitWorkArea = (context.ibitWorkArea << 8) + b; // BITS_PER_BYTE - if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS]; - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS]; - buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS]; - buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS]; - context.currentLinePos += BYTES_PER_ENCODED_BLOCK; - if (lineLength > 0 && lineLength <= context.currentLinePos) { - System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); - context.pos += lineSeparator.length; - context.currentLinePos = 0; - } - } - } - } - } - - /** - *

- * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once - * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1" - * call is not necessary when decoding, but it doesn't hurt, either. - *

- *

- * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are - * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, - * garbage-out philosophy: it will not check the provided data for validity. - *

- *

- * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. - * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ - *

- * - * @param in - * byte[] array of ascii data to base64 decode. - * @param inPos - * Position to start reading data from. - * @param inAvail - * Amount of bytes available from input for encoding. - * @param context - * the context to be used - */ - @Override - void decode(final byte[] in, int inPos, final int inAvail, final Context context) { - if (context.eof) { - return; - } - if (inAvail < 0) { - context.eof = true; - } - for (int i = 0; i < inAvail; i++) { - final byte[] buffer = ensureBufferSize(decodeSize, context); - final byte b = in[inPos++]; - if (b == pad) { - // We're done. - context.eof = true; - break; - } else { - if (b >= 0 && b < DECODE_TABLE.length) { - final int result = DECODE_TABLE[b]; - if (result >= 0) { - context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK; - context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result; - if (context.modulus == 0) { - buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS); - buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); - buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS); - } - } - } - } - } - - // Two forms of EOF as far as base64 decoder is concerned: actual - // EOF (-1) and first time '=' character is encountered in stream. - // This approach makes the '=' padding characters completely optional. - if (context.eof && context.modulus != 0) { - final byte[] buffer = ensureBufferSize(decodeSize, context); - - // We have some spare bits remaining - // Output all whole multiples of 8 bits and ignore the rest - switch (context.modulus) { -// case 0 : // impossible, as excluded above - case 1 : // 6 bits - ignore entirely - // TODO not currently tested; perhaps it is impossible? - break; - case 2 : // 12 bits = 8 + 4 - context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits - buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); - break; - case 3 : // 18 bits = 8 + 8 + 2 - context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits - buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); - buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); - break; - default: - throw new IllegalStateException("Impossible modulus "+context.modulus); - } - } - } - - /** - * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the - * method treats whitespace as valid. - * - * @param arrayOctet - * byte array to test - * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; - * false, otherwise - * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0. - */ - @Deprecated - public static boolean isArrayByteBase64(final byte[] arrayOctet) { - return isBase64(arrayOctet); - } - - /** - * Returns whether or not the octet is in the base 64 alphabet. - * - * @param octet - * The value to test - * @return true if the value is defined in the the base 64 alphabet, false otherwise. - * @since 1.4 - */ - public static boolean isBase64(final byte octet) { - return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1); - } - - /** - * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the - * method treats whitespace as valid. - * - * @param base64 - * String to test - * @return true if all characters in the String are valid characters in the Base64 alphabet or if - * the String is empty; false, otherwise - * @since 1.5 - */ - public static boolean isBase64(final String base64) { - return isBase64(StringUtils.getBytesUtf8(base64)); - } - - /** - * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the - * method treats whitespace as valid. - * - * @param arrayOctet - * byte array to test - * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; - * false, otherwise - * @since 1.5 - */ - public static boolean isBase64(final byte[] arrayOctet) { - for (int i = 0; i < arrayOctet.length; i++) { - if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) { - return false; - } - } - return true; - } - - /** - * Encodes binary data using the base64 algorithm but does not chunk the output. - * - * @param binaryData - * binary data to encode - * @return byte[] containing Base64 characters in their UTF-8 representation. - */ - public static byte[] encodeBase64(final byte[] binaryData) { - return encodeBase64(binaryData, false); - } - - /** - * Encodes binary data using the base64 algorithm but does not chunk the output. - * - * NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to - * single-line non-chunking (commons-codec-1.5). - * - * @param binaryData - * binary data to encode - * @return String containing Base64 characters. - * @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not). - */ - public static String encodeBase64String(final byte[] binaryData) { - return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); - } - - /** - * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The - * url-safe variation emits - and _ instead of + and / characters. - * Note: no padding is added. - * @param binaryData - * binary data to encode - * @return byte[] containing Base64 characters in their UTF-8 representation. - * @since 1.4 - */ - public static byte[] encodeBase64URLSafe(final byte[] binaryData) { - return encodeBase64(binaryData, false, true); - } - - /** - * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The - * url-safe variation emits - and _ instead of + and / characters. - * Note: no padding is added. - * @param binaryData - * binary data to encode - * @return String containing Base64 characters - * @since 1.4 - */ - public static String encodeBase64URLSafeString(final byte[] binaryData) { - return StringUtils.newStringUtf8(encodeBase64(binaryData, false, true)); - } - - /** - * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks - * - * @param binaryData - * binary data to encode - * @return Base64 characters chunked in 76 character blocks - */ - public static byte[] encodeBase64Chunked(final byte[] binaryData) { - return encodeBase64(binaryData, true); - } - - /** - * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. - * - * @param binaryData - * Array containing binary data to encode. - * @param isChunked - * if true this encoder will chunk the base64 output into 76 character blocks - * @return Base64-encoded data. - * @throws IllegalArgumentException - * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} - */ - public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) { - return encodeBase64(binaryData, isChunked, false); - } - - /** - * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. - * - * @param binaryData - * Array containing binary data to encode. - * @param isChunked - * if true this encoder will chunk the base64 output into 76 character blocks - * @param urlSafe - * if true this encoder will emit - and _ instead of the usual + and / characters. - * Note: no padding is added when encoding using the URL-safe alphabet. - * @return Base64-encoded data. - * @throws IllegalArgumentException - * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} - * @since 1.4 - */ - public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) { - return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE); - } - - /** - * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. - * - * @param binaryData - * Array containing binary data to encode. - * @param isChunked - * if true this encoder will chunk the base64 output into 76 character blocks - * @param urlSafe - * if true this encoder will emit - and _ instead of the usual + and / characters. - * Note: no padding is added when encoding using the URL-safe alphabet. - * @param maxResultSize - * The maximum result size to accept. - * @return Base64-encoded data. - * @throws IllegalArgumentException - * Thrown when the input array needs an output array bigger than maxResultSize - * @since 1.4 - */ - public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, - final boolean urlSafe, final int maxResultSize) { - if (binaryData == null || binaryData.length == 0) { - return binaryData; - } - - // Create this so can use the super-class method - // Also ensures that the same roundings are performed by the ctor and the code - final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); - final long len = b64.getEncodedLength(binaryData); - if (len > maxResultSize) { - throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + - len + - ") than the specified maximum size of " + - maxResultSize); - } - - return b64.encode(binaryData); - } - - /** - * Decodes a Base64 String into octets. - *

- * Note: this method seamlessly handles data encoded in URL-safe or normal mode. - *

- * - * @param base64String - * String containing Base64 data - * @return Array containing decoded data. - * @since 1.4 - */ - public static byte[] decodeBase64(final String base64String) { - return new Base64().decode(base64String); - } - - /** - * Decodes Base64 data into octets. - *

- * Note: this method seamlessly handles data encoded in URL-safe or normal mode. - *

- * - * @param base64Data - * Byte array containing Base64 data - * @return Array containing decoded data. - */ - public static byte[] decodeBase64(final byte[] base64Data) { - return new Base64().decode(base64Data); - } - - // Implementation of the Encoder Interface - - // Implementation of integer encoding used for crypto - /** - * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. - * - * @param pArray - * a byte array containing base64 character data - * @return A BigInteger - * @since 1.4 - */ - public static BigInteger decodeInteger(final byte[] pArray) { - return new BigInteger(1, decodeBase64(pArray)); - } - - /** - * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. - * - * @param bigInt - * a BigInteger - * @return A byte array containing base64 character data - * @throws NullPointerException - * if null is passed in - * @since 1.4 - */ - public static byte[] encodeInteger(final BigInteger bigInt) { - if (bigInt == null) { - throw new NullPointerException("encodeInteger called with null parameter"); - } - return encodeBase64(toIntegerBytes(bigInt), false); - } - - /** - * Returns a byte-array representation of a BigInteger without sign bit. - * - * @param bigInt - * BigInteger to be converted - * @return a byte array representation of the BigInteger parameter - */ - static byte[] toIntegerBytes(final BigInteger bigInt) { - int bitlen = bigInt.bitLength(); - // round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - final byte[] bigBytes = bigInt.toByteArray(); - - if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - // set up params for copying everything but sign bit - int startSrc = 0; - int len = bigBytes.length; - - // if bigInt is exactly byte-aligned, just skip signbit in copy - if ((bigInt.bitLength() % 8) == 0) { - startSrc = 1; - len--; - } - final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec - final byte[] resizedBytes = new byte[bitlen / 8]; - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); - return resizedBytes; - } - - /** - * Returns whether or not the octet is in the Base64 alphabet. - * - * @param octet - * The value to test - * @return true if the value is defined in the the Base64 alphabet false otherwise. - */ - @Override - protected boolean isInAlphabet(final byte octet) { - return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.eclipse.leshan.util; + +import java.math.BigInteger; + +/** + * Provides Base64 encoding and decoding as defined by RFC 2045. + * + *

+ * This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 Multipurpose + * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies by Freed and Borenstein. + *

+ *

+ * The class can be parameterized in the following manner with various constructors: + *

+ *
    + *
  • URL-safe mode: Default off.
  • + *
  • Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of + * 4 in the encoded data. + *
  • Line separator: Default is CRLF ("\r\n")
  • + *
+ *

+ * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes. + *

+ *

+ * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only + * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, + * UTF-8, etc). + *

+ *

+ * This class is thread-safe. + *

+ * + * @see RFC 2045 + * @since 1.0 + * @version $Id: Base64.java 1635986 2014-11-01 16:27:52Z tn $ + */ +public class Base64 extends BaseNCodec { + + /** + * BASE32 characters are 6 bits in length. + * They are formed by taking a block of 3 octets to form a 24-bit string, + * which is converted into 4 BASE64 characters. + */ + private static final int BITS_PER_ENCODED_BYTE = 6; + private static final int BYTES_PER_UNENCODED_BLOCK = 3; + private static final int BYTES_PER_ENCODED_BLOCK = 4; + + /** + * Chunk separator per RFC 2045 section 2.1. + * + *

+ * N.B. The next major release may break compatibility and make this field private. + *

+ * + * @see RFC 2045 section 2.1 + */ + static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; + + /** + * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" + * equivalents as specified in Table 1 of RFC 2045. + * + * Thanks to "commons" project in ws.apache.org for this code. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + */ + private static final byte[] STANDARD_ENCODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; + + /** + * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / + * changed to - and _ to make the encoded Base64 results more URL-SAFE. + * This table is only used when the Base64's mode is set to URL-SAFE. + */ + private static final byte[] URL_SAFE_ENCODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' + }; + + /** + * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified + * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 + * alphabet but fall within the bounds of the array are translated to -1. + * + * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both + * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit). + * + * Thanks to "commons" project in ws.apache.org for this code. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + */ + private static final byte[] DECODE_TABLE = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, 63, -1, 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 + }; + + /** + * Base64 uses 6-bit fields. + */ + /** Mask used to extract 6 bits, used when encoding */ + private static final int MASK_6BITS = 0x3f; + + // The static final fields above are used for the original static byte[] methods on Base64. + // The private member fields below are used with the new streaming approach, which requires + // some state be preserved between calls of encode() and decode(). + + /** + * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able + * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch + * between the two modes. + */ + private final byte[] encodeTable; + + // Only one decode table currently; keep for consistency with Base32 code + private final byte[] decodeTable = DECODE_TABLE; + + /** + * Line separator for encoding. Not used when decoding. Only used if lineLength > 0. + */ + private final byte[] lineSeparator; + + /** + * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. + * decodeSize = 3 + lineSeparator.length; + */ + private final int decodeSize; + + /** + * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. + * encodeSize = 4 + lineSeparator.length; + */ + private final int encodeSize; + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. + *

+ * + *

+ * When decoding all variants are supported. + *

+ */ + public Base64() { + this(0); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode. + *

+ * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE. + *

+ * + *

+ * When decoding all variants are supported. + *

+ * + * @param urlSafe + * if true, URL-safe encoding is used. In most cases this should be set to + * false. + * @since 1.4 + */ + public Base64(final boolean urlSafe) { + this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @since 1.4 + */ + public Base64(final int lineLength) { + this(lineLength, CHUNK_SEPARATOR); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length and line separator are given in the constructor, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @param lineSeparator + * Each line of encoded data will end with this sequence of bytes. + * @throws IllegalArgumentException + * Thrown when the provided lineSeparator included some base64 characters. + * @since 1.4 + */ + public Base64(final int lineLength, final byte[] lineSeparator) { + this(lineLength, lineSeparator, false); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length and line separator are given in the constructor, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @param lineSeparator + * Each line of encoded data will end with this sequence of bytes. + * @param urlSafe + * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode + * operations. Decoding seamlessly handles both modes. + * Note: no padding is added when using the URL-safe alphabet. + * @throws IllegalArgumentException + * The provided lineSeparator included some base64 characters. That's not going to work! + * @since 1.4 + */ + public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) { + super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, + lineLength, + lineSeparator == null ? 0 : lineSeparator.length); + // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0 + // @see test case Base64Test.testConstructors() + if (lineSeparator != null) { + if (containsAlphabetOrPad(lineSeparator)) { + final String sep = StringUtils.newStringUtf8(lineSeparator); + throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]"); + } + if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE + this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; + this.lineSeparator = new byte[lineSeparator.length]; + System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); + } else { + this.encodeSize = BYTES_PER_ENCODED_BLOCK; + this.lineSeparator = null; + } + } else { + this.encodeSize = BYTES_PER_ENCODED_BLOCK; + this.lineSeparator = null; + } + this.decodeSize = this.encodeSize - 1; + this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE; + } + + /** + * Returns our current encode mode. True if we're URL-SAFE, false otherwise. + * + * @return true if we're in URL-SAFE mode, false otherwise. + * @since 1.4 + */ + public boolean isUrlSafe() { + return this.encodeTable == URL_SAFE_ENCODE_TABLE; + } + + /** + *

+ * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with + * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last + * remaining bytes (if not multiple of 3). + *

+ *

Note: no padding is added when encoding using the URL-safe alphabet.

+ *

+ * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + *

+ * + * @param in + * byte[] array of binary data to base64 encode. + * @param inPos + * Position to start reading data from. + * @param inAvail + * Amount of bytes available from input for encoding. + * @param context + * the context to be used + */ + @Override + void encode(final byte[] in, int inPos, final int inAvail, final Context context) { + if (context.eof) { + return; + } + // inAvail < 0 is how we're informed of EOF in the underlying data we're + // encoding. + if (inAvail < 0) { + context.eof = true; + if (0 == context.modulus && lineLength == 0) { + return; // no leftovers to process and not using chunking + } + final byte[] buffer = ensureBufferSize(encodeSize, context); + final int savedPos = context.pos; + switch (context.modulus) { // 0-2 + case 0 : // nothing to do here + break; + case 1 : // 8 bits = 6 + 2 + // top 6 bits: + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS]; + // remaining 2: + buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS]; + // URL-SAFE skips the padding to further reduce size. + if (encodeTable == STANDARD_ENCODE_TABLE) { + buffer[context.pos++] = pad; + buffer[context.pos++] = pad; + } + break; + + case 2 : // 16 bits = 6 + 6 + 4 + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS]; + // URL-SAFE skips the padding to further reduce size. + if (encodeTable == STANDARD_ENCODE_TABLE) { + buffer[context.pos++] = pad; + } + break; + default: + throw new IllegalStateException("Impossible modulus "+context.modulus); + } + context.currentLinePos += context.pos - savedPos; // keep track of current line position + // if currentPos == 0 we are at the start of a line, so don't add CRLF + if (lineLength > 0 && context.currentLinePos > 0) { + System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); + context.pos += lineSeparator.length; + } + } else { + for (int i = 0; i < inAvail; i++) { + final byte[] buffer = ensureBufferSize(encodeSize, context); + context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; + int b = in[inPos++]; + if (b < 0) { + b += 256; + } + context.ibitWorkArea = (context.ibitWorkArea << 8) + b; // BITS_PER_BYTE + if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS]; + context.currentLinePos += BYTES_PER_ENCODED_BLOCK; + if (lineLength > 0 && lineLength <= context.currentLinePos) { + System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); + context.pos += lineSeparator.length; + context.currentLinePos = 0; + } + } + } + } + } + + /** + *

+ * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once + * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1" + * call is not necessary when decoding, but it doesn't hurt, either. + *

+ *

+ * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are + * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, + * garbage-out philosophy: it will not check the provided data for validity. + *

+ *

+ * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + *

+ * + * @param in + * byte[] array of ascii data to base64 decode. + * @param inPos + * Position to start reading data from. + * @param inAvail + * Amount of bytes available from input for encoding. + * @param context + * the context to be used + */ + @Override + void decode(final byte[] in, int inPos, final int inAvail, final Context context) { + if (context.eof) { + return; + } + if (inAvail < 0) { + context.eof = true; + } + for (int i = 0; i < inAvail; i++) { + final byte[] buffer = ensureBufferSize(decodeSize, context); + final byte b = in[inPos++]; + if (b == pad) { + // We're done. + context.eof = true; + break; + } else { + if (b >= 0 && b < DECODE_TABLE.length) { + final int result = DECODE_TABLE[b]; + if (result >= 0) { + context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK; + context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result; + if (context.modulus == 0) { + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS); + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); + buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS); + } + } + } + } + } + + // Two forms of EOF as far as base64 decoder is concerned: actual + // EOF (-1) and first time '=' character is encountered in stream. + // This approach makes the '=' padding characters completely optional. + if (context.eof && context.modulus != 0) { + final byte[] buffer = ensureBufferSize(decodeSize, context); + + // We have some spare bits remaining + // Output all whole multiples of 8 bits and ignore the rest + switch (context.modulus) { +// case 0 : // impossible, as excluded above + case 1 : // 6 bits - ignore entirely + // TODO not currently tested; perhaps it is impossible? + break; + case 2 : // 12 bits = 8 + 4 + context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits + buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); + break; + case 3 : // 18 bits = 8 + 8 + 2 + context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); + buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); + break; + default: + throw new IllegalStateException("Impossible modulus "+context.modulus); + } + } + } + + /** + * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param arrayOctet + * byte array to test + * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; + * false, otherwise + * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0. + */ + @Deprecated + public static boolean isArrayByteBase64(final byte[] arrayOctet) { + return isBase64(arrayOctet); + } + + /** + * Returns whether or not the octet is in the base 64 alphabet. + * + * @param octet + * The value to test + * @return true if the value is defined in the the base 64 alphabet, false otherwise. + * @since 1.4 + */ + public static boolean isBase64(final byte octet) { + return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1); + } + + /** + * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param base64 + * String to test + * @return true if all characters in the String are valid characters in the Base64 alphabet or if + * the String is empty; false, otherwise + * @since 1.5 + */ + public static boolean isBase64(final String base64) { + return isBase64(StringUtils.getBytesUtf8(base64)); + } + + /** + * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param arrayOctet + * byte array to test + * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; + * false, otherwise + * @since 1.5 + */ + public static boolean isBase64(final byte[] arrayOctet) { + for (int i = 0; i < arrayOctet.length; i++) { + if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) { + return false; + } + } + return true; + } + + /** + * Encodes binary data using the base64 algorithm but does not chunk the output. + * + * @param binaryData + * binary data to encode + * @return byte[] containing Base64 characters in their UTF-8 representation. + */ + public static byte[] encodeBase64(final byte[] binaryData) { + return encodeBase64(binaryData, false); + } + + /** + * Encodes binary data using the base64 algorithm but does not chunk the output. + * + * NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to + * single-line non-chunking (commons-codec-1.5). + * + * @param binaryData + * binary data to encode + * @return String containing Base64 characters. + * @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not). + */ + public static String encodeBase64String(final byte[] binaryData) { + return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); + } + + /** + * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The + * url-safe variation emits - and _ instead of + and / characters. + * Note: no padding is added. + * @param binaryData + * binary data to encode + * @return byte[] containing Base64 characters in their UTF-8 representation. + * @since 1.4 + */ + public static byte[] encodeBase64URLSafe(final byte[] binaryData) { + return encodeBase64(binaryData, false, true); + } + + /** + * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The + * url-safe variation emits - and _ instead of + and / characters. + * Note: no padding is added. + * @param binaryData + * binary data to encode + * @return String containing Base64 characters + * @since 1.4 + */ + public static String encodeBase64URLSafeString(final byte[] binaryData) { + return StringUtils.newStringUtf8(encodeBase64(binaryData, false, true)); + } + + /** + * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks + * + * @param binaryData + * binary data to encode + * @return Base64 characters chunked in 76 character blocks + */ + public static byte[] encodeBase64Chunked(final byte[] binaryData) { + return encodeBase64(binaryData, true); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) { + return encodeBase64(binaryData, isChunked, false); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @param urlSafe + * if true this encoder will emit - and _ instead of the usual + and / characters. + * Note: no padding is added when encoding using the URL-safe alphabet. + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} + * @since 1.4 + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) { + return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @param urlSafe + * if true this encoder will emit - and _ instead of the usual + and / characters. + * Note: no padding is added when encoding using the URL-safe alphabet. + * @param maxResultSize + * The maximum result size to accept. + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than maxResultSize + * @since 1.4 + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, + final boolean urlSafe, final int maxResultSize) { + if (binaryData == null || binaryData.length == 0) { + return binaryData; + } + + // Create this so can use the super-class method + // Also ensures that the same roundings are performed by the ctor and the code + final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); + final long len = b64.getEncodedLength(binaryData); + if (len > maxResultSize) { + throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + + len + + ") than the specified maximum size of " + + maxResultSize); + } + + return b64.encode(binaryData); + } + + /** + * Decodes a Base64 String into octets. + *

+ * Note: this method seamlessly handles data encoded in URL-safe or normal mode. + *

+ * + * @param base64String + * String containing Base64 data + * @return Array containing decoded data. + * @since 1.4 + */ + public static byte[] decodeBase64(final String base64String) { + return new Base64().decode(base64String); + } + + /** + * Decodes Base64 data into octets. + *

+ * Note: this method seamlessly handles data encoded in URL-safe or normal mode. + *

+ * + * @param base64Data + * Byte array containing Base64 data + * @return Array containing decoded data. + */ + public static byte[] decodeBase64(final byte[] base64Data) { + return new Base64().decode(base64Data); + } + + // Implementation of the Encoder Interface + + // Implementation of integer encoding used for crypto + /** + * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. + * + * @param pArray + * a byte array containing base64 character data + * @return A BigInteger + * @since 1.4 + */ + public static BigInteger decodeInteger(final byte[] pArray) { + return new BigInteger(1, decodeBase64(pArray)); + } + + /** + * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. + * + * @param bigInt + * a BigInteger + * @return A byte array containing base64 character data + * @throws NullPointerException + * if null is passed in + * @since 1.4 + */ + public static byte[] encodeInteger(final BigInteger bigInt) { + if (bigInt == null) { + throw new NullPointerException("encodeInteger called with null parameter"); + } + return encodeBase64(toIntegerBytes(bigInt), false); + } + + /** + * Returns a byte-array representation of a BigInteger without sign bit. + * + * @param bigInt + * BigInteger to be converted + * @return a byte array representation of the BigInteger parameter + */ + static byte[] toIntegerBytes(final BigInteger bigInt) { + int bitlen = bigInt.bitLength(); + // round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + final byte[] bigBytes = bigInt.toByteArray(); + + if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + // set up params for copying everything but sign bit + int startSrc = 0; + int len = bigBytes.length; + + // if bigInt is exactly byte-aligned, just skip signbit in copy + if ((bigInt.bitLength() % 8) == 0) { + startSrc = 1; + len--; + } + final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec + final byte[] resizedBytes = new byte[bitlen / 8]; + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); + return resizedBytes; + } + + /** + * Returns whether or not the octet is in the Base64 alphabet. + * + * @param octet + * The value to test + * @return true if the value is defined in the the Base64 alphabet false otherwise. + */ + @Override + protected boolean isInAlphabet(final byte octet) { + return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1; + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/BaseNCodec.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/BaseNCodec.java index 58f03a7..6a8f95b 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/BaseNCodec.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/BaseNCodec.java @@ -1,504 +1,504 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.eclipse.leshan.util; - -import java.util.Arrays; - -/** - * Abstract superclass for Base-N encoders and decoders. - * - *

- * This class is thread-safe. - *

- * - * @version $Id: BaseNCodec.java 1634404 2014-10-26 23:06:10Z ggregory $ - */ -public abstract class BaseNCodec { - - /** - * Holds thread context so classes can be thread-safe. - * - * This class is not itself thread-safe; each thread must allocate its own copy. - * - * @since 1.7 - */ - static class Context { - - /** - * Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the - * encoding or decoding from this variable. - */ - int ibitWorkArea; - - /** - * Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the - * encoding or decoding from this variable. - */ - long lbitWorkArea; - - /** - * Buffer for streaming. - */ - byte[] buffer; - - /** - * Position where next character should be written in the buffer. - */ - int pos; - - /** - * Position where next character should be read from the buffer. - */ - int readPos; - - /** - * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, - * and must be thrown away. - */ - boolean eof; - - /** - * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it - * to make sure each encoded line never goes beyond lineLength (if lineLength > 0). - */ - int currentLinePos; - - /** - * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This - * variable helps track that. - */ - int modulus; - - Context() { - } - - /** - * Returns a String useful for debugging (especially within a debugger.) - * - * @return a String useful for debugging. - */ - @SuppressWarnings("boxing") // OK to ignore boxing here - @Override - public String toString() { - return String.format( - "%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " - + "modulus=%s, pos=%s, readPos=%s]", - this.getClass().getSimpleName(), Arrays.toString(buffer), currentLinePos, eof, ibitWorkArea, - lbitWorkArea, modulus, pos, readPos); - } - } - - /** - * EOF - * - * @since 1.7 - */ - static final int EOF = -1; - - /** - * MIME chunk size per RFC 2045 section 6.8. - * - *

- * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any - * equal signs. - *

- * - * @see RFC 2045 section 6.8 - */ - public static final int MIME_CHUNK_SIZE = 76; - - /** - * PEM chunk size per RFC 1421 section 4.3.2.4. - * - *

- * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any - * equal signs. - *

- * - * @see RFC 1421 section 4.3.2.4 - */ - public static final int PEM_CHUNK_SIZE = 64; - - private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2; - - /** - * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded - * block+separator - */ - private static final int DEFAULT_BUFFER_SIZE = 8192; - - /** Mask used to extract 8 bits, used in decoding bytes */ - protected static final int MASK_8BITS = 0xff; - - /** - * Byte used to pad output. - */ - protected static final byte PAD_DEFAULT = '='; // Allow static access to default - - /** - * @deprecated Use {@link #pad}. Will be removed in 2.0. - */ - @Deprecated - protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later - - protected final byte pad; // instance variable just in case it needs to vary later - - /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */ - private final int unencodedBlockSize; - - /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */ - private final int encodedBlockSize; - - /** - * Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. - * Rounded down to nearest multiple of encodedBlockSize. - */ - protected final int lineLength; - - /** - * Size of chunk separator. Not used unless {@link #lineLength} > 0. - */ - private final int chunkSeparatorLength; - - /** - * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} If - * chunkSeparatorLength is zero, then chunking is disabled. - * - * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) - * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) - * @param lineLength if > 0, use chunking with a length lineLength - * @param chunkSeparatorLength the chunk separator length, if relevant - */ - protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, - final int chunkSeparatorLength) { - this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT); - } - - /** - * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} If - * chunkSeparatorLength is zero, then chunking is disabled. - * - * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) - * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) - * @param lineLength if > 0, use chunking with a length lineLength - * @param chunkSeparatorLength the chunk separator length, if relevant - * @param pad byte used as padding byte. - */ - protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, - final int chunkSeparatorLength, final byte pad) { - this.unencodedBlockSize = unencodedBlockSize; - this.encodedBlockSize = encodedBlockSize; - final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0; - this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0; - this.chunkSeparatorLength = chunkSeparatorLength; - - this.pad = pad; - } - - /** - * Returns true if this object has buffered data for reading. - * - * @param context the context to be used - * @return true if there is data still available for reading. - */ - boolean hasData(final Context context) { // package protected for access from I/O streams - return context.buffer != null; - } - - /** - * Returns the amount of buffered data available for reading. - * - * @param context the context to be used - * @return The amount of buffered data available for reading. - */ - int available(final Context context) { // package protected for access from I/O streams - return context.buffer != null ? context.pos - context.readPos : 0; - } - - /** - * Get the default buffer size. Can be overridden. - * - * @return {@link #DEFAULT_BUFFER_SIZE} - */ - protected int getDefaultBufferSize() { - return DEFAULT_BUFFER_SIZE; - } - - /** - * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. - * - * @param context the context to be used - */ - private byte[] resizeBuffer(final Context context) { - if (context.buffer == null) { - context.buffer = new byte[getDefaultBufferSize()]; - context.pos = 0; - context.readPos = 0; - } else { - final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR]; - System.arraycopy(context.buffer, 0, b, 0, context.buffer.length); - context.buffer = b; - } - return context.buffer; - } - - /** - * Ensure that the buffer has room for size bytes - * - * @param size minimum spare space required - * @param context the context to be used - * @return the buffer - */ - protected byte[] ensureBufferSize(final int size, final Context context) { - if ((context.buffer == null) || (context.buffer.length < context.pos + size)) { - return resizeBuffer(context); - } - return context.buffer; - } - - /** - * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail - * bytes. Returns how many bytes were actually extracted. - *

- * Package protected for access from I/O streams. - * - * @param b byte[] array to extract the buffered data into. - * @param bPos position in byte[] array to start extraction at. - * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). - * @param context the context to be used - * @return The number of bytes successfully extracted into the provided byte[] array. - */ - int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) { - if (context.buffer != null) { - final int len = Math.min(available(context), bAvail); - System.arraycopy(context.buffer, context.readPos, b, bPos, len); - context.readPos += len; - if (context.readPos >= context.pos) { - context.buffer = null; // so hasData() will return false, and this method can return -1 - } - return len; - } - return context.eof ? EOF : 0; - } - - /** - * Checks if a byte value is whitespace or not. Whitespace is taken to mean: space, tab, CR, LF - * - * @param byteToCheck the byte to check - * @return true if byte is whitespace, false otherwise - */ - protected static boolean isWhiteSpace(final byte byteToCheck) { - switch (byteToCheck) { - case ' ': - case '\n': - case '\r': - case '\t': - return true; - default: - return false; - } - } - - /** - * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the - * Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[]. - * - * @param obj Object to encode - * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied. - * @throws IllegalArgumentException if the parameter supplied is not of type byte[] - */ - public Object encode(final Object obj) throws IllegalArgumentException { - if (!(obj instanceof byte[])) { - throw new IllegalArgumentException("Parameter supplied to Base-N encode is not a byte[]"); - } - return encode((byte[]) obj); - } - - /** - * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. Uses UTF8 - * encoding. - * - * @param pArray a byte array containing binary data - * @return A String containing only Base-N character data - */ - public String encodeToString(final byte[] pArray) { - return StringUtils.newStringUtf8(encode(pArray)); - } - - /** - * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses - * UTF8 encoding. - * - * @param pArray a byte array containing binary data - * @return String containing only character data in the appropriate alphabet. - */ - public String encodeAsString(final byte[] pArray) { - return StringUtils.newStringUtf8(encode(pArray)); - } - - /** - * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the - * Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String. - * - * @param obj Object to decode - * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied. - * @throws IllegalArgumentException if the parameter supplied is not of type byte[] - */ - public Object decode(final Object obj) throws IllegalArgumentException { - if (obj instanceof byte[]) { - return decode((byte[]) obj); - } else if (obj instanceof String) { - return decode((String) obj); - } else { - throw new IllegalArgumentException("Parameter supplied to Base-N decode is not a byte[] or a String"); - } - } - - /** - * Decodes a String containing characters in the Base-N alphabet. - * - * @param pArray A String containing Base-N character data - * @return a byte array containing binary data - */ - public byte[] decode(final String pArray) { - return decode(StringUtils.getBytesUtf8(pArray)); - } - - /** - * Decodes a byte[] containing characters in the Base-N alphabet. - * - * @param pArray A byte array containing Base-N character data - * @return a byte array containing binary data - */ - public byte[] decode(final byte[] pArray) { - if (pArray == null || pArray.length == 0) { - return pArray; - } - final Context context = new Context(); - decode(pArray, 0, pArray.length, context); - decode(pArray, 0, EOF, context); // Notify decoder of EOF. - final byte[] result = new byte[context.pos]; - readResults(result, 0, result.length, context); - return result; - } - - /** - * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet. - * - * @param pArray a byte array containing binary data - * @return A byte array containing only the basen alphabetic character data - */ - public byte[] encode(final byte[] pArray) { - if (pArray == null || pArray.length == 0) { - return pArray; - } - final Context context = new Context(); - encode(pArray, 0, pArray.length, context); - encode(pArray, 0, EOF, context); // Notify encoder of EOF. - final byte[] buf = new byte[context.pos - context.readPos]; - readResults(buf, 0, buf.length, context); - return buf; - } - - // package protected for access from I/O streams - abstract void encode(byte[] pArray, int i, int length, Context context); - - // package protected for access from I/O streams - abstract void decode(byte[] pArray, int i, int length, Context context); - - /** - * Returns whether or not the octet is in the current alphabet. Does not allow whitespace or pad. - * - * @param value The value to test - * - * @return true if the value is defined in the current alphabet, false otherwise. - */ - protected abstract boolean isInAlphabet(byte value); - - /** - * Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally - * treats whitespace and pad as valid. - * - * @param arrayOctet byte array to test - * @param allowWSPad if true, then whitespace and PAD are also allowed - * - * @return true if all bytes are valid characters in the alphabet or if the byte array is empty; - * false, otherwise - */ - public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) { - for (int i = 0; i < arrayOctet.length; i++) { - if (!isInAlphabet(arrayOctet[i]) - && (!allowWSPad || (arrayOctet[i] != pad) && !isWhiteSpace(arrayOctet[i]))) { - return false; - } - } - return true; - } - - /** - * Tests a given String to see if it contains only valid characters within the alphabet. The method treats - * whitespace and PAD as valid. - * - * @param basen String to test - * @return true if all characters in the String are valid characters in the alphabet or if the String - * is empty; false, otherwise - * @see #isInAlphabet(byte[], boolean) - */ - public boolean isInAlphabet(final String basen) { - return isInAlphabet(StringUtils.getBytesUtf8(basen), true); - } - - /** - * Tests a given byte array to see if it contains any characters within the alphabet or PAD. - * - * Intended for use in checking line-ending arrays - * - * @param arrayOctet byte array to test - * @return true if any byte is a valid character in the alphabet or PAD; false otherwise - */ - protected boolean containsAlphabetOrPad(final byte[] arrayOctet) { - if (arrayOctet == null) { - return false; - } - for (final byte element : arrayOctet) { - if (pad == element || isInAlphabet(element)) { - return true; - } - } - return false; - } - - /** - * Calculates the amount of space needed to encode the supplied array. - * - * @param pArray byte[] array which will later be encoded - * - * @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require - * > Integer.MAX_VALUE - */ - public long getEncodedLength(final byte[] pArray) { - // Calculate non-chunked size - rounded up to allow for padding - // cast to long is needed to avoid possibility of overflow - long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize; - if (lineLength > 0) { // We're using chunking - // Round up to nearest multiple - len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength; - } - return len; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.eclipse.leshan.util; + +import java.util.Arrays; + +/** + * Abstract superclass for Base-N encoders and decoders. + * + *

+ * This class is thread-safe. + *

+ * + * @version $Id: BaseNCodec.java 1634404 2014-10-26 23:06:10Z ggregory $ + */ +public abstract class BaseNCodec { + + /** + * Holds thread context so classes can be thread-safe. + * + * This class is not itself thread-safe; each thread must allocate its own copy. + * + * @since 1.7 + */ + static class Context { + + /** + * Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the + * encoding or decoding from this variable. + */ + int ibitWorkArea; + + /** + * Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the + * encoding or decoding from this variable. + */ + long lbitWorkArea; + + /** + * Buffer for streaming. + */ + byte[] buffer; + + /** + * Position where next character should be written in the buffer. + */ + int pos; + + /** + * Position where next character should be read from the buffer. + */ + int readPos; + + /** + * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, + * and must be thrown away. + */ + boolean eof; + + /** + * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it + * to make sure each encoded line never goes beyond lineLength (if lineLength > 0). + */ + int currentLinePos; + + /** + * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This + * variable helps track that. + */ + int modulus; + + Context() { + } + + /** + * Returns a String useful for debugging (especially within a debugger.) + * + * @return a String useful for debugging. + */ + @SuppressWarnings("boxing") // OK to ignore boxing here + @Override + public String toString() { + return String.format( + "%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " + + "modulus=%s, pos=%s, readPos=%s]", + this.getClass().getSimpleName(), Arrays.toString(buffer), currentLinePos, eof, ibitWorkArea, + lbitWorkArea, modulus, pos, readPos); + } + } + + /** + * EOF + * + * @since 1.7 + */ + static final int EOF = -1; + + /** + * MIME chunk size per RFC 2045 section 6.8. + * + *

+ * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any + * equal signs. + *

+ * + * @see RFC 2045 section 6.8 + */ + public static final int MIME_CHUNK_SIZE = 76; + + /** + * PEM chunk size per RFC 1421 section 4.3.2.4. + * + *

+ * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any + * equal signs. + *

+ * + * @see RFC 1421 section 4.3.2.4 + */ + public static final int PEM_CHUNK_SIZE = 64; + + private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2; + + /** + * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded + * block+separator + */ + private static final int DEFAULT_BUFFER_SIZE = 8192; + + /** Mask used to extract 8 bits, used in decoding bytes */ + protected static final int MASK_8BITS = 0xff; + + /** + * Byte used to pad output. + */ + protected static final byte PAD_DEFAULT = '='; // Allow static access to default + + /** + * @deprecated Use {@link #pad}. Will be removed in 2.0. + */ + @Deprecated + protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later + + protected final byte pad; // instance variable just in case it needs to vary later + + /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */ + private final int unencodedBlockSize; + + /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */ + private final int encodedBlockSize; + + /** + * Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. + * Rounded down to nearest multiple of encodedBlockSize. + */ + protected final int lineLength; + + /** + * Size of chunk separator. Not used unless {@link #lineLength} > 0. + */ + private final int chunkSeparatorLength; + + /** + * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} If + * chunkSeparatorLength is zero, then chunking is disabled. + * + * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) + * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) + * @param lineLength if > 0, use chunking with a length lineLength + * @param chunkSeparatorLength the chunk separator length, if relevant + */ + protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, + final int chunkSeparatorLength) { + this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT); + } + + /** + * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} If + * chunkSeparatorLength is zero, then chunking is disabled. + * + * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) + * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) + * @param lineLength if > 0, use chunking with a length lineLength + * @param chunkSeparatorLength the chunk separator length, if relevant + * @param pad byte used as padding byte. + */ + protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, + final int chunkSeparatorLength, final byte pad) { + this.unencodedBlockSize = unencodedBlockSize; + this.encodedBlockSize = encodedBlockSize; + final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0; + this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0; + this.chunkSeparatorLength = chunkSeparatorLength; + + this.pad = pad; + } + + /** + * Returns true if this object has buffered data for reading. + * + * @param context the context to be used + * @return true if there is data still available for reading. + */ + boolean hasData(final Context context) { // package protected for access from I/O streams + return context.buffer != null; + } + + /** + * Returns the amount of buffered data available for reading. + * + * @param context the context to be used + * @return The amount of buffered data available for reading. + */ + int available(final Context context) { // package protected for access from I/O streams + return context.buffer != null ? context.pos - context.readPos : 0; + } + + /** + * Get the default buffer size. Can be overridden. + * + * @return {@link #DEFAULT_BUFFER_SIZE} + */ + protected int getDefaultBufferSize() { + return DEFAULT_BUFFER_SIZE; + } + + /** + * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. + * + * @param context the context to be used + */ + private byte[] resizeBuffer(final Context context) { + if (context.buffer == null) { + context.buffer = new byte[getDefaultBufferSize()]; + context.pos = 0; + context.readPos = 0; + } else { + final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR]; + System.arraycopy(context.buffer, 0, b, 0, context.buffer.length); + context.buffer = b; + } + return context.buffer; + } + + /** + * Ensure that the buffer has room for size bytes + * + * @param size minimum spare space required + * @param context the context to be used + * @return the buffer + */ + protected byte[] ensureBufferSize(final int size, final Context context) { + if ((context.buffer == null) || (context.buffer.length < context.pos + size)) { + return resizeBuffer(context); + } + return context.buffer; + } + + /** + * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail + * bytes. Returns how many bytes were actually extracted. + *

+ * Package protected for access from I/O streams. + * + * @param b byte[] array to extract the buffered data into. + * @param bPos position in byte[] array to start extraction at. + * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). + * @param context the context to be used + * @return The number of bytes successfully extracted into the provided byte[] array. + */ + int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) { + if (context.buffer != null) { + final int len = Math.min(available(context), bAvail); + System.arraycopy(context.buffer, context.readPos, b, bPos, len); + context.readPos += len; + if (context.readPos >= context.pos) { + context.buffer = null; // so hasData() will return false, and this method can return -1 + } + return len; + } + return context.eof ? EOF : 0; + } + + /** + * Checks if a byte value is whitespace or not. Whitespace is taken to mean: space, tab, CR, LF + * + * @param byteToCheck the byte to check + * @return true if byte is whitespace, false otherwise + */ + protected static boolean isWhiteSpace(final byte byteToCheck) { + switch (byteToCheck) { + case ' ': + case '\n': + case '\r': + case '\t': + return true; + default: + return false; + } + } + + /** + * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the + * Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[]. + * + * @param obj Object to encode + * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied. + * @throws IllegalArgumentException if the parameter supplied is not of type byte[] + */ + public Object encode(final Object obj) throws IllegalArgumentException { + if (!(obj instanceof byte[])) { + throw new IllegalArgumentException("Parameter supplied to Base-N encode is not a byte[]"); + } + return encode((byte[]) obj); + } + + /** + * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. Uses UTF8 + * encoding. + * + * @param pArray a byte array containing binary data + * @return A String containing only Base-N character data + */ + public String encodeToString(final byte[] pArray) { + return StringUtils.newStringUtf8(encode(pArray)); + } + + /** + * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses + * UTF8 encoding. + * + * @param pArray a byte array containing binary data + * @return String containing only character data in the appropriate alphabet. + */ + public String encodeAsString(final byte[] pArray) { + return StringUtils.newStringUtf8(encode(pArray)); + } + + /** + * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the + * Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String. + * + * @param obj Object to decode + * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied. + * @throws IllegalArgumentException if the parameter supplied is not of type byte[] + */ + public Object decode(final Object obj) throws IllegalArgumentException { + if (obj instanceof byte[]) { + return decode((byte[]) obj); + } else if (obj instanceof String) { + return decode((String) obj); + } else { + throw new IllegalArgumentException("Parameter supplied to Base-N decode is not a byte[] or a String"); + } + } + + /** + * Decodes a String containing characters in the Base-N alphabet. + * + * @param pArray A String containing Base-N character data + * @return a byte array containing binary data + */ + public byte[] decode(final String pArray) { + return decode(StringUtils.getBytesUtf8(pArray)); + } + + /** + * Decodes a byte[] containing characters in the Base-N alphabet. + * + * @param pArray A byte array containing Base-N character data + * @return a byte array containing binary data + */ + public byte[] decode(final byte[] pArray) { + if (pArray == null || pArray.length == 0) { + return pArray; + } + final Context context = new Context(); + decode(pArray, 0, pArray.length, context); + decode(pArray, 0, EOF, context); // Notify decoder of EOF. + final byte[] result = new byte[context.pos]; + readResults(result, 0, result.length, context); + return result; + } + + /** + * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet. + * + * @param pArray a byte array containing binary data + * @return A byte array containing only the basen alphabetic character data + */ + public byte[] encode(final byte[] pArray) { + if (pArray == null || pArray.length == 0) { + return pArray; + } + final Context context = new Context(); + encode(pArray, 0, pArray.length, context); + encode(pArray, 0, EOF, context); // Notify encoder of EOF. + final byte[] buf = new byte[context.pos - context.readPos]; + readResults(buf, 0, buf.length, context); + return buf; + } + + // package protected for access from I/O streams + abstract void encode(byte[] pArray, int i, int length, Context context); + + // package protected for access from I/O streams + abstract void decode(byte[] pArray, int i, int length, Context context); + + /** + * Returns whether or not the octet is in the current alphabet. Does not allow whitespace or pad. + * + * @param value The value to test + * + * @return true if the value is defined in the current alphabet, false otherwise. + */ + protected abstract boolean isInAlphabet(byte value); + + /** + * Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally + * treats whitespace and pad as valid. + * + * @param arrayOctet byte array to test + * @param allowWSPad if true, then whitespace and PAD are also allowed + * + * @return true if all bytes are valid characters in the alphabet or if the byte array is empty; + * false, otherwise + */ + public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) { + for (int i = 0; i < arrayOctet.length; i++) { + if (!isInAlphabet(arrayOctet[i]) + && (!allowWSPad || (arrayOctet[i] != pad) && !isWhiteSpace(arrayOctet[i]))) { + return false; + } + } + return true; + } + + /** + * Tests a given String to see if it contains only valid characters within the alphabet. The method treats + * whitespace and PAD as valid. + * + * @param basen String to test + * @return true if all characters in the String are valid characters in the alphabet or if the String + * is empty; false, otherwise + * @see #isInAlphabet(byte[], boolean) + */ + public boolean isInAlphabet(final String basen) { + return isInAlphabet(StringUtils.getBytesUtf8(basen), true); + } + + /** + * Tests a given byte array to see if it contains any characters within the alphabet or PAD. + * + * Intended for use in checking line-ending arrays + * + * @param arrayOctet byte array to test + * @return true if any byte is a valid character in the alphabet or PAD; false otherwise + */ + protected boolean containsAlphabetOrPad(final byte[] arrayOctet) { + if (arrayOctet == null) { + return false; + } + for (final byte element : arrayOctet) { + if (pad == element || isInAlphabet(element)) { + return true; + } + } + return false; + } + + /** + * Calculates the amount of space needed to encode the supplied array. + * + * @param pArray byte[] array which will later be encoded + * + * @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require + * > Integer.MAX_VALUE + */ + public long getEncodedLength(final byte[] pArray) { + // Calculate non-chunked size - rounded up to allow for padding + // cast to long is needed to avoid possibility of overflow + long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize; + if (lineLength > 0) { // We're using chunking + // Round up to nearest multiple + len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength; + } + return len; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Charsets.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Charsets.java index 07d8ffa..cb10049 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Charsets.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Charsets.java @@ -1,58 +1,58 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.eclipse.leshan.util; - -import java.nio.charset.Charset; - -/** - * Charset utilities. Contains the standard character sets guaranteed to be available on all implementations of the Java - * platform. Parts adapted from JDK 1.7 (in particular, the {@code java.nio.charset.StandardCharsets} class). - * - * @see java.nio.charset.Charset - */ -public final class Charsets { - - /** - * Seven-bit ASCII. ISO646-US. The Basic Latin block of the Unicode character set. - */ - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - - /** - * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. - */ - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - /** - * Eight-bit UCS Transformation Format. - */ - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - /** - * Sixteen-bit UCS Transformation Format, big-endian byte order. - */ - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - - /** - * Sixteen-bit UCS Transformation Format, little-endian byte order. - */ - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - - /** - * Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark. - */ - public static final Charset UTF_16 = Charset.forName("UTF-16"); -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.eclipse.leshan.util; + +import java.nio.charset.Charset; + +/** + * Charset utilities. Contains the standard character sets guaranteed to be available on all implementations of the Java + * platform. Parts adapted from JDK 1.7 (in particular, the {@code java.nio.charset.StandardCharsets} class). + * + * @see java.nio.charset.Charset + */ +public final class Charsets { + + /** + * Seven-bit ASCII. ISO646-US. The Basic Latin block of the Unicode character set. + */ + public static final Charset US_ASCII = Charset.forName("US-ASCII"); + + /** + * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. + */ + public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); + + /** + * Eight-bit UCS Transformation Format. + */ + public static final Charset UTF_8 = Charset.forName("UTF-8"); + + /** + * Sixteen-bit UCS Transformation Format, big-endian byte order. + */ + public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); + + /** + * Sixteen-bit UCS Transformation Format, little-endian byte order. + */ + public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); + + /** + * Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark. + */ + public static final Charset UTF_16 = Charset.forName("UTF-16"); +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Hex.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Hex.java index d4eabca..93d33ca 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Hex.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Hex.java @@ -1,295 +1,295 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.eclipse.leshan.util; - -import java.nio.charset.Charset; - -/** - * Converts hexadecimal Strings. The charset used for certain operation can be set, the default is set in - * {@link #DEFAULT_CHARSET_NAME} - * - * This class is thread-safe. - * - * @since 1.1 - * @version $Id: Hex.java 1619948 2014-08-22 22:53:55Z ggregory $ - */ -public class Hex { - - /** - * Default charset name is {@link Charsets#UTF_8} - * - * @since 1.7 - */ - public static final Charset DEFAULT_CHARSET = Charsets.UTF_8; - - /** - * Used to build output as Hex - */ - private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', - 'e', 'f' }; - - /** - * Used to build output as Hex - */ - private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', - 'E', 'F' }; - - /** - * Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The - * returned array will be half the length of the passed array, as it takes two characters to represent any given - * byte. An exception is thrown if the passed char array has an odd number of elements. - * - * @param data An array of characters containing hexadecimal digits - * @return A byte array containing binary data decoded from the supplied char array. - * @throws DecoderException Thrown if an odd number or illegal of characters is supplied - */ - public static byte[] decodeHex(final char[] data) throws IllegalArgumentException { - - final int len = data.length; - - if ((len & 0x01) != 0) { - throw new IllegalArgumentException("Odd number of characters."); - } - - final byte[] out = new byte[len >> 1]; - - // two characters form the hex value. - for (int i = 0, j = 0; j < len; i++) { - int f = toDigit(data[j], j) << 4; - j++; - f = f | toDigit(data[j], j); - j++; - out[i] = (byte) (f & 0xFF); - } - - return out; - } - - /** - * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. - * The returned array will be double the length of the passed array, as it takes two characters to represent any - * given byte. - * - * @param data a byte[] to convert to Hex characters - * @return A char[] containing hexadecimal characters - */ - public static char[] encodeHex(final byte[] data) { - return encodeHex(data, true); - } - - /** - * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. - * The returned array will be double the length of the passed array, as it takes two characters to represent any - * given byte. - * - * @param data a byte[] to convert to Hex characters - * @param toLowerCase true converts to lowercase, false to uppercase - * @return A char[] containing hexadecimal characters - * @since 1.4 - */ - public static char[] encodeHex(final byte[] data, final boolean toLowerCase) { - return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); - } - - /** - * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. - * The returned array will be double the length of the passed array, as it takes two characters to represent any - * given byte. - * - * @param data a byte[] to convert to Hex characters - * @param toDigits the output alphabet - * @return A char[] containing hexadecimal characters - * @since 1.4 - */ - protected static char[] encodeHex(final byte[] data, final char[] toDigits) { - final int l = data.length; - final char[] out = new char[l << 1]; - // two characters form the hex value. - for (int i = 0, j = 0; i < l; i++) { - out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; - out[j++] = toDigits[0x0F & data[i]]; - } - return out; - } - - /** - * Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned - * String will be double the length of the passed array, as it takes two characters to represent any given byte. - * - * @param data a byte[] to convert to Hex characters - * @return A String containing hexadecimal characters - * @since 1.4 - */ - public static String encodeHexString(final byte[] data) { - return new String(encodeHex(data)); - } - - /** - * Converts a hexadecimal character to an integer. - * - * @param ch A character to convert to an integer digit - * @param index The index of the character in the source - * @return An integer - * @throws DecoderException Thrown if ch is an illegal hex character - */ - protected static int toDigit(final char ch, final int index) throws IllegalArgumentException { - final int digit = Character.digit(ch, 16); - if (digit == -1) { - throw new IllegalArgumentException("Illegal hexadecimal character " + ch + " at index " + index); - } - return digit; - } - - private final Charset charset; - - /** - * Creates a new codec with the default charset name {@link #DEFAULT_CHARSET} - */ - public Hex() { - // use default encoding - this.charset = DEFAULT_CHARSET; - } - - /** - * Creates a new codec with the given Charset. - * - * @param charset the charset. - * @since 1.7 - */ - public Hex(final Charset charset) { - this.charset = charset; - } - - /** - * Creates a new codec with the given charset name. - * - * @param charsetName the charset name. - * @throws java.nio.charset.UnsupportedCharsetException If the named charset is unavailable - * @since 1.4 - * @since 1.7 throws UnsupportedCharsetException if the named charset is unavailable - */ - public Hex(final String charsetName) { - this(Charset.forName(charsetName)); - } - - /** - * Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values. - * The returned array will be half the length of the passed array, as it takes two characters to represent any given - * byte. An exception is thrown if the passed char array has an odd number of elements. - * - * @param array An array of character bytes containing hexadecimal digits - * @return A byte array containing binary data decoded from the supplied byte array (representing characters). - * @throws DecoderException Thrown if an odd number of characters is supplied to this function - * @see #decodeHex(char[]) - */ - public byte[] decode(final byte[] array) throws IllegalArgumentException { - return decodeHex(new String(array, getCharset()).toCharArray()); - } - - /** - * Converts a String or an array of character bytes representing hexadecimal values into an array of bytes of those - * same values. The returned array will be half the length of the passed String or array, as it takes two characters - * to represent any given byte. An exception is thrown if the passed char array has an odd number of elements. - * - * @param object A String or, an array of character bytes containing hexadecimal digits - * @return A byte array containing binary data decoded from the supplied byte array (representing characters). - * @throws DecoderException Thrown if an odd number of characters is supplied to this function or the object is not - * a String or char[] - * @see #decodeHex(char[]) - */ - public Object decode(final Object object) throws IllegalArgumentException { - try { - final char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object; - return decodeHex(charArray); - } catch (final ClassCastException e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - } - - /** - * Converts an array of bytes into an array of bytes for the characters representing the hexadecimal values of each - * byte in order. The returned array will be double the length of the passed array, as it takes two characters to - * represent any given byte. - *

- * The conversion from hexadecimal characters to the returned bytes is performed with the charset named by - * {@link #getCharset()}. - *

- * - * @param array a byte[] to convert to Hex characters - * @return A byte[] containing the bytes of the hexadecimal characters - * @since 1.7 No longer throws IllegalStateException if the charsetName is invalid. - * @see #encodeHex(byte[]) - */ - public byte[] encode(final byte[] array) { - return encodeHexString(array).getBytes(this.getCharset()); - } - - /** - * Converts a String or an array of bytes into an array of characters representing the hexadecimal values of each - * byte in order. The returned array will be double the length of the passed String or array, as it takes two - * characters to represent any given byte. - *

- * The conversion from hexadecimal characters to bytes to be encoded to performed with the charset named by - * {@link #getCharset()}. - *

- * - * @param object a String, or byte[] to convert to Hex characters - * @return A char[] containing hexadecimal characters - * @throws EncoderException Thrown if the given object is not a String or byte[] - * @see #encodeHex(byte[]) - */ - public Object encode(final Object object) throws IllegalArgumentException { - try { - final byte[] byteArray = object instanceof String ? ((String) object).getBytes(this.getCharset()) - : (byte[]) object; - return encodeHex(byteArray); - } catch (final ClassCastException e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - } - - /** - * Gets the charset. - * - * @return the charset. - * @since 1.7 - */ - public Charset getCharset() { - return this.charset; - } - - /** - * Gets the charset name. - * - * @return the charset name. - * @since 1.4 - */ - public String getCharsetName() { - return this.charset.name(); - } - - /** - * Returns a string representation of the object, which includes the charset name. - * - * @return a string representation of the object. - */ - @Override - public String toString() { - return super.toString() + "[charsetName=" + this.charset + "]"; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.eclipse.leshan.util; + +import java.nio.charset.Charset; + +/** + * Converts hexadecimal Strings. The charset used for certain operation can be set, the default is set in + * {@link #DEFAULT_CHARSET_NAME} + * + * This class is thread-safe. + * + * @since 1.1 + * @version $Id: Hex.java 1619948 2014-08-22 22:53:55Z ggregory $ + */ +public class Hex { + + /** + * Default charset name is {@link Charsets#UTF_8} + * + * @since 1.7 + */ + public static final Charset DEFAULT_CHARSET = Charsets.UTF_8; + + /** + * Used to build output as Hex + */ + private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', + 'e', 'f' }; + + /** + * Used to build output as Hex + */ + private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', + 'E', 'F' }; + + /** + * Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The + * returned array will be half the length of the passed array, as it takes two characters to represent any given + * byte. An exception is thrown if the passed char array has an odd number of elements. + * + * @param data An array of characters containing hexadecimal digits + * @return A byte array containing binary data decoded from the supplied char array. + * @throws DecoderException Thrown if an odd number or illegal of characters is supplied + */ + public static byte[] decodeHex(final char[] data) throws IllegalArgumentException { + + final int len = data.length; + + if ((len & 0x01) != 0) { + throw new IllegalArgumentException("Odd number of characters."); + } + + final byte[] out = new byte[len >> 1]; + + // two characters form the hex value. + for (int i = 0, j = 0; j < len; i++) { + int f = toDigit(data[j], j) << 4; + j++; + f = f | toDigit(data[j], j); + j++; + out[i] = (byte) (f & 0xFF); + } + + return out; + } + + /** + * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. + * The returned array will be double the length of the passed array, as it takes two characters to represent any + * given byte. + * + * @param data a byte[] to convert to Hex characters + * @return A char[] containing hexadecimal characters + */ + public static char[] encodeHex(final byte[] data) { + return encodeHex(data, true); + } + + /** + * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. + * The returned array will be double the length of the passed array, as it takes two characters to represent any + * given byte. + * + * @param data a byte[] to convert to Hex characters + * @param toLowerCase true converts to lowercase, false to uppercase + * @return A char[] containing hexadecimal characters + * @since 1.4 + */ + public static char[] encodeHex(final byte[] data, final boolean toLowerCase) { + return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); + } + + /** + * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. + * The returned array will be double the length of the passed array, as it takes two characters to represent any + * given byte. + * + * @param data a byte[] to convert to Hex characters + * @param toDigits the output alphabet + * @return A char[] containing hexadecimal characters + * @since 1.4 + */ + protected static char[] encodeHex(final byte[] data, final char[] toDigits) { + final int l = data.length; + final char[] out = new char[l << 1]; + // two characters form the hex value. + for (int i = 0, j = 0; i < l; i++) { + out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; + out[j++] = toDigits[0x0F & data[i]]; + } + return out; + } + + /** + * Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned + * String will be double the length of the passed array, as it takes two characters to represent any given byte. + * + * @param data a byte[] to convert to Hex characters + * @return A String containing hexadecimal characters + * @since 1.4 + */ + public static String encodeHexString(final byte[] data) { + return new String(encodeHex(data)); + } + + /** + * Converts a hexadecimal character to an integer. + * + * @param ch A character to convert to an integer digit + * @param index The index of the character in the source + * @return An integer + * @throws DecoderException Thrown if ch is an illegal hex character + */ + protected static int toDigit(final char ch, final int index) throws IllegalArgumentException { + final int digit = Character.digit(ch, 16); + if (digit == -1) { + throw new IllegalArgumentException("Illegal hexadecimal character " + ch + " at index " + index); + } + return digit; + } + + private final Charset charset; + + /** + * Creates a new codec with the default charset name {@link #DEFAULT_CHARSET} + */ + public Hex() { + // use default encoding + this.charset = DEFAULT_CHARSET; + } + + /** + * Creates a new codec with the given Charset. + * + * @param charset the charset. + * @since 1.7 + */ + public Hex(final Charset charset) { + this.charset = charset; + } + + /** + * Creates a new codec with the given charset name. + * + * @param charsetName the charset name. + * @throws java.nio.charset.UnsupportedCharsetException If the named charset is unavailable + * @since 1.4 + * @since 1.7 throws UnsupportedCharsetException if the named charset is unavailable + */ + public Hex(final String charsetName) { + this(Charset.forName(charsetName)); + } + + /** + * Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values. + * The returned array will be half the length of the passed array, as it takes two characters to represent any given + * byte. An exception is thrown if the passed char array has an odd number of elements. + * + * @param array An array of character bytes containing hexadecimal digits + * @return A byte array containing binary data decoded from the supplied byte array (representing characters). + * @throws DecoderException Thrown if an odd number of characters is supplied to this function + * @see #decodeHex(char[]) + */ + public byte[] decode(final byte[] array) throws IllegalArgumentException { + return decodeHex(new String(array, getCharset()).toCharArray()); + } + + /** + * Converts a String or an array of character bytes representing hexadecimal values into an array of bytes of those + * same values. The returned array will be half the length of the passed String or array, as it takes two characters + * to represent any given byte. An exception is thrown if the passed char array has an odd number of elements. + * + * @param object A String or, an array of character bytes containing hexadecimal digits + * @return A byte array containing binary data decoded from the supplied byte array (representing characters). + * @throws DecoderException Thrown if an odd number of characters is supplied to this function or the object is not + * a String or char[] + * @see #decodeHex(char[]) + */ + public Object decode(final Object object) throws IllegalArgumentException { + try { + final char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object; + return decodeHex(charArray); + } catch (final ClassCastException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + /** + * Converts an array of bytes into an array of bytes for the characters representing the hexadecimal values of each + * byte in order. The returned array will be double the length of the passed array, as it takes two characters to + * represent any given byte. + *

+ * The conversion from hexadecimal characters to the returned bytes is performed with the charset named by + * {@link #getCharset()}. + *

+ * + * @param array a byte[] to convert to Hex characters + * @return A byte[] containing the bytes of the hexadecimal characters + * @since 1.7 No longer throws IllegalStateException if the charsetName is invalid. + * @see #encodeHex(byte[]) + */ + public byte[] encode(final byte[] array) { + return encodeHexString(array).getBytes(this.getCharset()); + } + + /** + * Converts a String or an array of bytes into an array of characters representing the hexadecimal values of each + * byte in order. The returned array will be double the length of the passed String or array, as it takes two + * characters to represent any given byte. + *

+ * The conversion from hexadecimal characters to bytes to be encoded to performed with the charset named by + * {@link #getCharset()}. + *

+ * + * @param object a String, or byte[] to convert to Hex characters + * @return A char[] containing hexadecimal characters + * @throws EncoderException Thrown if the given object is not a String or byte[] + * @see #encodeHex(byte[]) + */ + public Object encode(final Object object) throws IllegalArgumentException { + try { + final byte[] byteArray = object instanceof String ? ((String) object).getBytes(this.getCharset()) + : (byte[]) object; + return encodeHex(byteArray); + } catch (final ClassCastException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + /** + * Gets the charset. + * + * @return the charset. + * @since 1.7 + */ + public Charset getCharset() { + return this.charset; + } + + /** + * Gets the charset name. + * + * @return the charset name. + * @since 1.4 + */ + public String getCharsetName() { + return this.charset.name(); + } + + /** + * Returns a string representation of the object, which includes the charset name. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + return super.toString() + "[charsetName=" + this.charset + "]"; + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/NamedThreadFactory.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/NamedThreadFactory.java index ce4118e..23ccf21 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/NamedThreadFactory.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/NamedThreadFactory.java @@ -1,48 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.html. - * - * Contributors: - * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) - * - initial API and implementation - *******************************************************************************/ -package org.eclipse.leshan.util; - -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Implementation of {@link ThreadFactory} that sets thread names according to given name format. All threads are - * created by {@link Executors#defaultThreadFactory() #newThread(Runnable)}. - */ -public final class NamedThreadFactory implements ThreadFactory { - private final String nameFormat; - private final AtomicLong counter = new AtomicLong(); - - /** - * Creates a new {@link NamedThreadFactory}. - * - * @param nameFormat result of {@link String#format(String, Object...)} with this format and unique counter will be - * used for thread name. Example: format of {@code xyz-%d} will result in thread names {@code xyz-1}, - * {@code xyz-2} etc. - */ - public NamedThreadFactory(final String nameFormat) { - this.nameFormat = nameFormat; - } - - @Override - public Thread newThread(final Runnable r) { - final Thread thread = Executors.defaultThreadFactory().newThread(r); - thread.setName(String.format(nameFormat, counter.getAndIncrement())); - return thread; - } +/******************************************************************************* + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Alexander Ellwein, Daniel Maier (Bosch Software Innovations GmbH) + * - initial API and implementation + *******************************************************************************/ +package org.eclipse.leshan.util; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Implementation of {@link ThreadFactory} that sets thread names according to given name format. All threads are + * created by {@link Executors#defaultThreadFactory() #newThread(Runnable)}. + */ +public final class NamedThreadFactory implements ThreadFactory { + private final String nameFormat; + private final AtomicLong counter = new AtomicLong(); + + /** + * Creates a new {@link NamedThreadFactory}. + * + * @param nameFormat result of {@link String#format(String, Object...)} with this format and unique counter will be + * used for thread name. Example: format of {@code xyz-%d} will result in thread names {@code xyz-1}, + * {@code xyz-2} etc. + */ + public NamedThreadFactory(final String nameFormat) { + this.nameFormat = nameFormat; + } + + @Override + public Thread newThread(final Runnable r) { + final Thread thread = Executors.defaultThreadFactory().newThread(r); + thread.setName(String.format(nameFormat, counter.getAndIncrement())); + return thread; + } } \ No newline at end of file diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/RandomStringUtils.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/RandomStringUtils.java index 0837874..6753402 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/RandomStringUtils.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/RandomStringUtils.java @@ -1,349 +1,349 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.eclipse.leshan.util; - -import java.util.Random; - -/** - *

- * Operations for random Strings. - *

- *

- * Currently private high surrogate characters are ignored. These are unicode characters that fall between the - * values 56192 (db80) and 56319 (dbff) as we don't know how to handle them. High and low surrogates are correctly dealt - * with - that is if a high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) then it is followed by a low - * surrogate. If a low surrogate is chosen, 56320 (dc00) to 57343 (dfff) then it is placed after a randomly chosen high - * surrogate. - *

- * - *

- * #ThreadSafe# - *

- * - * @author Apache Software Foundation - * @author Steven Caswell - * @author Gary Gregory - * @author Phil Steitz - * @since 1.0 - * @version $Id: RandomStringUtils.java 1056988 2011-01-09 17:58:53Z niallp $ - */ -public class RandomStringUtils { - - /** - *

- * Random object used by random method. This has to be not local to the random method so as to not return the same - * value in the same millisecond. - *

- */ - private static final Random RANDOM = new Random(); - - /** - *

- * RandomStringUtils instances should NOT be constructed in standard programming. Instead, the class - * should be used as RandomStringUtils.random(5);. - *

- * - *

- * This constructor is public to permit tools that require a JavaBean instance to operate. - *

- */ - public RandomStringUtils() { - super(); - } - - // Random - // ----------------------------------------------------------------------- - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of all characters. - *

- * - * @param count the length of random string to create - * @return the random string - */ - public static String random(int count) { - return random(count, false, false); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of characters whose ASCII value is between 32 and - * 126 (inclusive). - *

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAscii(int count) { - return random(count, 32, 127, false, false); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of alphabetic characters. - *

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphabetic(int count) { - return random(count, true, false); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of alpha-numeric characters. - *

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphanumeric(int count) { - return random(count, true, true); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of numeric characters. - *

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomNumeric(int count) { - return random(count, false, true); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - *

- * - * @param count the length of random string to create - * @param letters if true, generated string will include alphabetic characters - * @param numbers if true, generated string will include numeric characters - * @return the random string - */ - public static String random(int count, boolean letters, boolean numbers) { - return random(count, 0, 0, letters, numbers); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - *

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters if true, generated string will include alphabetic characters - * @param numbers if true, generated string will include numeric characters - * @return the random string - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers) { - return random(count, start, end, letters, numbers, null, RANDOM); - } - - /** - *

- * Creates a random string based on a variety of options, using default source of randomness. - *

- * - *

- * This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but - * instead of using an externally supplied source of randomness, it uses the internal static {@link Random} - * instance. - *

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. If null, then it will use the set of all - * chars. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not (end - start) + 1 characters in the set - * array. - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) { - return random(count, start, end, letters, numbers, chars, RANDOM); - } - - /** - *

- * Creates a random string based on a variety of options, using supplied source of randomness. - *

- * - *

- * If start and end are both 0, start and end are set to ' ' and 'z', the - * ASCII printable characters, will be used, unless letters and numbers are both false, in which case, - * start and end are set to 0 and Integer.MAX_VALUE. - * - *

- * If set is not null, characters between start and end are chosen. - *

- * - *

- * This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a single - * {@link Random} instance with a fixed seed and using it for each call, the same random sequence of strings can be - * generated repeatedly and predictably. - *

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. If null, then it will use the set of all - * chars. - * @param random a source of randomness. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not (end - start) + 1 characters in the set - * array. - * @throws IllegalArgumentException if count < 0. - * @since 2.0 - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, - Random random) { - if (count == 0) { - return ""; - } else if (count < 0) { - throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); - } - if ((start == 0) && (end == 0)) { - end = 'z' + 1; - start = ' '; - if (!letters && !numbers) { - start = 0; - end = Integer.MAX_VALUE; - } - } - - char[] buffer = new char[count]; - int gap = end - start; - - while (count-- != 0) { - char ch; - if (chars == null) { - ch = (char) (random.nextInt(gap) + start); - } else { - ch = chars[random.nextInt(gap) + start]; - } - if ((letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) { - if (ch >= 56320 && ch <= 57343) { - if (count == 0) { - count++; - } else { - // low surrogate, insert high surrogate after putting it in - buffer[count] = ch; - count--; - buffer[count] = (char) (55296 + random.nextInt(128)); - } - } else if (ch >= 55296 && ch <= 56191) { - if (count == 0) { - count++; - } else { - // high surrogate, insert low surrogate before putting it in - buffer[count] = (char) (56320 + random.nextInt(128)); - count--; - buffer[count] = ch; - } - } else if (ch >= 56192 && ch <= 56319) { - // private high surrogate, no effing clue, so skip it - count++; - } else { - buffer[count] = ch; - } - } else { - count++; - } - } - return new String(buffer); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of characters specified. - *

- * - * @param count the length of random string to create - * @param chars the String containing the set of characters to use, may be null - * @return the random string - * @throws IllegalArgumentException if count < 0. - */ - public static String random(int count, String chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, chars.toCharArray()); - } - - /** - *

- * Creates a random string whose length is the number of characters specified. - *

- * - *

- * Characters will be chosen from the set of characters specified. - *

- * - * @param count the length of random string to create - * @param chars the character array containing the set of characters to use, may be null - * @return the random string - * @throws IllegalArgumentException if count < 0. - */ - public static String random(int count, char[] chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, 0, chars.length, false, false, chars, RANDOM); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.eclipse.leshan.util; + +import java.util.Random; + +/** + *

+ * Operations for random Strings. + *

+ *

+ * Currently private high surrogate characters are ignored. These are unicode characters that fall between the + * values 56192 (db80) and 56319 (dbff) as we don't know how to handle them. High and low surrogates are correctly dealt + * with - that is if a high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) then it is followed by a low + * surrogate. If a low surrogate is chosen, 56320 (dc00) to 57343 (dfff) then it is placed after a randomly chosen high + * surrogate. + *

+ * + *

+ * #ThreadSafe# + *

+ * + * @author Apache Software Foundation + * @author Steven Caswell + * @author Gary Gregory + * @author Phil Steitz + * @since 1.0 + * @version $Id: RandomStringUtils.java 1056988 2011-01-09 17:58:53Z niallp $ + */ +public class RandomStringUtils { + + /** + *

+ * Random object used by random method. This has to be not local to the random method so as to not return the same + * value in the same millisecond. + *

+ */ + private static final Random RANDOM = new Random(); + + /** + *

+ * RandomStringUtils instances should NOT be constructed in standard programming. Instead, the class + * should be used as RandomStringUtils.random(5);. + *

+ * + *

+ * This constructor is public to permit tools that require a JavaBean instance to operate. + *

+ */ + public RandomStringUtils() { + super(); + } + + // Random + // ----------------------------------------------------------------------- + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of all characters. + *

+ * + * @param count the length of random string to create + * @return the random string + */ + public static String random(int count) { + return random(count, false, false); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of characters whose ASCII value is between 32 and + * 126 (inclusive). + *

+ * + * @param count the length of random string to create + * @return the random string + */ + public static String randomAscii(int count) { + return random(count, 32, 127, false, false); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of alphabetic characters. + *

+ * + * @param count the length of random string to create + * @return the random string + */ + public static String randomAlphabetic(int count) { + return random(count, true, false); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of alpha-numeric characters. + *

+ * + * @param count the length of random string to create + * @return the random string + */ + public static String randomAlphanumeric(int count) { + return random(count, true, true); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of numeric characters. + *

+ * + * @param count the length of random string to create + * @return the random string + */ + public static String randomNumeric(int count) { + return random(count, false, true); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. + *

+ * + * @param count the length of random string to create + * @param letters if true, generated string will include alphabetic characters + * @param numbers if true, generated string will include numeric characters + * @return the random string + */ + public static String random(int count, boolean letters, boolean numbers) { + return random(count, 0, 0, letters, numbers); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. + *

+ * + * @param count the length of random string to create + * @param start the position in set of chars to start at + * @param end the position in set of chars to end before + * @param letters if true, generated string will include alphabetic characters + * @param numbers if true, generated string will include numeric characters + * @return the random string + */ + public static String random(int count, int start, int end, boolean letters, boolean numbers) { + return random(count, start, end, letters, numbers, null, RANDOM); + } + + /** + *

+ * Creates a random string based on a variety of options, using default source of randomness. + *

+ * + *

+ * This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but + * instead of using an externally supplied source of randomness, it uses the internal static {@link Random} + * instance. + *

+ * + * @param count the length of random string to create + * @param start the position in set of chars to start at + * @param end the position in set of chars to end before + * @param letters only allow letters? + * @param numbers only allow numbers? + * @param chars the set of chars to choose randoms from. If null, then it will use the set of all + * chars. + * @return the random string + * @throws ArrayIndexOutOfBoundsException if there are not (end - start) + 1 characters in the set + * array. + */ + public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) { + return random(count, start, end, letters, numbers, chars, RANDOM); + } + + /** + *

+ * Creates a random string based on a variety of options, using supplied source of randomness. + *

+ * + *

+ * If start and end are both 0, start and end are set to ' ' and 'z', the + * ASCII printable characters, will be used, unless letters and numbers are both false, in which case, + * start and end are set to 0 and Integer.MAX_VALUE. + * + *

+ * If set is not null, characters between start and end are chosen. + *

+ * + *

+ * This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, the same random sequence of strings can be + * generated repeatedly and predictably. + *

+ * + * @param count the length of random string to create + * @param start the position in set of chars to start at + * @param end the position in set of chars to end before + * @param letters only allow letters? + * @param numbers only allow numbers? + * @param chars the set of chars to choose randoms from. If null, then it will use the set of all + * chars. + * @param random a source of randomness. + * @return the random string + * @throws ArrayIndexOutOfBoundsException if there are not (end - start) + 1 characters in the set + * array. + * @throws IllegalArgumentException if count < 0. + * @since 2.0 + */ + public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, + Random random) { + if (count == 0) { + return ""; + } else if (count < 0) { + throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); + } + if ((start == 0) && (end == 0)) { + end = 'z' + 1; + start = ' '; + if (!letters && !numbers) { + start = 0; + end = Integer.MAX_VALUE; + } + } + + char[] buffer = new char[count]; + int gap = end - start; + + while (count-- != 0) { + char ch; + if (chars == null) { + ch = (char) (random.nextInt(gap) + start); + } else { + ch = chars[random.nextInt(gap) + start]; + } + if ((letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) { + if (ch >= 56320 && ch <= 57343) { + if (count == 0) { + count++; + } else { + // low surrogate, insert high surrogate after putting it in + buffer[count] = ch; + count--; + buffer[count] = (char) (55296 + random.nextInt(128)); + } + } else if (ch >= 55296 && ch <= 56191) { + if (count == 0) { + count++; + } else { + // high surrogate, insert low surrogate before putting it in + buffer[count] = (char) (56320 + random.nextInt(128)); + count--; + buffer[count] = ch; + } + } else if (ch >= 56192 && ch <= 56319) { + // private high surrogate, no effing clue, so skip it + count++; + } else { + buffer[count] = ch; + } + } else { + count++; + } + } + return new String(buffer); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of characters specified. + *

+ * + * @param count the length of random string to create + * @param chars the String containing the set of characters to use, may be null + * @return the random string + * @throws IllegalArgumentException if count < 0. + */ + public static String random(int count, String chars) { + if (chars == null) { + return random(count, 0, 0, false, false, null, RANDOM); + } + return random(count, chars.toCharArray()); + } + + /** + *

+ * Creates a random string whose length is the number of characters specified. + *

+ * + *

+ * Characters will be chosen from the set of characters specified. + *

+ * + * @param count the length of random string to create + * @param chars the character array containing the set of characters to use, may be null + * @return the random string + * @throws IllegalArgumentException if count < 0. + */ + public static String random(int count, char[] chars) { + if (chars == null) { + return random(count, 0, 0, false, false, null, RANDOM); + } + return random(count, 0, chars.length, false, false, chars, RANDOM); + } + +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/StringUtils.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/StringUtils.java index ccfaaec..e7685ce 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/StringUtils.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/StringUtils.java @@ -1,354 +1,354 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.eclipse.leshan.util; - -import java.nio.charset.Charset; - -/** - *

- * Operations on {@link java.lang.String} that are null safe. - *

- * - *
    - *
  • IsEmpty/IsBlank - checks if a String contains text
  • - *
  • Trim/Strip - removes leading and trailing whitespace
  • - *
  • Equals - compares two strings null-safe
  • - *
  • startsWith - check if a String starts with a prefix null-safe
  • - *
  • endsWith - check if a String ends with a suffix null-safe
  • - *
  • IndexOf/LastIndexOf/Contains - null-safe index-of checks - *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
  • - *
  • ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
  • - *
  • Substring/Left/Right/Mid - null-safe substring extractions
  • - *
  • SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
  • - *
  • Split/Join - splits a String into an array of substrings and vice versa
  • - *
  • Remove/Delete - removes part of a String
  • - *
  • Replace/Overlay - Searches a String and replaces one String with another
  • - *
  • Chomp/Chop - removes the last part of a String
  • - *
  • LeftPad/RightPad/Center/Repeat - pads a String
  • - *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
  • - *
  • CountMatches - counts the number of occurrences of one String in another
  • - *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
  • - *
  • DefaultString - protects against a null input String
  • - *
  • Reverse/ReverseDelimited - reverses a String
  • - *
  • Abbreviate - abbreviates a string using ellipsis
  • - *
  • Difference - compares Strings and reports on their differences
  • - *
  • LevensteinDistance - the number of changes needed to change one String into another
  • - *
- * - *

- * The StringUtils class defines certain words related to String handling. - *

- * - *
    - *
  • null - null
  • - *
  • empty - a zero-length string ("")
  • - *
  • space - the space character (' ', char 32)
  • - *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • - *
  • trim - the characters <= 32 as in {@link String#trim()}
  • - *
- * - *

- * StringUtils handles null input Strings quietly. That is to say that a null - * input will return null. Where a boolean or int is being returned details vary - * by method. - *

- * - *

- * A side effect of the null handling is that a NullPointerException should be considered a - * bug in StringUtils (except for deprecated methods). - *

- * - *

- * Methods in this class give sample code to explain their operation. The symbol * is used to indicate any - * input including null. - *

- * - *

- * #ThreadSafe# - *

- * - * @see java.lang.String - * @author Apache Software Foundation - * @author Apache Jakarta Turbine - * @author Jon S. Stevens - * @author Daniel L. Rall - * @author Greg Coladonato - * @author Ed Korthof - * @author Rand McNeely - * @author Fredrik Westermarck - * @author Holger Krauth - * @author Alexander Day Chaffee - * @author Henning P. Schmiedehausen - * @author Arun Mammen Thomas - * @author Gary Gregory - * @author Phil Steitz - * @author Al Chou - * @author Michael Davey - * @author Reuben Sivan - * @author Chris Hyzer - * @author Scott Johnson - * @since 1.0 - * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $ - */ -// @Immutable -public class StringUtils { - - // Equals - // ----------------------------------------------------------------------- - /** - *

- * Compares two Strings, returning true if they are equal. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered to be equal. - * The comparison is case sensitive. - *

- * - *
-     * StringUtils.equals(null, null)   = true
-     * StringUtils.equals(null, "abc")  = false
-     * StringUtils.equals("abc", null)  = false
-     * StringUtils.equals("abc", "abc") = true
-     * StringUtils.equals("abc", "ABC") = false
-     * 
- * - * @see java.lang.String#equals(Object) - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return true if the Strings are equal, case sensitive, or both null - */ - public static boolean equals(String str1, String str2) { - return str1 == null ? str2 == null : str1.equals(str2); - } - - /** - *

- * Compares two Strings, returning true if they are equal ignoring the case. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered equal. - * Comparison is case insensitive. - *

- * - *
-     * StringUtils.equalsIgnoreCase(null, null)   = true
-     * StringUtils.equalsIgnoreCase(null, "abc")  = false
-     * StringUtils.equalsIgnoreCase("abc", null)  = false
-     * StringUtils.equalsIgnoreCase("abc", "abc") = true
-     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
-     * 
- * - * @see java.lang.String#equalsIgnoreCase(String) - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return true if the Strings are equal, case insensitive, or both null - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); - } - - // Empty checks - // ----------------------------------------------------------------------- - /** - *

- * Checks if a String is empty ("") or null. - *

- * - *
-     * StringUtils.isEmpty(null)      = true
-     * StringUtils.isEmpty("")        = true
-     * StringUtils.isEmpty(" ")       = false
-     * StringUtils.isEmpty("bob")     = false
-     * StringUtils.isEmpty("  bob  ") = false
-     * 
- * - *

- * NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in - * isBlank(). - *

- * - * @param str the String to check, may be null - * @return true if the String is empty or null - */ - public static boolean isEmpty(String str) { - return str == null || str.length() == 0; - } - - // Trim - // ----------------------------------------------------------------------- - /** - *

- * Removes control characters (char <= 32) from both ends of this String, handling null by returning - * null. - *

- * - *

- * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip - * whitespace use {@link #strip(String)}. - *

- * - *

- * To trim your choice of characters, use the {@link #strip(String, String)} methods. - *

- * - *
-     * StringUtils.trim(null)          = null
-     * StringUtils.trim("")            = ""
-     * StringUtils.trim("     ")       = ""
-     * StringUtils.trim("abc")         = "abc"
-     * StringUtils.trim("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed string, null if null String input - */ - public static String trim(String str) { - return str == null ? null : str.trim(); - } - - // Remove - // ----------------------------------------------------------------------- - /** - *

- * Removes a substring only if it is at the begining of a source string, otherwise returns the source string. - *

- * - *

- * A null source string will return null. An empty ("") source string will return the - * empty string. A null search string will return the source string. - *

- * - *
-     * StringUtils.removeStart(null, *)      = null
-     * StringUtils.removeStart("", *)        = ""
-     * StringUtils.removeStart(*, null)      = *
-     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
-     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
-     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeStart("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, null if null String input - * @since 2.1 - */ - public static String removeStart(String str, String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.startsWith(remove)) { - return str.substring(remove.length()); - } - return str; - } - - /** - *

- * Removes a substring only if it is at the end of a source string, otherwise returns the source string. - *

- * - *

- * A null source string will return null. An empty ("") source string will return the - * empty string. A null search string will return the source string. - *

- * - *
-     * StringUtils.removeEnd(null, *)      = null
-     * StringUtils.removeEnd("", *)        = ""
-     * StringUtils.removeEnd(*, null)      = *
-     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
-     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
-     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeEnd("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, null if null String input - * @since 2.1 - */ - public static String removeEnd(String str, String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.endsWith(remove)) { - return str.substring(0, str.length() - remove.length()); - } - return str; - } - - /** - * Constructs a new String by decoding the specified array of bytes using the given charset. - * - * @param bytes The bytes to be decoded into characters - * @param charset The {@link Charset} to encode the String - * @return A new String decoded from the specified array of bytes using the given charset, or - * null if the input byte array was null. - * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since - * it is required by the Java platform specification. - */ - private static String newString(final byte[] bytes, final Charset charset) { - return bytes == null ? null : new String(bytes, charset); - } - - /** - * Constructs a new String by decoding the specified array of bytes using the UTF-8 charset. - * - * @param bytes The bytes to be decoded into characters - * @return A new String decoded from the specified array of bytes using the UTF-8 charset, or - * null if the input byte array was null. - * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since - * it is required by the Java platform specification. - * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException - */ - public static String newStringUtf8(final byte[] bytes) { - return newString(bytes, Charsets.UTF_8); - } - - /** - * Calls {@link String#getBytes(Charset)} - * - * @param string The string to encode (if null, return null). - * @param charset The {@link Charset} to encode the String - * @return the encoded bytes - */ - private static byte[] getBytes(final String string, final Charset charset) { - if (string == null) { - return null; - } - return string.getBytes(charset); - } - - /** - * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte - * array. - * - * @param string the String to encode, may be null - * @return encoded bytes, or null if the input string was null - * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since - * it is required by the Java platform specification. - * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException - * @see Standard charsets - * @see #getBytesUnchecked(String, String) - */ - public static byte[] getBytesUtf8(final String string) { - return getBytes(string, Charsets.UTF_8); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.eclipse.leshan.util; + +import java.nio.charset.Charset; + +/** + *

+ * Operations on {@link java.lang.String} that are null safe. + *

+ * + *
    + *
  • IsEmpty/IsBlank - checks if a String contains text
  • + *
  • Trim/Strip - removes leading and trailing whitespace
  • + *
  • Equals - compares two strings null-safe
  • + *
  • startsWith - check if a String starts with a prefix null-safe
  • + *
  • endsWith - check if a String ends with a suffix null-safe
  • + *
  • IndexOf/LastIndexOf/Contains - null-safe index-of checks + *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
  • + *
  • ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
  • + *
  • Substring/Left/Right/Mid - null-safe substring extractions
  • + *
  • SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
  • + *
  • Split/Join - splits a String into an array of substrings and vice versa
  • + *
  • Remove/Delete - removes part of a String
  • + *
  • Replace/Overlay - Searches a String and replaces one String with another
  • + *
  • Chomp/Chop - removes the last part of a String
  • + *
  • LeftPad/RightPad/Center/Repeat - pads a String
  • + *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
  • + *
  • CountMatches - counts the number of occurrences of one String in another
  • + *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
  • + *
  • DefaultString - protects against a null input String
  • + *
  • Reverse/ReverseDelimited - reverses a String
  • + *
  • Abbreviate - abbreviates a string using ellipsis
  • + *
  • Difference - compares Strings and reports on their differences
  • + *
  • LevensteinDistance - the number of changes needed to change one String into another
  • + *
+ * + *

+ * The StringUtils class defines certain words related to String handling. + *

+ * + *
    + *
  • null - null
  • + *
  • empty - a zero-length string ("")
  • + *
  • space - the space character (' ', char 32)
  • + *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • + *
  • trim - the characters <= 32 as in {@link String#trim()}
  • + *
+ * + *

+ * StringUtils handles null input Strings quietly. That is to say that a null + * input will return null. Where a boolean or int is being returned details vary + * by method. + *

+ * + *

+ * A side effect of the null handling is that a NullPointerException should be considered a + * bug in StringUtils (except for deprecated methods). + *

+ * + *

+ * Methods in this class give sample code to explain their operation. The symbol * is used to indicate any + * input including null. + *

+ * + *

+ * #ThreadSafe# + *

+ * + * @see java.lang.String + * @author Apache Software Foundation + * @author Apache Jakarta Turbine + * @author Jon S. Stevens + * @author Daniel L. Rall + * @author Greg Coladonato + * @author Ed Korthof + * @author Rand McNeely + * @author Fredrik Westermarck + * @author Holger Krauth + * @author Alexander Day Chaffee + * @author Henning P. Schmiedehausen + * @author Arun Mammen Thomas + * @author Gary Gregory + * @author Phil Steitz + * @author Al Chou + * @author Michael Davey + * @author Reuben Sivan + * @author Chris Hyzer + * @author Scott Johnson + * @since 1.0 + * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $ + */ +// @Immutable +public class StringUtils { + + // Equals + // ----------------------------------------------------------------------- + /** + *

+ * Compares two Strings, returning true if they are equal. + *

+ * + *

+ * nulls are handled without exceptions. Two null references are considered to be equal. + * The comparison is case sensitive. + *

+ * + *
+     * StringUtils.equals(null, null)   = true
+     * StringUtils.equals(null, "abc")  = false
+     * StringUtils.equals("abc", null)  = false
+     * StringUtils.equals("abc", "abc") = true
+     * StringUtils.equals("abc", "ABC") = false
+     * 
+ * + * @see java.lang.String#equals(Object) + * @param str1 the first String, may be null + * @param str2 the second String, may be null + * @return true if the Strings are equal, case sensitive, or both null + */ + public static boolean equals(String str1, String str2) { + return str1 == null ? str2 == null : str1.equals(str2); + } + + /** + *

+ * Compares two Strings, returning true if they are equal ignoring the case. + *

+ * + *

+ * nulls are handled without exceptions. Two null references are considered equal. + * Comparison is case insensitive. + *

+ * + *
+     * StringUtils.equalsIgnoreCase(null, null)   = true
+     * StringUtils.equalsIgnoreCase(null, "abc")  = false
+     * StringUtils.equalsIgnoreCase("abc", null)  = false
+     * StringUtils.equalsIgnoreCase("abc", "abc") = true
+     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
+     * 
+ * + * @see java.lang.String#equalsIgnoreCase(String) + * @param str1 the first String, may be null + * @param str2 the second String, may be null + * @return true if the Strings are equal, case insensitive, or both null + */ + public static boolean equalsIgnoreCase(String str1, String str2) { + return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); + } + + // Empty checks + // ----------------------------------------------------------------------- + /** + *

+ * Checks if a String is empty ("") or null. + *

+ * + *
+     * StringUtils.isEmpty(null)      = true
+     * StringUtils.isEmpty("")        = true
+     * StringUtils.isEmpty(" ")       = false
+     * StringUtils.isEmpty("bob")     = false
+     * StringUtils.isEmpty("  bob  ") = false
+     * 
+ * + *

+ * NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in + * isBlank(). + *

+ * + * @param str the String to check, may be null + * @return true if the String is empty or null + */ + public static boolean isEmpty(String str) { + return str == null || str.length() == 0; + } + + // Trim + // ----------------------------------------------------------------------- + /** + *

+ * Removes control characters (char <= 32) from both ends of this String, handling null by returning + * null. + *

+ * + *

+ * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip + * whitespace use {@link #strip(String)}. + *

+ * + *

+ * To trim your choice of characters, use the {@link #strip(String, String)} methods. + *

+ * + *
+     * StringUtils.trim(null)          = null
+     * StringUtils.trim("")            = ""
+     * StringUtils.trim("     ")       = ""
+     * StringUtils.trim("abc")         = "abc"
+     * StringUtils.trim("    abc    ") = "abc"
+     * 
+ * + * @param str the String to be trimmed, may be null + * @return the trimmed string, null if null String input + */ + public static String trim(String str) { + return str == null ? null : str.trim(); + } + + // Remove + // ----------------------------------------------------------------------- + /** + *

+ * Removes a substring only if it is at the begining of a source string, otherwise returns the source string. + *

+ * + *

+ * A null source string will return null. An empty ("") source string will return the + * empty string. A null search string will return the source string. + *

+ * + *
+     * StringUtils.removeStart(null, *)      = null
+     * StringUtils.removeStart("", *)        = ""
+     * StringUtils.removeStart(*, null)      = *
+     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
+     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
+     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeStart("abc", "")    = "abc"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for and remove, may be null + * @return the substring with the string removed if found, null if null String input + * @since 2.1 + */ + public static String removeStart(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (str.startsWith(remove)) { + return str.substring(remove.length()); + } + return str; + } + + /** + *

+ * Removes a substring only if it is at the end of a source string, otherwise returns the source string. + *

+ * + *

+ * A null source string will return null. An empty ("") source string will return the + * empty string. A null search string will return the source string. + *

+ * + *
+     * StringUtils.removeEnd(null, *)      = null
+     * StringUtils.removeEnd("", *)        = ""
+     * StringUtils.removeEnd(*, null)      = *
+     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
+     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
+     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeEnd("abc", "")    = "abc"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for and remove, may be null + * @return the substring with the string removed if found, null if null String input + * @since 2.1 + */ + public static String removeEnd(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (str.endsWith(remove)) { + return str.substring(0, str.length() - remove.length()); + } + return str; + } + + /** + * Constructs a new String by decoding the specified array of bytes using the given charset. + * + * @param bytes The bytes to be decoded into characters + * @param charset The {@link Charset} to encode the String + * @return A new String decoded from the specified array of bytes using the given charset, or + * null if the input byte array was null. + * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since + * it is required by the Java platform specification. + */ + private static String newString(final byte[] bytes, final Charset charset) { + return bytes == null ? null : new String(bytes, charset); + } + + /** + * Constructs a new String by decoding the specified array of bytes using the UTF-8 charset. + * + * @param bytes The bytes to be decoded into characters + * @return A new String decoded from the specified array of bytes using the UTF-8 charset, or + * null if the input byte array was null. + * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since + * it is required by the Java platform specification. + * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException + */ + public static String newStringUtf8(final byte[] bytes) { + return newString(bytes, Charsets.UTF_8); + } + + /** + * Calls {@link String#getBytes(Charset)} + * + * @param string The string to encode (if null, return null). + * @param charset The {@link Charset} to encode the String + * @return the encoded bytes + */ + private static byte[] getBytes(final String string, final Charset charset) { + if (string == null) { + return null; + } + return string.getBytes(charset); + } + + /** + * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte + * array. + * + * @param string the String to encode, may be null + * @return encoded bytes, or null if the input string was null + * @throws NullPointerException Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since + * it is required by the Java platform specification. + * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException + * @see Standard charsets + * @see #getBytesUnchecked(String, String) + */ + public static byte[] getBytesUtf8(final String string) { + return getBytes(string, Charsets.UTF_8); + } +} diff --git a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Validate.java b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Validate.java index ad227d3..cdd0326 100644 --- a/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Validate.java +++ b/si-modules/LWM2M_IPE_Server/org/eclipse/leshan/util/Validate.java @@ -1,575 +1,575 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.eclipse.leshan.util; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -/** - *

- * This class assists in validating arguments. - *

- * - *

- * The class is based along the lines of JUnit. If an argument value is deemed invalid, an IllegalArgumentException is - * thrown. For example: - *

- * - *
- * Validate.isTrue(i > 0, "The value must be greater than zero: ", i);
- * Validate.notNull(surname, "The surname must not be null");
- * 
- * - * @author Apache Software Foundation - * @author Ola Berg - * @author Gary Gregory - * @author Norm Deane - * @since 2.0 - * @version $Id: Validate.java 1057051 2011-01-09 23:15:51Z sebb $ - */ -@SuppressWarnings("rawtypes") -public class Validate { - // Validate has no dependencies on other classes in Commons Lang at present - - /** - * Constructor. This class should not normally be instantiated. - */ - public Validate() { - super(); - } - - // isTrue - // --------------------------------------------------------------------------------- - /** - *

- * Validate that the argument condition is true; otherwise throwing an exception with the specified - * message. This method is useful when validating according to an arbitrary boolean expression, such as validating - * an object or using your own custom validation expression. - *

- * - *
-     * Validate.isTrue(myObject.isOk(), "The object is not OK: ", myObject);
-     * 
- * - *

- * For performance reasons, the object value is passed as a separate parameter and appended to the exception message - * only in the case of an error. - *

- * - * @param expression the boolean expression to check - * @param message the exception message if invalid - * @param value the value to append to the message when invalid - * @throws IllegalArgumentException if expression is false - */ - public static void isTrue(boolean expression, String message, Object value) { - if (expression == false) { - throw new IllegalArgumentException(message + value); - } - } - - /** - *

- * Validate that the argument condition is true; otherwise throwing an exception with the specified - * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a - * primitive number or using your own custom validation expression. - *

- * - *
-     * Validate.isTrue(i > 0.0, "The value must be greater than zero: ", i);
-     * 
- * - *

- * For performance reasons, the long value is passed as a separate parameter and appended to the exception message - * only in the case of an error. - *

- * - * @param expression the boolean expression to check - * @param message the exception message if invalid - * @param value the value to append to the message when invalid - * @throws IllegalArgumentException if expression is false - */ - public static void isTrue(boolean expression, String message, long value) { - if (expression == false) { - throw new IllegalArgumentException(message + value); - } - } - - /** - *

- * Validate that the argument condition is true; otherwise throwing an exception with the specified - * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a - * primitive number or using your own custom validation expression. - *

- * - *
-     * Validate.isTrue(d > 0.0, "The value must be greater than zero: ", d);
-     * 
- * - *

- * For performance reasons, the double value is passed as a separate parameter and appended to the exception message - * only in the case of an error. - *

- * - * @param expression the boolean expression to check - * @param message the exception message if invalid - * @param value the value to append to the message when invalid - * @throws IllegalArgumentException if expression is false - */ - public static void isTrue(boolean expression, String message, double value) { - if (expression == false) { - throw new IllegalArgumentException(message + value); - } - } - - /** - *

- * Validate that the argument condition is true; otherwise throwing an exception with the specified - * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a - * primitive number or using your own custom validation expression. - *

- * - *
-     * Validate.isTrue((i > 0), "The value must be greater than zero");
-     * Validate.isTrue(myObject.isOk(), "The object is not OK");
-     * 
- * - * @param expression the boolean expression to check - * @param message the exception message if invalid - * @throws IllegalArgumentException if expression is false - */ - public static void isTrue(boolean expression, String message) { - if (expression == false) { - throw new IllegalArgumentException(message); - } - } - - /** - *

- * Validate that the argument condition is true; otherwise throwing an exception. This method is useful - * when validating according to an arbitrary boolean expression, such as validating a primitive number or using your - * own custom validation expression. - *

- * - *
-     * Validate.isTrue(i > 0);
-     * Validate.isTrue(myObject.isOk());
-     * 
- * - *

- * The message of the exception is "The validated expression is false". - *

- * - * @param expression the boolean expression to check - * @throws IllegalArgumentException if expression is false - */ - public static void isTrue(boolean expression) { - if (expression == false) { - throw new IllegalArgumentException("The validated expression is false"); - } - } - - // notNull - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument is not null; otherwise throwing an exception. - * - *

-     * Validate.notNull(myObject);
-     * 
- * - *

- * The message of the exception is "The validated object is null". - *

- * - * @param object the object to check - * @throws IllegalArgumentException if the object is null - */ - public static void notNull(Object object) { - notNull(object, "The validated object is null"); - } - - /** - *

- * Validate that the specified argument is not null; otherwise throwing an exception with the specified - * message. - * - *

-     * Validate.notNull(myObject, "The object must not be null");
-     * 
- * - * @param object the object to check - * @param message the exception message if invalid - */ - public static void notNull(Object object, String message) { - if (object == null) { - throw new IllegalArgumentException(message); - } - } - - // notEmpty array - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument array is neither null nor a length of zero (no elements); - * otherwise throwing an exception with the specified message. - * - *

-     * Validate.notEmpty(myArray, "The array must not be empty");
-     * 
- * - * @param array the array to check - * @param message the exception message if invalid - * @throws IllegalArgumentException if the array is empty - */ - public static void notEmpty(Object[] array, String message) { - if (array == null || array.length == 0) { - throw new IllegalArgumentException(message); - } - } - - /** - *

- * Validate that the specified argument array is neither null nor a length of zero (no elements); - * otherwise throwing an exception. - * - *

-     * Validate.notEmpty(myArray);
-     * 
- * - *

- * The message in the exception is "The validated array is empty". - * - * @param array the array to check - * @throws IllegalArgumentException if the array is empty - */ - public static void notEmpty(Object[] array) { - notEmpty(array, "The validated array is empty"); - } - - // notEmpty collection - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument collection is neither null nor a size of zero (no elements); - * otherwise throwing an exception with the specified message. - * - *

-     * Validate.notEmpty(myCollection, "The collection must not be empty");
-     * 
- * - * @param collection the collection to check - * @param message the exception message if invalid - * @throws IllegalArgumentException if the collection is empty - */ - public static void notEmpty(Collection collection, String message) { - if (collection == null || collection.size() == 0) { - throw new IllegalArgumentException(message); - } - } - - /** - *

- * Validate that the specified argument collection is neither null nor a size of zero (no elements); - * otherwise throwing an exception. - * - *

-     * Validate.notEmpty(myCollection);
-     * 
- * - *

- * The message in the exception is "The validated collection is empty". - *

- * - * @param collection the collection to check - * @throws IllegalArgumentException if the collection is empty - */ - public static void notEmpty(Collection collection) { - notEmpty(collection, "The validated collection is empty"); - } - - // notEmpty map - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument map is neither null nor a size of zero (no elements); otherwise - * throwing an exception with the specified message. - * - *

-     * Validate.notEmpty(myMap, "The map must not be empty");
-     * 
- * - * @param map the map to check - * @param message the exception message if invalid - * @throws IllegalArgumentException if the map is empty - */ - public static void notEmpty(Map map, String message) { - if (map == null || map.size() == 0) { - throw new IllegalArgumentException(message); - } - } - - /** - *

- * Validate that the specified argument map is neither null nor a size of zero (no elements); otherwise - * throwing an exception. - * - *

-     * Validate.notEmpty(myMap);
-     * 
- * - *

- * The message in the exception is "The validated map is empty". - *

- * - * @param map the map to check - * @throws IllegalArgumentException if the map is empty - * @see #notEmpty(Map, String) - */ - public static void notEmpty(Map map) { - notEmpty(map, "The validated map is empty"); - } - - // notEmpty string - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument string is neither null nor a length of zero (no characters); - * otherwise throwing an exception with the specified message. - * - *

-     * Validate.notEmpty(myString, "The string must not be empty");
-     * 
- * - * @param string the string to check - * @param message the exception message if invalid - * @throws IllegalArgumentException if the string is empty - */ - public static void notEmpty(String string, String message) { - if (string == null || string.length() == 0) { - throw new IllegalArgumentException(message); - } - } - - /** - *

- * Validate that the specified argument string is neither null nor a length of zero (no characters); - * otherwise throwing an exception with the specified message. - * - *

-     * Validate.notEmpty(myString);
-     * 
- * - *

- * The message in the exception is "The validated string is empty". - *

- * - * @param string the string to check - * @throws IllegalArgumentException if the string is empty - */ - public static void notEmpty(String string) { - notEmpty(string, "The validated string is empty"); - } - - // notNullElements array - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument array is neither null nor contains any elements that are - * null; otherwise throwing an exception with the specified message. - * - *

-     * Validate.noNullElements(myArray, "The array contain null at position %d");
-     * 
- * - *

- * If the array is null, then the message in the exception is "The validated object is null". - *

- * - * @param array the array to check - * @param message the exception message if the collection has null elements - * @throws IllegalArgumentException if the array is null or an element in the array is - * null - */ - public static void noNullElements(Object[] array, String message) { - Validate.notNull(array); - for (int i = 0; i < array.length; i++) { - if (array[i] == null) { - throw new IllegalArgumentException(message); - } - } - } - - /** - *

- * Validate that the specified argument array is neither null nor contains any elements that are - * null; otherwise throwing an exception. - * - *

-     * Validate.noNullElements(myArray);
-     * 
- * - *

- * If the array is null, then the message in the exception is "The validated object is null". - *

- * - *

- * If the array has a null element, then the message in the exception is "The validated array - * contains null element at index: " followed by the index. - *

- * - * @param array the array to check - * @throws IllegalArgumentException if the array is null or an element in the array is - * null - */ - public static void noNullElements(Object[] array) { - Validate.notNull(array); - for (int i = 0; i < array.length; i++) { - if (array[i] == null) { - throw new IllegalArgumentException("The validated array contains null element at index: " + i); - } - } - } - - // notNullElements collection - // --------------------------------------------------------------------------------- - - /** - *

- * Validate that the specified argument collection is neither null nor contains any elements that are - * null; otherwise throwing an exception with the specified message. - * - *

-     * Validate.noNullElements(myCollection, "The collection contains null elements");
-     * 
- * - *

- * If the collection is null, then the message in the exception is "The validated object is - * null". - *

- * - * - * @param collection the collection to check - * @param message the exception message if the collection has - * @throws IllegalArgumentException if the collection is null or an element in the collection is - * null - */ - public static void noNullElements(Collection collection, String message) { - Validate.notNull(collection); - for (Iterator it = collection.iterator(); it.hasNext();) { - if (it.next() == null) { - throw new IllegalArgumentException(message); - } - } - } - - /** - *

- * Validate that the specified argument collection is neither null nor contains any elements that are - * null; otherwise throwing an exception. - * - *

-     * Validate.noNullElements(myCollection);
-     * 
- * - *

- * If the collection is null, then the message in the exception is "The validated object is - * null". - *

- * - *

- * If the collection has a null element, then the message in the exception is "The validated - * collection contains null element at index: " followed by the index. - *

- * - * @param collection the collection to check - * @throws IllegalArgumentException if the collection is null or an element in the collection is - * null - */ - public static void noNullElements(Collection collection) { - Validate.notNull(collection); - int i = 0; - for (Iterator it = collection.iterator(); it.hasNext(); i++) { - if (it.next() == null) { - throw new IllegalArgumentException("The validated collection contains null element at index: " + i); - } - } - } - - /** - *

- * Validate an argument, throwing IllegalArgumentException if the argument collection is - * null or has elements that are not of type clazz or a subclass. - *

- * - *
-     * Validate.allElementsOfType(collection, String.class, "Collection has invalid elements");
-     * 
- * - * @param collection the collection to check, not null - * @param clazz the Class which the collection's elements are expected to be, not null - * @param message the exception message if the Collection has elements not of type clazz - * @since 2.1 - */ - public static void allElementsOfType(Collection collection, Class clazz, String message) { - Validate.notNull(collection); - Validate.notNull(clazz); - for (Iterator it = collection.iterator(); it.hasNext();) { - if (clazz.isInstance(it.next()) == false) { - throw new IllegalArgumentException(message); - } - } - } - - /** - *

- * Validate an argument, throwing IllegalArgumentException if the argument collection is - * null or has elements that are not of type clazz or a subclass. - *

- * - *
-     * Validate.allElementsOfType(collection, String.class);
-     * 
- * - *

- * The message in the exception is 'The validated collection contains an element not of type clazz at index: '. - *

- * - * @param collection the collection to check, not null - * @param clazz the Class which the collection's elements are expected to be, not null - * @since 2.1 - */ - public static void allElementsOfType(Collection collection, Class clazz) { - Validate.notNull(collection); - Validate.notNull(clazz); - int i = 0; - for (Iterator it = collection.iterator(); it.hasNext(); i++) { - if (clazz.isInstance(it.next()) == false) { - throw new IllegalArgumentException("The validated collection contains an element not of type " - + clazz.getName() + " at index: " + i); - } - } - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.eclipse.leshan.util; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +/** + *

+ * This class assists in validating arguments. + *

+ * + *

+ * The class is based along the lines of JUnit. If an argument value is deemed invalid, an IllegalArgumentException is + * thrown. For example: + *

+ * + *
+ * Validate.isTrue(i > 0, "The value must be greater than zero: ", i);
+ * Validate.notNull(surname, "The surname must not be null");
+ * 
+ * + * @author Apache Software Foundation + * @author Ola Berg + * @author Gary Gregory + * @author Norm Deane + * @since 2.0 + * @version $Id: Validate.java 1057051 2011-01-09 23:15:51Z sebb $ + */ +@SuppressWarnings("rawtypes") +public class Validate { + // Validate has no dependencies on other classes in Commons Lang at present + + /** + * Constructor. This class should not normally be instantiated. + */ + public Validate() { + super(); + } + + // isTrue + // --------------------------------------------------------------------------------- + /** + *

+ * Validate that the argument condition is true; otherwise throwing an exception with the specified + * message. This method is useful when validating according to an arbitrary boolean expression, such as validating + * an object or using your own custom validation expression. + *

+ * + *
+     * Validate.isTrue(myObject.isOk(), "The object is not OK: ", myObject);
+     * 
+ * + *

+ * For performance reasons, the object value is passed as a separate parameter and appended to the exception message + * only in the case of an error. + *

+ * + * @param expression the boolean expression to check + * @param message the exception message if invalid + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is false + */ + public static void isTrue(boolean expression, String message, Object value) { + if (expression == false) { + throw new IllegalArgumentException(message + value); + } + } + + /** + *

+ * Validate that the argument condition is true; otherwise throwing an exception with the specified + * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression. + *

+ * + *
+     * Validate.isTrue(i > 0.0, "The value must be greater than zero: ", i);
+     * 
+ * + *

+ * For performance reasons, the long value is passed as a separate parameter and appended to the exception message + * only in the case of an error. + *

+ * + * @param expression the boolean expression to check + * @param message the exception message if invalid + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is false + */ + public static void isTrue(boolean expression, String message, long value) { + if (expression == false) { + throw new IllegalArgumentException(message + value); + } + } + + /** + *

+ * Validate that the argument condition is true; otherwise throwing an exception with the specified + * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression. + *

+ * + *
+     * Validate.isTrue(d > 0.0, "The value must be greater than zero: ", d);
+     * 
+ * + *

+ * For performance reasons, the double value is passed as a separate parameter and appended to the exception message + * only in the case of an error. + *

+ * + * @param expression the boolean expression to check + * @param message the exception message if invalid + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is false + */ + public static void isTrue(boolean expression, String message, double value) { + if (expression == false) { + throw new IllegalArgumentException(message + value); + } + } + + /** + *

+ * Validate that the argument condition is true; otherwise throwing an exception with the specified + * message. This method is useful when validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression. + *

+ * + *
+     * Validate.isTrue((i > 0), "The value must be greater than zero");
+     * Validate.isTrue(myObject.isOk(), "The object is not OK");
+     * 
+ * + * @param expression the boolean expression to check + * @param message the exception message if invalid + * @throws IllegalArgumentException if expression is false + */ + public static void isTrue(boolean expression, String message) { + if (expression == false) { + throw new IllegalArgumentException(message); + } + } + + /** + *

+ * Validate that the argument condition is true; otherwise throwing an exception. This method is useful + * when validating according to an arbitrary boolean expression, such as validating a primitive number or using your + * own custom validation expression. + *

+ * + *
+     * Validate.isTrue(i > 0);
+     * Validate.isTrue(myObject.isOk());
+     * 
+ * + *

+ * The message of the exception is "The validated expression is false". + *

+ * + * @param expression the boolean expression to check + * @throws IllegalArgumentException if expression is false + */ + public static void isTrue(boolean expression) { + if (expression == false) { + throw new IllegalArgumentException("The validated expression is false"); + } + } + + // notNull + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument is not null; otherwise throwing an exception. + * + *

+     * Validate.notNull(myObject);
+     * 
+ * + *

+ * The message of the exception is "The validated object is null". + *

+ * + * @param object the object to check + * @throws IllegalArgumentException if the object is null + */ + public static void notNull(Object object) { + notNull(object, "The validated object is null"); + } + + /** + *

+ * Validate that the specified argument is not null; otherwise throwing an exception with the specified + * message. + * + *

+     * Validate.notNull(myObject, "The object must not be null");
+     * 
+ * + * @param object the object to check + * @param message the exception message if invalid + */ + public static void notNull(Object object, String message) { + if (object == null) { + throw new IllegalArgumentException(message); + } + } + + // notEmpty array + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument array is neither null nor a length of zero (no elements); + * otherwise throwing an exception with the specified message. + * + *

+     * Validate.notEmpty(myArray, "The array must not be empty");
+     * 
+ * + * @param array the array to check + * @param message the exception message if invalid + * @throws IllegalArgumentException if the array is empty + */ + public static void notEmpty(Object[] array, String message) { + if (array == null || array.length == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + *

+ * Validate that the specified argument array is neither null nor a length of zero (no elements); + * otherwise throwing an exception. + * + *

+     * Validate.notEmpty(myArray);
+     * 
+ * + *

+ * The message in the exception is "The validated array is empty". + * + * @param array the array to check + * @throws IllegalArgumentException if the array is empty + */ + public static void notEmpty(Object[] array) { + notEmpty(array, "The validated array is empty"); + } + + // notEmpty collection + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument collection is neither null nor a size of zero (no elements); + * otherwise throwing an exception with the specified message. + * + *

+     * Validate.notEmpty(myCollection, "The collection must not be empty");
+     * 
+ * + * @param collection the collection to check + * @param message the exception message if invalid + * @throws IllegalArgumentException if the collection is empty + */ + public static void notEmpty(Collection collection, String message) { + if (collection == null || collection.size() == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + *

+ * Validate that the specified argument collection is neither null nor a size of zero (no elements); + * otherwise throwing an exception. + * + *

+     * Validate.notEmpty(myCollection);
+     * 
+ * + *

+ * The message in the exception is "The validated collection is empty". + *

+ * + * @param collection the collection to check + * @throws IllegalArgumentException if the collection is empty + */ + public static void notEmpty(Collection collection) { + notEmpty(collection, "The validated collection is empty"); + } + + // notEmpty map + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument map is neither null nor a size of zero (no elements); otherwise + * throwing an exception with the specified message. + * + *

+     * Validate.notEmpty(myMap, "The map must not be empty");
+     * 
+ * + * @param map the map to check + * @param message the exception message if invalid + * @throws IllegalArgumentException if the map is empty + */ + public static void notEmpty(Map map, String message) { + if (map == null || map.size() == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + *

+ * Validate that the specified argument map is neither null nor a size of zero (no elements); otherwise + * throwing an exception. + * + *

+     * Validate.notEmpty(myMap);
+     * 
+ * + *

+ * The message in the exception is "The validated map is empty". + *

+ * + * @param map the map to check + * @throws IllegalArgumentException if the map is empty + * @see #notEmpty(Map, String) + */ + public static void notEmpty(Map map) { + notEmpty(map, "The validated map is empty"); + } + + // notEmpty string + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument string is neither null nor a length of zero (no characters); + * otherwise throwing an exception with the specified message. + * + *

+     * Validate.notEmpty(myString, "The string must not be empty");
+     * 
+ * + * @param string the string to check + * @param message the exception message if invalid + * @throws IllegalArgumentException if the string is empty + */ + public static void notEmpty(String string, String message) { + if (string == null || string.length() == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + *

+ * Validate that the specified argument string is neither null nor a length of zero (no characters); + * otherwise throwing an exception with the specified message. + * + *

+     * Validate.notEmpty(myString);
+     * 
+ * + *

+ * The message in the exception is "The validated string is empty". + *

+ * + * @param string the string to check + * @throws IllegalArgumentException if the string is empty + */ + public static void notEmpty(String string) { + notEmpty(string, "The validated string is empty"); + } + + // notNullElements array + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument array is neither null nor contains any elements that are + * null; otherwise throwing an exception with the specified message. + * + *

+     * Validate.noNullElements(myArray, "The array contain null at position %d");
+     * 
+ * + *

+ * If the array is null, then the message in the exception is "The validated object is null". + *

+ * + * @param array the array to check + * @param message the exception message if the collection has null elements + * @throws IllegalArgumentException if the array is null or an element in the array is + * null + */ + public static void noNullElements(Object[] array, String message) { + Validate.notNull(array); + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + throw new IllegalArgumentException(message); + } + } + } + + /** + *

+ * Validate that the specified argument array is neither null nor contains any elements that are + * null; otherwise throwing an exception. + * + *

+     * Validate.noNullElements(myArray);
+     * 
+ * + *

+ * If the array is null, then the message in the exception is "The validated object is null". + *

+ * + *

+ * If the array has a null element, then the message in the exception is "The validated array + * contains null element at index: " followed by the index. + *

+ * + * @param array the array to check + * @throws IllegalArgumentException if the array is null or an element in the array is + * null + */ + public static void noNullElements(Object[] array) { + Validate.notNull(array); + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + throw new IllegalArgumentException("The validated array contains null element at index: " + i); + } + } + } + + // notNullElements collection + // --------------------------------------------------------------------------------- + + /** + *

+ * Validate that the specified argument collection is neither null nor contains any elements that are + * null; otherwise throwing an exception with the specified message. + * + *

+     * Validate.noNullElements(myCollection, "The collection contains null elements");
+     * 
+ * + *

+ * If the collection is null, then the message in the exception is "The validated object is + * null". + *

+ * + * + * @param collection the collection to check + * @param message the exception message if the collection has + * @throws IllegalArgumentException if the collection is null or an element in the collection is + * null + */ + public static void noNullElements(Collection collection, String message) { + Validate.notNull(collection); + for (Iterator it = collection.iterator(); it.hasNext();) { + if (it.next() == null) { + throw new IllegalArgumentException(message); + } + } + } + + /** + *

+ * Validate that the specified argument collection is neither null nor contains any elements that are + * null; otherwise throwing an exception. + * + *

+     * Validate.noNullElements(myCollection);
+     * 
+ * + *

+ * If the collection is null, then the message in the exception is "The validated object is + * null". + *

+ * + *

+ * If the collection has a null element, then the message in the exception is "The validated + * collection contains null element at index: " followed by the index. + *

+ * + * @param collection the collection to check + * @throws IllegalArgumentException if the collection is null or an element in the collection is + * null + */ + public static void noNullElements(Collection collection) { + Validate.notNull(collection); + int i = 0; + for (Iterator it = collection.iterator(); it.hasNext(); i++) { + if (it.next() == null) { + throw new IllegalArgumentException("The validated collection contains null element at index: " + i); + } + } + } + + /** + *

+ * Validate an argument, throwing IllegalArgumentException if the argument collection is + * null or has elements that are not of type clazz or a subclass. + *

+ * + *
+     * Validate.allElementsOfType(collection, String.class, "Collection has invalid elements");
+     * 
+ * + * @param collection the collection to check, not null + * @param clazz the Class which the collection's elements are expected to be, not null + * @param message the exception message if the Collection has elements not of type clazz + * @since 2.1 + */ + public static void allElementsOfType(Collection collection, Class clazz, String message) { + Validate.notNull(collection); + Validate.notNull(clazz); + for (Iterator it = collection.iterator(); it.hasNext();) { + if (clazz.isInstance(it.next()) == false) { + throw new IllegalArgumentException(message); + } + } + } + + /** + *

+ * Validate an argument, throwing IllegalArgumentException if the argument collection is + * null or has elements that are not of type clazz or a subclass. + *

+ * + *
+     * Validate.allElementsOfType(collection, String.class);
+     * 
+ * + *

+ * The message in the exception is 'The validated collection contains an element not of type clazz at index: '. + *

+ * + * @param collection the collection to check, not null + * @param clazz the Class which the collection's elements are expected to be, not null + * @since 2.1 + */ + public static void allElementsOfType(Collection collection, Class clazz) { + Validate.notNull(collection); + Validate.notNull(clazz); + int i = 0; + for (Iterator it = collection.iterator(); it.hasNext(); i++) { + if (clazz.isInstance(it.next()) == false) { + throw new IllegalArgumentException("The validated collection contains an element not of type " + + clazz.getName() + " at index: " + i); + } + } + } + +} diff --git a/si-modules/LWM2M_IPE_Server/pom.xml b/si-modules/LWM2M_IPE_Server/pom.xml index f4fc115..21ead24 100644 --- a/si-modules/LWM2M_IPE_Server/pom.xml +++ b/si-modules/LWM2M_IPE_Server/pom.xml @@ -1,15 +1,15 @@ - - 4.0.0 - - net.herit.iot - LWM2M_IPE_Server - 0.0.1-SNAPSHOT - pom - - LWM2M_IPE_Server - Lightweight M2M(LWM2M) based on leshan - - leshan-server-core - lwm2m-server-dms - + + 4.0.0 + + net.herit.iot + LWM2M_IPE_Server + 0.0.1-SNAPSHOT + pom + + LWM2M_IPE_Server + Lightweight M2M(LWM2M) based on leshan + + leshan-server-core + lwm2m-server-dms + \ No newline at end of file diff --git a/si-modules/OIC-IPE/.classpath b/si-modules/OIC-IPE/.classpath deleted file mode 100644 index b56f1e4..0000000 --- a/si-modules/OIC-IPE/.classpath +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-onem2m-src/.classpath b/si-onem2m-src/.classpath deleted file mode 100644 index b5ef8a2..0000000 --- a/si-onem2m-src/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/si-onem2m-src/incse.xml b/si-onem2m-src/incse.xml index 7f25e86..e1206c3 100644 --- a/si-onem2m-src/incse.xml +++ b/si-onem2m-src/incse.xml @@ -1,115 +1,115 @@ - - - - localhost - 27017 - IITP-IOT - - - - - - - - - 8080 - 8443 - 8081 - - 0 - 1024 - - - - - no - 1200 - - - tcp://10.10.0.22:1883 - - - - - no - 5683 - 4433 - - - - no - 8887 - - - - - 10.10.0.23 - herit-cse - herit-in - http://10.10.0.23:8080 - - 3 - 3 - - - 10 - 1 - - - http - 10.10.224.241 - 80 - - - - - - - -
http://10.101.101.107:8888
-
-
- - -1 - 64 - 300 - - - - 50 - - - -
- + + + + localhost + 27017 + IITP-IOT + + + + + + + + + 8080 + 8443 + 8081 + + 0 + 1024 + + + + + no + 1200 + + + tcp://10.10.0.22:1883 + + + + + no + 5683 + 4433 + + + + no + 8887 + + + + + 10.10.0.23 + herit-cse + herit-in + http://10.10.0.23:8080 + + 3 + 3 + + + 10 + 1 + + + http + 10.10.224.241 + 80 + + + + + + + +
http://10.101.101.107:8888
+
+
+ + -1 + 64 + 300 + + + + 50 + + + +
+