From d98a56c8673b218d3d17edf1d1736f52ca95a828 Mon Sep 17 00:00:00 2001 From: Matthew Schwartz Date: Fri, 24 May 2019 13:00:35 -0400 Subject: [PATCH 01/10] [maven-release-plugin] prepare for next development iteration --- jpo-ode-common/pom.xml | 2 +- jpo-ode-core/pom.xml | 6 +++--- jpo-ode-plugins/pom.xml | 4 ++-- jpo-ode-svcs/pom.xml | 6 +++--- pom.xml | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/jpo-ode-common/pom.xml b/jpo-ode-common/pom.xml index d6d0368a7..63e6af4ad 100644 --- a/jpo-ode-common/pom.xml +++ b/jpo-ode-common/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.8 + 0.0.9-SNAPSHOT jpo-ode-common diff --git a/jpo-ode-core/pom.xml b/jpo-ode-core/pom.xml index c5b7a39e3..acfc39dd3 100644 --- a/jpo-ode-core/pom.xml +++ b/jpo-ode-core/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.8 + 0.0.9-SNAPSHOT jpo-ode-core @@ -23,12 +23,12 @@ usdot.jpo.ode jpo-ode-common - 0.0.8 + 0.0.9-SNAPSHOT usdot.jpo.ode jpo-ode-plugins - 0.0.8 + 0.0.9-SNAPSHOT org.apache.httpcomponents diff --git a/jpo-ode-plugins/pom.xml b/jpo-ode-plugins/pom.xml index c537f83ca..f0cbfa9ff 100644 --- a/jpo-ode-plugins/pom.xml +++ b/jpo-ode-plugins/pom.xml @@ -11,7 +11,7 @@ usdot.jpo.ode jpo-ode - 0.0.8 + 0.0.9-SNAPSHOT @@ -27,7 +27,7 @@ usdot.jpo.ode jpo-ode-common - 0.0.8 + 0.0.9-SNAPSHOT /)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,""),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:"space"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,"");this.tokens.push({type:"code",text:!this.options.pedantic?cap.replace(/\n+$/,""):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")};for(i=0;i ?/gm,"");this.token(cap,top,true);this.tokens.push({type:"blockquote_end"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:"list_start",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join("\n")+src;i=l-1}}loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==="\n";if(!loose)loose=next}this.tokens.push({type:loose?"loose_item_start":"list_item_start"});this.token(item,false,bq);this.tokens.push({type:"list_item_end"})}this.tokens.push({type:"list_end"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&(cap[1]==="pre"||cap[1]==="script"||cap[1]==="style"),text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(i=0;i])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)();inline.reflink=replace(inline.reflink)("inside",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error("Tokens array requires a `links` property.")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out="",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==="@"){text=cap[1].charAt(6)===":"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle("mailto:")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g," ");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue}if(src){throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=="!"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"â€").replace(/\.{3}/g,"…")};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out="",l=text.length,i=0,ch;for(;i.5){ch="x"+ch.toString(16)}out+="&#"+ch+";"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return"
"+(escaped?code:escape(code,true))+"\n
"}return'
'+(escaped?code:escape(code,true))+"\n
\n"};Renderer.prototype.blockquote=function(quote){return"
\n"+quote+"
\n"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return"'+text+"\n"};Renderer.prototype.hr=function(){return this.options.xhtml?"
\n":"
\n"};Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+"\n"};Renderer.prototype.listitem=function(text){return"
  • "+text+"
  • \n"};Renderer.prototype.paragraph=function(text){return"

    "+text+"

    \n"};Renderer.prototype.table=function(header,body){return"\n"+"\n"+header+"\n"+"\n"+body+"\n"+"
    \n"};Renderer.prototype.tablerow=function(content){return"\n"+content+"\n"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";var tag=flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">";return tag+content+"\n"};Renderer.prototype.strong=function(text){return""+text+""};Renderer.prototype.em=function(text){return""+text+""};Renderer.prototype.codespan=function(text){return""+text+""};Renderer.prototype.br=function(){return this.options.xhtml?"
    ":"
    "};Renderer.prototype.del=function(text){return""+text+""};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(prot.indexOf("javascript:")===0||prot.indexOf("vbscript:")===0){return""}}var out='
    ";return out};Renderer.prototype.image=function(href,title,text){var out=''+text+'":">";return out};Renderer.prototype.text=function(text){return text};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out="";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==="text"){body+="\n"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case"space":{return""}case"hr":{return this.renderer.hr()}case"heading":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case"code":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case"table":{var header="",body="",i,row,cell,flags,j;cell="";for(i=0;i/g,">").replace(/"/g,""").replace(/'/g,"'")}function unescape(html){return html.replace(/&([#\w]+);/g,function(_,n){n=n.toLowerCase();if(n==="colon")return":";if(n.charAt(0)==="#"){return n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1))}return""})}function replace(regex,opt){regex=regex.source;opt=opt||"";return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^\[])\^/g,"$1");regex=regex.replace(name,val);return self}}function noop(){}noop.exec=noop;function merge(obj){var i=1,target,key;for(;iAn error occurred:

    "+escape(e.message+"",true)+"
    "}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:"lang-",smartypants:false,headerPrefix:"",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=="undefined"&&typeof exports==="object"){module.exports=marked}else if(typeof define==="function"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!=="undefined"?window:global)}()); - - - - - - - - -
    -
    - -
    -
    -
    -

    ODE REST API

    -
    -
    -
    - -
    -
    -

    LogFile

    -
    -
    -
    -

    uploadObulog

    -

    File upload interface

    -
    -
    -
    -

    -

    Uploads an OBU log file to ODE upload folder to be processed and propaged

    -

    -
    -
    /upload/obulog
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/upload/obulog"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.LogFileApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class LogFileApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        LogFileApi apiInstance = new LogFileApi();
    -        File file = /path/to/file.txt; // File | The file to upload.
    -        try {
    -            array[Status] result = apiInstance.uploadObulog(file);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling LogFileApi#uploadObulog");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.LogFileApi;
    -
    -public class LogFileApiExample {
    -
    -    public static void main(String[] args) {
    -        LogFileApi apiInstance = new LogFileApi();
    -        File file = /path/to/file.txt; // File | The file to upload.
    -        try {
    -            array[Status] result = apiInstance.uploadObulog(file);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling LogFileApi#uploadObulog");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    File *file = /path/to/file.txt; // The file to upload. (optional)
    -
    -LogFileApi *apiInstance = [[LogFileApi alloc] init];
    -
    -// File upload interface
    -[apiInstance uploadObulogWith:file
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.LogFileApi()
    -
    -var opts = { 
    -  'file': /path/to/file.txt // {File} The file to upload.
    -};
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.uploadObulog(opts, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class uploadObulogExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new LogFileApi();
    -            var file = new File(); // File | The file to upload. (optional) 
    -
    -            try
    -            {
    -                // File upload interface
    -                array[Status] result = apiInstance.uploadObulog(file);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling LogFileApi.uploadObulog: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\LogFileApi();
    -$file = /path/to/file.txt; // File | The file to upload.
    -
    -try {
    -    $result = $api_instance->uploadObulog($file);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling LogFileApi->uploadObulog: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::LogFileApi;
    -
    -my $api_instance = WWW::SwaggerClient::LogFileApi->new();
    -my $file = /path/to/file.txt; # File | The file to upload.
    -
    -eval { 
    -    my $result = $api_instance->uploadObulog(file => $file);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling LogFileApi->uploadObulog: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.LogFileApi()
    -file = /path/to/file.txt # File | The file to upload. (optional)
    -
    -try: 
    -    # File upload interface
    -    api_response = api_instance.upload_obulog(file=file)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling LogFileApi->uploadObulog: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - -
    Form parameters
    - - - - - - - - - -
    NameDescription
    file - - -
    -
    -
    - - File - - -
    - The file to upload. -
    -
    -
    -
    -
    - - -

    Responses

    -

    Status: 200 - File uploaded successfully

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    PDM

    -
    -
    -
    -

    pdmPost

    -

    PDM Interface

    -
    -
    -
    -

    -

    Submits a Probe Data Management message to ODE for distribution to the specified RSUs.

    -

    -
    -
    /pdm
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/pdm"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.PDMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class PDMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        PDMApi apiInstance = new PDMApi();
    -        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    -        try {
    -            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling PDMApi#pdmPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.PDMApi;
    -
    -public class PDMApiExample {
    -
    -    public static void main(String[] args) {
    -        PDMApi apiInstance = new PDMApi();
    -        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    -        try {
    -            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling PDMApi#pdmPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    ProbeDataManagement *probeDataManagement = ; // PDM Message
    -
    -PDMApi *apiInstance = [[PDMApi alloc] init];
    -
    -// PDM Interface
    -[apiInstance pdmPostWith:probeDataManagement
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.PDMApi()
    -
    -var probeDataManagement = ; // {ProbeDataManagement} PDM Message
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.pdmPost(probeDataManagement, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class pdmPostExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new PDMApi();
    -            var probeDataManagement = new ProbeDataManagement(); // ProbeDataManagement | PDM Message
    -
    -            try
    -            {
    -                // PDM Interface
    -                array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling PDMApi.pdmPost: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\PDMApi();
    -$probeDataManagement = ; // ProbeDataManagement | PDM Message
    -
    -try {
    -    $result = $api_instance->pdmPost($probeDataManagement);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling PDMApi->pdmPost: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::PDMApi;
    -
    -my $api_instance = WWW::SwaggerClient::PDMApi->new();
    -my $probeDataManagement = WWW::SwaggerClient::Object::ProbeDataManagement->new(); # ProbeDataManagement | PDM Message
    -
    -eval { 
    -    my $result = $api_instance->pdmPost(probeDataManagement => $probeDataManagement);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling PDMApi->pdmPost: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.PDMApi()
    -probeDataManagement =  # ProbeDataManagement | PDM Message
    -
    -try: 
    -    # PDM Interface
    -    api_response = api_instance.pdm_post(probeDataManagement)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling PDMApi->pdmPost: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    probeDataManagement * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Probe Data Management message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    SNMP

    -
    -
    -
    -

    snmpGet

    -

    RSU SNMP Query

    -
    -
    -
    -

    -

    Check the health and status of RSU devices through SNMP communication. You should receive a detailed plain text response that looks like the following example. If the device is off, a 4 second timeout will occur and the ODE will indicate this with an "[ERROR] Empty response" message. (This specific OID returns the amount of time since the device was last powered on) "[1.3.6.1.2.1.1.3.0 = 0:05:12.59]"

    -

    -
    -
    /rsuHeartbeat
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X GET "https://yourhostname/rsuHeartbeat?ip=&oid="
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.SNMPApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class SNMPApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        SNMPApi apiInstance = new SNMPApi();
    -        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    -        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -        try {
    -            Status result = apiInstance.snmpGet(ip, oid);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling SNMPApi#snmpGet");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.SNMPApi;
    -
    -public class SNMPApiExample {
    -
    -    public static void main(String[] args) {
    -        SNMPApi apiInstance = new SNMPApi();
    -        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    -        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -        try {
    -            Status result = apiInstance.snmpGet(ip, oid);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling SNMPApi#snmpGet");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    BigDecimal *ip = 8.14; // IP address of an RSU
    -BigDecimal *oid = 8.14; // OID of the attribute you wish to check on
    -
    -SNMPApi *apiInstance = [[SNMPApi alloc] init];
    -
    -// RSU SNMP Query
    -[apiInstance snmpGetWith:ip
    -    oid:oid
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.SNMPApi()
    -
    -var ip = 8.14; // {BigDecimal} IP address of an RSU
    -
    -var oid = 8.14; // {BigDecimal} OID of the attribute you wish to check on
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.snmpGet(ip, oid, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class snmpGetExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new SNMPApi();
    -            var ip = 8.14;  // BigDecimal | IP address of an RSU
    -            var oid = 8.14;  // BigDecimal | OID of the attribute you wish to check on
    -
    -            try
    -            {
    -                // RSU SNMP Query
    -                Status result = apiInstance.snmpGet(ip, oid);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling SNMPApi.snmpGet: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\SNMPApi();
    -$ip = 8.14; // BigDecimal | IP address of an RSU
    -$oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -
    -try {
    -    $result = $api_instance->snmpGet($ip, $oid);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling SNMPApi->snmpGet: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::SNMPApi;
    -
    -my $api_instance = WWW::SwaggerClient::SNMPApi->new();
    -my $ip = 8.14; # BigDecimal | IP address of an RSU
    -my $oid = 8.14; # BigDecimal | OID of the attribute you wish to check on
    -
    -eval { 
    -    my $result = $api_instance->snmpGet(ip => $ip, oid => $oid);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling SNMPApi->snmpGet: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.SNMPApi()
    -ip = 8.14 # BigDecimal | IP address of an RSU
    -oid = 8.14 # BigDecimal | OID of the attribute you wish to check on
    -
    -try: 
    -    # RSU SNMP Query
    -    api_response = api_instance.snmp_get(ip, oid)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling SNMPApi->snmpGet: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - - -
    Query parameters
    - - - - - - - - - - - - - -
    NameDescription
    ip* - - -
    -
    -
    - - BigDecimal - - - (string) - - -
    - IP address of an RSU -
    -
    -
    - Required -
    -
    -
    -
    oid* - - -
    -
    -
    - - BigDecimal - - - (string) - - -
    - OID of the attribute you wish to check on -
    -
    -
    - Required -
    -
    -
    -
    - -

    Responses

    -

    Status: 200 - OID responses

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Value input error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    TIM

    -
    -
    -
    -

    timDelete

    -

    Delete a TIM message on an RSU.

    -
    -
    -
    -

    -

    Sets the status of a designated message index on an RSU to 6.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X DELETE "https://yourhostname/tim?index="
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    -        try {
    -            Status result = apiInstance.timDelete(index);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timDelete");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    -        try {
    -            Status result = apiInstance.timDelete(index);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timDelete");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    BigDecimal *index = 8.14; // Index of message to be deleted
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Delete a TIM message on an RSU.
    -[apiInstance timDeleteWith:index
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var index = 8.14; // {BigDecimal} Index of message to be deleted
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timDelete(index, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timDeleteExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var index = 8.14;  // BigDecimal | Index of message to be deleted
    -
    -            try
    -            {
    -                // Delete a TIM message on an RSU.
    -                Status result = apiInstance.timDelete(index);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timDelete: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$index = 8.14; // BigDecimal | Index of message to be deleted
    -
    -try {
    -    $result = $api_instance->timDelete($index);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timDelete: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $index = 8.14; # BigDecimal | Index of message to be deleted
    -
    -eval { 
    -    my $result = $api_instance->timDelete(index => $index);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timDelete: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -index = 8.14 # BigDecimal | Index of message to be deleted
    -
    -try: 
    -    # Delete a TIM message on an RSU.
    -    api_response = api_instance.tim_delete(index)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timDelete: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - - -
    Query parameters
    - - - - - - - - - -
    NameDescription
    index* - - -
    -
    -
    - - BigDecimal - - - (integer) - - -
    - Index of message to be deleted -
    -
    -
    - Required -
    -
    -
    -
    - -

    Responses

    -

    Status: 200 - Deleted index

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Error in body request

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 408 - Timeout

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Misc error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timPost

    -

    Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.

    -
    -
    -
    -

    -

    Submits a TIM message to ODE for distribution to the specified RSUs and SDW.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/tim"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPost(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPost(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -[apiInstance timPostWith:travelerInputData
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timPost(travelerInputData, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timPostExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -            try
    -            {
    -                // Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -                array[Status] result = apiInstance.timPost(travelerInputData);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timPost: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try {
    -    $result = $api_instance->timPost($travelerInputData);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timPost: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -eval { 
    -    my $result = $api_instance->timPost(travelerInputData => $travelerInputData);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timPost: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try: 
    -    # Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -    api_response = api_instance.tim_post(travelerInputData)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timPost: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    travelerInputData * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timPut

    -

    Used to update an existing TIM already present on an RSU.

    -
    -
    -
    -

    -

    Update a Traveler Information Message (TIM) that has already been deposited to an RSU. Parameters and response codes are identical to the POST request. Will also deposit the new message to the SDW, if the SDW field is present.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X PUT "https://yourhostname/tim"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPut(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPut");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPut(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPut");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Used to update an existing TIM already present on an RSU.
    -[apiInstance timPutWith:travelerInputData
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timPut(travelerInputData, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timPutExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -            try
    -            {
    -                // Used to update an existing TIM already present on an RSU.
    -                array[Status] result = apiInstance.timPut(travelerInputData);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timPut: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try {
    -    $result = $api_instance->timPut($travelerInputData);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timPut: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -eval { 
    -    my $result = $api_instance->timPut(travelerInputData => $travelerInputData);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timPut: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try: 
    -    # Used to update an existing TIM already present on an RSU.
    -    api_response = api_instance.tim_put(travelerInputData)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timPut: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    travelerInputData * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timQuery

    -

    Query an RSU for set TIMs

    -
    -
    -
    -

    -

    Query an RSU for set TIMs

    -

    -
    -
    /tim/query
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/tim/query"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        RSU rSU = ; // RSU | 
    -        try {
    -            Status result = apiInstance.timQuery(rSU);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timQuery");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        RSU rSU = ; // RSU | 
    -        try {
    -            Status result = apiInstance.timQuery(rSU);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timQuery");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    RSU *rSU = ; // 
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Query an RSU for set TIMs
    -[apiInstance timQueryWith:rSU
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var rSU = ; // {RSU} 
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timQuery(rSU, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timQueryExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var rSU = new RSU(); // RSU | 
    -
    -            try
    -            {
    -                // Query an RSU for set TIMs
    -                Status result = apiInstance.timQuery(rSU);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timQuery: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$rSU = ; // RSU | 
    -
    -try {
    -    $result = $api_instance->timQuery($rSU);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timQuery: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $rSU = WWW::SwaggerClient::Object::RSU->new(); # RSU | 
    -
    -eval { 
    -    my $result = $api_instance->timQuery(rSU => $rSU);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timQuery: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -rSU =  # RSU | 
    -
    -try: 
    -    # Query an RSU for set TIMs
    -    api_response = api_instance.tim_query(rSU)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timQuery: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    rSU * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - List of messages in JSON form

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Error in body request

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 408 - Timeout

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Misc error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    - -
    -
    - Generated 2018-04-30T22:35:56.953Z -
    -
    -
    -
    -
    - - - - - - - - - - - - - - + + + + + ODE REST API + + + + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +

    ODE REST API

    +
    +
    +
    + +
    +
    +

    LogFile

    +
    +
    +
    +

    uploadObulog

    +

    File upload interface

    +
    +
    +
    +

    +

    Uploads an OBU log file to ODE upload folder to be processed and propaged

    +

    +
    +
    /upload/obulog
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/upload/obulog"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.LogFileApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class LogFileApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        LogFileApi apiInstance = new LogFileApi();
    +        File file = /path/to/file.txt; // File | The file to upload.
    +        try {
    +            array[Status] result = apiInstance.uploadObulog(file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling LogFileApi#uploadObulog");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.LogFileApi;
    +
    +public class LogFileApiExample {
    +
    +    public static void main(String[] args) {
    +        LogFileApi apiInstance = new LogFileApi();
    +        File file = /path/to/file.txt; // File | The file to upload.
    +        try {
    +            array[Status] result = apiInstance.uploadObulog(file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling LogFileApi#uploadObulog");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    File *file = /path/to/file.txt; // The file to upload. (optional)
    +
    +LogFileApi *apiInstance = [[LogFileApi alloc] init];
    +
    +// File upload interface
    +[apiInstance uploadObulogWith:file
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.LogFileApi()
    +
    +var opts = { 
    +  'file': /path/to/file.txt // {File} The file to upload.
    +};
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.uploadObulog(opts, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class uploadObulogExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new LogFileApi();
    +            var file = new File(); // File | The file to upload. (optional) 
    +
    +            try
    +            {
    +                // File upload interface
    +                array[Status] result = apiInstance.uploadObulog(file);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling LogFileApi.uploadObulog: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\LogFileApi();
    +$file = /path/to/file.txt; // File | The file to upload.
    +
    +try {
    +    $result = $api_instance->uploadObulog($file);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling LogFileApi->uploadObulog: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::LogFileApi;
    +
    +my $api_instance = WWW::SwaggerClient::LogFileApi->new();
    +my $file = /path/to/file.txt; # File | The file to upload.
    +
    +eval { 
    +    my $result = $api_instance->uploadObulog(file => $file);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling LogFileApi->uploadObulog: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.LogFileApi()
    +file = /path/to/file.txt # File | The file to upload. (optional)
    +
    +try: 
    +    # File upload interface
    +    api_response = api_instance.upload_obulog(file=file)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling LogFileApi->uploadObulog: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + +
    Form parameters
    + + + + + + + + + +
    NameDescription
    file + + +
    +
    +
    + + File + + +
    + The file to upload. +
    +
    +
    +
    +
    + + +

    Responses

    +

    Status: 200 - File uploaded successfully

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    PDM

    +
    +
    +
    +

    pdmPost

    +

    PDM Interface

    +
    +
    +
    +

    +

    Submits a Probe Data Management message to ODE for distribution to the specified RSUs.

    +

    +
    +
    /pdm
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/pdm"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.PDMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PDMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        PDMApi apiInstance = new PDMApi();
    +        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    +        try {
    +            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PDMApi#pdmPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.PDMApi;
    +
    +public class PDMApiExample {
    +
    +    public static void main(String[] args) {
    +        PDMApi apiInstance = new PDMApi();
    +        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    +        try {
    +            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PDMApi#pdmPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    ProbeDataManagement *probeDataManagement = ; // PDM Message
    +
    +PDMApi *apiInstance = [[PDMApi alloc] init];
    +
    +// PDM Interface
    +[apiInstance pdmPostWith:probeDataManagement
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.PDMApi()
    +
    +var probeDataManagement = ; // {ProbeDataManagement} PDM Message
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.pdmPost(probeDataManagement, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class pdmPostExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new PDMApi();
    +            var probeDataManagement = new ProbeDataManagement(); // ProbeDataManagement | PDM Message
    +
    +            try
    +            {
    +                // PDM Interface
    +                array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling PDMApi.pdmPost: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\PDMApi();
    +$probeDataManagement = ; // ProbeDataManagement | PDM Message
    +
    +try {
    +    $result = $api_instance->pdmPost($probeDataManagement);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PDMApi->pdmPost: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PDMApi;
    +
    +my $api_instance = WWW::SwaggerClient::PDMApi->new();
    +my $probeDataManagement = WWW::SwaggerClient::Object::ProbeDataManagement->new(); # ProbeDataManagement | PDM Message
    +
    +eval { 
    +    my $result = $api_instance->pdmPost(probeDataManagement => $probeDataManagement);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PDMApi->pdmPost: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PDMApi()
    +probeDataManagement =  # ProbeDataManagement | PDM Message
    +
    +try: 
    +    # PDM Interface
    +    api_response = api_instance.pdm_post(probeDataManagement)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PDMApi->pdmPost: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    probeDataManagement * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Probe Data Management message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    SNMP

    +
    +
    +
    +

    snmpGet

    +

    RSU SNMP Query

    +
    +
    +
    +

    +

    Check the health and status of RSU devices through SNMP communication. You should receive a detailed plain text response that looks like the following example. If the device is off, a 4 second timeout will occur and the ODE will indicate this with an "[ERROR] Empty response" message. (This specific OID returns the amount of time since the device was last powered on) "[1.3.6.1.2.1.1.3.0 = 0:05:12.59]"

    +

    +
    +
    /rsuHeartbeat
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X GET "https://yourhostname/rsuHeartbeat?ip=&oid="
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.SNMPApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class SNMPApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        SNMPApi apiInstance = new SNMPApi();
    +        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    +        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +        try {
    +            Status result = apiInstance.snmpGet(ip, oid);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling SNMPApi#snmpGet");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.SNMPApi;
    +
    +public class SNMPApiExample {
    +
    +    public static void main(String[] args) {
    +        SNMPApi apiInstance = new SNMPApi();
    +        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    +        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +        try {
    +            Status result = apiInstance.snmpGet(ip, oid);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling SNMPApi#snmpGet");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    BigDecimal *ip = 8.14; // IP address of an RSU
    +BigDecimal *oid = 8.14; // OID of the attribute you wish to check on
    +
    +SNMPApi *apiInstance = [[SNMPApi alloc] init];
    +
    +// RSU SNMP Query
    +[apiInstance snmpGetWith:ip
    +    oid:oid
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.SNMPApi()
    +
    +var ip = 8.14; // {BigDecimal} IP address of an RSU
    +
    +var oid = 8.14; // {BigDecimal} OID of the attribute you wish to check on
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.snmpGet(ip, oid, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class snmpGetExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new SNMPApi();
    +            var ip = 8.14;  // BigDecimal | IP address of an RSU
    +            var oid = 8.14;  // BigDecimal | OID of the attribute you wish to check on
    +
    +            try
    +            {
    +                // RSU SNMP Query
    +                Status result = apiInstance.snmpGet(ip, oid);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling SNMPApi.snmpGet: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\SNMPApi();
    +$ip = 8.14; // BigDecimal | IP address of an RSU
    +$oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +
    +try {
    +    $result = $api_instance->snmpGet($ip, $oid);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling SNMPApi->snmpGet: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::SNMPApi;
    +
    +my $api_instance = WWW::SwaggerClient::SNMPApi->new();
    +my $ip = 8.14; # BigDecimal | IP address of an RSU
    +my $oid = 8.14; # BigDecimal | OID of the attribute you wish to check on
    +
    +eval { 
    +    my $result = $api_instance->snmpGet(ip => $ip, oid => $oid);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling SNMPApi->snmpGet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.SNMPApi()
    +ip = 8.14 # BigDecimal | IP address of an RSU
    +oid = 8.14 # BigDecimal | OID of the attribute you wish to check on
    +
    +try: 
    +    # RSU SNMP Query
    +    api_response = api_instance.snmp_get(ip, oid)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling SNMPApi->snmpGet: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + + +
    Query parameters
    + + + + + + + + + + + + + +
    NameDescription
    ip* + + +
    +
    +
    + + BigDecimal + + + (string) + + +
    + IP address of an RSU +
    +
    +
    + Required +
    +
    +
    +
    oid* + + +
    +
    +
    + + BigDecimal + + + (string) + + +
    + OID of the attribute you wish to check on +
    +
    +
    + Required +
    +
    +
    +
    + +

    Responses

    +

    Status: 200 - OID responses

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Value input error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    TIM

    +
    +
    +
    +

    timDelete

    +

    Delete a TIM message on an RSU.

    +
    +
    +
    +

    +

    Sets the status of a designated message index on an RSU to 6.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X DELETE "https://yourhostname/tim?index="
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    +        try {
    +            Status result = apiInstance.timDelete(index);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timDelete");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    +        try {
    +            Status result = apiInstance.timDelete(index);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timDelete");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    BigDecimal *index = 8.14; // Index of message to be deleted
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Delete a TIM message on an RSU.
    +[apiInstance timDeleteWith:index
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var index = 8.14; // {BigDecimal} Index of message to be deleted
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timDelete(index, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timDeleteExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var index = 8.14;  // BigDecimal | Index of message to be deleted
    +
    +            try
    +            {
    +                // Delete a TIM message on an RSU.
    +                Status result = apiInstance.timDelete(index);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timDelete: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$index = 8.14; // BigDecimal | Index of message to be deleted
    +
    +try {
    +    $result = $api_instance->timDelete($index);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timDelete: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $index = 8.14; # BigDecimal | Index of message to be deleted
    +
    +eval { 
    +    my $result = $api_instance->timDelete(index => $index);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timDelete: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +index = 8.14 # BigDecimal | Index of message to be deleted
    +
    +try: 
    +    # Delete a TIM message on an RSU.
    +    api_response = api_instance.tim_delete(index)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timDelete: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + + +
    Query parameters
    + + + + + + + + + +
    NameDescription
    index* + + +
    +
    +
    + + BigDecimal + + + (integer) + + +
    + Index of message to be deleted +
    +
    +
    + Required +
    +
    +
    +
    + +

    Responses

    +

    Status: 200 - Deleted index

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Error in body request

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 408 - Timeout

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Misc error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timPost

    +

    Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.

    +
    +
    +
    +

    +

    Submits a TIM message to ODE for distribution to the specified RSUs and SDW.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/tim"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPost(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPost(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +[apiInstance timPostWith:travelerInputData
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timPost(travelerInputData, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timPostExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +            try
    +            {
    +                // Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +                array[Status] result = apiInstance.timPost(travelerInputData);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timPost: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try {
    +    $result = $api_instance->timPost($travelerInputData);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timPost: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +eval { 
    +    my $result = $api_instance->timPost(travelerInputData => $travelerInputData);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timPost: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try: 
    +    # Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +    api_response = api_instance.tim_post(travelerInputData)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timPost: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    travelerInputData * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timPut

    +

    Used to update an existing TIM already present on an RSU.

    +
    +
    +
    +

    +

    Update a Traveler Information Message (TIM) that has already been deposited to an RSU. Parameters and response codes are identical to the POST request. Will also deposit the new message to the SDW, if the SDW field is present.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X PUT "https://yourhostname/tim"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPut(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPut");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPut(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPut");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Used to update an existing TIM already present on an RSU.
    +[apiInstance timPutWith:travelerInputData
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timPut(travelerInputData, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timPutExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +            try
    +            {
    +                // Used to update an existing TIM already present on an RSU.
    +                array[Status] result = apiInstance.timPut(travelerInputData);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timPut: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try {
    +    $result = $api_instance->timPut($travelerInputData);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timPut: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +eval { 
    +    my $result = $api_instance->timPut(travelerInputData => $travelerInputData);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timPut: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try: 
    +    # Used to update an existing TIM already present on an RSU.
    +    api_response = api_instance.tim_put(travelerInputData)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timPut: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    travelerInputData * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timQuery

    +

    Query an RSU for set TIMs

    +
    +
    +
    +

    +

    Query an RSU for set TIMs

    +

    +
    +
    /tim/query
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/tim/query"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        RSU rSU = ; // RSU | 
    +        try {
    +            Status result = apiInstance.timQuery(rSU);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timQuery");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        RSU rSU = ; // RSU | 
    +        try {
    +            Status result = apiInstance.timQuery(rSU);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timQuery");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    RSU *rSU = ; // 
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Query an RSU for set TIMs
    +[apiInstance timQueryWith:rSU
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var rSU = ; // {RSU} 
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timQuery(rSU, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timQueryExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var rSU = new RSU(); // RSU | 
    +
    +            try
    +            {
    +                // Query an RSU for set TIMs
    +                Status result = apiInstance.timQuery(rSU);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timQuery: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$rSU = ; // RSU | 
    +
    +try {
    +    $result = $api_instance->timQuery($rSU);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timQuery: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $rSU = WWW::SwaggerClient::Object::RSU->new(); # RSU | 
    +
    +eval { 
    +    my $result = $api_instance->timQuery(rSU => $rSU);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timQuery: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +rSU =  # RSU | 
    +
    +try: 
    +    # Query an RSU for set TIMs
    +    api_response = api_instance.tim_query(rSU)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timQuery: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    rSU * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - List of messages in JSON form

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Error in body request

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 408 - Timeout

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Misc error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    + Generated 2018-04-30T22:35:56.953Z +
    +
    +
    +
    +
    + + + + + + + + + + + + + + diff --git a/docs/timEndpointCurl.sh b/docs/timEndpointCurl.sh index 222f38294..368dba948 100755 --- a/docs/timEndpointCurl.sh +++ b/docs/timEndpointCurl.sh @@ -1,235 +1,235 @@ -curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 4c014aac-3597-a40d-e992-271d377d6d4c" -d '{ - "timContent": { - "msgcnt": "1", - "timestamp": "op", - "packetID": "op", - "urlB": "op", - "travelerDataFrame": [{ - "header": { - "sspindex": "1", - "travelerInfoType": "1", - "msgId": { - "FurtherInfoID": "1", - "RoadSignID": { - "position3D": { - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }, - "HeadingSlice": "1010011010010100", - "MUTCDCode": "op", - "MsgCRC": "op" - } - }, - "DYear": "op", - "MinuteOfTheYear": "0", - "MinutesDuration": "0", - "SignPriority": "0" - }, - "region": { - "sspindex": "0", - "GeographicalPath": [{ - "name": "op", - "id": "op", - "anchor": "op", - "laneWidth": "op", - "diretionality": "op", - "closedPath": "op", - "direction": "op", - "description": [{ - "path": [{ - "scale": "op", - "offset": [{ - "xy": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }], - "computed": [{ - "referenceLaneID": "1", - "offsetXaxis": [{ - "small": "1", - "large": "1" - }], - "offsetYaxis": [{ - "small": "1", - "large": "1" - }] - }] - }], - "ll": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }] - }] - }] - }], - "geometry": [{ - "direction": "1001101100100100", - "circle": [{ - "center": [{ - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }], - "radius": "3", - "units": "4" - }] - }], - "oldRegion": [{ - "direction": "1001101100100100", - "area": [{ - "shapePointSet": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }], - "computed": [{ - "referenceLaneID": "1", - "offsetXaxis": [{ - "small": "1", - "large": "1" - }], - "offsetYaxis": [{ - "small": "1", - "large": "1" - }] - }] - }], - "circle": [{ - "center": [{ - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }], - "radius": "3", - "units": "4" - }], - "regionPointSet": [{ - "nodeList": [{ - "xOffset": "1", - "yOffset": "1" - }] - }] - }] - }] - }] - }] - }, - "content": { - "sspMsgRights1": "1", - "sspMsgRights2": "2", - "contentType": { - "advisory": [{ - "ITISCodes": "268", - "ITIStext": "Speed Limit" - } ], - "workZone": [], - "genericSign": [], - "speedLimit": [], - "exitService": [] - }, - "URL-Short": "op", - "regional": "op" - } - }], - "regional": "op" - }, - "RSUs": [{ - "target": "127.0.0.1", - "username": "v3user", - "password": "password", - "retries": "1", - "timeout": "2000" - }], - "snmp": { - "rsuid": "8300", - "msgid": "31", - "mode": "1", - "channel": "178", - "interval": "1", - "deliverystart": "010114111530", - "deliverystop": "010114130000", - "enable": "1", - "status": "4" - } -}' "http://localhost:8080/tim" +curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 4c014aac-3597-a40d-e992-271d377d6d4c" -d '{ + "timContent": { + "msgcnt": "1", + "timestamp": "op", + "packetID": "op", + "urlB": "op", + "travelerDataFrame": [{ + "header": { + "sspindex": "1", + "travelerInfoType": "1", + "msgId": { + "FurtherInfoID": "1", + "RoadSignID": { + "position3D": { + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }, + "HeadingSlice": "1010011010010100", + "MUTCDCode": "op", + "MsgCRC": "op" + } + }, + "DYear": "op", + "MinuteOfTheYear": "0", + "MinutesDuration": "0", + "SignPriority": "0" + }, + "region": { + "sspindex": "0", + "GeographicalPath": [{ + "name": "op", + "id": "op", + "anchor": "op", + "laneWidth": "op", + "diretionality": "op", + "closedPath": "op", + "direction": "op", + "description": [{ + "path": [{ + "scale": "op", + "offset": [{ + "xy": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }], + "computed": [{ + "referenceLaneID": "1", + "offsetXaxis": [{ + "small": "1", + "large": "1" + }], + "offsetYaxis": [{ + "small": "1", + "large": "1" + }] + }] + }], + "ll": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }] + }] + }] + }], + "geometry": [{ + "direction": "1001101100100100", + "circle": [{ + "center": [{ + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }], + "radius": "3", + "units": "4" + }] + }], + "oldRegion": [{ + "direction": "1001101100100100", + "area": [{ + "shapePointSet": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }], + "computed": [{ + "referenceLaneID": "1", + "offsetXaxis": [{ + "small": "1", + "large": "1" + }], + "offsetYaxis": [{ + "small": "1", + "large": "1" + }] + }] + }], + "circle": [{ + "center": [{ + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }], + "radius": "3", + "units": "4" + }], + "regionPointSet": [{ + "nodeList": [{ + "xOffset": "1", + "yOffset": "1" + }] + }] + }] + }] + }] + }] + }, + "content": { + "sspMsgRights1": "1", + "sspMsgRights2": "2", + "contentType": { + "advisory": [{ + "ITISCodes": "268", + "ITIStext": "Speed Limit" + } ], + "workZone": [], + "genericSign": [], + "speedLimit": [], + "exitService": [] + }, + "URL-Short": "op", + "regional": "op" + } + }], + "regional": "op" + }, + "RSUs": [{ + "target": "127.0.0.1", + "username": "v3user", + "password": "password", + "retries": "1", + "timeout": "2000" + }], + "snmp": { + "rsuid": "8300", + "msgid": "31", + "mode": "1", + "channel": "178", + "interval": "1", + "deliverystart": "010114111530", + "deliverystop": "010114130000", + "enable": "1", + "status": "4" + } +}' "http://localhost:8080/tim" diff --git a/docs/timEndpointPython.py b/docs/timEndpointPython.py index 73232755e..e4927cb0a 100644 --- a/docs/timEndpointPython.py +++ b/docs/timEndpointPython.py @@ -1,14 +1,14 @@ -import requests - -url = "http://localhost:8080/tim" - -payload = "{\r\n\t\"timContent\": {\r\n\t\t\"msgcnt\": \"1\",\r\n\t\t\"timestamp\": \"op\",\r\n\t\t\"packetID\": \"op\",\r\n\t\t\"urlB\": \"op\",\r\n\t\t\"travelerDataFrame\": [{\r\n\t\t\t\"header\": {\r\n\t\t\t\t\"sspindex\": \"1\",\r\n\t\t\t\t\"travelerInfoType\": \"1\",\r\n\t\t\t\t\"msgId\": {\r\n\t\t\t\t\t\"FurtherInfoID\": \"1\",\r\n\t\t\t\t\t\"RoadSignID\": {\r\n\t\t\t\t\t\t\"position3D\": {\r\n\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\"HeadingSlice\": \"1010011010010100\",\r\n\t\t\t\t\t\t\"MUTCDCode\": \"op\",\r\n\t\t\t\t\t\t\"MsgCRC\": \"op\"\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\"DYear\": \"op\",\r\n\t\t\t\t\"MinuteOfTheYear\": \"0\",\r\n\t\t\t\t\"MinutesDuration\": \"0\",\r\n\t\t\t\t\"SignPriority\": \"0\"\r\n\t\t\t},\r\n\t\t\t\"region\": {\r\n\t\t\t\t\"sspindex\": \"0\",\r\n\t\t\t\t\"GeographicalPath\": [{\r\n\t\t\t\t\t\"name\": \"op\",\r\n\t\t\t\t\t\"id\": \"op\",\r\n\t\t\t\t\t\"anchor\": \"op\",\r\n\t\t\t\t\t\"laneWidth\": \"op\",\r\n\t\t\t\t\t\"diretionality\": \"op\",\r\n\t\t\t\t\t\"closedPath\": \"op\",\r\n\t\t\t\t\t\"direction\": \"op\",\r\n\t\t\t\t\t\"description\": [{\r\n\t\t\t\t\t\t\"path\": [{\r\n\t\t\t\t\t\t\t\"scale\": \"op\",\r\n\t\t\t\t\t\t\t\"offset\": [{\r\n\t\t\t\t\t\t\t\t\"xy\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"ll\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"geometry\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"oldRegion\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"area\": [{\r\n\t\t\t\t\t\t\t\t\"shapePointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"regionPointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodeList\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"xOffset\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"yOffset\": \"1\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}]\r\n\t\t\t\t\t}]\r\n\t\t\t\t}]\r\n\t\t\t},\r\n\t\t\t\"content\": {\r\n\t\t\t\t\"sspMsgRights1\": \"1\",\r\n\t\t\t\t\"sspMsgRights2\": \"2\",\r\n\t\t\t\t\"contentType\": {\r\n\t\t\t\t\t\"advisory\": [{\r\n\t\t\t\t\t\t\"ITISCodes\": \"268\",\r\n\t\t\t\t\t\t\"ITIStext\": \"Speed Limit\"\r\n\t\t\t\t\t} ],\r\n\t\t\t\t\t\"workZone\": [],\r\n\t\t\t\t\t\"genericSign\": [],\r\n\t\t\t\t\t\"speedLimit\": [],\r\n\t\t\t\t\t\"exitService\": []\r\n\t\t\t\t},\r\n\t\t\t\t\"URL-Short\": \"op\",\r\n\t\t\t\t\"regional\": \"op\"\r\n\t\t\t}\r\n\t\t}],\r\n\t\t\"regional\": \"op\"\r\n\t},\r\n\t\"RSUs\": [{\r\n\t\t\"target\": \"127.0.0.1\",\r\n\t\t\"username\": \"v3user\",\r\n\t\t\"password\": \"password\",\r\n\t\t\"retries\": \"1\",\r\n\t\t\"timeout\": \"2000\"\r\n\t}], \r\n\t\"snmp\": {\r\n\t\t\"rsuid\": \"8300\",\r\n\t\t\"msgid\": \"31\",\r\n\t\t\"mode\": \"1\",\r\n\t\t\"channel\": \"178\",\r\n\t\t\"interval\": \"1\",\r\n\t\t\"deliverystart\": \"010114111530\",\r\n\t\t\"deliverystop\": \"010114130000\",\r\n\t\t\"enable\": \"1\",\r\n\t\t\"status\": \"4\"\r\n\t}\r\n}" -headers = { - 'content-type': "application/json", - 'cache-control': "no-cache", - 'postman-token': "e3aeeabb-569d-e3e9-0816-2b271aace18d" - } - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) +import requests + +url = "http://localhost:8080/tim" + +payload = "{\r\n\t\"timContent\": {\r\n\t\t\"msgcnt\": \"1\",\r\n\t\t\"timestamp\": \"op\",\r\n\t\t\"packetID\": \"op\",\r\n\t\t\"urlB\": \"op\",\r\n\t\t\"travelerDataFrame\": [{\r\n\t\t\t\"header\": {\r\n\t\t\t\t\"sspindex\": \"1\",\r\n\t\t\t\t\"travelerInfoType\": \"1\",\r\n\t\t\t\t\"msgId\": {\r\n\t\t\t\t\t\"FurtherInfoID\": \"1\",\r\n\t\t\t\t\t\"RoadSignID\": {\r\n\t\t\t\t\t\t\"position3D\": {\r\n\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\"HeadingSlice\": \"1010011010010100\",\r\n\t\t\t\t\t\t\"MUTCDCode\": \"op\",\r\n\t\t\t\t\t\t\"MsgCRC\": \"op\"\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\"DYear\": \"op\",\r\n\t\t\t\t\"MinuteOfTheYear\": \"0\",\r\n\t\t\t\t\"MinutesDuration\": \"0\",\r\n\t\t\t\t\"SignPriority\": \"0\"\r\n\t\t\t},\r\n\t\t\t\"region\": {\r\n\t\t\t\t\"sspindex\": \"0\",\r\n\t\t\t\t\"GeographicalPath\": [{\r\n\t\t\t\t\t\"name\": \"op\",\r\n\t\t\t\t\t\"id\": \"op\",\r\n\t\t\t\t\t\"anchor\": \"op\",\r\n\t\t\t\t\t\"laneWidth\": \"op\",\r\n\t\t\t\t\t\"diretionality\": \"op\",\r\n\t\t\t\t\t\"closedPath\": \"op\",\r\n\t\t\t\t\t\"direction\": \"op\",\r\n\t\t\t\t\t\"description\": [{\r\n\t\t\t\t\t\t\"path\": [{\r\n\t\t\t\t\t\t\t\"scale\": \"op\",\r\n\t\t\t\t\t\t\t\"offset\": [{\r\n\t\t\t\t\t\t\t\t\"xy\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"ll\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"geometry\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"oldRegion\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"area\": [{\r\n\t\t\t\t\t\t\t\t\"shapePointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"regionPointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodeList\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"xOffset\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"yOffset\": \"1\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}]\r\n\t\t\t\t\t}]\r\n\t\t\t\t}]\r\n\t\t\t},\r\n\t\t\t\"content\": {\r\n\t\t\t\t\"sspMsgRights1\": \"1\",\r\n\t\t\t\t\"sspMsgRights2\": \"2\",\r\n\t\t\t\t\"contentType\": {\r\n\t\t\t\t\t\"advisory\": [{\r\n\t\t\t\t\t\t\"ITISCodes\": \"268\",\r\n\t\t\t\t\t\t\"ITIStext\": \"Speed Limit\"\r\n\t\t\t\t\t} ],\r\n\t\t\t\t\t\"workZone\": [],\r\n\t\t\t\t\t\"genericSign\": [],\r\n\t\t\t\t\t\"speedLimit\": [],\r\n\t\t\t\t\t\"exitService\": []\r\n\t\t\t\t},\r\n\t\t\t\t\"URL-Short\": \"op\",\r\n\t\t\t\t\"regional\": \"op\"\r\n\t\t\t}\r\n\t\t}],\r\n\t\t\"regional\": \"op\"\r\n\t},\r\n\t\"RSUs\": [{\r\n\t\t\"target\": \"127.0.0.1\",\r\n\t\t\"username\": \"v3user\",\r\n\t\t\"password\": \"password\",\r\n\t\t\"retries\": \"1\",\r\n\t\t\"timeout\": \"2000\"\r\n\t}], \r\n\t\"snmp\": {\r\n\t\t\"rsuid\": \"8300\",\r\n\t\t\"msgid\": \"31\",\r\n\t\t\"mode\": \"1\",\r\n\t\t\"channel\": \"178\",\r\n\t\t\"interval\": \"1\",\r\n\t\t\"deliverystart\": \"010114111530\",\r\n\t\t\"deliverystop\": \"010114130000\",\r\n\t\t\"enable\": \"1\",\r\n\t\t\"status\": \"4\"\r\n\t}\r\n}" +headers = { + 'content-type': "application/json", + 'cache-control': "no-cache", + 'postman-token': "e3aeeabb-569d-e3e9-0816-2b271aace18d" + } + +response = requests.request("POST", url, data=payload, headers=headers) + +print(response.text) diff --git a/jpo-ode-common/LICENSE-2.0.html b/jpo-ode-common/LICENSE-2.0.html index d1055c8ad..16303d2c7 100644 --- a/jpo-ode-common/LICENSE-2.0.html +++ b/jpo-ode-common/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-common/pom.xml b/jpo-ode-common/pom.xml index da1882b32..63e6af4ad 100644 --- a/jpo-ode-common/pom.xml +++ b/jpo-ode-common/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT jpo-ode-common diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java index 96cf0a25a..d87c7692d 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Arrays; - -import us.dot.its.jpo.ode.util.CodecUtils; -import us.dot.its.jpo.ode.util.CrcCccitt; - -public class InetPacket { - - private static final int MAGIC_NUMBER = 982451653; - private static final int MIN_BUNDLE_LENGTH = 4 + 4 + 1 + 4 + 2; // magic + port + type + ip4 + CRC - - private InetPoint point; - private byte[] payload; - - public InetPacket(String host, int port, byte[] payload) throws UnknownHostException { - this(InetAddress.getByName( host ), port, payload); - } - - public InetPacket(InetAddress ipAddress, int port, byte[] payload) { - this(new InetPoint(ipAddress.getAddress(), port), payload); - } - - public InetPacket(InetPoint point, byte[] payload) { - this.point = point; - if ( !parseBundle(payload) ) - this.payload = payload; - } - - public InetPacket(DatagramPacket packet) { - point = new InetPoint(packet.getAddress().getAddress(), packet.getPort()); - byte[] data = Arrays.copyOfRange(packet.getData(), packet.getOffset(), packet.getLength()); - if ( !parseBundle(data) ) - payload = data; - } - - public InetPacket(byte[] bundle) { - if ( !parseBundle(bundle) ) - payload = bundle; - } - - public InetPoint getPoint() { - return point; - } - - public byte[] getPayload() { - return payload; - } - - public byte[] getBundle() { - if ( point == null ) - return payload; - int payloadLength = payload != null ? payload.length : 0; - int headerLength = MIN_BUNDLE_LENGTH - 4 + point.address.length; - byte [] bundle = new byte[headerLength + payloadLength]; - ByteBuffer buffer = ByteBuffer.allocate(headerLength).order(ByteOrder.BIG_ENDIAN); - buffer.putInt(MAGIC_NUMBER); - buffer.putInt(point.port); - buffer.put((byte)(point.address.length == 16 ? 1 : 0)); - buffer.put(point.address); - byte[] header = buffer.array(); - assert(header.length == headerLength); - CrcCccitt.setMsgCRC(header); - System.arraycopy(header, 0, bundle, 0, headerLength); - if ( payload != null ) - System.arraycopy(payload, 0, bundle, headerLength, payloadLength); - return bundle; - } - - public boolean parseBundle(byte[] bundle) { - if ( bundle == null || bundle.length < MIN_BUNDLE_LENGTH ) - return false; - ByteBuffer buffer = ByteBuffer.wrap(bundle); - int magic = buffer.getInt(); - if ( magic != MAGIC_NUMBER ) - return false; - int port = buffer.getInt(); - byte type = buffer.get(); - int addressLength = type == 1 ? 16 : 4; - if ( buffer.remaining() < addressLength + 2 ) - return false; - if ( !CrcCccitt.isValidMsgCRC(bundle, 0, MIN_BUNDLE_LENGTH - 4 + addressLength) ) - return false; - byte[] address = new byte[addressLength]; - buffer.get(address,0,addressLength); - buffer.getShort(); - point = new InetPoint(address, port, true); - int payloadLength = bundle.length - MIN_BUNDLE_LENGTH + 4 - addressLength; - payload = new byte[payloadLength]; - buffer.get(payload,0,payloadLength); - return true; - } - - public String toHexString() { - return CodecUtils.toHex(getBundle()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +import us.dot.its.jpo.ode.util.CodecUtils; +import us.dot.its.jpo.ode.util.CrcCccitt; + +public class InetPacket { + + private static final int MAGIC_NUMBER = 982451653; + private static final int MIN_BUNDLE_LENGTH = 4 + 4 + 1 + 4 + 2; // magic + port + type + ip4 + CRC + + private InetPoint point; + private byte[] payload; + + public InetPacket(String host, int port, byte[] payload) throws UnknownHostException { + this(InetAddress.getByName( host ), port, payload); + } + + public InetPacket(InetAddress ipAddress, int port, byte[] payload) { + this(new InetPoint(ipAddress.getAddress(), port), payload); + } + + public InetPacket(InetPoint point, byte[] payload) { + this.point = point; + if ( !parseBundle(payload) ) + this.payload = payload; + } + + public InetPacket(DatagramPacket packet) { + point = new InetPoint(packet.getAddress().getAddress(), packet.getPort()); + byte[] data = Arrays.copyOfRange(packet.getData(), packet.getOffset(), packet.getLength()); + if ( !parseBundle(data) ) + payload = data; + } + + public InetPacket(byte[] bundle) { + if ( !parseBundle(bundle) ) + payload = bundle; + } + + public InetPoint getPoint() { + return point; + } + + public byte[] getPayload() { + return payload; + } + + public byte[] getBundle() { + if ( point == null ) + return payload; + int payloadLength = payload != null ? payload.length : 0; + int headerLength = MIN_BUNDLE_LENGTH - 4 + point.address.length; + byte [] bundle = new byte[headerLength + payloadLength]; + ByteBuffer buffer = ByteBuffer.allocate(headerLength).order(ByteOrder.BIG_ENDIAN); + buffer.putInt(MAGIC_NUMBER); + buffer.putInt(point.port); + buffer.put((byte)(point.address.length == 16 ? 1 : 0)); + buffer.put(point.address); + byte[] header = buffer.array(); + assert(header.length == headerLength); + CrcCccitt.setMsgCRC(header); + System.arraycopy(header, 0, bundle, 0, headerLength); + if ( payload != null ) + System.arraycopy(payload, 0, bundle, headerLength, payloadLength); + return bundle; + } + + public boolean parseBundle(byte[] bundle) { + if ( bundle == null || bundle.length < MIN_BUNDLE_LENGTH ) + return false; + ByteBuffer buffer = ByteBuffer.wrap(bundle); + int magic = buffer.getInt(); + if ( magic != MAGIC_NUMBER ) + return false; + int port = buffer.getInt(); + byte type = buffer.get(); + int addressLength = type == 1 ? 16 : 4; + if ( buffer.remaining() < addressLength + 2 ) + return false; + if ( !CrcCccitt.isValidMsgCRC(bundle, 0, MIN_BUNDLE_LENGTH - 4 + addressLength) ) + return false; + byte[] address = new byte[addressLength]; + buffer.get(address,0,addressLength); + buffer.getShort(); + point = new InetPoint(address, port, true); + int payloadLength = bundle.length - MIN_BUNDLE_LENGTH + 4 - addressLength; + payload = new byte[payloadLength]; + buffer.get(payload,0,payloadLength); + return true; + } + + public String toHexString() { + return CodecUtils.toHex(getBundle()); + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java index 3058b4774..a1f36b5d6 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -public class InetPacketException extends Exception { - - private static final long serialVersionUID = 1L; - - public InetPacketException(String message) { - super(message); - } - - public InetPacketException(String message, Throwable cause) { - super(message, cause); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +public class InetPacketException extends Exception { + + private static final long serialVersionUID = 1L; + + public InetPacketException(String message) { + super(message); + } + + public InetPacketException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java index ced6cc3b5..f8e352ca9 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java @@ -1,160 +1,160 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.SocketException; - -import org.apache.log4j.Logger; - -/** - * Sender/Forwarder helper class for use by Forwarder, Transport, and Data Sink that need to send packets around - */ -public class InetPacketSender { - - private static final String INVALID_PARAMETERS_MSG = "Invalid Parameters. Parameters destination point and payload can not be null"; - - private static final Logger log = Logger.getLogger(InetPacketSender.class); - - /** - * Inet address and port to forward packets to - */ - private InetPoint frwdPoint; - - /** - * Specifies whether outbound IPv4 messages should be send directly or forwarded. Default is send directly. - * To force forwarding IPv4 messages, set this variable to true. - */ - private boolean forwardAll; - - public InetPacketSender() {} - - /** - * Creates an instance of the forwarder/sender helper class. - * @param frwdPoint is the destination to use for forwarding - */ - public InetPacketSender(InetPoint frwdPoint) { - this.frwdPoint = frwdPoint; - } - - /** - * Forward packet. Intended client is the forwarder that received a packet - * @param inbound UDP packet - * @throws InetPacketException - */ - public void forward(DatagramPacket packet) throws InetPacketException { - if ( packet == null ) { - log.warn("Ignoring forward request for null packet"); - return; - } - if ( frwdPoint == null ) - throw new InetPacketException("Couldn't forward packet. Reason: Forwarding destination is not defined."); - send(frwdPoint, new InetPacket(packet).getBundle()); - } - - /** - * Send packet. Intended client is the forwarder that sends outbound packet - * @param packet outbound packet that contains destination+payload bundle - * @throws InetPacketException - */ - public void send(DatagramPacket packet) throws InetPacketException { - if ( packet == null ) { - log.warn("Ignoring send request for null packet"); - return; - } - InetPacket p = new InetPacket(packet); - InetPoint point = p.getPoint(); - if ( point == null ) - throw new InetPacketException("Couldn't send packet. Reason: Destination is not defined in the packet (not a bundle?)"); - send(point, p.getPayload()); - } - - /** - * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder - * @param dstPoint destination address and port for forwarder to forward to - * @param payload data to forward - * @throws InetPacketException - */ - public void forward(InetPoint dstPoint, byte[] payload) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - if ( frwdPoint == null ) - log.warn("Couldn't forward packet. Reason: Forwarding destination is not defined."); - if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll()) ) { - send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); - } else { - log.debug("Using direct send instead of forwarding"); - send(dstPoint, payload); - } - } - - /** - * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder or direct - * @param dstPoint destination address and port of the final destination - * @param payload data to forward or send - * @param fromForwarder whether the original request came through a forwarder - * @throws InetPacketException - */ - public void forward(InetPoint dstPoint, byte[] payload, boolean fromForwarder) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll() || fromForwarder) ) { - send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); - } else { - log.debug("Using direct send instead of forwarding"); - send(dstPoint, payload); - } - } - - /** - * Send payload to the destination specified. Intended clients are Transport or Data Sink sending directly to the client - * @param dstPoint destination address and port to send to - * @param payload data to send - * @throws InetPacketException - */ - public void send(InetPoint dstPoint, byte[] payload) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - try(DatagramSocket sock = new DatagramSocket()) { - DatagramPacket packet = new DatagramPacket(payload, payload.length, dstPoint.getInetAddress(), dstPoint.port); - sock.send(packet); - } catch (SocketException ex) { - throw new InetPacketException("Couldn't send packet because socket closed.", ex); - } catch (IOException ex) { - throw new InetPacketException("Couldn't send packet due to IO exception.", ex); - } - } - - /** - * Reports whether outbound IPv4 messages should be send directly or forwarded. - * @return true if IPv4 packets are forwarded in addition to IPv6 packets - */ - public boolean isForwardAll() { - return forwardAll; - } - - /** - * - * @param forwardAll Directs how to handle IPv4 messages. - * Specify true to force forwarding IPv4 messages, and false to always send them directly. - */ - public void setForwardAll(boolean forwardAll) { - this.forwardAll = forwardAll; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.SocketException; + +import org.apache.log4j.Logger; + +/** + * Sender/Forwarder helper class for use by Forwarder, Transport, and Data Sink that need to send packets around + */ +public class InetPacketSender { + + private static final String INVALID_PARAMETERS_MSG = "Invalid Parameters. Parameters destination point and payload can not be null"; + + private static final Logger log = Logger.getLogger(InetPacketSender.class); + + /** + * Inet address and port to forward packets to + */ + private InetPoint frwdPoint; + + /** + * Specifies whether outbound IPv4 messages should be send directly or forwarded. Default is send directly. + * To force forwarding IPv4 messages, set this variable to true. + */ + private boolean forwardAll; + + public InetPacketSender() {} + + /** + * Creates an instance of the forwarder/sender helper class. + * @param frwdPoint is the destination to use for forwarding + */ + public InetPacketSender(InetPoint frwdPoint) { + this.frwdPoint = frwdPoint; + } + + /** + * Forward packet. Intended client is the forwarder that received a packet + * @param inbound UDP packet + * @throws InetPacketException + */ + public void forward(DatagramPacket packet) throws InetPacketException { + if ( packet == null ) { + log.warn("Ignoring forward request for null packet"); + return; + } + if ( frwdPoint == null ) + throw new InetPacketException("Couldn't forward packet. Reason: Forwarding destination is not defined."); + send(frwdPoint, new InetPacket(packet).getBundle()); + } + + /** + * Send packet. Intended client is the forwarder that sends outbound packet + * @param packet outbound packet that contains destination+payload bundle + * @throws InetPacketException + */ + public void send(DatagramPacket packet) throws InetPacketException { + if ( packet == null ) { + log.warn("Ignoring send request for null packet"); + return; + } + InetPacket p = new InetPacket(packet); + InetPoint point = p.getPoint(); + if ( point == null ) + throw new InetPacketException("Couldn't send packet. Reason: Destination is not defined in the packet (not a bundle?)"); + send(point, p.getPayload()); + } + + /** + * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder + * @param dstPoint destination address and port for forwarder to forward to + * @param payload data to forward + * @throws InetPacketException + */ + public void forward(InetPoint dstPoint, byte[] payload) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + if ( frwdPoint == null ) + log.warn("Couldn't forward packet. Reason: Forwarding destination is not defined."); + if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll()) ) { + send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); + } else { + log.debug("Using direct send instead of forwarding"); + send(dstPoint, payload); + } + } + + /** + * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder or direct + * @param dstPoint destination address and port of the final destination + * @param payload data to forward or send + * @param fromForwarder whether the original request came through a forwarder + * @throws InetPacketException + */ + public void forward(InetPoint dstPoint, byte[] payload, boolean fromForwarder) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll() || fromForwarder) ) { + send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); + } else { + log.debug("Using direct send instead of forwarding"); + send(dstPoint, payload); + } + } + + /** + * Send payload to the destination specified. Intended clients are Transport or Data Sink sending directly to the client + * @param dstPoint destination address and port to send to + * @param payload data to send + * @throws InetPacketException + */ + public void send(InetPoint dstPoint, byte[] payload) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + try(DatagramSocket sock = new DatagramSocket()) { + DatagramPacket packet = new DatagramPacket(payload, payload.length, dstPoint.getInetAddress(), dstPoint.port); + sock.send(packet); + } catch (SocketException ex) { + throw new InetPacketException("Couldn't send packet because socket closed.", ex); + } catch (IOException ex) { + throw new InetPacketException("Couldn't send packet due to IO exception.", ex); + } + } + + /** + * Reports whether outbound IPv4 messages should be send directly or forwarded. + * @return true if IPv4 packets are forwarded in addition to IPv6 packets + */ + public boolean isForwardAll() { + return forwardAll; + } + + /** + * + * @param forwardAll Directs how to handle IPv4 messages. + * Specify true to force forwarding IPv4 messages, and false to always send them directly. + */ + public void setForwardAll(boolean forwardAll) { + this.forwardAll = forwardAll; + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java index c63db8ed5..e91361c1c 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java @@ -1,73 +1,73 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPoint { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public final byte[] address; - public final int port; - public final boolean forward; - - public InetPoint(String host, int port, boolean forward) throws UnknownHostException { - this(InetAddress.getByName(host).getAddress(), port, forward); - } - - public InetPoint(byte[] address, int port) { - this(address, port, false); - } - - public InetPoint(byte[] address, int port, boolean forward ) { - if (address == null) { - throw new IllegalArgumentException("IP Address is required"); - } - this.address = address; - this.port = port; - this.forward = forward; - } - - public InetAddress getInetAddress() throws UnknownHostException { - return InetAddress.getByAddress(address); - } - - public boolean isIPv6Address() { - return address.length == 16; - } - - @Override - public String toString() { - String host = "?"; - try { - host = InetAddress.getByAddress(address).getHostAddress(); - } catch (UnknownHostException e) { - logger.error("Error", e); - } - return String.format("%s { port = %d (0x%x); address = %s (%s, %s); forward = %s }", - getClass().getSimpleName(), - port, port, - CodecUtils.toHex(address), address.length == 4 ? "IPv4" : "IPv6", host, - forward ? "true" : "false" - ); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPoint { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public final byte[] address; + public final int port; + public final boolean forward; + + public InetPoint(String host, int port, boolean forward) throws UnknownHostException { + this(InetAddress.getByName(host).getAddress(), port, forward); + } + + public InetPoint(byte[] address, int port) { + this(address, port, false); + } + + public InetPoint(byte[] address, int port, boolean forward ) { + if (address == null) { + throw new IllegalArgumentException("IP Address is required"); + } + this.address = address; + this.port = port; + this.forward = forward; + } + + public InetAddress getInetAddress() throws UnknownHostException { + return InetAddress.getByAddress(address); + } + + public boolean isIPv6Address() { + return address.length == 16; + } + + @Override + public String toString() { + String host = "?"; + try { + host = InetAddress.getByAddress(address).getHostAddress(); + } catch (UnknownHostException e) { + logger.error("Error", e); + } + return String.format("%s { port = %d (0x%x); address = %s (%s, %s); forward = %s }", + getClass().getSimpleName(), + port, port, + CodecUtils.toHex(address), address.length == 4 ? "IPv4" : "IPv6", host, + forward ? "true" : "false" + ); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java index 43d0d1b89..285dfe951 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.util.CodecUtils; - -public class OdeHexByteArray extends OdeObject { - - private static final long serialVersionUID = 6106562581659367345L; - - private String bytes; - - public OdeHexByteArray() { - super(); - } - - public OdeHexByteArray(String bytes) { - super(); - this.bytes = bytes; - } - - public OdeHexByteArray(byte[] bytes) { - setBytes(bytes); - } - - public String getBytes() { - return bytes; - } - - public void setBytes(String bytes) { - this.bytes = bytes; - } - - public void setBytes(byte[] bytes) { - this.bytes = CodecUtils.toHex(bytes); - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.util.CodecUtils; + +public class OdeHexByteArray extends OdeObject { + + private static final long serialVersionUID = 6106562581659367345L; + + private String bytes; + + public OdeHexByteArray() { + super(); + } + + public OdeHexByteArray(String bytes) { + super(); + this.bytes = bytes; + } + + public OdeHexByteArray(byte[] bytes) { + setBytes(bytes); + } + + public String getBytes() { + return bytes; + } + + public void setBytes(String bytes) { + this.bytes = bytes; + } + + public void setBytes(byte[] bytes) { + this.bytes = CodecUtils.toHex(bytes); + } + + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java index e0e7b15d5..3233878be 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.io.Serializable; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import us.dot.its.jpo.ode.util.JsonUtils; -import us.dot.its.jpo.ode.util.XmlUtils; -import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException; - -public class OdeObject implements Serializable { - private static final long serialVersionUID = 7514526408925039533L; - - public String toJson() { - return JsonUtils.toJson(this, false); - } - - public String toJson(boolean verbose) { - return JsonUtils.toJson(this, verbose); - } - - public String toXml() throws XmlUtilsException, JsonProcessingException { - return XmlUtils.toXmlStatic(this); - } - - @Override - public String toString() { - return this.toJson(true); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.io.Serializable; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import us.dot.its.jpo.ode.util.JsonUtils; +import us.dot.its.jpo.ode.util.XmlUtils; +import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException; + +public class OdeObject implements Serializable { + private static final long serialVersionUID = 7514526408925039533L; + + public String toJson() { + return JsonUtils.toJson(this, false); + } + + public String toJson(boolean verbose) { + return JsonUtils.toJson(this, verbose); + } + + public String toXml() throws XmlUtilsException, JsonProcessingException { + return XmlUtils.toXmlStatic(this); + } + + @Override + public String toString() { + return this.toJson(true); + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java index a93135061..c8ad2dccf 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java @@ -1,281 +1,281 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Arrays; - -import javax.xml.bind.DatatypeConverter; - -public class CodecUtils { - - private CodecUtils() { - } - - /** - * Converts an array of shorts to a byte array. - *

    - * Example: (short) 5 will be stored as {0, 5} since 5 = 00000000 00000101 - *

    - *

    - * Example: (short) 257 will be stored as {1, 1} since 257 = 00000001 00000001 - *

    - * - * @param shorts array of 16 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 16 bit integers - */ - public static byte[] shortsToBytes(short[] shorts, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(shorts.length * 2).order(bo); - for (short num : shorts) { - buffer.putShort(num); - } - return buffer.array(); - } - - /** - * Converts a single short to a byte array length 2. See - * {@link #shortsToBytes(short[])} - * - * @param number a 16 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 16 bit integer number - */ - public static byte[] shortToBytes(short number, ByteOrder bo) { - short[] shorts = new short[] { number }; - return shortsToBytes(shorts, bo); - } - - /** - * Converts an array of bytes to an array of shorts and returns the first - * element. See {@link #bytesToShorts(byte[])} - * - * @param bytes - * @return array of shorts - */ - public static short bytesToShort(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToShorts(bytes, offset, length, bo)[0]; - } - - /** - * Converts an array of bytes to an array of shorts. - *

    - * Example: {(byte) 1, (byte) 1} will return {(short) 257} since 257 = - * 00000001 00000001 - *

    - * - * @param bytes - * @return array of shorts - */ - public static short[] bytesToShorts(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfShorts = length / 2; - short[] shorts = new short[numberOfShorts]; - for (int i = 0; i < numberOfShorts; i++) { - shorts[i] = buffer.getShort(); - } - return shorts; - } - - /** - * Combines byte arrays. - * - * @param bytes - * @return combined array - * @throws IOException - */ - - public static byte[] mergeBytes(byte[]... bytes) throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - for (byte[] bArray : bytes) { - outputStream.write(bArray); - } - return outputStream.toByteArray(); - } - - /** - * Converts an array of integers to a byte array. - *

    - * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000101 - *

    - *

    - * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000001 00000001 - *

    - * - * @param ints array of 32 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 32 bit integers - */ - public static byte[] intsToBytes(int[] ints, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(ints.length * 4).order(bo); - for (int num : ints) { - buffer.putInt(num); - } - return buffer.array(); - } - - /** - * Converts a single int to a byte array length 4. See - * {@link #shortsToBytes(short[])} - * - * @param number a 32 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 32 bit integer number - */ - public static byte[] intToBytes(int number, ByteOrder bo) { - int[] ints = new int[] { number }; - return intsToBytes(ints, bo); - } - - public static int bytesToInt(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToInts(bytes, offset, length, bo)[0]; - } - - public static int[] bytesToInts(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfInts = length / 4; - int[] ints = new int[numberOfInts]; - for (int i = 0; i < numberOfInts; i++) { - ints[i] = buffer.getInt(); - } - return ints; - } - - /** - * Converts an array of longs to a byte array. - *

    - * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 - *

    - *

    - * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000001 - *

    - * - * @param longs array of 64 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 64 bit integers - */ - public static byte[] longsToBytes(long[] longs, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(longs.length * 8).order(bo); - for (long num : longs) { - buffer.putLong(num); - } - return buffer.array(); - } - - /** - * Converts a single long to a byte array length 8 in a 64 bit machine. See - * {@link #shortsToBytes(short[])} - * - * @param number a 64 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 64 bit integer number - */ - public static byte[] longToBytes(long number, ByteOrder bo) { - long[] longs = new long[] { number }; - return longsToBytes(longs, bo); - } - - public static long bytesToLong(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToLongs(bytes, offset, length, bo)[0]; - } - - public static long[] bytesToLongs(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfLongs = length / 8; - long[] longs = new long[numberOfLongs]; - for (int i = 0; i < numberOfLongs; i++) { - longs[i] = buffer.getLong(); - } - return longs; - } - - public static String toHex(byte[] bytes) { - return bytes != null ? DatatypeConverter.printHexBinary(bytes) : ""; - } - - public static String toHex(byte b) { - return DatatypeConverter.printHexBinary(new byte[]{b}); - } - - public static byte[] fromHex(String hex) { - return DatatypeConverter.parseHexBinary(hex); - } - - public static String toBase64(byte[] bytes) { - return bytes != null ? DatatypeConverter.printBase64Binary(bytes) : ""; - } - - public static byte[] fromBase64(String base64) { - return DatatypeConverter.parseBase64Binary(base64); - } - - /** - * @param strShort - * String representation of a short integer value in binary or hex - * format. If the string is in binary format, the length must be - * exactly 16 1s and zeros. If Hex format, the length must be - * exactly 4 Hex digits. - * - * @return a byte array equivalent of strShort - */ - public static byte[] shortStringToByteArray(String strShort) { - - byte[] byteArrayValue = null; - - int radix = radixOf(strShort); - - if (radix == 0) { - byteArrayValue = new byte[2]; // NOSONAR - } else { - byteArrayValue = Arrays - .copyOfRange(ByteBuffer.allocate(4).putInt(Integer.parseUnsignedInt(strShort, radix)).array(), 2, 4); - } - - return byteArrayValue; - } - - /** - * @param strShort - * String representation of a short integer value in binary or hex - * format. If strShort is in binary format, the length must be - * exactly 16 ones and zeros. If strShort is in Hex format, the - * length must be exactly 4 Hex digits. - * @return The radix of the strShort: Currently supporting only binary and - * hex, therefore the return value is either 2 or 16 - */ - private static int radixOf(String strShort) { - int radix = 0; - if (strShort == null || strShort.length() == 0) { - radix = 0; - } else if (strShort.length() == 16) { - radix = 2; - } else if (strShort.length() == 4) { - radix = 16; - } else { - throw new IllegalArgumentException("Short String length is invalid: " + strShort.length()); - } - return radix; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +import javax.xml.bind.DatatypeConverter; + +public class CodecUtils { + + private CodecUtils() { + } + + /** + * Converts an array of shorts to a byte array. + *

    + * Example: (short) 5 will be stored as {0, 5} since 5 = 00000000 00000101 + *

    + *

    + * Example: (short) 257 will be stored as {1, 1} since 257 = 00000001 00000001 + *

    + * + * @param shorts array of 16 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 16 bit integers + */ + public static byte[] shortsToBytes(short[] shorts, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(shorts.length * 2).order(bo); + for (short num : shorts) { + buffer.putShort(num); + } + return buffer.array(); + } + + /** + * Converts a single short to a byte array length 2. See + * {@link #shortsToBytes(short[])} + * + * @param number a 16 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 16 bit integer number + */ + public static byte[] shortToBytes(short number, ByteOrder bo) { + short[] shorts = new short[] { number }; + return shortsToBytes(shorts, bo); + } + + /** + * Converts an array of bytes to an array of shorts and returns the first + * element. See {@link #bytesToShorts(byte[])} + * + * @param bytes + * @return array of shorts + */ + public static short bytesToShort(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToShorts(bytes, offset, length, bo)[0]; + } + + /** + * Converts an array of bytes to an array of shorts. + *

    + * Example: {(byte) 1, (byte) 1} will return {(short) 257} since 257 = + * 00000001 00000001 + *

    + * + * @param bytes + * @return array of shorts + */ + public static short[] bytesToShorts(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfShorts = length / 2; + short[] shorts = new short[numberOfShorts]; + for (int i = 0; i < numberOfShorts; i++) { + shorts[i] = buffer.getShort(); + } + return shorts; + } + + /** + * Combines byte arrays. + * + * @param bytes + * @return combined array + * @throws IOException + */ + + public static byte[] mergeBytes(byte[]... bytes) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + for (byte[] bArray : bytes) { + outputStream.write(bArray); + } + return outputStream.toByteArray(); + } + + /** + * Converts an array of integers to a byte array. + *

    + * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000101 + *

    + *

    + * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000001 00000001 + *

    + * + * @param ints array of 32 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 32 bit integers + */ + public static byte[] intsToBytes(int[] ints, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(ints.length * 4).order(bo); + for (int num : ints) { + buffer.putInt(num); + } + return buffer.array(); + } + + /** + * Converts a single int to a byte array length 4. See + * {@link #shortsToBytes(short[])} + * + * @param number a 32 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 32 bit integer number + */ + public static byte[] intToBytes(int number, ByteOrder bo) { + int[] ints = new int[] { number }; + return intsToBytes(ints, bo); + } + + public static int bytesToInt(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToInts(bytes, offset, length, bo)[0]; + } + + public static int[] bytesToInts(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfInts = length / 4; + int[] ints = new int[numberOfInts]; + for (int i = 0; i < numberOfInts; i++) { + ints[i] = buffer.getInt(); + } + return ints; + } + + /** + * Converts an array of longs to a byte array. + *

    + * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 + *

    + *

    + * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000001 + *

    + * + * @param longs array of 64 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 64 bit integers + */ + public static byte[] longsToBytes(long[] longs, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(longs.length * 8).order(bo); + for (long num : longs) { + buffer.putLong(num); + } + return buffer.array(); + } + + /** + * Converts a single long to a byte array length 8 in a 64 bit machine. See + * {@link #shortsToBytes(short[])} + * + * @param number a 64 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 64 bit integer number + */ + public static byte[] longToBytes(long number, ByteOrder bo) { + long[] longs = new long[] { number }; + return longsToBytes(longs, bo); + } + + public static long bytesToLong(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToLongs(bytes, offset, length, bo)[0]; + } + + public static long[] bytesToLongs(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfLongs = length / 8; + long[] longs = new long[numberOfLongs]; + for (int i = 0; i < numberOfLongs; i++) { + longs[i] = buffer.getLong(); + } + return longs; + } + + public static String toHex(byte[] bytes) { + return bytes != null ? DatatypeConverter.printHexBinary(bytes) : ""; + } + + public static String toHex(byte b) { + return DatatypeConverter.printHexBinary(new byte[]{b}); + } + + public static byte[] fromHex(String hex) { + return DatatypeConverter.parseHexBinary(hex); + } + + public static String toBase64(byte[] bytes) { + return bytes != null ? DatatypeConverter.printBase64Binary(bytes) : ""; + } + + public static byte[] fromBase64(String base64) { + return DatatypeConverter.parseBase64Binary(base64); + } + + /** + * @param strShort + * String representation of a short integer value in binary or hex + * format. If the string is in binary format, the length must be + * exactly 16 1s and zeros. If Hex format, the length must be + * exactly 4 Hex digits. + * + * @return a byte array equivalent of strShort + */ + public static byte[] shortStringToByteArray(String strShort) { + + byte[] byteArrayValue = null; + + int radix = radixOf(strShort); + + if (radix == 0) { + byteArrayValue = new byte[2]; // NOSONAR + } else { + byteArrayValue = Arrays + .copyOfRange(ByteBuffer.allocate(4).putInt(Integer.parseUnsignedInt(strShort, radix)).array(), 2, 4); + } + + return byteArrayValue; + } + + /** + * @param strShort + * String representation of a short integer value in binary or hex + * format. If strShort is in binary format, the length must be + * exactly 16 ones and zeros. If strShort is in Hex format, the + * length must be exactly 4 Hex digits. + * @return The radix of the strShort: Currently supporting only binary and + * hex, therefore the return value is either 2 or 16 + */ + private static int radixOf(String strShort) { + int radix = 0; + if (strShort == null || strShort.length() == 0) { + radix = 0; + } else if (strShort.length() == 16) { + radix = 2; + } else if (strShort.length() == 4) { + radix = 16; + } else { + throw new IllegalArgumentException("Short String length is invalid: " + strShort.length()); + } + return radix; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java index 0a4e7f3ed..04ad4e17e 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -public class CommonUtils { - - private CommonUtils() {} - - /** - * Wrapper method for System.getenv() - * @param name Variable name - */ - public static String getEnvironmentVariable(String name) { - return System.getenv(name); - } - - public static long getPidOfProcess(Process p) { - long pid = -1; - - try { - if (p.getClass().getName().equals("java.lang.UNIXProcess")) { //NOSONAR - Field f = p.getClass().getDeclaredField("pid"); - f.setAccessible(true); - pid = f.getLong(p); - f.setAccessible(false); - } - } catch (Exception e) { - pid = -1; - } - return pid; - } - - public static List getClasspath() { - ArrayList classpath = new ArrayList<>(); - - ClassLoader cl = ClassLoader.getSystemClassLoader(); - - URL[] urls = ((URLClassLoader)cl).getURLs(); - - for(URL url: urls){ - classpath.add(url); - } - - return classpath; - } - - public static String enumToString(Class clazz, String enumNameOrOrdinal) { - - String enumName = null; - try { - Object[] enumConstants = clazz.getEnumConstants(); - if (enumConstants != null) { - int enumOrdinal = Integer.parseInt(enumNameOrOrdinal); - enumName = enumConstants[enumOrdinal].toString(); - } - } catch (NumberFormatException e) { - enumName = enumNameOrOrdinal; - } - return enumName; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +public class CommonUtils { + + private CommonUtils() {} + + /** + * Wrapper method for System.getenv() + * @param name Variable name + */ + public static String getEnvironmentVariable(String name) { + return System.getenv(name); + } + + public static long getPidOfProcess(Process p) { + long pid = -1; + + try { + if (p.getClass().getName().equals("java.lang.UNIXProcess")) { //NOSONAR + Field f = p.getClass().getDeclaredField("pid"); + f.setAccessible(true); + pid = f.getLong(p); + f.setAccessible(false); + } + } catch (Exception e) { + pid = -1; + } + return pid; + } + + public static List getClasspath() { + ArrayList classpath = new ArrayList<>(); + + ClassLoader cl = ClassLoader.getSystemClassLoader(); + + URL[] urls = ((URLClassLoader)cl).getURLs(); + + for(URL url: urls){ + classpath.add(url); + } + + return classpath; + } + + public static String enumToString(Class clazz, String enumNameOrOrdinal) { + + String enumName = null; + try { + Object[] enumConstants = clazz.getEnumConstants(); + if (enumConstants != null) { + int enumOrdinal = Integer.parseInt(enumNameOrOrdinal); + enumName = enumConstants[enumOrdinal].toString(); + } + } catch (NumberFormatException e) { + enumName = enumNameOrOrdinal; + } + return enumName; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java index d4d6160c7..587fdab75 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -public class CrcCccitt { - // CRC-CCITT polynomial: x^16 + x^12 + x^5 + 1 - final private static int ccittPolynomial = 0x1021; - final private static int ccittTableSize = 256; - final private static int[] ccittTable = new int[ccittTableSize]; - - static { - for (int i = 0; i < ccittTableSize; i++) { - int checkSum = i << 8; - for (int j = 0; j < 8; j++) - checkSum = (checkSum & 0x8000) == 0x8000 ? (checkSum << 1) ^ ccittPolynomial : (checkSum << 1); - ccittTable[i] = checkSum & 0xFFFF; - } - } - - public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC) { - return calculateCrcCccitt(msgIncludingMsgCRC) == 0; - } - - - public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC, int offset, int count) { - return calculateCrcCccitt(msgIncludingMsgCRC, offset, count) == 0; - } - - // update last two bytes of the message with CRC of all preceding bytes - public static void setMsgCRC(byte[] msg) { - if ( msg != null && msg.length > 2) { - int checkSum = calculateCrcCccitt(msg, 0, msg.length-2); - ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); - buffer.putShort((short)checkSum); - byte[] crcBytes = buffer.array(); - System.arraycopy(crcBytes, 0, msg, msg.length-2, 2); - } - } - - public static int calculateCrcCccitt(byte[] msg) { - return msg != null ? calculateCrcCccitt(msg, 0, msg.length) : 0; - } - - public static int calculateCrcCccitt(byte[] msg, int offset, int count) { - int checkSum = 0; - if ( msg != null && offset >= 0 ) { - final int size = Math.min(msg.length, count); - for( int i = 0; i < size; i++ ) { - checkSum = (ccittTable[((checkSum >> 8) & 0xFF) ^ (msg[i+offset] & 0xFF)] ^ (checkSum << 8)) & 0xFFFF; - } - } - return checkSum; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class CrcCccitt { + // CRC-CCITT polynomial: x^16 + x^12 + x^5 + 1 + final private static int ccittPolynomial = 0x1021; + final private static int ccittTableSize = 256; + final private static int[] ccittTable = new int[ccittTableSize]; + + static { + for (int i = 0; i < ccittTableSize; i++) { + int checkSum = i << 8; + for (int j = 0; j < 8; j++) + checkSum = (checkSum & 0x8000) == 0x8000 ? (checkSum << 1) ^ ccittPolynomial : (checkSum << 1); + ccittTable[i] = checkSum & 0xFFFF; + } + } + + public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC) { + return calculateCrcCccitt(msgIncludingMsgCRC) == 0; + } + + + public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC, int offset, int count) { + return calculateCrcCccitt(msgIncludingMsgCRC, offset, count) == 0; + } + + // update last two bytes of the message with CRC of all preceding bytes + public static void setMsgCRC(byte[] msg) { + if ( msg != null && msg.length > 2) { + int checkSum = calculateCrcCccitt(msg, 0, msg.length-2); + ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); + buffer.putShort((short)checkSum); + byte[] crcBytes = buffer.array(); + System.arraycopy(crcBytes, 0, msg, msg.length-2, 2); + } + } + + public static int calculateCrcCccitt(byte[] msg) { + return msg != null ? calculateCrcCccitt(msg, 0, msg.length) : 0; + } + + public static int calculateCrcCccitt(byte[] msg, int offset, int count) { + int checkSum = 0; + if ( msg != null && offset >= 0 ) { + final int size = Math.min(msg.length, count); + for( int i = 0; i < size; i++ ) { + checkSum = (ccittTable[((checkSum >> 8) & 0xFF) ^ (msg[i+offset] & 0xFF)] ^ (checkSum << 8)) & 0xFFFF; + } + } + return checkSum; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java index 40a1ab62f..65cefb459 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.text.ParseException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; - -public class DateTimeUtils { - - private DateTimeUtils() { - } - - public static String now() { - return nowZDT().format(DateTimeFormatter.ISO_INSTANT); - } - - public static ZonedDateTime nowZDT() { - return ZonedDateTime.now(ZoneId.of("UTC")); - } - - public static String isoDateTime(ZonedDateTime zonedDateTime) { - return zonedDateTime.format(DateTimeFormatter.ISO_INSTANT); - } - - public static ZonedDateTime - isoDateTime(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millisec) { - return ZonedDateTime.of(year, month, dayOfMonth, hourOfDay, minute, second, millisec * 1000000, ZoneOffset.UTC); - } - - public static ZonedDateTime isoDateTime(String s) throws ParseException { - return ZonedDateTime.parse(s); - } - - public static ZonedDateTime isoDateTime(Date date) { - return ZonedDateTime.from(date.toInstant().atZone(ZoneId.of("UTC"))); - } - - public static ZonedDateTime isoDateTime(long epockMillis) { - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(epockMillis), ZoneId.of("UTC")); - } - - public static boolean - isBetweenTimesInclusive(ZonedDateTime dateTime, ZonedDateTime startDateTime, ZonedDateTime endDateTime) { - - if (dateTime == null) - return true; - - if (startDateTime == null) { - if (endDateTime == null) {// Both startDate and endDate are null, so - // it's false - return true; - } else {// We only have the endDate, so any dateTime not after the - // endDateTime is true - return !dateTime.isAfter(endDateTime); - } - } else { - if (endDateTime == null) {// We only have the startDateTime, so any - // dateTime not before the startDateTime is - // true - return !dateTime.isBefore(startDateTime); - } else {// We have both startDateTime and endDateTime, so any dateTime - // not before the startDate and not after endDateTime is true - return !dateTime.isBefore(startDateTime) && !dateTime.isAfter(endDateTime); - } - } - } - - public static long difference(ZonedDateTime t1, ZonedDateTime t2) { - return t2.toInstant().toEpochMilli() - t1.toInstant().toEpochMilli(); - } - - public static Long elapsedTime(ZonedDateTime zonedDateTime) { - return difference(zonedDateTime, ZonedDateTime.now()); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.text.ParseException; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +public class DateTimeUtils { + + private DateTimeUtils() { + } + + public static String now() { + return nowZDT().format(DateTimeFormatter.ISO_INSTANT); + } + + public static ZonedDateTime nowZDT() { + return ZonedDateTime.now(ZoneId.of("UTC")); + } + + public static String isoDateTime(ZonedDateTime zonedDateTime) { + return zonedDateTime.format(DateTimeFormatter.ISO_INSTANT); + } + + public static ZonedDateTime + isoDateTime(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millisec) { + return ZonedDateTime.of(year, month, dayOfMonth, hourOfDay, minute, second, millisec * 1000000, ZoneOffset.UTC); + } + + public static ZonedDateTime isoDateTime(String s) throws ParseException { + return ZonedDateTime.parse(s); + } + + public static ZonedDateTime isoDateTime(Date date) { + return ZonedDateTime.from(date.toInstant().atZone(ZoneId.of("UTC"))); + } + + public static ZonedDateTime isoDateTime(long epockMillis) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(epockMillis), ZoneId.of("UTC")); + } + + public static boolean + isBetweenTimesInclusive(ZonedDateTime dateTime, ZonedDateTime startDateTime, ZonedDateTime endDateTime) { + + if (dateTime == null) + return true; + + if (startDateTime == null) { + if (endDateTime == null) {// Both startDate and endDate are null, so + // it's false + return true; + } else {// We only have the endDate, so any dateTime not after the + // endDateTime is true + return !dateTime.isAfter(endDateTime); + } + } else { + if (endDateTime == null) {// We only have the startDateTime, so any + // dateTime not before the startDateTime is + // true + return !dateTime.isBefore(startDateTime); + } else {// We have both startDateTime and endDateTime, so any dateTime + // not before the startDate and not after endDateTime is true + return !dateTime.isBefore(startDateTime) && !dateTime.isAfter(endDateTime); + } + } + } + + public static long difference(ZonedDateTime t1, ZonedDateTime t2) { + return t2.toInstant().toEpochMilli() - t1.toInstant().toEpochMilli(); + } + + public static Long elapsedTime(ZonedDateTime zonedDateTime) { + return difference(zonedDateTime, ZonedDateTime.now()); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java index d404b3118..92696439b 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -/** - * Timer class with formatting - * - */ -public class FormattedTimer { - /** */ - private long timerStart = 0L; - /** */ - - - /** - * Starts the timer - */ - public FormattedTimer() { - this.timerStart = System.currentTimeMillis(); - } - - /** - * Formats the time lapsed to "{HH} hours {mm} minutes {ss.sss} seconds". - * - * @param time - * @return - */ - protected String format(long time) { - - float seconds; - int minutes; - int hours; - - StringBuilder sb = new StringBuilder(); - float timeInSeconds = ((float) (time)) / 1000; - hours = (int) (timeInSeconds / 3600); - timeInSeconds = timeInSeconds - (hours * 3600); - minutes = (int) (timeInSeconds / 60); - timeInSeconds = timeInSeconds - (minutes * 60); - seconds = timeInSeconds; - sb.append(hours); - sb.append(" hours "); - sb.append(minutes); - sb.append(" minutes "); - sb.append(seconds); - sb.append(" seconds"); - return sb.toString(); - } - - /** - * @return the formatted time lapsed - */ - public String getFormattedTimer() { - return format(System.currentTimeMillis() - timerStart); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +/** + * Timer class with formatting + * + */ +public class FormattedTimer { + /** */ + private long timerStart = 0L; + /** */ + + + /** + * Starts the timer + */ + public FormattedTimer() { + this.timerStart = System.currentTimeMillis(); + } + + /** + * Formats the time lapsed to "{HH} hours {mm} minutes {ss.sss} seconds". + * + * @param time + * @return + */ + protected String format(long time) { + + float seconds; + int minutes; + int hours; + + StringBuilder sb = new StringBuilder(); + float timeInSeconds = ((float) (time)) / 1000; + hours = (int) (timeInSeconds / 3600); + timeInSeconds = timeInSeconds - (hours * 3600); + minutes = (int) (timeInSeconds / 60); + timeInSeconds = timeInSeconds - (minutes * 60); + seconds = timeInSeconds; + sb.append(hours); + sb.append(" hours "); + sb.append(minutes); + sb.append(" minutes "); + sb.append(seconds); + sb.append(" seconds"); + return sb.toString(); + } + + /** + * @return the formatted time lapsed + */ + public String getFormattedTimer() { + return format(System.currentTimeMillis() - timerStart); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java index dc6e87b2c..f15cd6b45 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java @@ -1,342 +1,342 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; - -public class GeoUtils { - public static final double ERROR_MARGIN = 0.0001; - public static final QELLIPSOID ellipsoid = new QELLIPSOID(6378206.4, 6356583.8, 0.08227185423947); - - public static final double EARTH_RADIUS_M = 6370997.0; - public static final double EARTH_RADIUS_MI = 3963.2263272; - - public static final ProjParams proj = new ProjParams(0.0); - - private GeoUtils() { - } - - public static class QELLIPSOID { - private double dEqRadius = 6378206.4; - private double dPolRadius = 6356583.8; - private double dEccentricity = 0.08227185423947; - - public QELLIPSOID() { - super(); - } - - public QELLIPSOID(double dEqRadius, double dPolRadius, double dEccentricity) { - this(); - this.dEqRadius = dEqRadius; - this.dPolRadius = dPolRadius; - this.dEccentricity = dEccentricity; - } - - public double getdEqRadius() { - return dEqRadius; - } - - public void setdEqRadius(double dEqRadius) { - this.dEqRadius = dEqRadius; - } - - public double getdPolRadius() { - return dPolRadius; - } - - public void setdPolRadius(double dPolRadius) { - this.dPolRadius = dPolRadius; - } - - public double getdEccentricity() { - return dEccentricity; - } - - public void setdEccentricity(double dEccentricity) { - this.dEccentricity = dEccentricity; - } - - } - - public static class ProjParams { - private double dCentralMeridian; - - public ProjParams() { - super(); - } - - public ProjParams(double dCentralMeridian) { - this(); - this.dCentralMeridian = dCentralMeridian; - } - - } - - public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) { - if (dest == null) { - dest = new Point2D.Double(); - } - - double apx = p.getX() - l.getX1(); - double apy = p.getY() - l.getY1(); - double abx = l.getX2() - l.getX1(); - double aby = l.getY2() - l.getY1(); - - double ab2 = abx * abx + aby * aby; - double ap_ab = apx * abx + apy * aby; - double t = ap_ab / ab2; - if (clampToSegment) { - if (t < 0) { - t = 0; - } else if (t > 1) { - t = 1; - } - } - dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t); - return dest; - } - - public static double lineLength(Point2D a, Point2D b) { - double abx = Math.abs(b.getX() - a.getX()); - double aby = Math.abs(b.getY() - a.getY()); - return Math.sqrt(abx * abx + aby * aby); - } - - public static double distanceToLine(Line2D l, Point2D p) { - - return l.ptLineDist(p); - } - - public static double distanceToLine2(Line2D l, Point2D p) { - - Point2D p2 = nearestPointOnLine(l, p, true, null); - return p.distance(p2); - } - - public static double distanceToLine3(Line2D l, Point2D p) - // Calculate the distance between the point (nX, nY) and the line through - // the - // points (nP1X, nP1Y), (nP2X, nP2Y). - { - double dDist = 0; - - if (l.getX1() == l.getX2()) - // Vertical line - dDist = p.getX() - l.getX1(); - else if (l.getY1() == l.getY2()) - // Horizontal line - dDist = p.getY() - l.getY1(); - else { - // Figure out the slope and Y intercept of the line - double dM1 = ((double) l.getY2() - l.getY1()) / ((double) l.getX2() - l.getX1()); - double dB1 = l.getY1() - (dM1 * l.getX1()); - // Figure out the slope and Y intercept of the perpendicular line - // through the third point - double dM2 = -(1 / dM1); - double dB2 = p.getY() - (dM2 * p.getX()); - - // Find the intersection of the two lines - double dXInt, dYInt; - dXInt = (dB2 - dB1) / (dM1 - dM2); - dYInt = (dM2 * dXInt) + dB2; - - // Now calulate the distance between the point and the intesection - // of - // the two lines. - dDist = Math.sqrt(Math.pow(dXInt - p.getX(), 2) + Math.pow(dYInt - p.getY(), 2)); - } - - return Math.abs(dDist); - } - - /** - * This function returns a Point2D that is offset to a point 'a' by distance - * 'k' and perpendicular to the line 'a-b' - * - * b / dest / *--- m ----- / | / l k / | a - * - * @param a - * @param b - * @param k - * @param dest - * @return - */ - public static Point2D pointOffset(Point2D a, Point2D b, double k, Point2D dest) { - if (dest == null) { - dest = new Point2D.Double(); - } - - double tanAlpha = (b.getY() - a.getY()) / (b.getX() - a.getX()); - double alpha = Math.atan(tanAlpha); - double sinAlpha = Math.sin(alpha); - double cosAlpha = Math.cos(alpha); - - double destX; - double destY; - if (b.getX() < a.getX()) { - destX = (a.getX() + k * sinAlpha); - destY = (a.getY() - k * cosAlpha); - } else { - destX = (a.getX() - k * sinAlpha); - destY = (a.getY() + k * cosAlpha); - } - - dest.setLocation(destX, destY); - return dest; - } - - public static double DEG2RAD(double deg) { - return ((double) deg * (Math.PI / 180.0)); - } - - public static double RAD2DEG(double rad) { - return ((double) rad * (180.0 / Math.PI)); - } - - public static Point2D latLngToMap(double dLat, double dLng) { - Point2D p = new Point2D.Double(); - - // Calculate map x - double px = ellipsoid.dEqRadius * DEG2RAD(dLng - proj.dCentralMeridian); - - double onePlusESine, oneMinusESine, tangent; - double eSine; - double divPowerE; - double lnValue; - - eSine = ellipsoid.dEccentricity * Math.sin(DEG2RAD(dLat)); - - onePlusESine = 1 + eSine; - oneMinusESine = 1 - eSine; - - divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); - - tangent = Math.tan(DEG2RAD((45.0 + dLat / 2.0))); - - lnValue = tangent * divPowerE; - double py = ellipsoid.dEqRadius * Math.log(lnValue); - - p.setLocation(px, py); - return p; - } - - public static Point2D mapToLatLng(Point2D d) { - // Calculate the lat - double t; - double onePlusESine, oneMinusESine; - double arcTangent; - double divPowerE; - double error = 0.0; - Point2D p = new Point2D.Double(); - - t = Math.exp(-(d.getY() / ellipsoid.dEqRadius)); - // Initial value far the lat - - double lat0 = 90 - 2 * RAD2DEG(Math.atan(t)); - - int i = 0; - do { - onePlusESine = 1 + (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); - oneMinusESine = 1 - (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); - - divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); - arcTangent = RAD2DEG(Math.atan(t * divPowerE)); - double lat = 90 - (2 * arcTangent); - error = Math.abs(lat - lat0); - lat0 = lat; - i++; // to avoid infinite loop; - } while (error > ERROR_MARGIN && i < 5); - - // Calculate the longitude - double lng = RAD2DEG(d.getY() / ellipsoid.dEqRadius) + proj.dCentralMeridian; - p.setLocation(lat0, lng); - - return p; - } - - public static double distance(Point2D a, Point2D b) { - return a.distance(b); - } - - public static double distanceLatLng(double dLat1, double dLng1, double dLat2, double dLng2, - LengthUtils.UnitOfMeasure u) { - double cd; - - // special case - if (dLat1 == dLat2 && dLng1 == dLng2) - return 0.0; - - double dDiff = dLng1 - dLng2; - int nSegs = (int) (Math.abs(dDiff) / 180.0); - double dDistance = 0; - - if (nSegs > 0 && dLat1 == dLat2) { - // if the span is bigger than 180 degrees, adjust the distance - cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) - + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(180.0)); - - cd = EARTH_RADIUS_M * Math.acos(cd); // This is in miles - dDistance = nSegs * cd; - dDiff = Math.abs(dDiff) - 180.0 * nSegs; - } - - cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) - + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(dDiff)); - - cd = EARTH_RADIUS_M * Math.acos(cd); // This is in meters - - cd += dDistance; - - switch (u) { - case KM: - cd = LengthUtils.MILES2KM(cd); - break; - case YARD: - cd = (LengthUtils.MILES2KM(cd) * 1000.0) / 0.9; // 90cm = 1 yard - break; - case MILE: - cd = LengthUtils.METERS2MILES(cd) * 1000.0; - break; - case NAUTICAL_MILE: - cd = LengthUtils.MILES2KNOTS(cd); - break; - case M: - default: - // already cd is in meters. we don't have to convert. - break; - } - - return cd; - } - - public static double distanceXY(double aLat, double aLng, double bLat, double bLng) { - - Point2D a = GeoUtils.latLngToMap(aLat, aLng); - Point2D b = GeoUtils.latLngToMap(bLat, bLng); - - return a.distance(b); - } - - public static boolean isPointWithinBounds(Point2D p, Line2D l, double tolerance) { - // Make sure the point p is inside the bounding rectangle of the segment - // a-b - return ((p.getX() >= (Math.min(l.getX1(), l.getX2()) - tolerance)) - && (p.getX() <= (Math.max(l.getX1(), l.getX2()) + tolerance)) - && (p.getY() >= (Math.min(l.getY1(), l.getY2()) - tolerance)) - && (p.getY() <= (Math.max(l.getY1(), l.getY2()) + tolerance))); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; + +public class GeoUtils { + public static final double ERROR_MARGIN = 0.0001; + public static final QELLIPSOID ellipsoid = new QELLIPSOID(6378206.4, 6356583.8, 0.08227185423947); + + public static final double EARTH_RADIUS_M = 6370997.0; + public static final double EARTH_RADIUS_MI = 3963.2263272; + + public static final ProjParams proj = new ProjParams(0.0); + + private GeoUtils() { + } + + public static class QELLIPSOID { + private double dEqRadius = 6378206.4; + private double dPolRadius = 6356583.8; + private double dEccentricity = 0.08227185423947; + + public QELLIPSOID() { + super(); + } + + public QELLIPSOID(double dEqRadius, double dPolRadius, double dEccentricity) { + this(); + this.dEqRadius = dEqRadius; + this.dPolRadius = dPolRadius; + this.dEccentricity = dEccentricity; + } + + public double getdEqRadius() { + return dEqRadius; + } + + public void setdEqRadius(double dEqRadius) { + this.dEqRadius = dEqRadius; + } + + public double getdPolRadius() { + return dPolRadius; + } + + public void setdPolRadius(double dPolRadius) { + this.dPolRadius = dPolRadius; + } + + public double getdEccentricity() { + return dEccentricity; + } + + public void setdEccentricity(double dEccentricity) { + this.dEccentricity = dEccentricity; + } + + } + + public static class ProjParams { + private double dCentralMeridian; + + public ProjParams() { + super(); + } + + public ProjParams(double dCentralMeridian) { + this(); + this.dCentralMeridian = dCentralMeridian; + } + + } + + public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) { + if (dest == null) { + dest = new Point2D.Double(); + } + + double apx = p.getX() - l.getX1(); + double apy = p.getY() - l.getY1(); + double abx = l.getX2() - l.getX1(); + double aby = l.getY2() - l.getY1(); + + double ab2 = abx * abx + aby * aby; + double ap_ab = apx * abx + apy * aby; + double t = ap_ab / ab2; + if (clampToSegment) { + if (t < 0) { + t = 0; + } else if (t > 1) { + t = 1; + } + } + dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t); + return dest; + } + + public static double lineLength(Point2D a, Point2D b) { + double abx = Math.abs(b.getX() - a.getX()); + double aby = Math.abs(b.getY() - a.getY()); + return Math.sqrt(abx * abx + aby * aby); + } + + public static double distanceToLine(Line2D l, Point2D p) { + + return l.ptLineDist(p); + } + + public static double distanceToLine2(Line2D l, Point2D p) { + + Point2D p2 = nearestPointOnLine(l, p, true, null); + return p.distance(p2); + } + + public static double distanceToLine3(Line2D l, Point2D p) + // Calculate the distance between the point (nX, nY) and the line through + // the + // points (nP1X, nP1Y), (nP2X, nP2Y). + { + double dDist = 0; + + if (l.getX1() == l.getX2()) + // Vertical line + dDist = p.getX() - l.getX1(); + else if (l.getY1() == l.getY2()) + // Horizontal line + dDist = p.getY() - l.getY1(); + else { + // Figure out the slope and Y intercept of the line + double dM1 = ((double) l.getY2() - l.getY1()) / ((double) l.getX2() - l.getX1()); + double dB1 = l.getY1() - (dM1 * l.getX1()); + // Figure out the slope and Y intercept of the perpendicular line + // through the third point + double dM2 = -(1 / dM1); + double dB2 = p.getY() - (dM2 * p.getX()); + + // Find the intersection of the two lines + double dXInt, dYInt; + dXInt = (dB2 - dB1) / (dM1 - dM2); + dYInt = (dM2 * dXInt) + dB2; + + // Now calulate the distance between the point and the intesection + // of + // the two lines. + dDist = Math.sqrt(Math.pow(dXInt - p.getX(), 2) + Math.pow(dYInt - p.getY(), 2)); + } + + return Math.abs(dDist); + } + + /** + * This function returns a Point2D that is offset to a point 'a' by distance + * 'k' and perpendicular to the line 'a-b' + * + * b / dest / *--- m ----- / | / l k / | a + * + * @param a + * @param b + * @param k + * @param dest + * @return + */ + public static Point2D pointOffset(Point2D a, Point2D b, double k, Point2D dest) { + if (dest == null) { + dest = new Point2D.Double(); + } + + double tanAlpha = (b.getY() - a.getY()) / (b.getX() - a.getX()); + double alpha = Math.atan(tanAlpha); + double sinAlpha = Math.sin(alpha); + double cosAlpha = Math.cos(alpha); + + double destX; + double destY; + if (b.getX() < a.getX()) { + destX = (a.getX() + k * sinAlpha); + destY = (a.getY() - k * cosAlpha); + } else { + destX = (a.getX() - k * sinAlpha); + destY = (a.getY() + k * cosAlpha); + } + + dest.setLocation(destX, destY); + return dest; + } + + public static double DEG2RAD(double deg) { + return ((double) deg * (Math.PI / 180.0)); + } + + public static double RAD2DEG(double rad) { + return ((double) rad * (180.0 / Math.PI)); + } + + public static Point2D latLngToMap(double dLat, double dLng) { + Point2D p = new Point2D.Double(); + + // Calculate map x + double px = ellipsoid.dEqRadius * DEG2RAD(dLng - proj.dCentralMeridian); + + double onePlusESine, oneMinusESine, tangent; + double eSine; + double divPowerE; + double lnValue; + + eSine = ellipsoid.dEccentricity * Math.sin(DEG2RAD(dLat)); + + onePlusESine = 1 + eSine; + oneMinusESine = 1 - eSine; + + divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); + + tangent = Math.tan(DEG2RAD((45.0 + dLat / 2.0))); + + lnValue = tangent * divPowerE; + double py = ellipsoid.dEqRadius * Math.log(lnValue); + + p.setLocation(px, py); + return p; + } + + public static Point2D mapToLatLng(Point2D d) { + // Calculate the lat + double t; + double onePlusESine, oneMinusESine; + double arcTangent; + double divPowerE; + double error = 0.0; + Point2D p = new Point2D.Double(); + + t = Math.exp(-(d.getY() / ellipsoid.dEqRadius)); + // Initial value far the lat + + double lat0 = 90 - 2 * RAD2DEG(Math.atan(t)); + + int i = 0; + do { + onePlusESine = 1 + (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); + oneMinusESine = 1 - (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); + + divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); + arcTangent = RAD2DEG(Math.atan(t * divPowerE)); + double lat = 90 - (2 * arcTangent); + error = Math.abs(lat - lat0); + lat0 = lat; + i++; // to avoid infinite loop; + } while (error > ERROR_MARGIN && i < 5); + + // Calculate the longitude + double lng = RAD2DEG(d.getY() / ellipsoid.dEqRadius) + proj.dCentralMeridian; + p.setLocation(lat0, lng); + + return p; + } + + public static double distance(Point2D a, Point2D b) { + return a.distance(b); + } + + public static double distanceLatLng(double dLat1, double dLng1, double dLat2, double dLng2, + LengthUtils.UnitOfMeasure u) { + double cd; + + // special case + if (dLat1 == dLat2 && dLng1 == dLng2) + return 0.0; + + double dDiff = dLng1 - dLng2; + int nSegs = (int) (Math.abs(dDiff) / 180.0); + double dDistance = 0; + + if (nSegs > 0 && dLat1 == dLat2) { + // if the span is bigger than 180 degrees, adjust the distance + cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) + + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(180.0)); + + cd = EARTH_RADIUS_M * Math.acos(cd); // This is in miles + dDistance = nSegs * cd; + dDiff = Math.abs(dDiff) - 180.0 * nSegs; + } + + cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) + + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(dDiff)); + + cd = EARTH_RADIUS_M * Math.acos(cd); // This is in meters + + cd += dDistance; + + switch (u) { + case KM: + cd = LengthUtils.MILES2KM(cd); + break; + case YARD: + cd = (LengthUtils.MILES2KM(cd) * 1000.0) / 0.9; // 90cm = 1 yard + break; + case MILE: + cd = LengthUtils.METERS2MILES(cd) * 1000.0; + break; + case NAUTICAL_MILE: + cd = LengthUtils.MILES2KNOTS(cd); + break; + case M: + default: + // already cd is in meters. we don't have to convert. + break; + } + + return cd; + } + + public static double distanceXY(double aLat, double aLng, double bLat, double bLng) { + + Point2D a = GeoUtils.latLngToMap(aLat, aLng); + Point2D b = GeoUtils.latLngToMap(bLat, bLng); + + return a.distance(b); + } + + public static boolean isPointWithinBounds(Point2D p, Line2D l, double tolerance) { + // Make sure the point p is inside the bounding rectangle of the segment + // a-b + return ((p.getX() >= (Math.min(l.getX1(), l.getX2()) - tolerance)) + && (p.getX() <= (Math.max(l.getX1(), l.getX2()) + tolerance)) + && (p.getY() >= (Math.min(l.getY1(), l.getY2()) - tolerance)) + && (p.getY() <= (Math.max(l.getY1(), l.getY2()) + tolerance))); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java index 1b77fa493..3cc01bb5d 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class JsonUtils { - - public static class JsonUtilsException extends Exception { - - private static final long serialVersionUID = 1L; - - public JsonUtilsException(String string, Exception e) { - super(string, e); - } - - } - - private static Gson gsonCompact; - private static Gson gsonVerbose; - private static ObjectMapper mapper; - private static Logger logger; - - private JsonUtils() { - logger = LoggerFactory.getLogger(JsonUtils.class); - } - - static { - gsonCompact = new GsonBuilder().create(); - gsonVerbose = new GsonBuilder().serializeNulls().create(); - mapper = new ObjectMapper(); - } - - public static String toJson(Object o, boolean verbose) { - - // convert java object to JSON format, - // and returned as JSON formatted string - return verbose ? gsonVerbose.toJson(o) : gsonCompact.toJson(o); - } - - public static Object fromJson(String s, Class clazz) { - return gsonCompact.fromJson(s, clazz); - } - - public static Object jacksonFromJson(String s, Class clazz) throws JsonUtilsException { - try { - return mapper.readValue(s, clazz); - } catch (IOException e) { - throw new JsonUtilsException("Error deserializing JSON tree to " + clazz.getName(), e); - } - } - - public static String newJson(String key, Object value) { - return newObjectNode(key, value).toString(); - } - - public static ObjectNode cloneObjectNode(ObjectNode src) { - return src.deepCopy(); - } - - public static ObjectNode newObjectNode(String key, Object value) { - ObjectNode json = mapper.createObjectNode(); - json.putPOJO(key, value); - return json; - } - - public static ObjectNode addNode(ObjectNode tree, String fieldName, Object fieldValue) { - tree.putPOJO(fieldName, fieldValue); - return tree; - } - - public static JsonNode getJsonNode(String tree, String fieldName) { - JsonNode node = null; - try { - JsonNode jsonNode = mapper.readTree(tree); - node = jsonNode.get(fieldName); - - } catch (IOException e) { - logger.error("IOException", e); - } - return node; - } - - public static ObjectNode newNode() { - return mapper.createObjectNode(); - } - - public static ArrayNode newArrayNode() { - return mapper.createArrayNode(); - } - - public static ObjectNode toObjectNode(String tree) throws JsonUtilsException { - ObjectNode jsonNode; - try { - jsonNode = (ObjectNode) mapper.readTree(tree); - } catch (Exception e) { - throw new JsonUtilsException("Error converting JSON tree to ObjectNode", e); - } - return jsonNode; - } - - public static JSONObject toJSONObject(String json) throws JsonUtilsException { - try { - return new JSONObject(json); - } catch (Exception e) { - throw new JsonUtilsException("Error decoding " + json + "to JSONObject", e); - } - } - - public static boolean isValid(String tree) throws IOException { - try { - ObjectNode jsonNode = (ObjectNode) mapper.readTree(tree); - return jsonNode != null; - } catch (JsonProcessingException jpe) { - return false; - } - } - - public static HashMap jsonNodeToHashMap(JsonNode jsonNode) { - HashMap nodeProps = new HashMap(); - Iterator> iter = jsonNode.fields(); - - while (iter.hasNext()) { - Entry element = iter.next(); - nodeProps.put(element.getKey(), element.getValue()); - } - return nodeProps; - } - - /** - * Takes in a key, value pair and returns a valid JSON string such as - * {"error":"message"} - * - * @param key - * @param value - * @return - */ - public static String jsonKeyValue(String key, String value) { - return "{\"" + key + "\":\"" + value + "\"}"; - } - - public static BigDecimal decimalValue(JsonNode v) { - BigDecimal result; - if (v.isTextual()) { - result = new BigDecimal(v.textValue()); - } else { - result = v.decimalValue(); - } - return result; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class JsonUtils { + + public static class JsonUtilsException extends Exception { + + private static final long serialVersionUID = 1L; + + public JsonUtilsException(String string, Exception e) { + super(string, e); + } + + } + + private static Gson gsonCompact; + private static Gson gsonVerbose; + private static ObjectMapper mapper; + private static Logger logger; + + private JsonUtils() { + logger = LoggerFactory.getLogger(JsonUtils.class); + } + + static { + gsonCompact = new GsonBuilder().create(); + gsonVerbose = new GsonBuilder().serializeNulls().create(); + mapper = new ObjectMapper(); + } + + public static String toJson(Object o, boolean verbose) { + + // convert java object to JSON format, + // and returned as JSON formatted string + return verbose ? gsonVerbose.toJson(o) : gsonCompact.toJson(o); + } + + public static Object fromJson(String s, Class clazz) { + return gsonCompact.fromJson(s, clazz); + } + + public static Object jacksonFromJson(String s, Class clazz) throws JsonUtilsException { + try { + return mapper.readValue(s, clazz); + } catch (IOException e) { + throw new JsonUtilsException("Error deserializing JSON tree to " + clazz.getName(), e); + } + } + + public static String newJson(String key, Object value) { + return newObjectNode(key, value).toString(); + } + + public static ObjectNode cloneObjectNode(ObjectNode src) { + return src.deepCopy(); + } + + public static ObjectNode newObjectNode(String key, Object value) { + ObjectNode json = mapper.createObjectNode(); + json.putPOJO(key, value); + return json; + } + + public static ObjectNode addNode(ObjectNode tree, String fieldName, Object fieldValue) { + tree.putPOJO(fieldName, fieldValue); + return tree; + } + + public static JsonNode getJsonNode(String tree, String fieldName) { + JsonNode node = null; + try { + JsonNode jsonNode = mapper.readTree(tree); + node = jsonNode.get(fieldName); + + } catch (IOException e) { + logger.error("IOException", e); + } + return node; + } + + public static ObjectNode newNode() { + return mapper.createObjectNode(); + } + + public static ArrayNode newArrayNode() { + return mapper.createArrayNode(); + } + + public static ObjectNode toObjectNode(String tree) throws JsonUtilsException { + ObjectNode jsonNode; + try { + jsonNode = (ObjectNode) mapper.readTree(tree); + } catch (Exception e) { + throw new JsonUtilsException("Error converting JSON tree to ObjectNode", e); + } + return jsonNode; + } + + public static JSONObject toJSONObject(String json) throws JsonUtilsException { + try { + return new JSONObject(json); + } catch (Exception e) { + throw new JsonUtilsException("Error decoding " + json + "to JSONObject", e); + } + } + + public static boolean isValid(String tree) throws IOException { + try { + ObjectNode jsonNode = (ObjectNode) mapper.readTree(tree); + return jsonNode != null; + } catch (JsonProcessingException jpe) { + return false; + } + } + + public static HashMap jsonNodeToHashMap(JsonNode jsonNode) { + HashMap nodeProps = new HashMap(); + Iterator> iter = jsonNode.fields(); + + while (iter.hasNext()) { + Entry element = iter.next(); + nodeProps.put(element.getKey(), element.getValue()); + } + return nodeProps; + } + + /** + * Takes in a key, value pair and returns a valid JSON string such as + * {"error":"message"} + * + * @param key + * @param value + * @return + */ + public static String jsonKeyValue(String key, String value) { + return "{\"" + key + "\":\"" + value + "\"}"; + } + + public static BigDecimal decimalValue(JsonNode v) { + BigDecimal result; + if (v.isTextual()) { + result = new BigDecimal(v.textValue()); + } else { + result = v.decimalValue(); + } + return result; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java index 9143f1ff5..224a01e54 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -public class LengthUtils { - public enum UnitOfMeasure { - MM, CM, M, KM, INCH, FOOT, YARD, MILE, NAUTICAL_MILE - } - - public static double MILES2KM(double m) {return ((double)m * 1.609347);} - - public static double KM2MILES(double m) {return ((double)m / 1.609347);} - - public static double MILES2METERS(double m) {return ((double)m * 1609.347);} - public static double METERS2MILES(double m) {return ((double)m / 1609.347);} - - public static double MILES2KNOTS(double m) {return ((double)m / 1.150568);} - public static double KNOTS2MILES(double m) {return ((double)m * 1.150568);} - - public static double MILES2YARDS(double m) {return ((double)m * 1760.0);} - public static double YARDS2MILES(double m) {return ((double)m / 1760.0);} -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +public class LengthUtils { + public enum UnitOfMeasure { + MM, CM, M, KM, INCH, FOOT, YARD, MILE, NAUTICAL_MILE + } + + public static double MILES2KM(double m) {return ((double)m * 1.609347);} + + public static double KM2MILES(double m) {return ((double)m / 1.609347);} + + public static double MILES2METERS(double m) {return ((double)m * 1609.347);} + public static double METERS2MILES(double m) {return ((double)m / 1609.347);} + + public static double MILES2KNOTS(double m) {return ((double)m / 1.150568);} + public static double KNOTS2MILES(double m) {return ((double)m * 1.150568);} + + public static double MILES2YARDS(double m) {return ((double)m * 1760.0);} + public static double YARDS2MILES(double m) {return ((double)m / 1760.0);} +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java index 85849305a..d3b1b2976 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.Serializable; -import java.util.Enumeration; -import java.util.Hashtable; - -public abstract class SerializableObjectPool implements Serializable { - private static final long serialVersionUID = 914977959079989774L; - - private long expirationTime; - - private Hashtable locked, unlocked; - - public SerializableObjectPool() { - expirationTime = 30000; // 30 seconds - locked = new Hashtable(); - unlocked = new Hashtable(); - } - - protected abstract T create(); - - public abstract boolean validate(T o); - - public abstract void expire(T o); - - public synchronized T checkOut() { - long now = System.currentTimeMillis(); - T t; - if (unlocked.size() > 0) { - Enumeration e = unlocked.keys(); - while (e.hasMoreElements()) { - t = e.nextElement(); - if ((now - unlocked.get(t)) > expirationTime) { - // object has expired - unlocked.remove(t); - expire(t); - t = null; //NOSONAR - } else { - if (validate(t)) { - unlocked.remove(t); - locked.put(t, now); - return (t); - } else { - // object failed validation - unlocked.remove(t); - expire(t); - t = null; //NOSONAR - } - } - } - } - // no objects available, create a new one - t = create(); - locked.put(t, now); - return (t); - } - - public synchronized void checkIn(T t) { - locked.remove(t); - unlocked.put(t, System.currentTimeMillis()); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.Serializable; +import java.util.Enumeration; +import java.util.Hashtable; + +public abstract class SerializableObjectPool implements Serializable { + private static final long serialVersionUID = 914977959079989774L; + + private long expirationTime; + + private Hashtable locked, unlocked; + + public SerializableObjectPool() { + expirationTime = 30000; // 30 seconds + locked = new Hashtable(); + unlocked = new Hashtable(); + } + + protected abstract T create(); + + public abstract boolean validate(T o); + + public abstract void expire(T o); + + public synchronized T checkOut() { + long now = System.currentTimeMillis(); + T t; + if (unlocked.size() > 0) { + Enumeration e = unlocked.keys(); + while (e.hasMoreElements()) { + t = e.nextElement(); + if ((now - unlocked.get(t)) > expirationTime) { + // object has expired + unlocked.remove(t); + expire(t); + t = null; //NOSONAR + } else { + if (validate(t)) { + unlocked.remove(t); + locked.put(t, now); + return (t); + } else { + // object failed validation + unlocked.remove(t); + expire(t); + t = null; //NOSONAR + } + } + } + } + // no objects available, create a new one + t = create(); + locked.put(t, now); + return (t); + } + + public synchronized void checkIn(T t) { + locked.remove(t); + unlocked.put(t, System.currentTimeMillis()); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java index 1014ee942..2334843c6 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java @@ -1,49 +1,49 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.IOException; - -import javax.websocket.Session; - -public class WebSocketUtils { - - /** - * @param session - * @param message - * @throws IOException - */ - public static void send(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getBasicRemote().sendText(message); - } - } - - public static void sendSync(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getBasicRemote().sendText(message); - } - } - - public static void sendAsync(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getAsyncRemote().sendText(message); - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.IOException; + +import javax.websocket.Session; + +public class WebSocketUtils { + + /** + * @param session + * @param message + * @throws IOException + */ + public static void send(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getBasicRemote().sendText(message); + } + } + + public static void sendSync(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getBasicRemote().sendText(message); + } + } + + public static void sendAsync(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getAsyncRemote().sendText(message); + } + } +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java index e01d0c2ad..5359e8b5c 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java @@ -1,116 +1,116 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.junit.Ignore; -import org.junit.Test; - -import mockit.Capturing; -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPacketFunctionalTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - private static boolean isVerbose = false; - - @Test - public void testConstrcutor() throws UnknownHostException { - InetPacket pkt = new InetPacket("bah.com", 1111, null); - - assertNull(pkt.getPayload()); - } - - @Test @Ignore - public void test() throws UnknownHostException { - test("127.0.0.1", 12, "01234567890".getBytes()); - test("::1", 47561, "0123456789001234567890".getBytes()); - test("1080:0:0:0:8:800:200C:417A", 345, "".getBytes()); - test("1080:0:0:0:8:800:200C:417A", 345, null); - test("1.0.0", 47561, "".getBytes()); - test("::FFFF:129.144.52.38", 4756, "0".getBytes()); - test("1080::8:800:200C:417A", 4756, new byte[] { (byte)0, (byte)1 }); - test("2001:0:9d38:90d7:3ce3:339d:f5c3:c42b", 11111, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); - test(null, 22222, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); - test("fdf8:f53b:82e4::53", 11111, new byte[] { (byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe }); - } - - public void test(String address, int port, byte[] payload) throws UnknownHostException { - if ( payload == null ) - return; - if ( isVerbose ) - System.out.println("---------- Test ----------"); - DatagramPacket packet = new DatagramPacket(payload, payload.length, InetAddress.getByName(address), port); - InetPacket pbOut = new InetPacket(packet); - test(address, port, payload, pbOut); - } - - public void test(String address, int port, byte[] payload, InetPacket pbOut) throws UnknownHostException { - InetPacket pbIn = new InetPacket(pbOut.getBundle()); - if ( isVerbose ) { - print("From params", pbOut); - print("From bundle", pbIn); - } - InetPoint pointIn = pbIn.getPoint(); - assertNotNull(pointIn); - InetPoint pointOut = pbOut.getPoint(); - assertEquals(pointOut.port, pointIn.port); - assertArrayEquals(pointOut.address, pointIn.address); - byte[] pbOutPayload = pbOut.getPayload(); - byte[] pyInPayload = pbIn.getPayload(); - if ( pbOutPayload != null && pbOutPayload != null ) - assertTrue(Arrays.equals(pbOutPayload, pyInPayload)); - else if (pbOutPayload != null || pbOutPayload != null) - assertTrue(false); - assertTrue(Arrays.equals(pbOut.getBundle(), pbIn.getBundle())); - } - - void print(String header, InetPacket pb) throws UnknownHostException { - assertNotNull(pb); - InetPoint point = pb.getPoint(); - if( point != null ) { - System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port ); - System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, - CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress() ); - System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false" ); - } else { - System.out.printf("%s: Inet point is null\n", header); - } - byte[] p = pb.getPayload(); - System.out.printf("%s payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); - System.out.printf("%s bundle: %s\n", header, pb.toHexString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; + +import org.junit.Ignore; +import org.junit.Test; + +import mockit.Capturing; +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPacketFunctionalTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + private static boolean isVerbose = false; + + @Test + public void testConstrcutor() throws UnknownHostException { + InetPacket pkt = new InetPacket("bah.com", 1111, null); + + assertNull(pkt.getPayload()); + } + + @Test @Ignore + public void test() throws UnknownHostException { + test("127.0.0.1", 12, "01234567890".getBytes()); + test("::1", 47561, "0123456789001234567890".getBytes()); + test("1080:0:0:0:8:800:200C:417A", 345, "".getBytes()); + test("1080:0:0:0:8:800:200C:417A", 345, null); + test("1.0.0", 47561, "".getBytes()); + test("::FFFF:129.144.52.38", 4756, "0".getBytes()); + test("1080::8:800:200C:417A", 4756, new byte[] { (byte)0, (byte)1 }); + test("2001:0:9d38:90d7:3ce3:339d:f5c3:c42b", 11111, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); + test(null, 22222, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); + test("fdf8:f53b:82e4::53", 11111, new byte[] { (byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe }); + } + + public void test(String address, int port, byte[] payload) throws UnknownHostException { + if ( payload == null ) + return; + if ( isVerbose ) + System.out.println("---------- Test ----------"); + DatagramPacket packet = new DatagramPacket(payload, payload.length, InetAddress.getByName(address), port); + InetPacket pbOut = new InetPacket(packet); + test(address, port, payload, pbOut); + } + + public void test(String address, int port, byte[] payload, InetPacket pbOut) throws UnknownHostException { + InetPacket pbIn = new InetPacket(pbOut.getBundle()); + if ( isVerbose ) { + print("From params", pbOut); + print("From bundle", pbIn); + } + InetPoint pointIn = pbIn.getPoint(); + assertNotNull(pointIn); + InetPoint pointOut = pbOut.getPoint(); + assertEquals(pointOut.port, pointIn.port); + assertArrayEquals(pointOut.address, pointIn.address); + byte[] pbOutPayload = pbOut.getPayload(); + byte[] pyInPayload = pbIn.getPayload(); + if ( pbOutPayload != null && pbOutPayload != null ) + assertTrue(Arrays.equals(pbOutPayload, pyInPayload)); + else if (pbOutPayload != null || pbOutPayload != null) + assertTrue(false); + assertTrue(Arrays.equals(pbOut.getBundle(), pbIn.getBundle())); + } + + void print(String header, InetPacket pb) throws UnknownHostException { + assertNotNull(pb); + InetPoint point = pb.getPoint(); + if( point != null ) { + System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port ); + System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, + CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress() ); + System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false" ); + } else { + System.out.printf("%s: Inet point is null\n", header); + } + byte[] p = pb.getPayload(); + System.out.printf("%s payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); + System.out.printf("%s bundle: %s\n", header, pb.toHexString()); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java index b192d6f71..53a52aa82 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java @@ -1,480 +1,480 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.apache.log4j.Logger; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import mockit.Capturing; -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPacketSenderTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - static final private boolean isDebugOutput = false; - - private static Logger log = Logger.getLogger(InetPacketSenderTest.class); - - private static final int DEFAULT_MAX_PACKET_SIZE = 65535; - - private static final String TRANSPORT_HOST = "localhost"; - private static final int TRANSPORT_PORT = 46751; - - private static final String FORWARDER_HOST = "localhost"; - private static final int FORWARDER_PORT = 46752; - - private static final String CLIENT_HOST_IPV4 = "localhost"; - private static final String CLIENT_HOST_IPV6 = "::1"; - private static final int CLIENT_PORT = 46753; - - private static final byte[] PAYLOAD = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xca, - (byte) 0xfe, (byte) 0xba, (byte) 0xbe }; - - AssertionError assertionError = null; - - private enum TestCase { - TestForwardPacketInbound, TestSendPacketOutbound, TestIPv6ForwardOutbound, TestIPv4ForwardOutboundForward, TestIPv4ForwardOutboundSend, TestIPv6SendOutbound, TestIPv4SendOutbound, - }; - - @BeforeClass - public static void init() { - } - - @Test - public void testForwardPacketInboundIPV4() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Forwarder forwards incoming IPV4 packet to transport - testForwardPacketInbound(CLIENT_HOST_IPV4); - } - - @Test - public void testForwardPacketInboundIPV6() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Forwarder forwards incoming IPV6 packet to transport - testForwardPacketInbound(CLIENT_HOST_IPV6); - } - - public void testForwardPacketInbound(String hostname) - throws UnknownHostException, InetPacketException, InterruptedException { - startUdpListener(TRANSPORT_PORT, TestCase.TestForwardPacketInbound); - InetPoint transport = new InetPoint(getAddressBytes(TRANSPORT_HOST), TRANSPORT_PORT); - InetPacketSender sender = new InetPacketSender(transport); - DatagramPacket packet = new DatagramPacket(PAYLOAD, PAYLOAD.length, InetAddress.getByName(hostname), CLIENT_PORT); - sender.forward(packet); - checkBackgroundThreadAssertion(); - } - - @Test @Ignore - public void testSendPacketOutboundIPv4() throws UnknownHostException, InterruptedException, InetPacketException { - // Use case: Forwarder sends outgoing IPv4 packet out - testSendPacketOutbound(CLIENT_HOST_IPV4); - } - - @Test @Ignore - public void testSendPacketOutboundIPv6() throws UnknownHostException, InterruptedException, InetPacketException { - // Use case: Forwarder sends outgoing IPv6 packet out - testSendPacketOutbound(CLIENT_HOST_IPV6); - } - - public void testSendPacketOutbound(String hostname) - throws UnknownHostException, InetPacketException, InterruptedException { - startUdpListener(CLIENT_PORT, TestCase.TestSendPacketOutbound); - InetPoint client = new InetPoint(getAddressBytes(hostname), CLIENT_PORT); - byte[] bundle = new InetPacket(client, PAYLOAD).getBundle(); - InetPacketSender sender = new InetPacketSender(); - DatagramPacket packet = new DatagramPacket(bundle, bundle.length, InetAddress.getByName(FORWARDER_HOST), - FORWARDER_PORT); - sender.send(packet); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv6ForwardOutbound() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Transport or Data Sink send IPv6 message out via forwarder - startUdpListener(FORWARDER_PORT, TestCase.TestIPv6ForwardOutbound); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4ForwardOutboundForward() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out via forwarder - startUdpListener(FORWARDER_PORT, TestCase.TestIPv4ForwardOutboundForward); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - sender.setForwardAll(true); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4ForwardOutboundSend() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out via forwarder - // but it's being send out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv4ForwardOutboundSend); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv6SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv6 message out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv6SendOutbound); - InetPacketSender sender = new InetPacketSender(); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); - sender.send(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv4SendOutbound); - InetPacketSender sender = new InetPacketSender(); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.send(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - private static byte[] getAddressBytes(String host) throws UnknownHostException { - return InetAddress.getByName(host).getAddress(); - } - - private void startUdpListener(int port, TestCase tc) { - final int listenPort = port; - final TestCase testCase = tc; - - Thread listener = new Thread(new Runnable() { - @Override - public void run() { - DatagramSocket socket = null; - try { - socket = new DatagramSocket(listenPort); - DatagramPacket datagramPacket = new DatagramPacket(new byte[DEFAULT_MAX_PACKET_SIZE], - DEFAULT_MAX_PACKET_SIZE); - socket.setSoTimeout(1000); - socket.receive(datagramPacket); - validatePacket(datagramPacket); - } catch (SocketTimeoutException ex) { - log.error( - String.format("Caught socket timeout exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), - ex); - } catch (SocketException ex) { - log.error(String.format("Caught socket exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), ex); - } catch (IOException ex) { - log.error( - String.format("Caught IO exception exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), - ex); - } finally { - if (socket != null && !socket.isClosed()) { - socket.close(); - socket = null; - } - } - } - - private void validatePacket(DatagramPacket packet) throws UnknownHostException { - assertNotNull(packet); - - final byte[] data = packet.getData(); - assertNotNull(data); - - final int length = packet.getLength(); - assertTrue(length > 0); - - final int offset = packet.getOffset(); - - byte[] packetData = Arrays.copyOfRange(data, offset, length); - - try { - switch (testCase) { - case TestForwardPacketInbound: - validateForwardPacketInbound(packetData); - validateForwardPacketInbound(packet); - break; - case TestSendPacketOutbound: - validateSendPacketOutbound(packetData); - validateSendPacketOutbound(packet); - break; - case TestIPv6ForwardOutbound: - validateIPv6ForwardOutbound(packetData); - validateIPv6ForwardOutbound(packet); - break; - case TestIPv4ForwardOutboundForward: - validateIPv4ForwardOutboundForward(packetData); - validateIPv4ForwardOutboundForward(packet); - break; - case TestIPv4ForwardOutboundSend: - validateIPv4ForwardOutboundSend(packetData); - validateIPv4ForwardOutboundSend(packet); - break; - case TestIPv6SendOutbound: - validateIPv6SendOutbound(packetData); - validateIPv6SendOutbound(packet); - break; - case TestIPv4SendOutbound: - validateIPv4SendOutbound(packetData); - validateIPv4SendOutbound(packet); - break; - } - } catch (AssertionError ex) { - assertionError = ex; - } - } - - private void validateForwardPacketInbound(byte[] payload) throws UnknownHostException { - validateForwardPacketInbound("Payload", new InetPacket(payload)); - } - - private void validateForwardPacketInbound(DatagramPacket packet) throws UnknownHostException { - validateForwardPacketInbound("Packet", new InetPacket(packet)); - } - - private void validateForwardPacketInbound(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("ForwardPacketInbound", p); - assertEquals(TRANSPORT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV6), point.address); - else - assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV4), point.address); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(PAYLOAD, p.getPayload()); - } - - private void validateSendPacketOutbound(byte[] payload) throws UnknownHostException { - InetPacket p = new InetPacket(payload); - assertNotNull(p); - if (isDebugOutput) - print("SendPacketOutbound Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateSendPacketOutbound(DatagramPacket packet) throws UnknownHostException { - InetPacket p = new InetPacket(packet); - assertNotNull(p); - if (isDebugOutput) - print("SendPacketOutbound Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv6ForwardOutbound(byte[] payload) throws UnknownHostException { - validateIPv6ForwardOutbound("Payload", new InetPacket(payload)); - } - - private void validateIPv6ForwardOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPv6ForwardOutbound("Packet", new InetPacket(packet)); - } - - private void validateIPv6ForwardOutbound(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPv6ForwardOutbound " + tail, p); - assertEquals(FORWARDER_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - assertTrue(point.isIPv6Address()); - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundForward(byte[] payload) throws UnknownHostException { - validateIPv4ForwardOutboundForward("Payload", new InetPacket(payload)); - } - - private void validateIPv4ForwardOutboundForward(DatagramPacket packet) throws UnknownHostException { - validateIPv4ForwardOutboundForward("Packet", new InetPacket(packet)); - } - - private void validateIPv4ForwardOutboundForward(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundForward " + tail, p); - assertEquals(FORWARDER_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - assertFalse(point.isIPv6Address()); - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundSend(byte[] payload) throws UnknownHostException { - InetPacket p = new InetPacket(payload); - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundSend Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundSend(DatagramPacket packet) throws UnknownHostException { - InetPacket p = new InetPacket(packet); - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundSend Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv6SendOutbound(byte[] payload) throws UnknownHostException { - validateIPvXSendOutboundPayload(new InetPacket(payload)); - } - - private void validateIPv4SendOutbound(byte[] payload) throws UnknownHostException { - validateIPvXSendOutboundPayload(new InetPacket(payload)); - } - - private void validateIPv6SendOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPvXSendOutboundPacket(new InetPacket(packet)); - } - - private void validateIPv4SendOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPvXSendOutboundPacket(new InetPacket(packet)); - } - - private void validateIPvXSendOutboundPayload(InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPvXSendOutbound Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPvXSendOutboundPacket(InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPvXSendOutbound Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void print(String header, InetPacket pb) throws UnknownHostException { - assertNotNull(pb); - InetPoint point = pb.getPoint(); - if (point != null) { - System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port); - System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, - CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress()); - System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false"); - } else { - System.out.printf("%s: Inet point is null\n", header); - } - byte[] p = pb.getPayload(); - System.out.printf("%s: payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); - System.out.printf("%s: bundle: %s\n", header, pb.toHexString()); - } - }); - listener.start(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - } - } - - void checkBackgroundThreadAssertion() { - try { - Thread.sleep(1500); - } catch (InterruptedException unused) { - } - - if (assertionError != null) - throw assertionError; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.Arrays; + +import org.apache.log4j.Logger; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import mockit.Capturing; +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPacketSenderTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + static final private boolean isDebugOutput = false; + + private static Logger log = Logger.getLogger(InetPacketSenderTest.class); + + private static final int DEFAULT_MAX_PACKET_SIZE = 65535; + + private static final String TRANSPORT_HOST = "localhost"; + private static final int TRANSPORT_PORT = 46751; + + private static final String FORWARDER_HOST = "localhost"; + private static final int FORWARDER_PORT = 46752; + + private static final String CLIENT_HOST_IPV4 = "localhost"; + private static final String CLIENT_HOST_IPV6 = "::1"; + private static final int CLIENT_PORT = 46753; + + private static final byte[] PAYLOAD = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xca, + (byte) 0xfe, (byte) 0xba, (byte) 0xbe }; + + AssertionError assertionError = null; + + private enum TestCase { + TestForwardPacketInbound, TestSendPacketOutbound, TestIPv6ForwardOutbound, TestIPv4ForwardOutboundForward, TestIPv4ForwardOutboundSend, TestIPv6SendOutbound, TestIPv4SendOutbound, + }; + + @BeforeClass + public static void init() { + } + + @Test + public void testForwardPacketInboundIPV4() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Forwarder forwards incoming IPV4 packet to transport + testForwardPacketInbound(CLIENT_HOST_IPV4); + } + + @Test + public void testForwardPacketInboundIPV6() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Forwarder forwards incoming IPV6 packet to transport + testForwardPacketInbound(CLIENT_HOST_IPV6); + } + + public void testForwardPacketInbound(String hostname) + throws UnknownHostException, InetPacketException, InterruptedException { + startUdpListener(TRANSPORT_PORT, TestCase.TestForwardPacketInbound); + InetPoint transport = new InetPoint(getAddressBytes(TRANSPORT_HOST), TRANSPORT_PORT); + InetPacketSender sender = new InetPacketSender(transport); + DatagramPacket packet = new DatagramPacket(PAYLOAD, PAYLOAD.length, InetAddress.getByName(hostname), CLIENT_PORT); + sender.forward(packet); + checkBackgroundThreadAssertion(); + } + + @Test @Ignore + public void testSendPacketOutboundIPv4() throws UnknownHostException, InterruptedException, InetPacketException { + // Use case: Forwarder sends outgoing IPv4 packet out + testSendPacketOutbound(CLIENT_HOST_IPV4); + } + + @Test @Ignore + public void testSendPacketOutboundIPv6() throws UnknownHostException, InterruptedException, InetPacketException { + // Use case: Forwarder sends outgoing IPv6 packet out + testSendPacketOutbound(CLIENT_HOST_IPV6); + } + + public void testSendPacketOutbound(String hostname) + throws UnknownHostException, InetPacketException, InterruptedException { + startUdpListener(CLIENT_PORT, TestCase.TestSendPacketOutbound); + InetPoint client = new InetPoint(getAddressBytes(hostname), CLIENT_PORT); + byte[] bundle = new InetPacket(client, PAYLOAD).getBundle(); + InetPacketSender sender = new InetPacketSender(); + DatagramPacket packet = new DatagramPacket(bundle, bundle.length, InetAddress.getByName(FORWARDER_HOST), + FORWARDER_PORT); + sender.send(packet); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv6ForwardOutbound() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Transport or Data Sink send IPv6 message out via forwarder + startUdpListener(FORWARDER_PORT, TestCase.TestIPv6ForwardOutbound); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4ForwardOutboundForward() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out via forwarder + startUdpListener(FORWARDER_PORT, TestCase.TestIPv4ForwardOutboundForward); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + sender.setForwardAll(true); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4ForwardOutboundSend() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out via forwarder + // but it's being send out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv4ForwardOutboundSend); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv6SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv6 message out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv6SendOutbound); + InetPacketSender sender = new InetPacketSender(); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); + sender.send(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv4SendOutbound); + InetPacketSender sender = new InetPacketSender(); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.send(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + private static byte[] getAddressBytes(String host) throws UnknownHostException { + return InetAddress.getByName(host).getAddress(); + } + + private void startUdpListener(int port, TestCase tc) { + final int listenPort = port; + final TestCase testCase = tc; + + Thread listener = new Thread(new Runnable() { + @Override + public void run() { + DatagramSocket socket = null; + try { + socket = new DatagramSocket(listenPort); + DatagramPacket datagramPacket = new DatagramPacket(new byte[DEFAULT_MAX_PACKET_SIZE], + DEFAULT_MAX_PACKET_SIZE); + socket.setSoTimeout(1000); + socket.receive(datagramPacket); + validatePacket(datagramPacket); + } catch (SocketTimeoutException ex) { + log.error( + String.format("Caught socket timeout exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), + ex); + } catch (SocketException ex) { + log.error(String.format("Caught socket exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), ex); + } catch (IOException ex) { + log.error( + String.format("Caught IO exception exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), + ex); + } finally { + if (socket != null && !socket.isClosed()) { + socket.close(); + socket = null; + } + } + } + + private void validatePacket(DatagramPacket packet) throws UnknownHostException { + assertNotNull(packet); + + final byte[] data = packet.getData(); + assertNotNull(data); + + final int length = packet.getLength(); + assertTrue(length > 0); + + final int offset = packet.getOffset(); + + byte[] packetData = Arrays.copyOfRange(data, offset, length); + + try { + switch (testCase) { + case TestForwardPacketInbound: + validateForwardPacketInbound(packetData); + validateForwardPacketInbound(packet); + break; + case TestSendPacketOutbound: + validateSendPacketOutbound(packetData); + validateSendPacketOutbound(packet); + break; + case TestIPv6ForwardOutbound: + validateIPv6ForwardOutbound(packetData); + validateIPv6ForwardOutbound(packet); + break; + case TestIPv4ForwardOutboundForward: + validateIPv4ForwardOutboundForward(packetData); + validateIPv4ForwardOutboundForward(packet); + break; + case TestIPv4ForwardOutboundSend: + validateIPv4ForwardOutboundSend(packetData); + validateIPv4ForwardOutboundSend(packet); + break; + case TestIPv6SendOutbound: + validateIPv6SendOutbound(packetData); + validateIPv6SendOutbound(packet); + break; + case TestIPv4SendOutbound: + validateIPv4SendOutbound(packetData); + validateIPv4SendOutbound(packet); + break; + } + } catch (AssertionError ex) { + assertionError = ex; + } + } + + private void validateForwardPacketInbound(byte[] payload) throws UnknownHostException { + validateForwardPacketInbound("Payload", new InetPacket(payload)); + } + + private void validateForwardPacketInbound(DatagramPacket packet) throws UnknownHostException { + validateForwardPacketInbound("Packet", new InetPacket(packet)); + } + + private void validateForwardPacketInbound(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("ForwardPacketInbound", p); + assertEquals(TRANSPORT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV6), point.address); + else + assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV4), point.address); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(PAYLOAD, p.getPayload()); + } + + private void validateSendPacketOutbound(byte[] payload) throws UnknownHostException { + InetPacket p = new InetPacket(payload); + assertNotNull(p); + if (isDebugOutput) + print("SendPacketOutbound Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateSendPacketOutbound(DatagramPacket packet) throws UnknownHostException { + InetPacket p = new InetPacket(packet); + assertNotNull(p); + if (isDebugOutput) + print("SendPacketOutbound Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv6ForwardOutbound(byte[] payload) throws UnknownHostException { + validateIPv6ForwardOutbound("Payload", new InetPacket(payload)); + } + + private void validateIPv6ForwardOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPv6ForwardOutbound("Packet", new InetPacket(packet)); + } + + private void validateIPv6ForwardOutbound(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPv6ForwardOutbound " + tail, p); + assertEquals(FORWARDER_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + assertTrue(point.isIPv6Address()); + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundForward(byte[] payload) throws UnknownHostException { + validateIPv4ForwardOutboundForward("Payload", new InetPacket(payload)); + } + + private void validateIPv4ForwardOutboundForward(DatagramPacket packet) throws UnknownHostException { + validateIPv4ForwardOutboundForward("Packet", new InetPacket(packet)); + } + + private void validateIPv4ForwardOutboundForward(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundForward " + tail, p); + assertEquals(FORWARDER_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + assertFalse(point.isIPv6Address()); + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundSend(byte[] payload) throws UnknownHostException { + InetPacket p = new InetPacket(payload); + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundSend Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundSend(DatagramPacket packet) throws UnknownHostException { + InetPacket p = new InetPacket(packet); + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundSend Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv6SendOutbound(byte[] payload) throws UnknownHostException { + validateIPvXSendOutboundPayload(new InetPacket(payload)); + } + + private void validateIPv4SendOutbound(byte[] payload) throws UnknownHostException { + validateIPvXSendOutboundPayload(new InetPacket(payload)); + } + + private void validateIPv6SendOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPvXSendOutboundPacket(new InetPacket(packet)); + } + + private void validateIPv4SendOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPvXSendOutboundPacket(new InetPacket(packet)); + } + + private void validateIPvXSendOutboundPayload(InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPvXSendOutbound Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPvXSendOutboundPacket(InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPvXSendOutbound Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void print(String header, InetPacket pb) throws UnknownHostException { + assertNotNull(pb); + InetPoint point = pb.getPoint(); + if (point != null) { + System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port); + System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, + CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress()); + System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false"); + } else { + System.out.printf("%s: Inet point is null\n", header); + } + byte[] p = pb.getPayload(); + System.out.printf("%s: payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); + System.out.printf("%s: bundle: %s\n", header, pb.toHexString()); + } + }); + listener.start(); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + } + + void checkBackgroundThreadAssertion() { + try { + Thread.sleep(1500); + } catch (InterruptedException unused) { + } + + if (assertionError != null) + throw assertionError; + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java index b66bf931c..b0d22e447 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java @@ -1,172 +1,172 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Before; -import org.junit.Test; - -import mockit.Capturing; -import mockit.Expectations; -import mockit.Mock; -import mockit.MockUp; -import mockit.Mocked; -import us.dot.its.jpo.ode.util.CrcCccitt; - -public class InetPacketTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - @Mocked - DatagramPacket mockDatagramPacket; - byte[] mockPayload; - - @Mocked InetAddress address; - - @Before - public void setup() { - new MockUp() { - @Mock - public InetAddress getByName(String host) { - return address; - } - }; - } - - - @Test - public void testStringConstructorCallsPointConstructor() { - try { - new InetPacket("testHost", 5, new byte[] { 1, 2, 3 }); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testDatagramPacketConstructor() { - new InetPacket(mockDatagramPacket); - } - - @Test - public void testByteConstructor() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - testPacket.getPoint(); - testPacket.getPayload(); - testPacket.getBundle(); - testPacket.toHexString(); - - } - - /* - * @Test public void testEvenNum() { boolean ans = false; boolean val; byte[] - * bundle = null; - * - * - * val = InetPacket.parseBundle(bundle); assertEquals(ans,val); } - */ - - @Test - public void parseBundleNulll() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = null; - - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleNotMagic() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMagic() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMagicother() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 1, 1, 1, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMaxLength() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMaxMaxLength() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 9, 8, 2, 4, 5, 1, 6, 5, 3 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void setByteBuffer() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - - } - - @Test - public void parseBundleAddressLengthLessThanRemaining() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; - - assertFalse(testPacket.parseBundle(bundle)); - - } - - @Test - public void parseBundleCrcCccittReturnsTrue() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; - - new Expectations(CrcCccitt.class) { - { - CrcCccitt.isValidMsgCRC((byte[]) any, anyInt, anyInt); - result = true; - } - }; - assertTrue(testPacket.parseBundle(bundle)); - - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.junit.Before; +import org.junit.Test; + +import mockit.Capturing; +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import us.dot.its.jpo.ode.util.CrcCccitt; + +public class InetPacketTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + @Mocked + DatagramPacket mockDatagramPacket; + byte[] mockPayload; + + @Mocked InetAddress address; + + @Before + public void setup() { + new MockUp() { + @Mock + public InetAddress getByName(String host) { + return address; + } + }; + } + + + @Test + public void testStringConstructorCallsPointConstructor() { + try { + new InetPacket("testHost", 5, new byte[] { 1, 2, 3 }); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testDatagramPacketConstructor() { + new InetPacket(mockDatagramPacket); + } + + @Test + public void testByteConstructor() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + testPacket.getPoint(); + testPacket.getPayload(); + testPacket.getBundle(); + testPacket.toHexString(); + + } + + /* + * @Test public void testEvenNum() { boolean ans = false; boolean val; byte[] + * bundle = null; + * + * + * val = InetPacket.parseBundle(bundle); assertEquals(ans,val); } + */ + + @Test + public void parseBundleNulll() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = null; + + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleNotMagic() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMagic() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMagicother() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 1, 1, 1, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMaxLength() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMaxMaxLength() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 9, 8, 2, 4, 5, 1, 6, 5, 3 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void setByteBuffer() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + + } + + @Test + public void parseBundleAddressLengthLessThanRemaining() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; + + assertFalse(testPacket.parseBundle(bundle)); + + } + + @Test + public void parseBundleCrcCccittReturnsTrue() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; + + new Expectations(CrcCccitt.class) { + { + CrcCccitt.isValidMsgCRC((byte[]) any, anyInt, anyInt); + result = true; + } + }; + assertTrue(testPacket.parseBundle(bundle)); + + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java index 082541092..5aa56eabc 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java @@ -1,141 +1,141 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Test; - -import mockit.Capturing; -import mockit.Expectations; - -public class InetPointTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - @Capturing - InetAddress capturingInetAddress; - - @Test - public void testStringConstructorCreatesAddress() { - try { - new Expectations() { - { - InetAddress.getByName(anyString).getAddress(); - } - }; - - new InetPoint("hostString123", 5, true); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test(expected = IllegalArgumentException.class) - public void testStringConstructorFailsNullAddress() { - try { - new Expectations() { - { - InetAddress.getByName(anyString).getAddress(); - result = null; - } - }; - new InetPoint("hostString123", 5, true); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testByteConstructorCreatesAddress() { - new InetPoint(new byte[] { 1, 2, 3 }, 5, true); - } - - @Test(expected = IllegalArgumentException.class) - public void testByteConstructorFailsNullAddress() { - new InetPoint((byte[]) null, 5, true); - } - - @Test - public void testBBytePortConstructorCreatesAddress() { - new InetPoint(new byte[] { 1, 2, 3 }, 5); - } - - @Test(expected = IllegalArgumentException.class) - public void testBytePortConstructorFailsNullAddress() { - new InetPoint((byte[]) null, 5); - } - - @Test - public void getInetAddressCallsGetAddress() { - try { - new Expectations() { - { - InetAddress.getByAddress((byte[]) any); - } - }; - new InetPoint(new byte[] { 1, 2, 3 }, 5).getInetAddress(); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testAddressLength16IsIpv6() { - assertTrue(new InetPoint(new byte[16], 5).isIPv6Address()); - } - - @Test - public void testAddressLength4IsNotIpv6() { - assertFalse(new InetPoint(new byte[4], 5).isIPv6Address()); - } - - @Test - public void testToStringMethodIPV6() { - assertEquals( - "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", - new InetPoint(new byte[16], 5).toString()); - } - - @Test - public void testToStringException() { - assertEquals( - "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", - new InetPoint(new byte[16], 5).toString()); - } - - @Test - public void testToStringMethodIPV4() { - assertEquals("InetPoint { port = 5 (0x5); address = 00000000 (IPv4, null); forward = false }", - new InetPoint(new byte[4], 5).toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.junit.Test; + +import mockit.Capturing; +import mockit.Expectations; + +public class InetPointTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + @Capturing + InetAddress capturingInetAddress; + + @Test + public void testStringConstructorCreatesAddress() { + try { + new Expectations() { + { + InetAddress.getByName(anyString).getAddress(); + } + }; + + new InetPoint("hostString123", 5, true); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testStringConstructorFailsNullAddress() { + try { + new Expectations() { + { + InetAddress.getByName(anyString).getAddress(); + result = null; + } + }; + new InetPoint("hostString123", 5, true); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testByteConstructorCreatesAddress() { + new InetPoint(new byte[] { 1, 2, 3 }, 5, true); + } + + @Test(expected = IllegalArgumentException.class) + public void testByteConstructorFailsNullAddress() { + new InetPoint((byte[]) null, 5, true); + } + + @Test + public void testBBytePortConstructorCreatesAddress() { + new InetPoint(new byte[] { 1, 2, 3 }, 5); + } + + @Test(expected = IllegalArgumentException.class) + public void testBytePortConstructorFailsNullAddress() { + new InetPoint((byte[]) null, 5); + } + + @Test + public void getInetAddressCallsGetAddress() { + try { + new Expectations() { + { + InetAddress.getByAddress((byte[]) any); + } + }; + new InetPoint(new byte[] { 1, 2, 3 }, 5).getInetAddress(); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testAddressLength16IsIpv6() { + assertTrue(new InetPoint(new byte[16], 5).isIPv6Address()); + } + + @Test + public void testAddressLength4IsNotIpv6() { + assertFalse(new InetPoint(new byte[4], 5).isIPv6Address()); + } + + @Test + public void testToStringMethodIPV6() { + assertEquals( + "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", + new InetPoint(new byte[16], 5).toString()); + } + + @Test + public void testToStringException() { + assertEquals( + "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", + new InetPoint(new byte[16], 5).toString()); + } + + @Test + public void testToStringMethodIPV4() { + assertEquals("InetPoint { port = 5 (0x5); address = 00000000 (IPv4, null); forward = false }", + new InetPoint(new byte[4], 5).toString()); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java index 8bb3e482b..9e44a234c 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.Arrays; - -import org.junit.Test; - -public class CodecUtilsTest { - - @Test - public void testShortsToBytes() { - - byte[] expectedValue = new byte[] { 0, 5, 0, -2, 1, 1 }; - - byte[] actualValue = CodecUtils.shortsToBytes(new short[] { (short) 5, (short) 254, (short) 257 }, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testShortToBytes() { - byte[] expectedValue = new byte[] { 1, 37 }; - - byte[] actualValue = CodecUtils.shortToBytes((short) 293, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testBytesToShorts() { - short[] expectedValue = new short[] { (short) 513 }; - - short[] actualValue = CodecUtils.bytesToShorts(new byte[] { 2, 1 }, 0, 2, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testBytesToShort() { - short expectedValue = (short) 258; - - short actualValue = CodecUtils.bytesToShort(new byte[] { 1, 2, 5, 2 }, 0, 4, ByteOrder.BIG_ENDIAN); - - assertEquals(expectedValue, actualValue); - } - - @Test - public void testMergeBytes() { - - byte[] expectedValue = new byte[] { 1, 1, 2, 3, 5, 8 }; - - try { - byte[] actualValue = CodecUtils.mergeBytes(new byte[] { 1 }, new byte[] { 1, 2 }, new byte[] { 3, 5, 8 }); - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } catch (IOException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void bytesToLongs() { - // 598273498 decimal == 23A8EDDA hex == 0, 0, 0, 0, 35, 168, 237, 218 - // 54 decimal = 0, 0, 0, 0, 0, 0, 0, 54 - long[] expectedValue = new long[] { (long) 598273498, (long) 54 }; - long[] actualValue = CodecUtils.bytesToLongs( - new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 35, (byte) 168, (byte) 237, (byte) 218, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 54 }, - 0, 16, ByteOrder.BIG_ENDIAN); - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.nio.ByteOrder; +import java.util.Arrays; + +import org.junit.Test; + +public class CodecUtilsTest { + + @Test + public void testShortsToBytes() { + + byte[] expectedValue = new byte[] { 0, 5, 0, -2, 1, 1 }; + + byte[] actualValue = CodecUtils.shortsToBytes(new short[] { (short) 5, (short) 254, (short) 257 }, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testShortToBytes() { + byte[] expectedValue = new byte[] { 1, 37 }; + + byte[] actualValue = CodecUtils.shortToBytes((short) 293, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testBytesToShorts() { + short[] expectedValue = new short[] { (short) 513 }; + + short[] actualValue = CodecUtils.bytesToShorts(new byte[] { 2, 1 }, 0, 2, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testBytesToShort() { + short expectedValue = (short) 258; + + short actualValue = CodecUtils.bytesToShort(new byte[] { 1, 2, 5, 2 }, 0, 4, ByteOrder.BIG_ENDIAN); + + assertEquals(expectedValue, actualValue); + } + + @Test + public void testMergeBytes() { + + byte[] expectedValue = new byte[] { 1, 1, 2, 3, 5, 8 }; + + try { + byte[] actualValue = CodecUtils.mergeBytes(new byte[] { 1 }, new byte[] { 1, 2 }, new byte[] { 3, 5, 8 }); + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } catch (IOException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void bytesToLongs() { + // 598273498 decimal == 23A8EDDA hex == 0, 0, 0, 0, 35, 168, 237, 218 + // 54 decimal = 0, 0, 0, 0, 0, 0, 0, 54 + long[] expectedValue = new long[] { (long) 598273498, (long) 54 }; + long[] actualValue = CodecUtils.bytesToLongs( + new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 35, (byte) 168, (byte) 237, (byte) 218, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 54 }, + 0, 16, ByteOrder.BIG_ENDIAN); + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java index 148d13118..2dd4b18a3 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import static org.junit.Assert.*; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class CrcCccittTest { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCalculateCrcCccitt() { - testCalculateCrcCccitt(0x0000, ""); - testCalculateCrcCccitt(0x2672, "1"); - testCalculateCrcCccitt(0x31c3, "123456789"); - testCalculateCrcCccitt(0x69df, "The generating polynomial used is the CRC-CCITT commonly expressed as x^16 + x^12 + x^5 + 1. An initial seed value of zero shall be used."); - testCalculateCrcCccitt(0xd4f9, "MsgCRC ::= OCTET STRING (SIZE(2)) -- created with the CRC-CCITT polynomial"); - } - - @Test - public void testCalculateCrcCccitt2() { - int checkSum = CrcCccitt.calculateCrcCccitt(null); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt(null, 1, 10); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("".getBytes(), 1, 10); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), -1, 1); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("1".getBytes(), 0, 10); - assertEquals(0x2672, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), 0, 1); - assertEquals(0x2672, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 1, 9); - assertEquals(0x31c3, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 5, 4); - assertEquals(0xccf0, checkSum); - } - - @Test - public void testSetMsgCRC() { - byte[] msg = "12345678900".getBytes(); - int checkSum = CrcCccitt.calculateCrcCccitt(msg,0,msg.length-2); - assertEquals(0x31c3, checkSum); - CrcCccitt.setMsgCRC(msg); - assertEquals((byte)0x31, msg[msg.length-2]); - assertEquals((byte)0xc3, msg[msg.length-1]); - assertTrue(CrcCccitt.isValidMsgCRC(msg)); - } - - public void testCalculateCrcCccitt(int expectedCheckSum, String text ) { - byte[] textBytes = text.getBytes(); - int checkSum = CrcCccitt.calculateCrcCccitt(textBytes); - assertEquals(expectedCheckSum, checkSum); - ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); - buffer.putShort((short)checkSum); - byte[] crcBytes = buffer.array(); - byte[] msg = new byte[text.length()+2]; - System.arraycopy(textBytes, 0, msg, 0, textBytes.length); - System.arraycopy(crcBytes, 0, msg, textBytes.length, 2); - boolean isValid = CrcCccitt.isValidMsgCRC(msg); - assertTrue(isValid); - //System.out.printf("0x%04x: %s: %3d %s\n", checkSum, isValid ? "valid" : "invalid", text.length(), text); - System.arraycopy("12".getBytes(), 0, msg, textBytes.length, 2); - isValid = CrcCccitt.isValidMsgCRC(msg); - assertFalse(isValid); - if ( textBytes.length > 0 ) { - isValid = CrcCccitt.isValidMsgCRC(textBytes); - assertFalse(isValid); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import static org.junit.Assert.*; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CrcCccittTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCalculateCrcCccitt() { + testCalculateCrcCccitt(0x0000, ""); + testCalculateCrcCccitt(0x2672, "1"); + testCalculateCrcCccitt(0x31c3, "123456789"); + testCalculateCrcCccitt(0x69df, "The generating polynomial used is the CRC-CCITT commonly expressed as x^16 + x^12 + x^5 + 1. An initial seed value of zero shall be used."); + testCalculateCrcCccitt(0xd4f9, "MsgCRC ::= OCTET STRING (SIZE(2)) -- created with the CRC-CCITT polynomial"); + } + + @Test + public void testCalculateCrcCccitt2() { + int checkSum = CrcCccitt.calculateCrcCccitt(null); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt(null, 1, 10); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("".getBytes(), 1, 10); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), -1, 1); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("1".getBytes(), 0, 10); + assertEquals(0x2672, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), 0, 1); + assertEquals(0x2672, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 1, 9); + assertEquals(0x31c3, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 5, 4); + assertEquals(0xccf0, checkSum); + } + + @Test + public void testSetMsgCRC() { + byte[] msg = "12345678900".getBytes(); + int checkSum = CrcCccitt.calculateCrcCccitt(msg,0,msg.length-2); + assertEquals(0x31c3, checkSum); + CrcCccitt.setMsgCRC(msg); + assertEquals((byte)0x31, msg[msg.length-2]); + assertEquals((byte)0xc3, msg[msg.length-1]); + assertTrue(CrcCccitt.isValidMsgCRC(msg)); + } + + public void testCalculateCrcCccitt(int expectedCheckSum, String text ) { + byte[] textBytes = text.getBytes(); + int checkSum = CrcCccitt.calculateCrcCccitt(textBytes); + assertEquals(expectedCheckSum, checkSum); + ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); + buffer.putShort((short)checkSum); + byte[] crcBytes = buffer.array(); + byte[] msg = new byte[text.length()+2]; + System.arraycopy(textBytes, 0, msg, 0, textBytes.length); + System.arraycopy(crcBytes, 0, msg, textBytes.length, 2); + boolean isValid = CrcCccitt.isValidMsgCRC(msg); + assertTrue(isValid); + //System.out.printf("0x%04x: %s: %3d %s\n", checkSum, isValid ? "valid" : "invalid", text.length(), text); + System.arraycopy("12".getBytes(), 0, msg, textBytes.length, 2); + isValid = CrcCccitt.isValidMsgCRC(msg); + assertFalse(isValid); + if ( textBytes.length > 0 ) { + isValid = CrcCccitt.isValidMsgCRC(textBytes); + assertFalse(isValid); + } + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java index a04bd8e7a..fe1849670 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.text.ParseException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - -import org.junit.Test; - -import junit.framework.TestCase; -import us.dot.its.jpo.ode.util.DateTimeUtils; - -public class DateTimeUtilsTest extends TestCase { - - @Test - public void testIsoDateTime() throws ParseException { - ZonedDateTime expectedDate = ZonedDateTime.now(ZoneOffset.UTC); - String sExpectedDate = DateTimeUtils.isoDateTime(expectedDate); - String sdate = DateTimeUtils.isoDateTime( - expectedDate.getYear(), - expectedDate.getMonthValue(), - expectedDate.getDayOfMonth(), - expectedDate.getHour(), - expectedDate.getMinute(), - expectedDate.getSecond(), - expectedDate.getNano()/1000000).format(DateTimeFormatter.ISO_INSTANT); - - assertEquals(sExpectedDate.substring(0, 18), sdate.substring(0, 18)); - ZonedDateTime date2 = DateTimeUtils.isoDateTime("2015-11-30T16:06:15.679Z"); - assertNotNull(date2); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.text.ParseException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import org.junit.Test; + +import junit.framework.TestCase; +import us.dot.its.jpo.ode.util.DateTimeUtils; + +public class DateTimeUtilsTest extends TestCase { + + @Test + public void testIsoDateTime() throws ParseException { + ZonedDateTime expectedDate = ZonedDateTime.now(ZoneOffset.UTC); + String sExpectedDate = DateTimeUtils.isoDateTime(expectedDate); + String sdate = DateTimeUtils.isoDateTime( + expectedDate.getYear(), + expectedDate.getMonthValue(), + expectedDate.getDayOfMonth(), + expectedDate.getHour(), + expectedDate.getMinute(), + expectedDate.getSecond(), + expectedDate.getNano()/1000000).format(DateTimeFormatter.ISO_INSTANT); + + assertEquals(sExpectedDate.substring(0, 18), sdate.substring(0, 18)); + ZonedDateTime date2 = DateTimeUtils.isoDateTime("2015-11-30T16:06:15.679Z"); + assertNotNull(date2); + } +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java index 527e31523..01e066a03 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; - -import org.junit.Test; - -import junit.framework.TestCase; -import us.dot.its.jpo.ode.util.GeoUtils; -import us.dot.its.jpo.ode.util.LengthUtils; - -public class GeoUtilsTest extends TestCase { - - public void testNearestPointOnLine() { - } - - @Test - public void testPointOffset() { - assertOffset(5.0, 5.0, 10.0, 5.0, 5.0, 8.0); //0 deg - assertOffset(5.0, 5.0, 10.0, 10.0, 2.878, 7.121); //45 deg - assertOffset(5.0, 5.0, 5.0, 10.0, 2.0, 5.0); //90 deg - assertOffset(5.0, 5.0, 0.0, 10.0, 2.878, 2.878); //135 deg - assertOffset(5.0, 5.0, 0.0, 5.0, 5.0, 2.0); //180 deg - assertOffset(5.0, 5.0, 0.0, 0.0, 7.121, 2.878); //225 deg - assertOffset(5.0, 5.0, 5.0, 0.0, 8.0, 5.0); //270 deg - assertOffset(5.0, 5.0, 10.0, 0.0, 7.121, 7.121); //315 deg - } - - @Test - public void assertOffset(double ax, double ay, double bx, double by, double ox, double oy) { - Point2D a = new Point2D.Double(ax, ay); - Point2D b = new Point2D.Double(bx, by); - double k = 3d; - double scale = 1000d; - - Point2D p1 = GeoUtils.pointOffset(a , b , k, null); - long p1x = (long) (p1.getX() * scale); - long p1y = (long) (p1.getY() * scale); - - assertEquals((long) (ox * scale), p1x); - assertEquals((long) (oy * scale), p1y); - } - - @Test - public void testDistanceInMapCoordinates() { - double aLat = 43.652969118285434; - double aLng = -85.94707489013672; - double bLat = 40.96538194577475; - double bLng = -81.03858947753906; - double pLat = 42.0; - double pLng = -83.5; - - Point2D a = GeoUtils.latLngToMap(aLat, aLng); - Point2D b = GeoUtils.latLngToMap(bLat, bLng); - Point2D p = GeoUtils.latLngToMap(pLat, pLng); - Line2D l = new Line2D.Double(a, b); - - double distanceInMeters = GeoUtils.distanceLatLng(aLat, aLng, bLat, bLng, - LengthUtils.UnitOfMeasure.M); - assertEquals(502073, Math.round(distanceInMeters)); - - double distanceInMapCoord = GeoUtils.distance(a, b); - assertEquals(679050, Math.round(distanceInMapCoord)); - - double d1 = GeoUtils.distanceToLine(l, p); - double d2 = GeoUtils.distanceToLine2(l, p); - double d3 = GeoUtils.distanceToLine3(l, p); - - assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); - assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); - } - - @Test - public void testDistanceInLatLng() { - double aLat = 43.652969118285434; - double aLng = -85.94707489013672; - double bLat = 40.96538194577475; - double bLng = -81.03858947753906; - double pLat = 42.0; - double pLng = -83.5; - - Point2D a = new Point2D.Double(aLat, aLng); - Point2D b = new Point2D.Double(bLat, bLng); - Point2D p = new Point2D.Double(pLat, pLng); - Line2D l = new Line2D.Double(a, b); - - double d1 = GeoUtils.distanceToLine(l, p); - double d2 = GeoUtils.distanceToLine2(l, p); - double d3 = GeoUtils.distanceToLine3(l, p); - - assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); - assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; + +import org.junit.Test; + +import junit.framework.TestCase; +import us.dot.its.jpo.ode.util.GeoUtils; +import us.dot.its.jpo.ode.util.LengthUtils; + +public class GeoUtilsTest extends TestCase { + + public void testNearestPointOnLine() { + } + + @Test + public void testPointOffset() { + assertOffset(5.0, 5.0, 10.0, 5.0, 5.0, 8.0); //0 deg + assertOffset(5.0, 5.0, 10.0, 10.0, 2.878, 7.121); //45 deg + assertOffset(5.0, 5.0, 5.0, 10.0, 2.0, 5.0); //90 deg + assertOffset(5.0, 5.0, 0.0, 10.0, 2.878, 2.878); //135 deg + assertOffset(5.0, 5.0, 0.0, 5.0, 5.0, 2.0); //180 deg + assertOffset(5.0, 5.0, 0.0, 0.0, 7.121, 2.878); //225 deg + assertOffset(5.0, 5.0, 5.0, 0.0, 8.0, 5.0); //270 deg + assertOffset(5.0, 5.0, 10.0, 0.0, 7.121, 7.121); //315 deg + } + + @Test + public void assertOffset(double ax, double ay, double bx, double by, double ox, double oy) { + Point2D a = new Point2D.Double(ax, ay); + Point2D b = new Point2D.Double(bx, by); + double k = 3d; + double scale = 1000d; + + Point2D p1 = GeoUtils.pointOffset(a , b , k, null); + long p1x = (long) (p1.getX() * scale); + long p1y = (long) (p1.getY() * scale); + + assertEquals((long) (ox * scale), p1x); + assertEquals((long) (oy * scale), p1y); + } + + @Test + public void testDistanceInMapCoordinates() { + double aLat = 43.652969118285434; + double aLng = -85.94707489013672; + double bLat = 40.96538194577475; + double bLng = -81.03858947753906; + double pLat = 42.0; + double pLng = -83.5; + + Point2D a = GeoUtils.latLngToMap(aLat, aLng); + Point2D b = GeoUtils.latLngToMap(bLat, bLng); + Point2D p = GeoUtils.latLngToMap(pLat, pLng); + Line2D l = new Line2D.Double(a, b); + + double distanceInMeters = GeoUtils.distanceLatLng(aLat, aLng, bLat, bLng, + LengthUtils.UnitOfMeasure.M); + assertEquals(502073, Math.round(distanceInMeters)); + + double distanceInMapCoord = GeoUtils.distance(a, b); + assertEquals(679050, Math.round(distanceInMapCoord)); + + double d1 = GeoUtils.distanceToLine(l, p); + double d2 = GeoUtils.distanceToLine2(l, p); + double d3 = GeoUtils.distanceToLine3(l, p); + + assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); + assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); + } + + @Test + public void testDistanceInLatLng() { + double aLat = 43.652969118285434; + double aLng = -85.94707489013672; + double bLat = 40.96538194577475; + double bLng = -81.03858947753906; + double pLat = 42.0; + double pLng = -83.5; + + Point2D a = new Point2D.Double(aLat, aLng); + Point2D b = new Point2D.Double(bLat, bLng); + Point2D p = new Point2D.Double(pLat, pLng); + Line2D l = new Line2D.Double(a, b); + + double d1 = GeoUtils.distanceToLine(l, p); + double d2 = GeoUtils.distanceToLine2(l, p); + double d3 = GeoUtils.distanceToLine3(l, p); + + assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); + assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); + } + +} diff --git a/jpo-ode-common/src/test/resources/logback-test.xml b/jpo-ode-common/src/test/resources/logback-test.xml index a7a69c483..de5097a2d 100644 --- a/jpo-ode-common/src/test/resources/logback-test.xml +++ b/jpo-ode-common/src/test/resources/logback-test.xml @@ -1,10 +1,10 @@ - - - - %msg%n - - - - - + + + + %msg%n + + + + + \ No newline at end of file diff --git a/jpo-ode-consumer-example/README.md b/jpo-ode-consumer-example/README.md index 311d14ad4..53dae2f6f 100644 --- a/jpo-ode-consumer-example/README.md +++ b/jpo-ode-consumer-example/README.md @@ -1,68 +1,68 @@ -# Kafka Consumer Example - -This project is intended to serve as a sample consumer application to subscribe to a Kafka topic of streams. After the ODE is up and running, this example project will showcase how you can build a Java application to subscribe to the outputs of a Kafka Stream. - -## Quick Run - - -The sample project needs to be compiled with assembly to ensure that that resulting jar is runnable with the Kafka libraries. It will produce a jar under `target/` with a "with-dependencies" tag. - -``` -mvn clean compile assembly:single install -``` - -To run the jar, be sure to include the topic at the end and group id at the end. If this is not a distributed system, the group can be any string. - -``` -java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar - -usage: Consumer Example - -b,--bootstrap-server Endpoint ('ip:port') - -g,--group Consumer Group - -t,--topic Topic Name - -type,--type string|byte message type -``` - -Example Usage As Of: 1/11/17 - -``` -java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar --bootstrap-server localhost:9092 -g group1 -t topic.J2735Bsm -type byte -``` - -It should return the following confirmation - -``` -Subscribed to topic topic.J2735Bsm -``` -Triggering an upload into the ODE, the output should be seen decoded into JSON in the console. - -![CLI-output](images/cli-output.png) - -## Additional Resources - -With the Kafka installed locally on a machine, here are a few additional commands that may be helpful while debugging Kafka topics. - -[Kafka Install Instructions](https://www.cloudera.com/documentation/kafka/latest/topics/kafka_installing.html#concept_ngx_4l4_4r) - -The IP used is the location of the Kafka endpoints. - -####Create, alter, list, and describe topics. - -``` -kafka-topics --zookeeper 192.168.1.151:2181 --list -sink1 -t1 -t2 -``` - -####Read data from a Kafka topic and write it to standard output. - -``` -kafka-console-consumer --zookeeper 192.168.1.151:2181 --topic topic.J2735Bsm -``` - -####Read data from standard output and write it to a Kafka topic. - -``` -kafka-console-producer --broker-list 192.168.1.151:9092 --topic topic.J2735Bsm -``` +# Kafka Consumer Example + +This project is intended to serve as a sample consumer application to subscribe to a Kafka topic of streams. After the ODE is up and running, this example project will showcase how you can build a Java application to subscribe to the outputs of a Kafka Stream. + +## Quick Run + + +The sample project needs to be compiled with assembly to ensure that that resulting jar is runnable with the Kafka libraries. It will produce a jar under `target/` with a "with-dependencies" tag. + +``` +mvn clean compile assembly:single install +``` + +To run the jar, be sure to include the topic at the end and group id at the end. If this is not a distributed system, the group can be any string. + +``` +java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar + +usage: Consumer Example + -b,--bootstrap-server Endpoint ('ip:port') + -g,--group Consumer Group + -t,--topic Topic Name + -type,--type string|byte message type +``` + +Example Usage As Of: 1/11/17 + +``` +java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar --bootstrap-server localhost:9092 -g group1 -t topic.J2735Bsm -type byte +``` + +It should return the following confirmation + +``` +Subscribed to topic topic.J2735Bsm +``` +Triggering an upload into the ODE, the output should be seen decoded into JSON in the console. + +![CLI-output](images/cli-output.png) + +## Additional Resources + +With the Kafka installed locally on a machine, here are a few additional commands that may be helpful while debugging Kafka topics. + +[Kafka Install Instructions](https://www.cloudera.com/documentation/kafka/latest/topics/kafka_installing.html#concept_ngx_4l4_4r) + +The IP used is the location of the Kafka endpoints. + +####Create, alter, list, and describe topics. + +``` +kafka-topics --zookeeper 192.168.1.151:2181 --list +sink1 +t1 +t2 +``` + +####Read data from a Kafka topic and write it to standard output. + +``` +kafka-console-consumer --zookeeper 192.168.1.151:2181 --topic topic.J2735Bsm +``` + +####Read data from standard output and write it to a Kafka topic. + +``` +kafka-console-producer --broker-list 192.168.1.151:9092 --topic topic.J2735Bsm +``` diff --git a/jpo-ode-consumer-example/pom.xml b/jpo-ode-consumer-example/pom.xml index 8d3f26391..8ad267598 100644 --- a/jpo-ode-consumer-example/pom.xml +++ b/jpo-ode-consumer-example/pom.xml @@ -1,64 +1,64 @@ - - 4.0.0 - - com.consumerexample - 0.0.1-SNAPSHOT - consumer-example - jar - consumer-example - - - junit - junit - 4.12 - test - - - - org.apache.kafka - kafka-clients - 0.10.1.0 - - - usdot.jpo.ode - jpo-ode-core - 0.0.1-SNAPSHOT - - - - commons-cli - commons-cli - 1.3 - - - - org.apache.commons - commons-lang3 - 3.0 - - - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.4 - - - - com.consumerexample.app.ConsumerExample - - - - jar-with-dependencies - - - - - - - + + 4.0.0 + + com.consumerexample + 0.0.1-SNAPSHOT + consumer-example + jar + consumer-example + + + junit + junit + 4.12 + test + + + + org.apache.kafka + kafka-clients + 0.10.1.0 + + + usdot.jpo.ode + jpo-ode-core + 0.0.1-SNAPSHOT + + + + commons-cli + commons-cli + 1.3 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.4 + + + + com.consumerexample.app.ConsumerExample + + + + jar-with-dependencies + + + + + + + diff --git a/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java b/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java index b63be9aab..74967e502 100644 --- a/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java +++ b/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java @@ -1,111 +1,111 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 com.consumerexample.app; - -import java.util.Properties; -import java.util.Arrays; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.commons.cli.*; -import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; -import us.dot.its.jpo.ode.util.SerializationUtils; - -public class ConsumerExample { - - public static void main( String[] args ){ - - // Option parsing - Options options = new Options(); - - Option bootstrap_server = new Option("b", "bootstrap-server", true, "Endpoint ('ip:port')"); - bootstrap_server.setRequired(true); - options.addOption(bootstrap_server); - - Option topic_option = new Option("t", "topic", true, "Topic Name"); - topic_option.setRequired(true); - options.addOption(topic_option); - - Option group_option = new Option("g", "group", true, "Consumer Group"); - group_option.setRequired(true); - options.addOption(group_option); - - Option type_option = new Option("type", "type", true, "string|byte message type"); - type_option.setRequired(true); - options.addOption(type_option); - - CommandLineParser parser = new DefaultParser(); - HelpFormatter formatter = new HelpFormatter(); - CommandLine cmd; - - try { - cmd = parser.parse(options, args); - } catch (ParseException e) { - System.out.println(e.getMessage()); - formatter.printHelp("Consumer Example", options); - - System.exit(1); - return; - } - - String endpoint = cmd.getOptionValue("bootstrap-server"); - String topic = cmd.getOptionValue("topic"); - String group = cmd.getOptionValue("group"); - String type = cmd.getOptionValue("type"); - - // Properties for the kafka topic - Properties props = new Properties(); - props.put("bootstrap.servers", endpoint); - props.put("group.id", group); - props.put("enable.auto.commit", "false"); - props.put("auto.commit.interval.ms", "1000"); - props.put("session.timeout.ms", "30000"); - props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - if (type.equals("byte")){ - props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); - } else { - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - } - - if (type.equals("byte")) { - KafkaConsumer byteArrayConsumer = new KafkaConsumer(props); - - byteArrayConsumer.subscribe(Arrays.asList(topic)); - System.out.println("Subscribed to topic " + topic); - while (true) { - ConsumerRecords records = byteArrayConsumer.poll(100); - for (ConsumerRecord record : records) { - // Serialize the record value - SerializationUtils serializer = new SerializationUtils(); - J2735Bsm bsm = serializer.deserialize(record.value()); - System.out.println(bsm.toString()); - } - } - } else { - KafkaConsumer stringConsumer = new KafkaConsumer(props); - - stringConsumer.subscribe(Arrays.asList(topic)); - System.out.println("Subscribed to topic " + topic); - while (true) { - ConsumerRecords records = stringConsumer.poll(100); - for (ConsumerRecord record : records) { - System.out.println(record.value()); - } - } - - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 com.consumerexample.app; + +import java.util.Properties; +import java.util.Arrays; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.commons.cli.*; +import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; +import us.dot.its.jpo.ode.util.SerializationUtils; + +public class ConsumerExample { + + public static void main( String[] args ){ + + // Option parsing + Options options = new Options(); + + Option bootstrap_server = new Option("b", "bootstrap-server", true, "Endpoint ('ip:port')"); + bootstrap_server.setRequired(true); + options.addOption(bootstrap_server); + + Option topic_option = new Option("t", "topic", true, "Topic Name"); + topic_option.setRequired(true); + options.addOption(topic_option); + + Option group_option = new Option("g", "group", true, "Consumer Group"); + group_option.setRequired(true); + options.addOption(group_option); + + Option type_option = new Option("type", "type", true, "string|byte message type"); + type_option.setRequired(true); + options.addOption(type_option); + + CommandLineParser parser = new DefaultParser(); + HelpFormatter formatter = new HelpFormatter(); + CommandLine cmd; + + try { + cmd = parser.parse(options, args); + } catch (ParseException e) { + System.out.println(e.getMessage()); + formatter.printHelp("Consumer Example", options); + + System.exit(1); + return; + } + + String endpoint = cmd.getOptionValue("bootstrap-server"); + String topic = cmd.getOptionValue("topic"); + String group = cmd.getOptionValue("group"); + String type = cmd.getOptionValue("type"); + + // Properties for the kafka topic + Properties props = new Properties(); + props.put("bootstrap.servers", endpoint); + props.put("group.id", group); + props.put("enable.auto.commit", "false"); + props.put("auto.commit.interval.ms", "1000"); + props.put("session.timeout.ms", "30000"); + props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + if (type.equals("byte")){ + props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); + } else { + props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + } + + if (type.equals("byte")) { + KafkaConsumer byteArrayConsumer = new KafkaConsumer(props); + + byteArrayConsumer.subscribe(Arrays.asList(topic)); + System.out.println("Subscribed to topic " + topic); + while (true) { + ConsumerRecords records = byteArrayConsumer.poll(100); + for (ConsumerRecord record : records) { + // Serialize the record value + SerializationUtils serializer = new SerializationUtils(); + J2735Bsm bsm = serializer.deserialize(record.value()); + System.out.println(bsm.toString()); + } + } + } else { + KafkaConsumer stringConsumer = new KafkaConsumer(props); + + stringConsumer.subscribe(Arrays.asList(topic)); + System.out.println("Subscribed to topic " + topic); + while (true) { + ConsumerRecords records = stringConsumer.poll(100); + for (ConsumerRecord record : records) { + System.out.println(record.value()); + } + } + + } + } +} diff --git a/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java b/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java index 866d78a56..803e72531 100644 --- a/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java +++ b/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 com.consumerexample.app; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class ConsumerExampleTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public ConsumerExampleTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( ConsumerExampleTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 com.consumerexample.app; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class ConsumerExampleTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public ConsumerExampleTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( ConsumerExampleTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties b/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties index c954cec91..5235dd160 100644 --- a/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties +++ b/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties @@ -1 +1 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/jpo-ode-core/LICENSE-2.0.html b/jpo-ode-core/LICENSE-2.0.html index d1055c8ad..16303d2c7 100644 --- a/jpo-ode-core/LICENSE-2.0.html +++ b/jpo-ode-core/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-core/mvnw b/jpo-ode-core/mvnw index a1ba1bf55..223618a5c 100644 --- a/jpo-ode-core/mvnw +++ b/jpo-ode-core/mvnw @@ -1,233 +1,233 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" +#!/bin/sh +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" diff --git a/jpo-ode-core/mvnw.cmd b/jpo-ode-core/mvnw.cmd index 2b934e89d..beda8f144 100644 --- a/jpo-ode-core/mvnw.cmd +++ b/jpo-ode-core/mvnw.cmd @@ -1,145 +1,145 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + exit /B %ERROR_CODE% \ No newline at end of file diff --git a/jpo-ode-core/pom.xml b/jpo-ode-core/pom.xml index 7b3d02eb7..acfc39dd3 100644 --- a/jpo-ode-core/pom.xml +++ b/jpo-ode-core/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT jpo-ode-core @@ -23,12 +23,12 @@ usdot.jpo.ode jpo-ode-common - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT usdot.jpo.ode jpo-ode-plugins - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT org.apache.httpcomponents diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java index fb3a35c3d..a35fda0fc 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java @@ -1,149 +1,149 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.context; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.UUID; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -@Configuration -public class AppContext { - // CONSTANTS - public static final String ODE_HOSTNAME = "ODE_HOSTNAME"; - public static final String PAYLOAD_STRING = "payload"; - public static final String METADATA_STRING = "metadata"; - public static final String ODE_ASN1_DATA = "OdeAsn1Data"; - public static final String DATA_STRING = "data"; - public static final String ENCODINGS_STRING = "encodings"; - public static final String PAYLOAD_TYPE_STRING = "payloadType"; - public static final String DATA_TYPE_STRING = "dataType"; - public static final String SERIAL_ID_STRING = "serialId"; - public static final String SANITIZED_STRING = "Sanitized-"; - public static final String DEFAULT_KAFKA_PRODUCER_TYPE = "sync"; - - public static final int DEFAULT_SPARK_ROAD_SEGMENT_SNAPPING_TOLERANCE = 20; - public static final int DEFAULT_METRICS_GRAPHITE_PORT = 2003; - public static final int DEFAULT_METRICS_POLLING_RATE_SECONDS = 10; - - // Kafka Parameters - public static final String KAFKA_METADATA_BROKER_LIST = "kafka.metadata.broker.list"; - public static final String KAFKA_CONSUMER_THREADS = "kafka.consumer.threads"; - public static final String ZK_CONNECTION_STRINGS = "zk.connection.strings"; - public static final int DEFAULT_KAFKA_CONSUMER_THREADS = 1; - - public static final String TOKEN_KEY_RSA_PEM = "token.key.rsa.pem"; - - public static final String METRICS_PREFIX = "metrics.prefix"; - public static final String METRICS_POLLING_RATE_SECONDS = "metrics.polling.rate.seconds"; - public static final String METRICS_GRAPHITE_HOST = "metrics.graphite.host"; - public static final String METRICS_GRAPHITE_PORT = "metrics.graphite.port"; - - private static AppContext instance = null; - - @Autowired - Environment env; - - private String hostId; - - public AppContext() { - } - - public static AppContext getInstance() { - if (null == instance) { - synchronized (AppContext.class) { - if (null == instance) - instance = new AppContext(); - instance.init(); - } - } - return instance; - } - - private void init() { - String hostname; - - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - // Let's just use a random hostname - hostname = UUID.randomUUID().toString(); - } - hostId = hostname; - } - - public String getHostId() { - return hostId; - } - - public String getParam(String key) { - String result = null; - if (key != null) { - result = env.getProperty(key); - } - - return result; - } - - public String getParam(String key, String defaultValue) { - String result = getParam(key); - if (result != null) { - return result; - } else { - return defaultValue; - } - } - - public int getInt(String key, int defaultValue) { - String result = getParam(key); - if (result != null) { - return Integer.parseInt(result); - } else { - return defaultValue; - } - } - - public long getLong(String key, long defaultValue) { - String result = getParam(key); - if (result != null) { - return Long.parseLong(result); - } else { - return defaultValue; - } - } - - public double getDouble(String key, double defaultValue) { - String result = getParam(key); - if (result != null) { - return Double.parseDouble(result); - } else { - return defaultValue; - } - } - - public boolean getBoolean(String key, boolean defaultValue) { - String result = getParam(key); - if (result != null) { - return Boolean.parseBoolean(result); - } else { - return defaultValue; - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.context; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +@Configuration +public class AppContext { + // CONSTANTS + public static final String ODE_HOSTNAME = "ODE_HOSTNAME"; + public static final String PAYLOAD_STRING = "payload"; + public static final String METADATA_STRING = "metadata"; + public static final String ODE_ASN1_DATA = "OdeAsn1Data"; + public static final String DATA_STRING = "data"; + public static final String ENCODINGS_STRING = "encodings"; + public static final String PAYLOAD_TYPE_STRING = "payloadType"; + public static final String DATA_TYPE_STRING = "dataType"; + public static final String SERIAL_ID_STRING = "serialId"; + public static final String SANITIZED_STRING = "Sanitized-"; + public static final String DEFAULT_KAFKA_PRODUCER_TYPE = "sync"; + + public static final int DEFAULT_SPARK_ROAD_SEGMENT_SNAPPING_TOLERANCE = 20; + public static final int DEFAULT_METRICS_GRAPHITE_PORT = 2003; + public static final int DEFAULT_METRICS_POLLING_RATE_SECONDS = 10; + + // Kafka Parameters + public static final String KAFKA_METADATA_BROKER_LIST = "kafka.metadata.broker.list"; + public static final String KAFKA_CONSUMER_THREADS = "kafka.consumer.threads"; + public static final String ZK_CONNECTION_STRINGS = "zk.connection.strings"; + public static final int DEFAULT_KAFKA_CONSUMER_THREADS = 1; + + public static final String TOKEN_KEY_RSA_PEM = "token.key.rsa.pem"; + + public static final String METRICS_PREFIX = "metrics.prefix"; + public static final String METRICS_POLLING_RATE_SECONDS = "metrics.polling.rate.seconds"; + public static final String METRICS_GRAPHITE_HOST = "metrics.graphite.host"; + public static final String METRICS_GRAPHITE_PORT = "metrics.graphite.port"; + + private static AppContext instance = null; + + @Autowired + Environment env; + + private String hostId; + + public AppContext() { + } + + public static AppContext getInstance() { + if (null == instance) { + synchronized (AppContext.class) { + if (null == instance) + instance = new AppContext(); + instance.init(); + } + } + return instance; + } + + private void init() { + String hostname; + + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + // Let's just use a random hostname + hostname = UUID.randomUUID().toString(); + } + hostId = hostname; + } + + public String getHostId() { + return hostId; + } + + public String getParam(String key) { + String result = null; + if (key != null) { + result = env.getProperty(key); + } + + return result; + } + + public String getParam(String key, String defaultValue) { + String result = getParam(key); + if (result != null) { + return result; + } else { + return defaultValue; + } + } + + public int getInt(String key, int defaultValue) { + String result = getParam(key); + if (result != null) { + return Integer.parseInt(result); + } else { + return defaultValue; + } + } + + public long getLong(String key, long defaultValue) { + String result = getParam(key); + if (result != null) { + return Long.parseLong(result); + } else { + return defaultValue; + } + } + + public double getDouble(String key, double defaultValue) { + String result = getParam(key); + if (result != null) { + return Double.parseDouble(result); + } else { + return defaultValue; + } + } + + public boolean getBoolean(String key, boolean defaultValue) { + String result = getParam(key); + if (result != null) { + return Boolean.parseBoolean(result); + } else { + return defaultValue; + } + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java index d47658251..c4df9b379 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - - -/** - * "DEPOSIT: { \"systemDepositName\": \"%s\", \"encodeType\": \"%s\", \"encodedMsg\": \"%s\" }" - * - */ -public class DdsDepRequest extends DdsRequest { - - private static final long serialVersionUID = 6066887685895268828L; - - private String systemDepositName; - private String encodeType; - private String encodedMsg; - - - public String getSystemDepositName() { - return systemDepositName; - } - - public DdsDepRequest setSystemDepositName(String systemDepositName) { - this.systemDepositName = systemDepositName; - return this; - } - - public String getEncodeType() { - return encodeType; - } - - public DdsDepRequest setEncodeType(String encodeType) { - this.encodeType = encodeType; - return this; - } - - public String getEncodedMsg() { - return encodedMsg; - } - - public DdsDepRequest setEncodedMsg(String encodedMsg) { - this.encodedMsg = encodedMsg; - return this; - } - - @Override - public String toString() { - return "DEPOSIT:" + this.toJson(false); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((encodeType == null) ? 0 : encodeType.hashCode()); - result = prime * result - + ((encodedMsg == null) ? 0 : encodedMsg.hashCode()); - result = prime * result - + ((systemDepositName == null) ? 0 : systemDepositName.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; - DdsDepRequest other = (DdsDepRequest) obj; - if (encodeType == null) { - if (other.encodeType != null) - return false; - } else if (!encodeType.equals(other.encodeType)) - return false; - if (encodedMsg == null) { - if (other.encodedMsg != null) - return false; - } else if (!encodedMsg.equals(other.encodedMsg)) - return false; - if (systemDepositName == null) { - if (other.systemDepositName != null) - return false; - } else if (!systemDepositName.equals(other.systemDepositName)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + + +/** + * "DEPOSIT: { \"systemDepositName\": \"%s\", \"encodeType\": \"%s\", \"encodedMsg\": \"%s\" }" + * + */ +public class DdsDepRequest extends DdsRequest { + + private static final long serialVersionUID = 6066887685895268828L; + + private String systemDepositName; + private String encodeType; + private String encodedMsg; + + + public String getSystemDepositName() { + return systemDepositName; + } + + public DdsDepRequest setSystemDepositName(String systemDepositName) { + this.systemDepositName = systemDepositName; + return this; + } + + public String getEncodeType() { + return encodeType; + } + + public DdsDepRequest setEncodeType(String encodeType) { + this.encodeType = encodeType; + return this; + } + + public String getEncodedMsg() { + return encodedMsg; + } + + public DdsDepRequest setEncodedMsg(String encodedMsg) { + this.encodedMsg = encodedMsg; + return this; + } + + @Override + public String toString() { + return "DEPOSIT:" + this.toJson(false); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((encodeType == null) ? 0 : encodeType.hashCode()); + result = prime * result + + ((encodedMsg == null) ? 0 : encodedMsg.hashCode()); + result = prime * result + + ((systemDepositName == null) ? 0 : systemDepositName.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; + DdsDepRequest other = (DdsDepRequest) obj; + if (encodeType == null) { + if (other.encodeType != null) + return false; + } else if (!encodeType.equals(other.encodeType)) + return false; + if (encodedMsg == null) { + if (other.encodedMsg != null) + return false; + } else if (!encodedMsg.equals(other.encodedMsg)) + return false; + if (systemDepositName == null) { + if (other.systemDepositName != null) + return false; + } else if (!systemDepositName.equals(other.systemDepositName)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java index 765b3ce9d..c5a4cbc66 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import us.dot.its.jpo.ode.model.BaseRequest; - -@SuppressWarnings("serial") -public class DdsRequest extends BaseRequest { - - public enum Dialog { - VSD (154), - ISD (162), - ASD (156), - ALL (-1); - - private final int id; - - Dialog(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public static Dialog getById(int id) { - Dialog result = null; - for (Dialog d : Dialog.values()) { - if (d.getId() == id) { - result = d; - break; - } - } - return result; - } - } - - public enum SystemName { - SDC ("SDC 2.3"), - SDW ("SDW 2.3"), - SDPC ("SDPC 2.3"); - - private final String name; - - SystemName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - - public enum EncodeType {BASE64, HEX} - - private int dialogID; - private String resultEncoding; - - public int getDialogID() { - return dialogID; - } - - public DdsRequest setDialogID(int dialogID) { - this.dialogID = dialogID; - return this; - } - - public String getResultEncoding() { - return resultEncoding; - } - - public DdsRequest setResultEncoding(String resultEncoding) { - this.resultEncoding = resultEncoding; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + dialogID; - result = prime * result + ((resultEncoding == null) ? 0 : resultEncoding.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; - DdsRequest other = (DdsRequest) obj; - if (dialogID != other.dialogID) - return false; - if (resultEncoding == null) { - if (other.resultEncoding != null) - return false; - } else if (!resultEncoding.equals(other.resultEncoding)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import us.dot.its.jpo.ode.model.BaseRequest; + +@SuppressWarnings("serial") +public class DdsRequest extends BaseRequest { + + public enum Dialog { + VSD (154), + ISD (162), + ASD (156), + ALL (-1); + + private final int id; + + Dialog(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public static Dialog getById(int id) { + Dialog result = null; + for (Dialog d : Dialog.values()) { + if (d.getId() == id) { + result = d; + break; + } + } + return result; + } + } + + public enum SystemName { + SDC ("SDC 2.3"), + SDW ("SDW 2.3"), + SDPC ("SDPC 2.3"); + + private final String name; + + SystemName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + + public enum EncodeType {BASE64, HEX} + + private int dialogID; + private String resultEncoding; + + public int getDialogID() { + return dialogID; + } + + public DdsRequest setDialogID(int dialogID) { + this.dialogID = dialogID; + return this; + } + + public String getResultEncoding() { + return resultEncoding; + } + + public DdsRequest setResultEncoding(String resultEncoding) { + this.resultEncoding = resultEncoding; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + dialogID; + result = prime * result + ((resultEncoding == null) ? 0 : resultEncoding.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; + DdsRequest other = (DdsRequest) obj; + if (dialogID != other.dialogID) + return false; + if (resultEncoding == null) { + if (other.resultEncoding != null) + return false; + } else if (!resultEncoding.equals(other.resultEncoding)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java index cc08ff5e0..7891043e3 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessage implements DdsMessage { - private StatusTag tag; - private String encoding; - private Dialog dialog; - private long recordCount; - private String connectionDetails; - - public DdsStatusMessage() { - super(); - } - - public DdsStatusMessage(StatusTag tag, String encoding, Dialog dialog) { - super(); - this.tag = tag; - this.encoding = encoding; - this.dialog = dialog; - } - - public StatusTag getTag() { - return tag; - } - - public DdsStatusMessage setTag(StatusTag tag) { - this.tag = tag; - return this; - } - - public String getEncoding() { - return encoding; - } - - public DdsStatusMessage setEncoding(String encoding) { - this.encoding = encoding; - return this; - } - - public Dialog getDialog() { - return dialog; - } - - public DdsStatusMessage setDialog(Dialog dialog) { - this.dialog = dialog; - return this; - } - - public long getRecordCount() { - return recordCount; - } - - public DdsStatusMessage setRecordCount(long recordCount) { - this.recordCount = recordCount; - return this; - } - - public String getConnectionDetails() { - return connectionDetails; - } - - public DdsStatusMessage setConnectionDetails(String connectionDetails) { - this.connectionDetails = connectionDetails; - return this; - } - - @Override - public String toString() { - return "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" - + recordCount + ", connectionDetails=" + connectionDetails + "]"; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessage implements DdsMessage { + private StatusTag tag; + private String encoding; + private Dialog dialog; + private long recordCount; + private String connectionDetails; + + public DdsStatusMessage() { + super(); + } + + public DdsStatusMessage(StatusTag tag, String encoding, Dialog dialog) { + super(); + this.tag = tag; + this.encoding = encoding; + this.dialog = dialog; + } + + public StatusTag getTag() { + return tag; + } + + public DdsStatusMessage setTag(StatusTag tag) { + this.tag = tag; + return this; + } + + public String getEncoding() { + return encoding; + } + + public DdsStatusMessage setEncoding(String encoding) { + this.encoding = encoding; + return this; + } + + public Dialog getDialog() { + return dialog; + } + + public DdsStatusMessage setDialog(Dialog dialog) { + this.dialog = dialog; + return this; + } + + public long getRecordCount() { + return recordCount; + } + + public DdsStatusMessage setRecordCount(long recordCount) { + this.recordCount = recordCount; + return this; + } + + public String getConnectionDetails() { + return connectionDetails; + } + + public DdsStatusMessage setConnectionDetails(String connectionDetails) { + this.connectionDetails = connectionDetails; + return this; + } + + @Override + public String toString() { + return "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" + + recordCount + ", connectionDetails=" + connectionDetails + "]"; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java index 7dcd8ad2c..a4f4969f4 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -@SuppressWarnings("serial") -public class BaseRequest extends OdeObject { - - public BaseRequest() { - super(); - } - - static BaseRequest create() { - return new BaseRequest(); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +@SuppressWarnings("serial") +public class BaseRequest extends OdeObject { + + public BaseRequest() { + super(); + } + + static BaseRequest create() { + return new BaseRequest(); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java index c38a99aad..69e6269a3 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public interface HasKey extends OdeFilterable { - String getKey(); -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public interface HasKey extends OdeFilterable { + String getKey(); +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java index 65b3eca2a..640f69d98 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.OdeGeoRegion; -import us.dot.its.jpo.ode.plugin.j2735.OdePosition3D; - -public interface HasPosition extends OdeFilterable { - OdePosition3D getPosition(); - boolean isWithinBounds(OdeGeoRegion region); -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.OdeGeoRegion; +import us.dot.its.jpo.ode.plugin.j2735.OdePosition3D; + +public interface HasPosition extends OdeFilterable { + OdePosition3D getPosition(); + boolean isWithinBounds(OdeGeoRegion region); +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java index 296be0dcb..edb52655d 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java @@ -1,138 +1,138 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.math.BigDecimal; - -public final class OdeAggregateData extends OdeData implements HasKey { - - private static final long serialVersionUID = 1595406822366147861L; - - private String key; - private Long count; - private BigDecimal minSpeed; - private BigDecimal avgSpeed; - private BigDecimal maxSpeed; - - public OdeAggregateData() { - super(); - } - - public OdeAggregateData(String key, Long count, BigDecimal minSpeed, BigDecimal avgSpeed, BigDecimal maxSpeed) { - super(); - this.key = key; - this.count = count; - this.minSpeed = minSpeed; - this.avgSpeed = avgSpeed; - this.maxSpeed = maxSpeed; -} - -@Override - public String getKey() { - return key; - } - - public OdeAggregateData setKey(String key) { - this.key = key; - return this; - } - - public Long getCount() { - return count; - } - - public OdeAggregateData setCount(Long count) { - this.count = count; - return this; - } - - public BigDecimal getMinSpeed() { - return minSpeed; - } - - public OdeAggregateData setMinSpeed(BigDecimal minSpeed) { - this.minSpeed = minSpeed; - return this; - } - - public BigDecimal getAvgSpeed() { - return avgSpeed; - } - - public OdeAggregateData setAvgSpeed(BigDecimal avgSpeed) { - this.avgSpeed = avgSpeed; - return this; - } - - public BigDecimal getMaxSpeed() { - return maxSpeed; - } - - public void setMaxSpeed(BigDecimal maxSpeed) { - this.maxSpeed = maxSpeed; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((avgSpeed == null) ? 0 : avgSpeed.hashCode()); - result = prime * result + ((count == null) ? 0 : count.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((maxSpeed == null) ? 0 : maxSpeed.hashCode()); - result = prime * result + ((minSpeed == null) ? 0 : minSpeed.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeAggregateData other = (OdeAggregateData) obj; - if (avgSpeed == null) { - if (other.avgSpeed != null) - return false; - } else if (!avgSpeed.equals(other.avgSpeed)) - return false; - if (count == null) { - if (other.count != null) - return false; - } else if (!count.equals(other.count)) - return false; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) - return false; - if (maxSpeed == null) { - if (other.maxSpeed != null) - return false; - } else if (!maxSpeed.equals(other.maxSpeed)) - return false; - if (minSpeed == null) { - if (other.minSpeed != null) - return false; - } else if (!minSpeed.equals(other.minSpeed)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.math.BigDecimal; + +public final class OdeAggregateData extends OdeData implements HasKey { + + private static final long serialVersionUID = 1595406822366147861L; + + private String key; + private Long count; + private BigDecimal minSpeed; + private BigDecimal avgSpeed; + private BigDecimal maxSpeed; + + public OdeAggregateData() { + super(); + } + + public OdeAggregateData(String key, Long count, BigDecimal minSpeed, BigDecimal avgSpeed, BigDecimal maxSpeed) { + super(); + this.key = key; + this.count = count; + this.minSpeed = minSpeed; + this.avgSpeed = avgSpeed; + this.maxSpeed = maxSpeed; +} + +@Override + public String getKey() { + return key; + } + + public OdeAggregateData setKey(String key) { + this.key = key; + return this; + } + + public Long getCount() { + return count; + } + + public OdeAggregateData setCount(Long count) { + this.count = count; + return this; + } + + public BigDecimal getMinSpeed() { + return minSpeed; + } + + public OdeAggregateData setMinSpeed(BigDecimal minSpeed) { + this.minSpeed = minSpeed; + return this; + } + + public BigDecimal getAvgSpeed() { + return avgSpeed; + } + + public OdeAggregateData setAvgSpeed(BigDecimal avgSpeed) { + this.avgSpeed = avgSpeed; + return this; + } + + public BigDecimal getMaxSpeed() { + return maxSpeed; + } + + public void setMaxSpeed(BigDecimal maxSpeed) { + this.maxSpeed = maxSpeed; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((avgSpeed == null) ? 0 : avgSpeed.hashCode()); + result = prime * result + ((count == null) ? 0 : count.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((maxSpeed == null) ? 0 : maxSpeed.hashCode()); + result = prime * result + ((minSpeed == null) ? 0 : minSpeed.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeAggregateData other = (OdeAggregateData) obj; + if (avgSpeed == null) { + if (other.avgSpeed != null) + return false; + } else if (!avgSpeed.equals(other.avgSpeed)) + return false; + if (count == null) { + if (other.count != null) + return false; + } else if (!count.equals(other.count)) + return false; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (maxSpeed == null) { + if (other.maxSpeed != null) + return false; + } else if (!maxSpeed.equals(other.maxSpeed)) + return false; + if (minSpeed == null) { + if (other.minSpeed != null) + return false; + } else if (!minSpeed.equals(other.minSpeed)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java index be6e575ac..84f843fa3 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.DdsAdvisorySituationData; - -public class OdeAsdPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - - public OdeAsdPayload() { - this(new DdsAdvisorySituationData()); - } - - public OdeAsdPayload(DdsAdvisorySituationData asd) { - super(asd); - this.setData(asd); - } - - public DdsAdvisorySituationData getAsd() { - return (DdsAdvisorySituationData) getData(); - } - - public void setAsd(DdsAdvisorySituationData asd) { - setData(asd); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.DdsAdvisorySituationData; + +public class OdeAsdPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + + public OdeAsdPayload() { + this(new DdsAdvisorySituationData()); + } + + public OdeAsdPayload(DdsAdvisorySituationData asd) { + super(asd); + this.setData(asd); + } + + public DdsAdvisorySituationData getAsd() { + return (DdsAdvisorySituationData) getData(); + } + + public void setAsd(DdsAdvisorySituationData asd) { + setData(asd); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java index e48186239..52a2b0e4c 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeAsn1Data extends OdeData { - private static final long serialVersionUID = 8844322473807845737L; - - public OdeAsn1Data() { - super(); - } - - public OdeAsn1Data(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeAsn1Data extends OdeData { + private static final long serialVersionUID = 8844322473807845737L; + + public OdeAsn1Data() { + super(); + } + + public OdeAsn1Data(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java index 200af90e5..156d9c34c 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeAuthorization extends OdeMessage{ - - private static final long serialVersionUID = -8496344900381434672L; - - private String token; - - public String getToken() { - return token; - } - - public OdeAuthorization setToken(String token) { - this.token = token; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((token == null) ? 0 : token.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeAuthorization other = (OdeAuthorization) obj; - if (token == null) { - if (other.token != null) - return false; - } else if (!token.equals(other.token)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeAuthorization extends OdeMessage{ + + private static final long serialVersionUID = -8496344900381434672L; + + private String token; + + public String getToken() { + return token; + } + + public OdeAuthorization setToken(String token) { + this.token = token; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((token == null) ? 0 : token.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeAuthorization other = (OdeAuthorization) obj; + if (token == null) { + if (other.token != null) + return false; + } else if (!token.equals(other.token)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java index a16745cc6..87c56b435 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java @@ -1,156 +1,156 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.dds.DdsStatusMessage; - -public class OdeControlData extends OdeMessage { - - private static final long serialVersionUID = 1L; - - private Long dataSourceBundleCount; - private Long receivedRecordCount; - private Long sentRecordCount; - private Long depositCount; - private StatusTag tag; - private String message; - - public OdeControlData() { - super(); - } - - public OdeControlData(StatusTag tag) { - super(); - setTag(tag); - } - - public OdeControlData(DdsStatusMessage controlMessage) { - setTag(controlMessage.getTag()); - if (controlMessage.getTag() == StatusTag.STOP) - setDataSourceBundleCount(controlMessage.getRecordCount()); - else if (controlMessage.getTag() == StatusTag.DEPOSITED) - setDepositCount(controlMessage.getRecordCount()); - } - - public Long getDataSourceBundleCount() { - return dataSourceBundleCount; - } - - public OdeControlData setDataSourceBundleCount(Long dataSourceBundleCount) { - this.dataSourceBundleCount = dataSourceBundleCount; - return this; - } - - public Long getReceivedRecordCount() { - return receivedRecordCount; - } - - public OdeControlData setReceivedRecordCount(Long receivedRecordCount) { - this.receivedRecordCount = receivedRecordCount; - return this; - } - - public Long getSentRecordCount() { - return sentRecordCount; - } - - public OdeControlData setSentRecordCount(Long sentRecordCount) { - this.sentRecordCount = sentRecordCount; - return this; - } - - public Long getDepositCount() { - return depositCount; - } - - public void setDepositCount(Long depositCount) { - this.depositCount = depositCount; - } - - public StatusTag getTag() { - return tag; - } - - public void setTag(StatusTag tag) { - this.tag = tag; - } - - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((dataSourceBundleCount == null) ? 0 - : dataSourceBundleCount.hashCode()); - result = prime * result - + ((depositCount == null) ? 0 : depositCount.hashCode()); - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result + ((receivedRecordCount == null) ? 0 - : receivedRecordCount.hashCode()); - result = prime * result - + ((sentRecordCount == null) ? 0 : sentRecordCount.hashCode()); - result = prime * result + ((tag == null) ? 0 : tag.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeControlData other = (OdeControlData) obj; - if (dataSourceBundleCount == null) { - if (other.dataSourceBundleCount != null) - return false; - } else if (!dataSourceBundleCount.equals(other.dataSourceBundleCount)) - return false; - if (depositCount == null) { - if (other.depositCount != null) - return false; - } else if (!depositCount.equals(other.depositCount)) - return false; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - if (receivedRecordCount == null) { - if (other.receivedRecordCount != null) - return false; - } else if (!receivedRecordCount.equals(other.receivedRecordCount)) - return false; - if (sentRecordCount == null) { - if (other.sentRecordCount != null) - return false; - } else if (!sentRecordCount.equals(other.sentRecordCount)) - return false; - if (tag != other.tag) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.dds.DdsStatusMessage; + +public class OdeControlData extends OdeMessage { + + private static final long serialVersionUID = 1L; + + private Long dataSourceBundleCount; + private Long receivedRecordCount; + private Long sentRecordCount; + private Long depositCount; + private StatusTag tag; + private String message; + + public OdeControlData() { + super(); + } + + public OdeControlData(StatusTag tag) { + super(); + setTag(tag); + } + + public OdeControlData(DdsStatusMessage controlMessage) { + setTag(controlMessage.getTag()); + if (controlMessage.getTag() == StatusTag.STOP) + setDataSourceBundleCount(controlMessage.getRecordCount()); + else if (controlMessage.getTag() == StatusTag.DEPOSITED) + setDepositCount(controlMessage.getRecordCount()); + } + + public Long getDataSourceBundleCount() { + return dataSourceBundleCount; + } + + public OdeControlData setDataSourceBundleCount(Long dataSourceBundleCount) { + this.dataSourceBundleCount = dataSourceBundleCount; + return this; + } + + public Long getReceivedRecordCount() { + return receivedRecordCount; + } + + public OdeControlData setReceivedRecordCount(Long receivedRecordCount) { + this.receivedRecordCount = receivedRecordCount; + return this; + } + + public Long getSentRecordCount() { + return sentRecordCount; + } + + public OdeControlData setSentRecordCount(Long sentRecordCount) { + this.sentRecordCount = sentRecordCount; + return this; + } + + public Long getDepositCount() { + return depositCount; + } + + public void setDepositCount(Long depositCount) { + this.depositCount = depositCount; + } + + public StatusTag getTag() { + return tag; + } + + public void setTag(StatusTag tag) { + this.tag = tag; + } + + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((dataSourceBundleCount == null) ? 0 + : dataSourceBundleCount.hashCode()); + result = prime * result + + ((depositCount == null) ? 0 : depositCount.hashCode()); + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((receivedRecordCount == null) ? 0 + : receivedRecordCount.hashCode()); + result = prime * result + + ((sentRecordCount == null) ? 0 : sentRecordCount.hashCode()); + result = prime * result + ((tag == null) ? 0 : tag.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeControlData other = (OdeControlData) obj; + if (dataSourceBundleCount == null) { + if (other.dataSourceBundleCount != null) + return false; + } else if (!dataSourceBundleCount.equals(other.dataSourceBundleCount)) + return false; + if (depositCount == null) { + if (other.depositCount != null) + return false; + } else if (!depositCount.equals(other.depositCount)) + return false; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (receivedRecordCount == null) { + if (other.receivedRecordCount != null) + return false; + } else if (!receivedRecordCount.equals(other.receivedRecordCount)) + return false; + if (sentRecordCount == null) { + if (other.sentRecordCount != null) + return false; + } else if (!sentRecordCount.equals(other.sentRecordCount)) + return false; + if (tag != other.tag) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java index 3f0732dec..f9f235425 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeData extends OdeObject implements OdeFilterable { - private static final long serialVersionUID = -7711340868799607662L; - - private OdeMsgMetadata metadata; - private OdeMsgPayload payload; - - public OdeData() { - super(); - } - - public OdeData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(); - this.metadata = metadata; - this.payload = payload; - this.metadata.setPayloadType(payload.getClass().getName()); - } - - public OdeMsgMetadata getMetadata() { - return metadata; - } - - public void setMetadata(OdeMsgMetadata metadata) { - this.metadata = metadata; - } - - public OdeMsgPayload getPayload() { - return payload; - } - - public void setPayload(OdeMsgPayload payload) { - this.payload = payload; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.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; - OdeData other = (OdeData) obj; - if (metadata == null) { - if (other.metadata != null) - return false; - } else if (!metadata.equals(other.metadata)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeData extends OdeObject implements OdeFilterable { + private static final long serialVersionUID = -7711340868799607662L; + + private OdeMsgMetadata metadata; + private OdeMsgPayload payload; + + public OdeData() { + super(); + } + + public OdeData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(); + this.metadata = metadata; + this.payload = payload; + this.metadata.setPayloadType(payload.getClass().getName()); + } + + public OdeMsgMetadata getMetadata() { + return metadata; + } + + public void setMetadata(OdeMsgMetadata metadata) { + this.metadata = metadata; + } + + public OdeMsgPayload getPayload() { + return payload; + } + + public void setPayload(OdeMsgPayload payload) { + this.payload = payload; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.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; + OdeData other = (OdeData) obj; + if (metadata == null) { + if (other.metadata != null) + return false; + } else if (!metadata.equals(other.metadata)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java index bf4929ebd..9db394e38 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.databind.JsonNode; - -import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; - -public enum OdeDataType { - Status("status", OdeStatus.class), - Control("control", OdeControlData.class), - Authorization("auth", OdeAuthorization.class), - BasicSafetyMessage("bsm", J2735Bsm.class), - TravelerInformationMessage("tim", OdeTravelerInputData.class), - AggregateData("agg", OdeAggregateData.class), - AsnBase64("asnbase64", String.class), - AsnHex("asnhex", String.class), - OtherData("other", OdeMsgPayload.class), - Unknown("unknown", OdeMsgPayload.class); - - private static List shortNames = shortNamesAsList(); - - private final String shortName; - - private final Class clazz; - - private OdeDataType(String shortName, Class clazz) { - this.shortName = shortName; - this.clazz = clazz; - } - - public String getShortName() { - return shortName; - } - - public Class getClazz() { - return clazz; - } - - public static OdeDataType getByShortName(String shortName) { - OdeDataType result = null; - - for (OdeDataType value : OdeDataType.values()) { - if (shortName.equals(value.getShortName())) { - result = value; - break; - } - } - return result; - } - - public static OdeDataType getByClazz(Class clazz) { - OdeDataType result = null; - - for (OdeDataType value : OdeDataType.values()) { - if (clazz == value.getClazz()) { - result = value; - break; - } - } - return result; - } - - public static OdeDataType getByClassName(String className) throws ClassNotFoundException { - return getByClazz(Class.forName(className)); - } - - public static String shortNames() { - return shortNamesAsList().toString(); - } - - public static List shortNamesAsList() { - if (shortNames == null) { - shortNames = new ArrayList(); - for (OdeDataType value : OdeDataType.values()) { - shortNames.add(value.getShortName()); - } - } - return shortNames; - } - - public static OdeDataType getFromJsonNode(JsonNode data, String name) throws IOException { - OdeDataType odeDataType = null; - if (data != null) { - JsonNode dataType = data.get(name); - if (dataType != null) { - odeDataType = OdeDataType.getByShortName(dataType.textValue()); - } - } - return odeDataType; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.databind.JsonNode; + +import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; + +public enum OdeDataType { + Status("status", OdeStatus.class), + Control("control", OdeControlData.class), + Authorization("auth", OdeAuthorization.class), + BasicSafetyMessage("bsm", J2735Bsm.class), + TravelerInformationMessage("tim", OdeTravelerInputData.class), + AggregateData("agg", OdeAggregateData.class), + AsnBase64("asnbase64", String.class), + AsnHex("asnhex", String.class), + OtherData("other", OdeMsgPayload.class), + Unknown("unknown", OdeMsgPayload.class); + + private static List shortNames = shortNamesAsList(); + + private final String shortName; + + private final Class clazz; + + private OdeDataType(String shortName, Class clazz) { + this.shortName = shortName; + this.clazz = clazz; + } + + public String getShortName() { + return shortName; + } + + public Class getClazz() { + return clazz; + } + + public static OdeDataType getByShortName(String shortName) { + OdeDataType result = null; + + for (OdeDataType value : OdeDataType.values()) { + if (shortName.equals(value.getShortName())) { + result = value; + break; + } + } + return result; + } + + public static OdeDataType getByClazz(Class clazz) { + OdeDataType result = null; + + for (OdeDataType value : OdeDataType.values()) { + if (clazz == value.getClazz()) { + result = value; + break; + } + } + return result; + } + + public static OdeDataType getByClassName(String className) throws ClassNotFoundException { + return getByClazz(Class.forName(className)); + } + + public static String shortNames() { + return shortNamesAsList().toString(); + } + + public static List shortNamesAsList() { + if (shortNames == null) { + shortNames = new ArrayList(); + for (OdeDataType value : OdeDataType.values()) { + shortNames.add(value.getShortName()); + } + } + return shortNames; + } + + public static OdeDataType getFromJsonNode(JsonNode data, String name) throws IOException { + OdeDataType odeDataType = null; + if (data != null) { + JsonNode dataType = data.get(name); + if (dataType != null) { + odeDataType = OdeDataType.getByShortName(dataType.textValue()); + } + } + return odeDataType; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java index d25ac9daf..c3d3cca40 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeDepRequest extends OdeRequest { - - private static final long serialVersionUID = -6766743372518752149L; - - private String encodeType; - private String data; - - - public String getEncodeType() { - return encodeType; - } - - public void setEncodeType(String encodeType) { - this.encodeType = encodeType; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result - + ((encodeType == null) ? 0 : encodeType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeDepRequest other = (OdeDepRequest) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (encodeType == null) { - if (other.encodeType != null) - return false; - } else if (!encodeType.equals(other.encodeType)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeDepRequest extends OdeRequest { + + private static final long serialVersionUID = -6766743372518752149L; + + private String encodeType; + private String data; + + + public String getEncodeType() { + return encodeType; + } + + public void setEncodeType(String encodeType) { + this.encodeType = encodeType; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + + ((encodeType == null) ? 0 : encodeType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeDepRequest other = (OdeDepRequest) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (encodeType == null) { + if (other.encodeType != null) + return false; + } else if (!encodeType.equals(other.encodeType)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java index 0eec5e2f2..ed2d58f15 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -/** - * Created by anthonychen on 11/4/17. - */ -public class OdeDriverAlertData extends OdeData { - - private static final long serialVersionUID = 2057040404896561615L; - - public OdeDriverAlertData() { - super(); - } - - public OdeDriverAlertData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +/** + * Created by anthonychen on 11/4/17. + */ +public class OdeDriverAlertData extends OdeData { + + private static final long serialVersionUID = 2057040404896561615L; + + public OdeDriverAlertData() { + super(); + } + + public OdeDriverAlertData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java index a596c9b4d..fcb44bc91 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -/** - * Created by anthonychen on 11/4/17. - */ -public class OdeDriverAlertPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - private String alert; - - public OdeDriverAlertPayload(String alert) { - this.alert = alert; - } - - public String getAlert() { - return this.alert; - } - - public void setAlert(String alert) { - this.alert = alert; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +/** + * Created by anthonychen on 11/4/17. + */ +public class OdeDriverAlertPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + private String alert; + + public OdeDriverAlertPayload(String alert) { + this.alert = alert; + } + + public String getAlert() { + return this.alert; + } + + public void setAlert(String alert) { + this.alert = alert; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java index 6e4387902..9ac25b5d5 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java @@ -1,67 +1,67 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import com.fasterxml.jackson.databind.node.ObjectNode; - -import us.dot.its.jpo.ode.util.JsonUtils; - -public class OdeException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -4133732677963262764L; - - OdeStatus.Code code; - - public OdeException() { - super(); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException(Throwable cause) { - super(cause); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (String message) { - super(message); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (String message, Throwable cause) { - super(message, cause); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (OdeStatus.Code code, String message) { - super(message); - this.code = code; - } - - public OdeException (OdeStatus.Code code, String message, Throwable cause) { - super(message, cause); - this.code = code; - } - - public String toJson() { - ObjectNode jsonObject = JsonUtils.newObjectNode("code", code.name()); - JsonUtils.addNode(jsonObject, "message", getMessage()); - JsonUtils.addNode(jsonObject, "cause", getCause().toString()); - return jsonObject.toString(); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +import us.dot.its.jpo.ode.util.JsonUtils; + +public class OdeException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -4133732677963262764L; + + OdeStatus.Code code; + + public OdeException() { + super(); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException(Throwable cause) { + super(cause); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (String message) { + super(message); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (String message, Throwable cause) { + super(message, cause); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (OdeStatus.Code code, String message) { + super(message); + this.code = code; + } + + public OdeException (OdeStatus.Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public String toJson() { + ObjectNode jsonObject = JsonUtils.newObjectNode("code", code.name()); + JsonUtils.addNode(jsonObject, "message", getMessage()); + JsonUtils.addNode(jsonObject, "cause", getCause().toString()); + return jsonObject.toString(); + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java index fd2ebbb34..39816fde9 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public interface OdeFilterable { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public interface OdeFilterable { + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java index 8fa6eb858..456524dbd 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java @@ -1,81 +1,81 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeLogMsgMetadataLocation extends OdeObject { - - private static final long serialVersionUID = 3174683494132372801L; - - String latitude; - String longitude; - String elevation; - String speed; - String heading; - - public OdeLogMsgMetadataLocation() { - super(); - } - - public OdeLogMsgMetadataLocation(String latitude, String longitude, String elevation, String speed, String heading) { - super(); - this.latitude = latitude; - this.longitude = longitude; - this.elevation = elevation; - this.speed = speed; - this.heading = heading; - } - - public String getLatitude() { - return latitude; - } - - public void setLatitude(String latitude) { - this.latitude = latitude; - } - - public String getLongitude() { - return longitude; - } - - public void setLongitude(String longitude) { - this.longitude = longitude; - } - - public String getElevation() { - return elevation; - } - - public void setElevation(String elevation) { - this.elevation = elevation; - } - - public String getSpeed() { - return speed; - } - - public void setSpeed(String speed) { - this.speed = speed; - } - - public String getHeading() { - return heading; - } - - public void setHeading(String heading) { - this.heading = heading; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeLogMsgMetadataLocation extends OdeObject { + + private static final long serialVersionUID = 3174683494132372801L; + + String latitude; + String longitude; + String elevation; + String speed; + String heading; + + public OdeLogMsgMetadataLocation() { + super(); + } + + public OdeLogMsgMetadataLocation(String latitude, String longitude, String elevation, String speed, String heading) { + super(); + this.latitude = latitude; + this.longitude = longitude; + this.elevation = elevation; + this.speed = speed; + this.heading = heading; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + public String getElevation() { + return elevation; + } + + public void setElevation(String elevation) { + this.elevation = elevation; + } + + public String getSpeed() { + return speed; + } + + public void setSpeed(String speed) { + this.speed = speed; + } + + public String getHeading() { + return heading; + } + + public void setHeading(String heading) { + this.heading = heading; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java index 777de37e1..4391924fa 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeMessage extends OdeObject { - - private static final long serialVersionUID = 6381260328835278701L; - - private Integer schemaVersion; - - public OdeMessage() { - super(); - this.schemaVersion = 3; - } - - public Integer getSchemaVersion() { - return schemaVersion; - } - - public void setSchemaVersion(Integer schemaVersion) { - this.schemaVersion = schemaVersion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((schemaVersion == null) ? 0 : schemaVersion.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; - OdeMessage other = (OdeMessage) obj; - if (schemaVersion == null) { - if (other.schemaVersion != null) - return false; - } else if (!schemaVersion.equals(other.schemaVersion)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeMessage extends OdeObject { + + private static final long serialVersionUID = 6381260328835278701L; + + private Integer schemaVersion; + + public OdeMessage() { + super(); + this.schemaVersion = 3; + } + + public Integer getSchemaVersion() { + return schemaVersion; + } + + public void setSchemaVersion(Integer schemaVersion) { + this.schemaVersion = schemaVersion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((schemaVersion == null) ? 0 : schemaVersion.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; + OdeMessage other = (OdeMessage) obj; + if (schemaVersion == null) { + if (other.schemaVersion != null) + return false; + } else if (!schemaVersion.equals(other.schemaVersion)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java index 3605f4959..41e91ca5e 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java @@ -1,181 +1,181 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.util.DateTimeUtils; - -public class OdeMsgMetadata extends OdeObject { - - public enum GeneratedBy { - TMC, OBU, RSU, TMC_VIA_SAT, TMC_VIA_SNMP, UNKNOWN - } - - private static final long serialVersionUID = 3979762143291085955L; - - private static int staticSchemaVersion; - - private String payloadType; - private SerialId serialId; - private String odeReceivedAt; - private int schemaVersion; - private String recordGeneratedAt; - private GeneratedBy recordGeneratedBy; - private boolean sanitized = false; - - public OdeMsgMetadata() { - this(OdeMsgPayload.class.getName(), new SerialId(), DateTimeUtils.now()); - } - - public OdeMsgMetadata(OdeMsgPayload payload) { - this(payload, new SerialId(), DateTimeUtils.now()); - } - - private OdeMsgMetadata(OdeMsgPayload payload, SerialId serialId, String receivedAt) { - this(payload.getClass().getName(), serialId, receivedAt); - } - - public OdeMsgMetadata(String payloadType, SerialId serialId, String receivedAt) { - super(); - this.schemaVersion = staticSchemaVersion; - this.payloadType = payloadType; - this.serialId = serialId; - this.odeReceivedAt = receivedAt; - } - - public String getPayloadType() { - return payloadType; - } - - public OdeMsgMetadata setPayloadType(OdeDataType payloadType) { - this.payloadType = payloadType.getShortName(); - return this; - } - - public OdeMsgMetadata setPayloadType(String payloadType) { - this.payloadType = payloadType; - return this; - } - - public SerialId getSerialId() { - return serialId; - } - - public void setSerialId(SerialId serialId) { - this.serialId = serialId; - } - - public String getOdeReceivedAt() { - return odeReceivedAt; - } - - public void setOdeReceivedAt(String receivedAt) { - this.odeReceivedAt = receivedAt; - } - - public int getSchemaVersion() { - return schemaVersion; - } - - public void setSchemaVersion(int aSchemaVersion) { - schemaVersion = aSchemaVersion; - } - - public String getRecordGeneratedAt() { - return recordGeneratedAt; - } - - public void setRecordGeneratedAt(String recordGeneratedAt) { - this.recordGeneratedAt = recordGeneratedAt; - } - - public GeneratedBy getRecordGeneratedBy() { - return recordGeneratedBy; - } - - public void setRecordGeneratedBy(GeneratedBy recordGeneratedBy) { - this.recordGeneratedBy = recordGeneratedBy; - } - - public boolean isSanitized() { - return sanitized; - } - - public void setSanitized(boolean sanitized) { - this.sanitized = sanitized; - } - - - public static int getStaticSchemaVersion() { - return staticSchemaVersion; - } - - public static void setStaticSchemaVersion(int aSchemaVersion) { - staticSchemaVersion = aSchemaVersion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((odeReceivedAt == null) ? 0 : odeReceivedAt.hashCode()); - result = prime * result + ((payloadType == null) ? 0 : payloadType.hashCode()); - result = prime * result + ((recordGeneratedAt == null) ? 0 : recordGeneratedAt.hashCode()); - result = prime * result + ((recordGeneratedBy == null) ? 0 : recordGeneratedBy.hashCode()); - result = prime * result + (sanitized ? 1231 : 1237); - result = prime * result + schemaVersion; - result = prime * result + ((serialId == null) ? 0 : serialId.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; - OdeMsgMetadata other = (OdeMsgMetadata) obj; - if (odeReceivedAt == null) { - if (other.odeReceivedAt != null) - return false; - } else if (!odeReceivedAt.equals(other.odeReceivedAt)) - return false; - if (payloadType == null) { - if (other.payloadType != null) - return false; - } else if (!payloadType.equals(other.payloadType)) - return false; - if (recordGeneratedAt == null) { - if (other.recordGeneratedAt != null) - return false; - } else if (!recordGeneratedAt.equals(other.recordGeneratedAt)) - return false; - if (recordGeneratedBy != other.recordGeneratedBy) - return false; - if (sanitized != other.sanitized) - return false; - if (schemaVersion != other.schemaVersion) - return false; - if (serialId == null) { - if (other.serialId != null) - return false; - } else if (!serialId.equals(other.serialId)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.util.DateTimeUtils; + +public class OdeMsgMetadata extends OdeObject { + + public enum GeneratedBy { + TMC, OBU, RSU, TMC_VIA_SAT, TMC_VIA_SNMP, UNKNOWN + } + + private static final long serialVersionUID = 3979762143291085955L; + + private static int staticSchemaVersion; + + private String payloadType; + private SerialId serialId; + private String odeReceivedAt; + private int schemaVersion; + private String recordGeneratedAt; + private GeneratedBy recordGeneratedBy; + private boolean sanitized = false; + + public OdeMsgMetadata() { + this(OdeMsgPayload.class.getName(), new SerialId(), DateTimeUtils.now()); + } + + public OdeMsgMetadata(OdeMsgPayload payload) { + this(payload, new SerialId(), DateTimeUtils.now()); + } + + private OdeMsgMetadata(OdeMsgPayload payload, SerialId serialId, String receivedAt) { + this(payload.getClass().getName(), serialId, receivedAt); + } + + public OdeMsgMetadata(String payloadType, SerialId serialId, String receivedAt) { + super(); + this.schemaVersion = staticSchemaVersion; + this.payloadType = payloadType; + this.serialId = serialId; + this.odeReceivedAt = receivedAt; + } + + public String getPayloadType() { + return payloadType; + } + + public OdeMsgMetadata setPayloadType(OdeDataType payloadType) { + this.payloadType = payloadType.getShortName(); + return this; + } + + public OdeMsgMetadata setPayloadType(String payloadType) { + this.payloadType = payloadType; + return this; + } + + public SerialId getSerialId() { + return serialId; + } + + public void setSerialId(SerialId serialId) { + this.serialId = serialId; + } + + public String getOdeReceivedAt() { + return odeReceivedAt; + } + + public void setOdeReceivedAt(String receivedAt) { + this.odeReceivedAt = receivedAt; + } + + public int getSchemaVersion() { + return schemaVersion; + } + + public void setSchemaVersion(int aSchemaVersion) { + schemaVersion = aSchemaVersion; + } + + public String getRecordGeneratedAt() { + return recordGeneratedAt; + } + + public void setRecordGeneratedAt(String recordGeneratedAt) { + this.recordGeneratedAt = recordGeneratedAt; + } + + public GeneratedBy getRecordGeneratedBy() { + return recordGeneratedBy; + } + + public void setRecordGeneratedBy(GeneratedBy recordGeneratedBy) { + this.recordGeneratedBy = recordGeneratedBy; + } + + public boolean isSanitized() { + return sanitized; + } + + public void setSanitized(boolean sanitized) { + this.sanitized = sanitized; + } + + + public static int getStaticSchemaVersion() { + return staticSchemaVersion; + } + + public static void setStaticSchemaVersion(int aSchemaVersion) { + staticSchemaVersion = aSchemaVersion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((odeReceivedAt == null) ? 0 : odeReceivedAt.hashCode()); + result = prime * result + ((payloadType == null) ? 0 : payloadType.hashCode()); + result = prime * result + ((recordGeneratedAt == null) ? 0 : recordGeneratedAt.hashCode()); + result = prime * result + ((recordGeneratedBy == null) ? 0 : recordGeneratedBy.hashCode()); + result = prime * result + (sanitized ? 1231 : 1237); + result = prime * result + schemaVersion; + result = prime * result + ((serialId == null) ? 0 : serialId.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; + OdeMsgMetadata other = (OdeMsgMetadata) obj; + if (odeReceivedAt == null) { + if (other.odeReceivedAt != null) + return false; + } else if (!odeReceivedAt.equals(other.odeReceivedAt)) + return false; + if (payloadType == null) { + if (other.payloadType != null) + return false; + } else if (!payloadType.equals(other.payloadType)) + return false; + if (recordGeneratedAt == null) { + if (other.recordGeneratedAt != null) + return false; + } else if (!recordGeneratedAt.equals(other.recordGeneratedAt)) + return false; + if (recordGeneratedBy != other.recordGeneratedBy) + return false; + if (sanitized != other.sanitized) + return false; + if (schemaVersion != other.schemaVersion) + return false; + if (serialId == null) { + if (other.serialId != null) + return false; + } else if (!serialId.equals(other.serialId)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java index 3bd5c32e4..863eabd13 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeMsgPayload extends OdeObject { - private static final long serialVersionUID = -7711340868799607662L; - - private String dataType; - private OdeObject data; - - public OdeMsgPayload() { - super(); - } - - public OdeMsgPayload(OdeObject data) { - super(); - this.dataType = data.getClass().getName(); - this.data = data; - } - - public OdeMsgPayload(String dataType, OdeObject data) { - super(); - this.dataType = dataType; - this.data = data; - } - - public String getDataType() { - return dataType; - } - - public void setDataType(String dataType) { - this.dataType = dataType; - } - - public OdeObject getData() { - return data; - } - - public void setData(OdeObject data) { - this.data = data; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeMsgPayload other = (OdeMsgPayload) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (dataType == null) { - if (other.dataType != null) - return false; - } else if (!dataType.equals(other.dataType)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeMsgPayload extends OdeObject { + private static final long serialVersionUID = -7711340868799607662L; + + private String dataType; + private OdeObject data; + + public OdeMsgPayload() { + super(); + } + + public OdeMsgPayload(OdeObject data) { + super(); + this.dataType = data.getClass().getName(); + this.data = data; + } + + public OdeMsgPayload(String dataType, OdeObject data) { + super(); + this.dataType = dataType; + this.data = data; + } + + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + public OdeObject getData() { + return data; + } + + public void setData(OdeObject data) { + this.data = data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeMsgPayload other = (OdeMsgPayload) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (dataType == null) { + if (other.dataType != null) + return false; + } else if (!dataType.equals(other.dataType)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java index 671f7b6d4..8edf7b0c9 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java @@ -1,113 +1,113 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdePayloadViolation { - - private String fieldName; - private double fieldValue; - private double validMin; - private double validMax; - - public OdePayloadViolation() { - super(); - fieldName = null; - fieldValue = Double.NaN; - validMin = Double.NaN; - validMax = Double.NaN; - } - - public OdePayloadViolation(String fieldName, double value, double validMin, double validMax) { - super(); - this.fieldName = fieldName; - this.fieldValue = value; - this.validMin = validMin; - this.validMax = validMax; - } - - public String getFieldName() { - return fieldName; - } - - public OdePayloadViolation setFieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - public double getFieldValue() { - return fieldValue; - } - - public void setFieldValue(double fieldValue) { - this.fieldValue = fieldValue; - } - - public double getValidMin() { - return validMin; - } - - public OdePayloadViolation setValidMin(double validMin) { - this.validMin = validMin; - return this; - } - - public double getValidMax() { - return validMax; - } - - public OdePayloadViolation setValidMax(double validMax) { - this.validMax = validMax; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode()); - long temp; - temp = Double.doubleToLongBits(validMax); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(validMin); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(fieldValue); - result = prime * result + (int) (temp ^ (temp >>> 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; - OdePayloadViolation other = (OdePayloadViolation) obj; - if (fieldName == null) { - if (other.fieldName != null) - return false; - } else if (!fieldName.equals(other.fieldName)) - return false; - if (Double.doubleToLongBits(validMax) != Double.doubleToLongBits(other.validMax)) - return false; - if (Double.doubleToLongBits(validMin) != Double.doubleToLongBits(other.validMin)) - return false; - if (Double.doubleToLongBits(fieldValue) != Double.doubleToLongBits(other.fieldValue)) - return false; - return true; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdePayloadViolation { + + private String fieldName; + private double fieldValue; + private double validMin; + private double validMax; + + public OdePayloadViolation() { + super(); + fieldName = null; + fieldValue = Double.NaN; + validMin = Double.NaN; + validMax = Double.NaN; + } + + public OdePayloadViolation(String fieldName, double value, double validMin, double validMax) { + super(); + this.fieldName = fieldName; + this.fieldValue = value; + this.validMin = validMin; + this.validMax = validMax; + } + + public String getFieldName() { + return fieldName; + } + + public OdePayloadViolation setFieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + public double getFieldValue() { + return fieldValue; + } + + public void setFieldValue(double fieldValue) { + this.fieldValue = fieldValue; + } + + public double getValidMin() { + return validMin; + } + + public OdePayloadViolation setValidMin(double validMin) { + this.validMin = validMin; + return this; + } + + public double getValidMax() { + return validMax; + } + + public OdePayloadViolation setValidMax(double validMax) { + this.validMax = validMax; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode()); + long temp; + temp = Double.doubleToLongBits(validMax); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(validMin); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(fieldValue); + result = prime * result + (int) (temp ^ (temp >>> 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; + OdePayloadViolation other = (OdePayloadViolation) obj; + if (fieldName == null) { + if (other.fieldName != null) + return false; + } else if (!fieldName.equals(other.fieldName)) + return false; + if (Double.doubleToLongBits(validMax) != Double.doubleToLongBits(other.validMax)) + return false; + if (Double.doubleToLongBits(validMin) != Double.doubleToLongBits(other.validMin)) + return false; + if (Double.doubleToLongBits(fieldValue) != Double.doubleToLongBits(other.fieldValue)) + return false; + return true; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java index 630d83f77..91ca47302 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.math.BigDecimal; - -public class OdePoint extends OdeObject { - - private static final long serialVersionUID = 6030294798158488311L; - - private BigDecimal latitude; - private BigDecimal longitude; - public OdePoint() { - super(); - } - public OdePoint(BigDecimal latitude, BigDecimal longitude) { - super(); - this.latitude = latitude; - this.longitude = longitude; - } - public BigDecimal getLatitude() { - return latitude; - } - public OdePoint setLatitude(BigDecimal latitude) { - this.latitude = latitude; - return this; - } - public BigDecimal getLongitude() { - return longitude; - } - public OdePoint setLongitude(BigDecimal longitude) { - this.longitude = longitude; - return this; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((latitude == null) ? 0 : latitude.hashCode()); - result = prime * result - + ((longitude == null) ? 0 : longitude.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; - OdePoint other = (OdePoint) obj; - if (latitude == null) { - if (other.latitude != null) - return false; - } else if (!latitude.equals(other.latitude)) - return false; - if (longitude == null) { - if (other.longitude != null) - return false; - } else if (!longitude.equals(other.longitude)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.math.BigDecimal; + +public class OdePoint extends OdeObject { + + private static final long serialVersionUID = 6030294798158488311L; + + private BigDecimal latitude; + private BigDecimal longitude; + public OdePoint() { + super(); + } + public OdePoint(BigDecimal latitude, BigDecimal longitude) { + super(); + this.latitude = latitude; + this.longitude = longitude; + } + public BigDecimal getLatitude() { + return latitude; + } + public OdePoint setLatitude(BigDecimal latitude) { + this.latitude = latitude; + return this; + } + public BigDecimal getLongitude() { + return longitude; + } + public OdePoint setLongitude(BigDecimal longitude) { + this.longitude = longitude; + return this; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((latitude == null) ? 0 : latitude.hashCode()); + result = prime * result + + ((longitude == null) ? 0 : longitude.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; + OdePoint other = (OdePoint) obj; + if (latitude == null) { + if (other.latitude != null) + return false; + } else if (!latitude.equals(other.latitude)) + return false; + if (longitude == null) { + if (other.longitude != null) + return false; + } else if (!longitude.equals(other.longitude)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java index e83e3cbe3..98893a0ce 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java @@ -1,157 +1,157 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.context.AppContext; -import us.dot.its.jpo.ode.util.JsonUtils; - -@SuppressWarnings("serial") -public class OdeRequest extends BaseRequest { - public static class OdeRequestException extends OdeException { - - public OdeRequestException(String message) { - super(message); - } - - } - - public enum DataSource { - SDC, SDW, SDPC, TEST_UPLOAD, DEPOSIT_SDC, DEPOSIT_SDW - } - - private String id; - private DataSource dataSource; - private OdeRequestType requestType; - private OdeDataType dataType; - - public OdeRequest() { - super(); - } - - public OdeRequest(OdeRequest other) { - super(); - this.setDataSource(other.getDataSource()); - this.setDataType(other.getDataType()); - this.setId(other.getId()); - this.setRequestType(other.getRequestType()); - } - - public static OdeRequest create(String rtype, String dtype, String message) throws OdeRequestException { - OdeRequest odeRequest = null; - OdeRequestType requestType = OdeRequestType.getByShortName(rtype); - if (requestType == OdeRequestType.Deposit) { - odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeDepRequest.class); -// } else if (requestType == OdeRequestType.Subscription) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeSubRequest.class); -// } else if (requestType == OdeRequestType.Query) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeQryRequest.class); -// } else if (requestType == OdeRequestType.Test) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeTstRequest.class); - } else { - OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_REQUEST_TYPE_ERROR).setMessage(String - .format("Invalid request type %s. Valid request types are %s.", rtype, OdeRequestType.shortNames())); - throw new OdeRequestException(status.toString()); - } - odeRequest.setRequestType(requestType); - - OdeDataType dataType = OdeDataType.getByShortName(dtype); - if (dataType == null) { - OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_DATA_TYPE_ERROR).setMessage( - String.format("Invalid data type %s. Valid data types are %s.", dtype, OdeDataType.shortNames())); - throw new OdeRequestException(status.toString()); - } - odeRequest.setDataType(dataType); - - odeRequest.setId(buildRequestId(odeRequest)); - return odeRequest; - } - - public static String buildRequestId(OdeRequest odeRequest) { - return AppContext.getInstance().getParam(AppContext.ODE_HOSTNAME) + odeRequest.getClass().getSimpleName() - + String.valueOf(odeRequest.hashCode()); - } - - public String getId() { - return id; - } - - public OdeRequest setId(String id) { - this.id = id; - return this; - } - - public OdeRequestType getRequestType() { - return requestType; - } - - public DataSource getDataSource() { - return dataSource; - } - - public OdeRequest setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - return this; - } - - public OdeRequest setRequestType(OdeRequestType requestType) { - this.requestType = requestType; - return this; - } - - public OdeDataType getDataType() { - return dataType; - } - - public OdeRequest setDataType(OdeDataType dataType) { - this.dataType = dataType; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((dataSource == null) ? 0 : dataSource.hashCode()); - result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((requestType == null) ? 0 : requestType.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; - OdeRequest other = (OdeRequest) obj; - if (dataSource != other.dataSource) - return false; - if (dataType != other.dataType) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (requestType != other.requestType) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.context.AppContext; +import us.dot.its.jpo.ode.util.JsonUtils; + +@SuppressWarnings("serial") +public class OdeRequest extends BaseRequest { + public static class OdeRequestException extends OdeException { + + public OdeRequestException(String message) { + super(message); + } + + } + + public enum DataSource { + SDC, SDW, SDPC, TEST_UPLOAD, DEPOSIT_SDC, DEPOSIT_SDW + } + + private String id; + private DataSource dataSource; + private OdeRequestType requestType; + private OdeDataType dataType; + + public OdeRequest() { + super(); + } + + public OdeRequest(OdeRequest other) { + super(); + this.setDataSource(other.getDataSource()); + this.setDataType(other.getDataType()); + this.setId(other.getId()); + this.setRequestType(other.getRequestType()); + } + + public static OdeRequest create(String rtype, String dtype, String message) throws OdeRequestException { + OdeRequest odeRequest = null; + OdeRequestType requestType = OdeRequestType.getByShortName(rtype); + if (requestType == OdeRequestType.Deposit) { + odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeDepRequest.class); +// } else if (requestType == OdeRequestType.Subscription) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeSubRequest.class); +// } else if (requestType == OdeRequestType.Query) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeQryRequest.class); +// } else if (requestType == OdeRequestType.Test) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeTstRequest.class); + } else { + OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_REQUEST_TYPE_ERROR).setMessage(String + .format("Invalid request type %s. Valid request types are %s.", rtype, OdeRequestType.shortNames())); + throw new OdeRequestException(status.toString()); + } + odeRequest.setRequestType(requestType); + + OdeDataType dataType = OdeDataType.getByShortName(dtype); + if (dataType == null) { + OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_DATA_TYPE_ERROR).setMessage( + String.format("Invalid data type %s. Valid data types are %s.", dtype, OdeDataType.shortNames())); + throw new OdeRequestException(status.toString()); + } + odeRequest.setDataType(dataType); + + odeRequest.setId(buildRequestId(odeRequest)); + return odeRequest; + } + + public static String buildRequestId(OdeRequest odeRequest) { + return AppContext.getInstance().getParam(AppContext.ODE_HOSTNAME) + odeRequest.getClass().getSimpleName() + + String.valueOf(odeRequest.hashCode()); + } + + public String getId() { + return id; + } + + public OdeRequest setId(String id) { + this.id = id; + return this; + } + + public OdeRequestType getRequestType() { + return requestType; + } + + public DataSource getDataSource() { + return dataSource; + } + + public OdeRequest setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + return this; + } + + public OdeRequest setRequestType(OdeRequestType requestType) { + this.requestType = requestType; + return this; + } + + public OdeDataType getDataType() { + return dataType; + } + + public OdeRequest setDataType(OdeDataType dataType) { + this.dataType = dataType; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((dataSource == null) ? 0 : dataSource.hashCode()); + result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((requestType == null) ? 0 : requestType.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; + OdeRequest other = (OdeRequest) obj; + if (dataSource != other.dataSource) + return false; + if (dataType != other.dataType) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (requestType != other.requestType) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java index b57b1289d..194405a4a 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.util.ArrayList; -import java.util.List; - -public enum OdeRequestType { - Subscription("sub"), Query("qry"), Test("tst"), Deposit("dep"); - - private static List shortNames = shortNamesAsList(); - private final String shortName; - - private OdeRequestType(String shortName) { - this.shortName = shortName; - } - - public String getShortName() { - return shortName; - } - - public static OdeRequestType getByShortName(String shortName) { - OdeRequestType result = null; - - for (OdeRequestType value : OdeRequestType.values()) { - if (shortName.equals(value.getShortName())) { - result = value; - break; - } - } - return result; - } - - public static String shortNames() { - return shortNamesAsList().toString(); - } - - public static List shortNamesAsList() { - if (shortNames == null) { - shortNames = new ArrayList(); - - for (OdeRequestType value : OdeRequestType.values()) { - shortNames.add(value.getShortName()); - } - } - return shortNames; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.util.ArrayList; +import java.util.List; + +public enum OdeRequestType { + Subscription("sub"), Query("qry"), Test("tst"), Deposit("dep"); + + private static List shortNames = shortNamesAsList(); + private final String shortName; + + private OdeRequestType(String shortName) { + this.shortName = shortName; + } + + public String getShortName() { + return shortName; + } + + public static OdeRequestType getByShortName(String shortName) { + OdeRequestType result = null; + + for (OdeRequestType value : OdeRequestType.values()) { + if (shortName.equals(value.getShortName())) { + result = value; + break; + } + } + return result; + } + + public static String shortNames() { + return shortNamesAsList().toString(); + } + + public static List shortNamesAsList() { + if (shortNames == null) { + shortNames = new ArrayList(); + + for (OdeRequestType value : OdeRequestType.values()) { + shortNames.add(value.getShortName()); + } + } + return shortNames; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java index 96cabd54e..2a05312cd 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - - -public class OdeStatus extends OdeMessage { - private static final long serialVersionUID = -8787345244306039604L; - - public static enum Code { - SUCCESS, FAILURE, - SOURCE_CONNECTION_ERROR, INVALID_REQUEST_TYPE_ERROR, - INVALID_DATA_TYPE_ERROR, COMMENT, DATA_TYPE_NOT_SUPPORTED - } - - Code code; - String message; - String requestId; - - public OdeStatus() { - super(); - } - - public OdeStatus(Code code, String message) { - super(); - this.code = code; - this.message = message; - } - - public Code getCode() { - return code; - } - - public OdeStatus setCode(Code code) { - this.code = code; - return this; - } - - public String getMessage() { - return message; - } - - public OdeStatus setMessage(String message) { - this.message = message; - return this; - } - - public String getRequestId() { - return requestId; - } - - public OdeStatus setRequestId(String requestId) { - this.requestId = requestId; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((code == null) ? 0 : code.hashCode()); - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result - + ((requestId == null) ? 0 : requestId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeStatus other = (OdeStatus) obj; - if (code != other.code) - return false; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - if (requestId == null) { - if (other.requestId != null) - return false; - } else if (!requestId.equals(other.requestId)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + + +public class OdeStatus extends OdeMessage { + private static final long serialVersionUID = -8787345244306039604L; + + public static enum Code { + SUCCESS, FAILURE, + SOURCE_CONNECTION_ERROR, INVALID_REQUEST_TYPE_ERROR, + INVALID_DATA_TYPE_ERROR, COMMENT, DATA_TYPE_NOT_SUPPORTED + } + + Code code; + String message; + String requestId; + + public OdeStatus() { + super(); + } + + public OdeStatus(Code code, String message) { + super(); + this.code = code; + this.message = message; + } + + public Code getCode() { + return code; + } + + public OdeStatus setCode(Code code) { + this.code = code; + return this; + } + + public String getMessage() { + return message; + } + + public OdeStatus setMessage(String message) { + this.message = message; + return this; + } + + public String getRequestId() { + return requestId; + } + + public OdeStatus setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((code == null) ? 0 : code.hashCode()); + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + + ((requestId == null) ? 0 : requestId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeStatus other = (OdeStatus) obj; + if (code != other.code) + return false; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (requestId == null) { + if (other.requestId != null) + return false; + } else if (!requestId.equals(other.requestId)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java index 1f1fac5f4..10b38108e 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeTimData extends OdeData { - - private static final long serialVersionUID = 2057040404896561615L; - - - public OdeTimData() { - super(); - } - - - public OdeTimData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeTimData extends OdeData { + + private static final long serialVersionUID = 2057040404896561615L; + + + public OdeTimData() { + super(); + } + + + public OdeTimData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java index b3ecd5565..a4adeffb9 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.OdeTravelerInformationMessage; - -public class OdeTimPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - - public OdeTimPayload() { - this(new OdeTravelerInformationMessage()); - } - - public OdeTimPayload(OdeTravelerInformationMessage tim) { - super(tim); - this.setData(tim); - } - - public OdeTravelerInformationMessage getTim() { - return (OdeTravelerInformationMessage) getData(); - } - - public void setTim(OdeTravelerInformationMessage tim) { - setData(tim); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.OdeTravelerInformationMessage; + +public class OdeTimPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + + public OdeTimPayload() { + this(new OdeTravelerInformationMessage()); + } + + public OdeTimPayload(OdeTravelerInformationMessage tim) { + super(tim); + this.setData(tim); + } + + public OdeTravelerInformationMessage getTim() { + return (OdeTravelerInformationMessage) getData(); + } + + public void setTim(OdeTravelerInformationMessage tim) { + setData(tim); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java index a2ccd752b..491393108 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class ReceivedMessageDetails extends OdeObject { - - private static final long serialVersionUID = -122988228561853841L; - - private OdeLogMsgMetadataLocation locationData; - private RxSource rxSource; - - public ReceivedMessageDetails() { - super(); - } - - public ReceivedMessageDetails(OdeLogMsgMetadataLocation locationData, RxSource rxSource) { - super(); - this.setLocationData(locationData); - this.setRxSource(rxSource); - } - - public OdeLogMsgMetadataLocation getLocationData() { - return locationData; - } - - public void setLocationData(OdeLogMsgMetadataLocation locationData) { - this.locationData = locationData; - } - - public RxSource getRxSource() { - return rxSource; - } - - public void setRxSource(RxSource rxSource) { - this.rxSource = rxSource; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class ReceivedMessageDetails extends OdeObject { + + private static final long serialVersionUID = -122988228561853841L; + + private OdeLogMsgMetadataLocation locationData; + private RxSource rxSource; + + public ReceivedMessageDetails() { + super(); + } + + public ReceivedMessageDetails(OdeLogMsgMetadataLocation locationData, RxSource rxSource) { + super(); + this.setLocationData(locationData); + this.setRxSource(rxSource); + } + + public OdeLogMsgMetadataLocation getLocationData() { + return locationData; + } + + public void setLocationData(OdeLogMsgMetadataLocation locationData) { + this.locationData = locationData; + } + + public RxSource getRxSource() { + return rxSource; + } + + public void setRxSource(RxSource rxSource) { + this.rxSource = rxSource; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java index 3491055bb..fca8fa2fe 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public enum RxSource { - RSU, - SAT, // XM satellite - RV, // for BSM rx - SNMP,// for SRM payload from back-end/ODE - NA, // Not applicable (for example, Distress Notification or Driver Alert - UNKNOWN -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public enum RxSource { + RSU, + SAT, // XM satellite + RV, // for BSM rx + SNMP,// for SRM payload from back-end/ODE + NA, // Not applicable (for example, Distress Notification or Driver Alert + UNKNOWN +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java index 7f7af7e07..1c4ef7416 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public enum StatusTag { - CONNECTED, START, STOP, ERROR, DEPOSITED, CLOSED, OPENED -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public enum StatusTag { + CONNECTED, START, STOP, ERROR, DEPOSITED, CLOSED, OPENED +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java index 36050ccb4..051bf43e0 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -/** - * @author 572682 - * - * This abstract class provides a basic pipeline functionality through the messaging - * framework. The objects of this class subscribe to a topic, process received messages - * and publish the results to another topic. - * - * @param Message Key type - * @param Received Message Value Type - * @param

    Published Message Value Type - */ -public abstract class AbstractSubPubTransformer extends AbstractSubscriberProcessor { - - protected int messagesPublished = 0; - protected MessageProducer producer; - protected String outputTopic; - - public AbstractSubPubTransformer(MessageProducer producer, String outputTopic) { - super(); - this.producer = producer; - this.outputTopic = outputTopic; - } - - @Override - public Object call() { - @SuppressWarnings("unchecked") - P toBePublished = (P) super.call(); - - if (null != toBePublished) { - producer.send(outputTopic, getRecord().key(), toBePublished); - } - - return toBePublished; - } - - public MessageProducer getProducer() { - return producer; - } - - public void setProducer(MessageProducer producer) { - this.producer = producer; - } - - public String getOutputTopic() { - return outputTopic; - } - - public void setOutputTopic(String outputTopic) { - this.outputTopic = outputTopic; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +/** + * @author 572682 + * + * This abstract class provides a basic pipeline functionality through the messaging + * framework. The objects of this class subscribe to a topic, process received messages + * and publish the results to another topic. + * + * @param Message Key type + * @param Received Message Value Type + * @param

    Published Message Value Type + */ +public abstract class AbstractSubPubTransformer extends AbstractSubscriberProcessor { + + protected int messagesPublished = 0; + protected MessageProducer producer; + protected String outputTopic; + + public AbstractSubPubTransformer(MessageProducer producer, String outputTopic) { + super(); + this.producer = producer; + this.outputTopic = outputTopic; + } + + @Override + public Object call() { + @SuppressWarnings("unchecked") + P toBePublished = (P) super.call(); + + if (null != toBePublished) { + producer.send(outputTopic, getRecord().key(), toBePublished); + } + + return toBePublished; + } + + public MessageProducer getProducer() { + return producer; + } + + public void setProducer(MessageProducer producer) { + this.producer = producer; + } + + public String getOutputTopic() { + return outputTopic; + } + + public void setOutputTopic(String outputTopic) { + this.outputTopic = outputTopic; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java index 0fda858a1..1249c47d2 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import java.util.Arrays; -import java.util.concurrent.Executors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author 572682 - * - * This abstract class provides a basic service that subscribes to one - * or more topics and process the received messages in the derived - * classes. - * - * @param - * Message Key type - * @param - * Received Message Value Type - */ -public abstract class AbstractSubscriberProcessor extends MessageProcessor { - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - protected int messagesConsumed = 0; - - /** - * Starts a Kafka listener that runs call() every time a new msg arrives - * - * @param consumer - * @param inputTopics - */ - public void start(MessageConsumer consumer, String... inputTopics) { - logger.info("Subscribing to {}", Arrays.asList(inputTopics).toString()); - - Executors.newSingleThreadExecutor().submit(new Runnable() { - @Override - public void run() { - consumer.subscribe(inputTopics); - } - }); - } - - @Override - public Object call() { - messagesConsumed++; - - S consumedData = getRecord().value(); - - return process(consumedData); - } - - protected abstract Object process(S consumedData); - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import java.util.Arrays; +import java.util.concurrent.Executors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 572682 + * + * This abstract class provides a basic service that subscribes to one + * or more topics and process the received messages in the derived + * classes. + * + * @param + * Message Key type + * @param + * Received Message Value Type + */ +public abstract class AbstractSubscriberProcessor extends MessageProcessor { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + protected int messagesConsumed = 0; + + /** + * Starts a Kafka listener that runs call() every time a new msg arrives + * + * @param consumer + * @param inputTopics + */ + public void start(MessageConsumer consumer, String... inputTopics) { + logger.info("Subscribing to {}", Arrays.asList(inputTopics).toString()); + + Executors.newSingleThreadExecutor().submit(new Runnable() { + @Override + public void run() { + consumer.subscribe(inputTopics); + } + }); + } + + @Override + public Object call() { + messagesConsumed++; + + S consumedData = getRecord().value(); + + return process(consumedData); + } + + protected abstract Object process(S consumedData); + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java index 1c425b9d5..43b5f9d01 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java @@ -1,323 +1,323 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.cookie.Cookie; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This class provides an abstraction layer for making HTTP and HTTPS - * connections to an HTTP server. Follow the steps below to create an HTTP - * client and send HTTP requests to the HTTP server. - * - *

      - *
    1. Call {@link HttpClientFactory#build(SSLContext)} to create a factory - * instance. This factory can be used to create individual HTTP connections - * to an HTTP Server.
    2. - *
    3. Use the obtained factory from step 1 to create a {@link HttpClient} - * object by calling {@link HttpClientFactory#createHttpClient()} method.
    4. - *
    5. Use {@link HttpClient} object to send HTTP GET, POST and other requests - * to the server using {@link HttpClient#get(String, Map, Map)}, - * {@link HttpClient#post(String, Map, Map, String)} methods.
    6. - *
    7. Use the returned {@link HttpResponse} object to retrieve the various - * components of a response including: {@link HttpResponse#getBody()} and - * {@link HttpResponse#getStatusCode()}
    8. - *
    - */ -public class HttpClientFactory { - - private SSLConnectionSocketFactory sslSocketFactory; - - public class HttpClient { - private CloseableHttpClient closeableHttpClient; - private CookieStore cookieStore; - - private HttpClient() { - cookieStore = new BasicCookieStore(); - closeableHttpClient = HttpClientFactory.buildHttpClient(cookieStore, - sslSocketFactory); - } - - /** - * Sends HTTP GET request to server with the given - * headers and specified params. - * - * @param server - to which request will be sent - * @param headers - request headers - * @param params - request query parameters - * @return the server's response. - * @throws HttpException - in case of a problem or the connection was - * aborted or an http protocol error - */ - public HttpResponse get(String server, Map headers, - Map params) throws HttpException { - - try { - RequestBuilder builder = RequestBuilder.get().setUri(server); - - CloseableHttpResponse closeableresponse = executeRequest(headers, - params, builder); - - return new HttpResponse(Response.Status.fromStatusCode(closeableresponse - .getStatusLine().getStatusCode()), - EntityUtils.toString(closeableresponse.getEntity())); - - } catch (Throwable t) { - throw new HttpException(t); - } finally { - } - } - - /** - * Sends HTTP POST request to server with the given - * headers and specified params and body. - * - * @param server - to which request will be sent - * @param headers - request headers - * @param params - request query parameters - * @param body - the body of the post request - * @return the server's response. - * @throws HttpException - in case of a problem or the connection was - * aborted or an http protocol error - */ - public HttpResponse post(String server, Map headers, - Map params, String body) throws HttpException { - - try { - RequestBuilder builder = RequestBuilder.post().setUri(server); - - if (body != null) - builder.setEntity(new StringEntity(body)); - - CloseableHttpResponse closeableresponse = executeRequest(headers, - params, builder); - - return new HttpResponse(Response.Status.fromStatusCode(closeableresponse - .getStatusLine().getStatusCode()), - EntityUtils.toString(closeableresponse.getEntity())); - - } catch (Throwable t) { - throw new HttpException(t); - } finally { - } - } - - /** - * Executes a HTTP Client request using the given parameters. - * - * @param headers - request headers - * @param params - request query parameters - * @param builder - the {@link RequestBuilder} to be used for building the - * request. - * @return the {@link CloseableHttpResponse} returned by the server - * @throws IOException - in case of a problem or the connection was aborted - * @throws ClientProtocolException - in case of an http protocol error - * - */ - private CloseableHttpResponse executeRequest(Map headers, - Map params, RequestBuilder builder) - throws IOException, ClientProtocolException { - if (params != null) { - for (Map.Entry param : params.entrySet()) { - builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue())); - } - } - - HttpUriRequest request = builder.build(); - - if (headers != null) { - for (Map.Entry header : headers.entrySet()){ - request.setHeader(header.getKey(), header.getValue()); - } - } - - CloseableHttpResponse closeableresponse = - closeableHttpClient.execute(request); - return closeableresponse; - } - - /** - * Returns the cookies. - * - * @return - returning the cookie parameters from the HTTP connection. - */ - public Map getCookies() { - ConcurrentHashMap cookies = new ConcurrentHashMap(); - for (Cookie c : cookieStore.getCookies()) { - cookies.put(c.getName(), c.getValue()); - } - - return cookies; - } - - /** - * Closes the connection. - * - * @throws HttpException - in case an I/O error occurs - */ - public void close() throws HttpException { - try { - closeableHttpClient.close(); - } catch (Exception e) { - throw new HttpException(e); - } - } - } - - /** - * Encapsulates an HTTP Response containing the statusCode and - * body of the response which would be the resource returned - * by a REST call. - */ - public class HttpResponse { - private Response.Status statusCode; - private String body; - - /** - * General constructor. - * - * @param statucCode - response status code - * @param body - response body - */ - private HttpResponse(Response.Status statucCode, String body) { - super(); - this.statusCode = statucCode; - this.body = body; - } - - /** - * @return - status code - */ - public Response.Status getStatusCode() { - return statusCode; - } - - /** - * Sets the status code in the response object - * @param statucCode - the status code - * @return the response object. - */ - public HttpResponse setStatusCode(Response.Status statucCode) { - this.statusCode = statucCode; - return this; - } - - /** - * @return the response body. - */ - public String getBody() { - return body; - } - - /** - * Sets the response body/entity. - * - * @param body - the response body/entity. - * @return - the response object. - */ - public HttpResponse setBody(String body) { - this.body = body; - return this; - } - - } - - public class HttpException extends Exception { - - private static final long serialVersionUID = 1L; - - public HttpException(Throwable t) { - super(t); - } - } - - /** - * Builds {@link HttpClientFactory} object which is used to create {@link HttpClient} object. - * - * @param sslContext with which the client factory to be built. - * @return {@link HttpClientFactory} object - * @throws HttpException if building the socket factory fails. - */ - public static HttpClientFactory build(SSLContext sslContext) - throws HttpException { - HttpClientFactory factory = new HttpClientFactory(); - - try { - factory.sslSocketFactory = buildSSLConnectionSocketFactory(sslContext); - } catch (Throwable t) { - throw factory.new HttpException(t); - } - - return factory; - } - - /** - * Builds a {@link SSLConnectionSocketFactory} object - * - * @param sslContext with which the client factory to be built. - * @return SSL connection factory object that is used to create SSL socket - * connections. - */ - private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory( - SSLContext sslContext) { - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); -// , new String[] { "TLSv1" }, null, -// SSLConnectionSocketFactory.getDefaultHostnameVerifier()); - return sslsf; - } - - /** - * Creates a {@link CloseableHttpClient} object. - * @param cookieStore - * or null if no cookies required - * @param sslSocketFactory - * or null if not using SSL - * @return a {@link CloseableHttpClient} object - */ - private static CloseableHttpClient buildHttpClient(CookieStore cookieStore, - SSLConnectionSocketFactory sslSocketFactory) { - return HttpClients.custom().setDefaultCookieStore(cookieStore) - .setSSLSocketFactory(sslSocketFactory).build(); - } - - /** - * Creates a {@link HttpClient} object. - * @return a new {@link HttpClient} object - */ - public HttpClient createHttpClient() { - HttpClient httpClient = new HttpClient(); - - return httpClient; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CookieStore; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.cookie.Cookie; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * This class provides an abstraction layer for making HTTP and HTTPS + * connections to an HTTP server. Follow the steps below to create an HTTP + * client and send HTTP requests to the HTTP server. + * + *
      + *
    1. Call {@link HttpClientFactory#build(SSLContext)} to create a factory + * instance. This factory can be used to create individual HTTP connections + * to an HTTP Server.
    2. + *
    3. Use the obtained factory from step 1 to create a {@link HttpClient} + * object by calling {@link HttpClientFactory#createHttpClient()} method.
    4. + *
    5. Use {@link HttpClient} object to send HTTP GET, POST and other requests + * to the server using {@link HttpClient#get(String, Map, Map)}, + * {@link HttpClient#post(String, Map, Map, String)} methods.
    6. + *
    7. Use the returned {@link HttpResponse} object to retrieve the various + * components of a response including: {@link HttpResponse#getBody()} and + * {@link HttpResponse#getStatusCode()}
    8. + *
    + */ +public class HttpClientFactory { + + private SSLConnectionSocketFactory sslSocketFactory; + + public class HttpClient { + private CloseableHttpClient closeableHttpClient; + private CookieStore cookieStore; + + private HttpClient() { + cookieStore = new BasicCookieStore(); + closeableHttpClient = HttpClientFactory.buildHttpClient(cookieStore, + sslSocketFactory); + } + + /** + * Sends HTTP GET request to server with the given + * headers and specified params. + * + * @param server - to which request will be sent + * @param headers - request headers + * @param params - request query parameters + * @return the server's response. + * @throws HttpException - in case of a problem or the connection was + * aborted or an http protocol error + */ + public HttpResponse get(String server, Map headers, + Map params) throws HttpException { + + try { + RequestBuilder builder = RequestBuilder.get().setUri(server); + + CloseableHttpResponse closeableresponse = executeRequest(headers, + params, builder); + + return new HttpResponse(Response.Status.fromStatusCode(closeableresponse + .getStatusLine().getStatusCode()), + EntityUtils.toString(closeableresponse.getEntity())); + + } catch (Throwable t) { + throw new HttpException(t); + } finally { + } + } + + /** + * Sends HTTP POST request to server with the given + * headers and specified params and body. + * + * @param server - to which request will be sent + * @param headers - request headers + * @param params - request query parameters + * @param body - the body of the post request + * @return the server's response. + * @throws HttpException - in case of a problem or the connection was + * aborted or an http protocol error + */ + public HttpResponse post(String server, Map headers, + Map params, String body) throws HttpException { + + try { + RequestBuilder builder = RequestBuilder.post().setUri(server); + + if (body != null) + builder.setEntity(new StringEntity(body)); + + CloseableHttpResponse closeableresponse = executeRequest(headers, + params, builder); + + return new HttpResponse(Response.Status.fromStatusCode(closeableresponse + .getStatusLine().getStatusCode()), + EntityUtils.toString(closeableresponse.getEntity())); + + } catch (Throwable t) { + throw new HttpException(t); + } finally { + } + } + + /** + * Executes a HTTP Client request using the given parameters. + * + * @param headers - request headers + * @param params - request query parameters + * @param builder - the {@link RequestBuilder} to be used for building the + * request. + * @return the {@link CloseableHttpResponse} returned by the server + * @throws IOException - in case of a problem or the connection was aborted + * @throws ClientProtocolException - in case of an http protocol error + * + */ + private CloseableHttpResponse executeRequest(Map headers, + Map params, RequestBuilder builder) + throws IOException, ClientProtocolException { + if (params != null) { + for (Map.Entry param : params.entrySet()) { + builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue())); + } + } + + HttpUriRequest request = builder.build(); + + if (headers != null) { + for (Map.Entry header : headers.entrySet()){ + request.setHeader(header.getKey(), header.getValue()); + } + } + + CloseableHttpResponse closeableresponse = + closeableHttpClient.execute(request); + return closeableresponse; + } + + /** + * Returns the cookies. + * + * @return - returning the cookie parameters from the HTTP connection. + */ + public Map getCookies() { + ConcurrentHashMap cookies = new ConcurrentHashMap(); + for (Cookie c : cookieStore.getCookies()) { + cookies.put(c.getName(), c.getValue()); + } + + return cookies; + } + + /** + * Closes the connection. + * + * @throws HttpException - in case an I/O error occurs + */ + public void close() throws HttpException { + try { + closeableHttpClient.close(); + } catch (Exception e) { + throw new HttpException(e); + } + } + } + + /** + * Encapsulates an HTTP Response containing the statusCode and + * body of the response which would be the resource returned + * by a REST call. + */ + public class HttpResponse { + private Response.Status statusCode; + private String body; + + /** + * General constructor. + * + * @param statucCode - response status code + * @param body - response body + */ + private HttpResponse(Response.Status statucCode, String body) { + super(); + this.statusCode = statucCode; + this.body = body; + } + + /** + * @return - status code + */ + public Response.Status getStatusCode() { + return statusCode; + } + + /** + * Sets the status code in the response object + * @param statucCode - the status code + * @return the response object. + */ + public HttpResponse setStatusCode(Response.Status statucCode) { + this.statusCode = statucCode; + return this; + } + + /** + * @return the response body. + */ + public String getBody() { + return body; + } + + /** + * Sets the response body/entity. + * + * @param body - the response body/entity. + * @return - the response object. + */ + public HttpResponse setBody(String body) { + this.body = body; + return this; + } + + } + + public class HttpException extends Exception { + + private static final long serialVersionUID = 1L; + + public HttpException(Throwable t) { + super(t); + } + } + + /** + * Builds {@link HttpClientFactory} object which is used to create {@link HttpClient} object. + * + * @param sslContext with which the client factory to be built. + * @return {@link HttpClientFactory} object + * @throws HttpException if building the socket factory fails. + */ + public static HttpClientFactory build(SSLContext sslContext) + throws HttpException { + HttpClientFactory factory = new HttpClientFactory(); + + try { + factory.sslSocketFactory = buildSSLConnectionSocketFactory(sslContext); + } catch (Throwable t) { + throw factory.new HttpException(t); + } + + return factory; + } + + /** + * Builds a {@link SSLConnectionSocketFactory} object + * + * @param sslContext with which the client factory to be built. + * @return SSL connection factory object that is used to create SSL socket + * connections. + */ + private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory( + SSLContext sslContext) { + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); +// , new String[] { "TLSv1" }, null, +// SSLConnectionSocketFactory.getDefaultHostnameVerifier()); + return sslsf; + } + + /** + * Creates a {@link CloseableHttpClient} object. + * @param cookieStore + * or null if no cookies required + * @param sslSocketFactory + * or null if not using SSL + * @return a {@link CloseableHttpClient} object + */ + private static CloseableHttpClient buildHttpClient(CookieStore cookieStore, + SSLConnectionSocketFactory sslSocketFactory) { + return HttpClients.custom().setDefaultCookieStore(cookieStore) + .setSSLSocketFactory(sslSocketFactory).build(); + } + + /** + * Creates a {@link HttpClient} object. + * @return a new {@link HttpClient} object + */ + public HttpClient createHttpClient() { + HttpClient httpClient = new HttpClient(); + + return httpClient; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java index 571ef5eb6..75b9b03bf 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java @@ -1,99 +1,99 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import java.io.InputStream; -import java.security.KeyStore; - -import javax.net.ssl.SSLContext; - -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; - -/** - * This class is used to build a SSL Context - */ -public class SSLBuilder { - - /** - * Creates SSL context. - * To create a custom SSLContext that accepts CA and self-signed certs, - * pass a valid keystoreStream and keystorePass. To create a default SSLContext - * pass null for keystoreStream; - * - * @param keystoreStream - * Input Stream of the keystore file. If null, a default SSL context - * will be created. - * @param keystorePass - * The password required to access the Keystore file. If null, - * blank is passed as password. - * - * @return SSLContext object - * @throws SSLException - * - if no Provider supports a KeyStoreSpi implementation for the specified type. - * - if an I/O error occurs - * - or any other causes will be attached to the exception. - */ - public static SSLContext buildSSLContext( - InputStream keystoreStream, - String keystorePass) throws SSLException { - - SSLContext sslcontext = null; - try { - if (keystoreStream != null) { // Create custom context - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - - - try { - keystore.load(keystoreStream, - keystorePass == null ? "".toCharArray() : - keystorePass.toCharArray()); - } finally { - keystoreStream.close(); - } - - // Trust own CA and all self-signed certs - sslcontext = SSLContexts.custom() - .loadTrustMaterial(keystore, new TrustSelfSignedStrategy()) - .build(); - } else { //get the default context - sslcontext = SSLContexts.createDefault(); - } - } catch (Exception e) { - throw new SSLException(e); - } - return sslcontext; - } - - /** - * The exception thrown when errors occur within this class - */ - public static class SSLException extends Exception { - - - private static final long serialVersionUID = 1L; - - public SSLException(String string) { - super(string); - } - - public SSLException(Exception e) { - super(e); - } - - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import java.io.InputStream; +import java.security.KeyStore; + +import javax.net.ssl.SSLContext; + +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; + +/** + * This class is used to build a SSL Context + */ +public class SSLBuilder { + + /** + * Creates SSL context. + * To create a custom SSLContext that accepts CA and self-signed certs, + * pass a valid keystoreStream and keystorePass. To create a default SSLContext + * pass null for keystoreStream; + * + * @param keystoreStream + * Input Stream of the keystore file. If null, a default SSL context + * will be created. + * @param keystorePass + * The password required to access the Keystore file. If null, + * blank is passed as password. + * + * @return SSLContext object + * @throws SSLException + * - if no Provider supports a KeyStoreSpi implementation for the specified type. + * - if an I/O error occurs + * - or any other causes will be attached to the exception. + */ + public static SSLContext buildSSLContext( + InputStream keystoreStream, + String keystorePass) throws SSLException { + + SSLContext sslcontext = null; + try { + if (keystoreStream != null) { // Create custom context + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + + + try { + keystore.load(keystoreStream, + keystorePass == null ? "".toCharArray() : + keystorePass.toCharArray()); + } finally { + keystoreStream.close(); + } + + // Trust own CA and all self-signed certs + sslcontext = SSLContexts.custom() + .loadTrustMaterial(keystore, new TrustSelfSignedStrategy()) + .build(); + } else { //get the default context + sslcontext = SSLContexts.createDefault(); + } + } catch (Exception e) { + throw new SSLException(e); + } + return sslcontext; + } + + /** + * The exception thrown when errors occur within this class + */ + public static class SSLException extends Exception { + + + private static final long serialVersionUID = 1L; + + public SSLException(String string) { + super(string); + } + + public SSLException(Exception e) { + super(e); + } + + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java index ba627e6a3..23dd48ebf 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import javax.websocket.Decoder; - -/** - * This interface abstracts the use of {@link Decoder.Text} from the rest of - * the application. - * - * @param - the type of object being decoded by this decoder. - */ -public interface WebSocketMessageDecoder extends Decoder.Text { - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import javax.websocket.Decoder; + +/** + * This interface abstracts the use of {@link Decoder.Text} from the rest of + * the application. + * + * @param - the type of object being decoded by this decoder. + */ +public interface WebSocketMessageDecoder extends Decoder.Text { + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java index 8d9a64ecf..d61c59802 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import javax.websocket.CloseReason; -import javax.websocket.EndpointConfig; -import javax.websocket.MessageHandler; -import javax.websocket.Session; - -/** - * This interface abstracts the use of {@link MessageHandler.Whole} from the - * rest of the application. - * - * @param - the type of message being handled by this message handler. - */ -public interface WebSocketMessageHandler extends MessageHandler.Whole { - - void onOpen(Session session, EndpointConfig config); - - void onClose(Session session, CloseReason reason); - - void onError(Session session, Throwable t); - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import javax.websocket.CloseReason; +import javax.websocket.EndpointConfig; +import javax.websocket.MessageHandler; +import javax.websocket.Session; + +/** + * This interface abstracts the use of {@link MessageHandler.Whole} from the + * rest of the application. + * + * @param - the type of message being handled by this message handler. + */ +public interface WebSocketMessageHandler extends MessageHandler.Whole { + + void onOpen(Session session, EndpointConfig config); + + void onClose(Session session, CloseReason reason); + + void onError(Session session, Throwable t); + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java index 9cdc0df3a..9cdf91962 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; - -import us.dot.its.jpo.ode.model.OdeTimData; - -public class OdeTimDeserializer extends MessagingDeserializer { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; + +import us.dot.its.jpo.ode.model.OdeTimData; + +public class OdeTimDeserializer extends MessagingDeserializer { + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java index 59e508f9e..08e468655 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; - -import us.dot.its.jpo.ode.model.OdeTimData; - -public class OdeTimSerializer extends MessagingSerializer { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; + +import us.dot.its.jpo.ode.model.OdeTimData; + +public class OdeTimSerializer extends MessagingSerializer { + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java index 5d5722f20..0c644f6ab 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java @@ -1,527 +1,527 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.core.Response.Status; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; -import us.dot.its.jpo.ode.dds.CASClient.CASException; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpClient; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpException; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpResponse; - -@RunWith(JMockit.class) -public class CASClientTest { - @Mocked HttpClientFactory mockHttpClientFactory; - @Mocked SSLContext sslContext; - @Mocked private HttpResponse mockResponse; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the following very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - * -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running us.dot.its.jpo.ode.asn1.j2735.CVMessageTest -Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.673 sec - in us.dot.its.jpo.ode.asn1.j2735.CVMessageTest -Running us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest -01:20:03.199 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehicleSituationDataServiceRequest.uper into object ServiceRequest -01:20:03.227 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehSitDataMessage.uper into object VehSitDataMessage -2017-05-29 05:20:03.239 UTC -2017-05-29 05:21:03.000 UTC -Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.25 sec - in us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest -Running us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest -Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec - in us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest -Running us.dot.its.jpo.ode.dds.CASClientTest -Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.521 sec - in us.dot.its.jpo.ode.dds.CASClientTest -Running us.dot.its.jpo.ode.dds.DdsClientTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsClientTest -us.dot.its.jpo.ode.dds.DdsClientTest Time elapsed: 0.01 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsDepRequestTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsDepRequestTest -us.dot.its.jpo.ode.dds.DdsDepRequestTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsRequestTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.002 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsRequestTest -us.dot.its.jpo.ode.dds.DdsRequestTest Time elapsed: 0.002 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.016 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest -us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest Time elapsed: 0.016 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsStatusMessageTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageTest -us.dot.its.jpo.ode.dds.DdsStatusMessageTest Time elapsed: 0.003 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DepositResponseDecoderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DepositResponseDecoderTest -us.dot.its.jpo.ode.dds.DepositResponseDecoderTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.StatusMessageHandlerTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.StatusMessageHandlerTest -us.dot.its.jpo.ode.dds.StatusMessageHandlerTest Time elapsed: 0.011 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.model.J2735GeoRegionTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in us.dot.its.jpo.ode.model.J2735GeoRegionTest -us.dot.its.jpo.ode.model.J2735GeoRegionTest Time elapsed: 0.001 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.snmp.SNMPTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.snmp.SNMPTest -us.dot.its.jpo.ode.snmp.SNMPTest Time elapsed: 0.01 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.DateTimeUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.DateTimeUtilsTest -us.dot.its.jpo.ode.util.DateTimeUtilsTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.GeoUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.GeoUtilsTest -us.dot.its.jpo.ode.util.GeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.JsonUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.JsonUtilsTest -us.dot.its.jpo.ode.util.JsonUtilsTest Time elapsed: 0.003 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.OdeGeoUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.OdeGeoUtilsTest -us.dot.its.jpo.ode.util.OdeGeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest -us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest Time elapsed: 0.005 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.HttpClientTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientTest -us.dot.its.jpo.ode.wrapper.HttpClientTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.SSLBuilderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.015 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.SSLBuilderTest -us.dot.its.jpo.ode.wrapper.SSLBuilderTest Time elapsed: 0.015 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest -us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0 - -Results : - -Tests in error: - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - -Tests run: 26, Failures: 0, Errors: 17, Skipped: 0 - -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD FAILURE -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 7.387 s -[INFO] Finished at: 2017-05-29T01:20:05-04:00 -[INFO] Final Memory: 19M/227M -[INFO] ------------------------------------------------------------------------ -[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project jpo-ode-core: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process -[ERROR] org.apache.maven.surefire.testset.TestSetFailedException: java.lang.NullPointerException -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures(JUnit4RunListener.java:209) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:169) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) -[ERROR] Caused by: java.lang.NullPointerException -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.extractClassName(JUnit4RunListener.java:188) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.getClassName(JUnit4RunListener.java:157) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.createReportEntry(JUnit4RunListener.java:181) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.testFinished(JUnit4RunListener.java:143) -[ERROR] at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56) -[ERROR] at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190) -[ERROR] at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72) -[ERROR] at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187) -[ERROR] at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38) -[ERROR] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331) -[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) -[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) -[ERROR] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) -[ERROR] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) -[ERROR] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) -[ERROR] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) -[ERROR] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) -[ERROR] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) -[ERROR] ... 3 more -[ERROR] -[ERROR] -> [Help 1] -[ERROR] -[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. -[ERROR] Re-run Maven using the -X switch to enable full debug logging. -[ERROR] -[ERROR] For more information about the errors and possible solutions, please read the following articles: -[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException - * - */ -// @Mocked private Pattern mockPattern; -// @Mocked private Matcher mockMatcher; - - String casUser = "testUser"; - String casPass = "testPass"; - String casUrl = "testUrl"; - - @Test - public void testConfigure() { - CASClient casClient = null; - try { - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - } catch (CASException e) { - fail("Unexpected exception: " + e.toString()); - } - assertEquals(casClient.getDdsCasUrl(), casUrl); - assertEquals(casClient.getDdsCasUsername(), casUser); - } - - @Test(expected = CASException.class) - public void testConfigureException() - throws CASException, HttpException { - new Expectations() { - { - HttpClientFactory.build((SSLContext) any); - result = new Exception(); - } - }; - CASClient.configure(sslContext, casUrl, casUser, casPass); - } - - @SuppressWarnings("unchecked") - @Test - public void testLogin() throws HttpException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.OK; - result = Status.OK; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - - mockHttpClientFactory.createHttpClient().getCookies(); - result = cookies; - } - }; - - CASClient casClient; - String sessionId = ""; - try { - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - sessionId = casClient.login(websocketURL); - assertEquals(casClient.getSessionID(), sessionId); - assertEquals("1bif45f-testSessionId", sessionId); - } catch (CASException e) { - fail("Unexpected exception: " + e.toString()); - } - - new Verifications() { - { - HttpClient httpClient = mockHttpClientFactory.createHttpClient(); - minTimes = 3; - - httpClient.post(anyString, null, (Map) any, anyString); - minTimes = 2; - - httpClient.get(anyString, null, (Map) any); - minTimes = 1; - - httpClient.close(); - minTimes = 3; - - Pattern.compile(anyString); - } - }; - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetTicket1() throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.BAD_REQUEST; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetTicket2() throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = false; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetServiceTicket() - throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.BAD_REQUEST; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - - @Test(expected = CASException.class) - public void testLoginExceptionInGetServiceCall() - throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.OK; - result = Status.BAD_REQUEST; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - - } - }; - - CASClient casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.core.Response.Status; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; +import us.dot.its.jpo.ode.dds.CASClient.CASException; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpClient; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpException; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpResponse; + +@RunWith(JMockit.class) +public class CASClientTest { + @Mocked HttpClientFactory mockHttpClientFactory; + @Mocked SSLContext sslContext; + @Mocked private HttpResponse mockResponse; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the following very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + * +------------------------------------------------------- + T E S T S +------------------------------------------------------- +Running us.dot.its.jpo.ode.asn1.j2735.CVMessageTest +Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.673 sec - in us.dot.its.jpo.ode.asn1.j2735.CVMessageTest +Running us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest +01:20:03.199 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehicleSituationDataServiceRequest.uper into object ServiceRequest +01:20:03.227 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehSitDataMessage.uper into object VehSitDataMessage +2017-05-29 05:20:03.239 UTC +2017-05-29 05:21:03.000 UTC +Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.25 sec - in us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest +Running us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest +Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec - in us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest +Running us.dot.its.jpo.ode.dds.CASClientTest +Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.521 sec - in us.dot.its.jpo.ode.dds.CASClientTest +Running us.dot.its.jpo.ode.dds.DdsClientTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsClientTest +us.dot.its.jpo.ode.dds.DdsClientTest Time elapsed: 0.01 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsDepRequestTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsDepRequestTest +us.dot.its.jpo.ode.dds.DdsDepRequestTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsRequestTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.002 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsRequestTest +us.dot.its.jpo.ode.dds.DdsRequestTest Time elapsed: 0.002 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.016 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest +us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest Time elapsed: 0.016 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsStatusMessageTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageTest +us.dot.its.jpo.ode.dds.DdsStatusMessageTest Time elapsed: 0.003 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DepositResponseDecoderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DepositResponseDecoderTest +us.dot.its.jpo.ode.dds.DepositResponseDecoderTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.StatusMessageHandlerTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.StatusMessageHandlerTest +us.dot.its.jpo.ode.dds.StatusMessageHandlerTest Time elapsed: 0.011 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.model.J2735GeoRegionTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in us.dot.its.jpo.ode.model.J2735GeoRegionTest +us.dot.its.jpo.ode.model.J2735GeoRegionTest Time elapsed: 0.001 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.snmp.SNMPTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.snmp.SNMPTest +us.dot.its.jpo.ode.snmp.SNMPTest Time elapsed: 0.01 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.DateTimeUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.DateTimeUtilsTest +us.dot.its.jpo.ode.util.DateTimeUtilsTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.GeoUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.GeoUtilsTest +us.dot.its.jpo.ode.util.GeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.JsonUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.JsonUtilsTest +us.dot.its.jpo.ode.util.JsonUtilsTest Time elapsed: 0.003 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.OdeGeoUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.OdeGeoUtilsTest +us.dot.its.jpo.ode.util.OdeGeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest +us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest Time elapsed: 0.005 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.HttpClientTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientTest +us.dot.its.jpo.ode.wrapper.HttpClientTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.SSLBuilderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.015 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.SSLBuilderTest +us.dot.its.jpo.ode.wrapper.SSLBuilderTest Time elapsed: 0.015 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest +us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0 + +Results : + +Tests in error: + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + +Tests run: 26, Failures: 0, Errors: 17, Skipped: 0 + +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD FAILURE +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 7.387 s +[INFO] Finished at: 2017-05-29T01:20:05-04:00 +[INFO] Final Memory: 19M/227M +[INFO] ------------------------------------------------------------------------ +[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project jpo-ode-core: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process +[ERROR] org.apache.maven.surefire.testset.TestSetFailedException: java.lang.NullPointerException +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures(JUnit4RunListener.java:209) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:169) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) +[ERROR] Caused by: java.lang.NullPointerException +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.extractClassName(JUnit4RunListener.java:188) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.getClassName(JUnit4RunListener.java:157) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.createReportEntry(JUnit4RunListener.java:181) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.testFinished(JUnit4RunListener.java:143) +[ERROR] at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56) +[ERROR] at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190) +[ERROR] at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72) +[ERROR] at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187) +[ERROR] at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38) +[ERROR] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331) +[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) +[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) +[ERROR] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) +[ERROR] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) +[ERROR] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) +[ERROR] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) +[ERROR] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) +[ERROR] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) +[ERROR] ... 3 more +[ERROR] +[ERROR] -> [Help 1] +[ERROR] +[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. +[ERROR] Re-run Maven using the -X switch to enable full debug logging. +[ERROR] +[ERROR] For more information about the errors and possible solutions, please read the following articles: +[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException + * + */ +// @Mocked private Pattern mockPattern; +// @Mocked private Matcher mockMatcher; + + String casUser = "testUser"; + String casPass = "testPass"; + String casUrl = "testUrl"; + + @Test + public void testConfigure() { + CASClient casClient = null; + try { + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + } catch (CASException e) { + fail("Unexpected exception: " + e.toString()); + } + assertEquals(casClient.getDdsCasUrl(), casUrl); + assertEquals(casClient.getDdsCasUsername(), casUser); + } + + @Test(expected = CASException.class) + public void testConfigureException() + throws CASException, HttpException { + new Expectations() { + { + HttpClientFactory.build((SSLContext) any); + result = new Exception(); + } + }; + CASClient.configure(sslContext, casUrl, casUser, casPass); + } + + @SuppressWarnings("unchecked") + @Test + public void testLogin() throws HttpException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.OK; + result = Status.OK; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + + mockHttpClientFactory.createHttpClient().getCookies(); + result = cookies; + } + }; + + CASClient casClient; + String sessionId = ""; + try { + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + sessionId = casClient.login(websocketURL); + assertEquals(casClient.getSessionID(), sessionId); + assertEquals("1bif45f-testSessionId", sessionId); + } catch (CASException e) { + fail("Unexpected exception: " + e.toString()); + } + + new Verifications() { + { + HttpClient httpClient = mockHttpClientFactory.createHttpClient(); + minTimes = 3; + + httpClient.post(anyString, null, (Map) any, anyString); + minTimes = 2; + + httpClient.get(anyString, null, (Map) any); + minTimes = 1; + + httpClient.close(); + minTimes = 3; + + Pattern.compile(anyString); + } + }; + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetTicket1() throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.BAD_REQUEST; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetTicket2() throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = false; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetServiceTicket() + throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.BAD_REQUEST; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + + @Test(expected = CASException.class) + public void testLoginExceptionInGetServiceCall() + throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.OK; + result = Status.BAD_REQUEST; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + + } + }; + + CASClient casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java index 7d349d230..61dc913c6 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java @@ -1,142 +1,142 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import java.io.InputStream; -import java.net.URI; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLContext; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; -import us.dot.its.jpo.ode.dds.CASClient.CASException; -import us.dot.its.jpo.ode.dds.DdsClient.DdsClientException; -import us.dot.its.jpo.ode.wrapper.SSLBuilder; -import us.dot.its.jpo.ode.wrapper.WebSocketEndpoint; -import us.dot.its.jpo.ode.wrapper.WebSocketMessageDecoder; -import us.dot.its.jpo.ode.wrapper.WebSocketMessageHandler; - -@RunWith(JMockit.class) -public class DdsClientTest { - @Mocked private WebSocketMessageHandler mockMessageHandler; - @Mocked private CASClient mockCasClient; - - String ddsCasUrl = "ddsCasUrl"; - String ddsCasUsername = "ddsCasUsername"; - String ddsCasPassword = "ddsCasPassword"; - String websocketURL = "ws://websocket.org"; - String keystoreFile = "keystoreFile"; - String keystorePass = "keystorePass"; - - @Ignore - @Test - public void testConstructor() { - try { - new Expectations() { - { - CASClient.configure((SSLContext) any, anyString, anyString, anyString); - } - }; - } catch (CASException e1) { - e1.printStackTrace(); - } - - try { - new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); - } catch (DdsClientException e) { - e.printStackTrace(); - } - - try { - new Verifications() { - { - new URI("websocketURL"); - minTimes = 1; - CASClient.class.getClassLoader().getResourceAsStream("keystoreFile"); - SSLBuilder.buildSSLContext((InputStream) any, "keystorePass"); - } - }; - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Ignore - @Test(expected = DdsClientException.class) - public void testConstructorException() - throws DdsClientException, CASException { - - new Expectations() { - { - CASClient.configure((SSLContext) any, anyString, anyString, anyString); - result = new Exception(); - } - }; - - new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); - } - - @SuppressWarnings("unchecked") - @Ignore - @Test - public void testLogin() { - try { - DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, - keystoreFile, keystorePass); - ddsClient.login(null, mockMessageHandler); - - new Verifications() { - { - mockCasClient.login(anyString); - new WebSocketEndpoint((URI) any, (SSLContext) any, null, - (Map>) any, (WebSocketMessageHandler) any, - (List>>) any); - } - }; - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Ignore - @SuppressWarnings("unchecked") - @Test(expected = DdsClientException.class) - public void testLoginException() - throws DdsClientException, CASException { - - new Expectations() { - { - mockCasClient.login(anyString); - new WebSocketEndpoint((URI) any, (SSLContext) any, null, (Map>) any, - (WebSocketMessageHandler) any, (List>>) any); - result = new DdsClientException(null); - } - }; - - DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, - keystoreFile, keystorePass); - ddsClient.login(null, mockMessageHandler); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import java.io.InputStream; +import java.net.URI; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLContext; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; +import us.dot.its.jpo.ode.dds.CASClient.CASException; +import us.dot.its.jpo.ode.dds.DdsClient.DdsClientException; +import us.dot.its.jpo.ode.wrapper.SSLBuilder; +import us.dot.its.jpo.ode.wrapper.WebSocketEndpoint; +import us.dot.its.jpo.ode.wrapper.WebSocketMessageDecoder; +import us.dot.its.jpo.ode.wrapper.WebSocketMessageHandler; + +@RunWith(JMockit.class) +public class DdsClientTest { + @Mocked private WebSocketMessageHandler mockMessageHandler; + @Mocked private CASClient mockCasClient; + + String ddsCasUrl = "ddsCasUrl"; + String ddsCasUsername = "ddsCasUsername"; + String ddsCasPassword = "ddsCasPassword"; + String websocketURL = "ws://websocket.org"; + String keystoreFile = "keystoreFile"; + String keystorePass = "keystorePass"; + + @Ignore + @Test + public void testConstructor() { + try { + new Expectations() { + { + CASClient.configure((SSLContext) any, anyString, anyString, anyString); + } + }; + } catch (CASException e1) { + e1.printStackTrace(); + } + + try { + new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); + } catch (DdsClientException e) { + e.printStackTrace(); + } + + try { + new Verifications() { + { + new URI("websocketURL"); + minTimes = 1; + CASClient.class.getClassLoader().getResourceAsStream("keystoreFile"); + SSLBuilder.buildSSLContext((InputStream) any, "keystorePass"); + } + }; + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Ignore + @Test(expected = DdsClientException.class) + public void testConstructorException() + throws DdsClientException, CASException { + + new Expectations() { + { + CASClient.configure((SSLContext) any, anyString, anyString, anyString); + result = new Exception(); + } + }; + + new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); + } + + @SuppressWarnings("unchecked") + @Ignore + @Test + public void testLogin() { + try { + DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, + keystoreFile, keystorePass); + ddsClient.login(null, mockMessageHandler); + + new Verifications() { + { + mockCasClient.login(anyString); + new WebSocketEndpoint((URI) any, (SSLContext) any, null, + (Map>) any, (WebSocketMessageHandler) any, + (List>>) any); + } + }; + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Ignore + @SuppressWarnings("unchecked") + @Test(expected = DdsClientException.class) + public void testLoginException() + throws DdsClientException, CASException { + + new Expectations() { + { + mockCasClient.login(anyString); + new WebSocketEndpoint((URI) any, (SSLContext) any, null, (Map>) any, + (WebSocketMessageHandler) any, (List>>) any); + result = new DdsClientException(null); + } + }; + + DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, + keystoreFile, keystorePass); + ddsClient.login(null, mockMessageHandler); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java index 256225340..f76f34079 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; -import org.junit.Test; - -public class DdsDepRequestTest { - - @Test - public void testSystemDepositName() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String depositName = "test deposit name"; - ddsDepRequest.setSystemDepositName(depositName); - assertEquals(depositName, ddsDepRequest.getSystemDepositName()); - } - - @Test - public void testEncodeType() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodeType = "hex"; - ddsDepRequest.setEncodeType(encodeType); - assertEquals(encodeType, ddsDepRequest.getEncodeType()); - assertNotEquals("base64", ddsDepRequest.getEncodeType()); - } - - @Test - public void testEncodedMsg() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodedMsg = "Sample Encode Msg"; - ddsDepRequest.setEncodedMsg(encodedMsg); - assertEquals(encodedMsg, ddsDepRequest.getEncodedMsg()); - assertNotEquals("invalid encoded msg", ddsDepRequest.getEncodedMsg()); - } - - @Test - public void testToString() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodedMsg = "testEncodeMsg"; - String encodeType = "hex"; - String depositName = "testDepositName"; - - ddsDepRequest.setEncodeType(encodedMsg); - ddsDepRequest.setEncodeType(encodeType); - ddsDepRequest.setSystemDepositName(depositName); - String expectedStr = "DEPOSIT:{\"systemDepositName\":\"testDepositName\",\"encodeType\":\"hex\",\"dialogID\":0}"; - assertEquals(ddsDepRequest.toString(), expectedStr); - } - - @Test - public void testHashCode() { - DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); - DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - String encodeType = "hex"; - ddsDepRequest1.setEncodeType(encodeType); - assertNotEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - ddsDepRequest2.setEncodeType(encodeType); - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - String encodedMsg = "testEncodeMsg"; - ddsDepRequest1.setEncodedMsg(encodedMsg); - ddsDepRequest2.setEncodedMsg(encodedMsg); - - String depositName = "testDepositName"; - ddsDepRequest1.setSystemDepositName(depositName); - ddsDepRequest2.setSystemDepositName(depositName); - - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - } - - @Test - public void testEquals() { - DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); - DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); - Object randomObject = new Object(); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - assertTrue(ddsDepRequest1.equals(ddsDepRequest1)); - assertFalse(ddsDepRequest1.equals(randomObject)); - assertFalse(ddsDepRequest1.equals(null)); - - ddsDepRequest2.setEncodeType("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String encodeType = "hex"; - ddsDepRequest1.setEncodeType(encodeType); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodeType(encodeType); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodedMsg("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String encodedMsg = "testEncodeMsg"; - ddsDepRequest1.setEncodedMsg(encodedMsg); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodedMsg(encodedMsg); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setSystemDepositName("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String depositName = "testDepositName"; - ddsDepRequest1.setSystemDepositName(depositName); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setSystemDepositName(depositName); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - } - - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class DdsDepRequestTest { + + @Test + public void testSystemDepositName() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String depositName = "test deposit name"; + ddsDepRequest.setSystemDepositName(depositName); + assertEquals(depositName, ddsDepRequest.getSystemDepositName()); + } + + @Test + public void testEncodeType() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodeType = "hex"; + ddsDepRequest.setEncodeType(encodeType); + assertEquals(encodeType, ddsDepRequest.getEncodeType()); + assertNotEquals("base64", ddsDepRequest.getEncodeType()); + } + + @Test + public void testEncodedMsg() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodedMsg = "Sample Encode Msg"; + ddsDepRequest.setEncodedMsg(encodedMsg); + assertEquals(encodedMsg, ddsDepRequest.getEncodedMsg()); + assertNotEquals("invalid encoded msg", ddsDepRequest.getEncodedMsg()); + } + + @Test + public void testToString() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodedMsg = "testEncodeMsg"; + String encodeType = "hex"; + String depositName = "testDepositName"; + + ddsDepRequest.setEncodeType(encodedMsg); + ddsDepRequest.setEncodeType(encodeType); + ddsDepRequest.setSystemDepositName(depositName); + String expectedStr = "DEPOSIT:{\"systemDepositName\":\"testDepositName\",\"encodeType\":\"hex\",\"dialogID\":0}"; + assertEquals(ddsDepRequest.toString(), expectedStr); + } + + @Test + public void testHashCode() { + DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); + DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + String encodeType = "hex"; + ddsDepRequest1.setEncodeType(encodeType); + assertNotEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + ddsDepRequest2.setEncodeType(encodeType); + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + String encodedMsg = "testEncodeMsg"; + ddsDepRequest1.setEncodedMsg(encodedMsg); + ddsDepRequest2.setEncodedMsg(encodedMsg); + + String depositName = "testDepositName"; + ddsDepRequest1.setSystemDepositName(depositName); + ddsDepRequest2.setSystemDepositName(depositName); + + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + } + + @Test + public void testEquals() { + DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); + DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); + Object randomObject = new Object(); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + assertTrue(ddsDepRequest1.equals(ddsDepRequest1)); + assertFalse(ddsDepRequest1.equals(randomObject)); + assertFalse(ddsDepRequest1.equals(null)); + + ddsDepRequest2.setEncodeType("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String encodeType = "hex"; + ddsDepRequest1.setEncodeType(encodeType); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodeType(encodeType); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodedMsg("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String encodedMsg = "testEncodeMsg"; + ddsDepRequest1.setEncodedMsg(encodedMsg); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodedMsg(encodedMsg); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setSystemDepositName("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String depositName = "testDepositName"; + ddsDepRequest1.setSystemDepositName(depositName); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setSystemDepositName(depositName); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + } + + + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java index dd2fac010..b0464a5c2 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java @@ -1,123 +1,123 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.dds.DdsRequest.EncodeType; -import us.dot.its.jpo.ode.dds.DdsRequest.SystemName; - -public class DdsRequestTest { - - private DdsRequest ddsRequest; - - @Before - public void setUp() throws Exception { - ddsRequest = new DdsRequest(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testDialogEnum() { - Dialog dialog = Dialog.ASD; - - assertEquals(Dialog.ISD, Dialog.getById(162)); - assertEquals(156, dialog.getId()); - assertNull(Dialog.getById(999)); - } - - @Test - public void testSystemNameEnum() { - SystemName systemName = SystemName.SDC; - assertEquals("SDC 2.3", systemName.getName()); - } - - @Test - public void testDialogId() { - ddsRequest.setDialogID(156); - assertEquals(156, ddsRequest.getDialogID()); - } - - @Test - public void testResultEncoding() { - String encodingType = "hex"; - ddsRequest.setResultEncoding(encodingType); - assertEquals(encodingType, ddsRequest.getResultEncoding()); - } - - @Test - public void testHashCode() { - int hashCode1, hashCode2; - DdsRequest ddsRequest2 = new DdsRequest(); - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - - ddsRequest2.setResultEncoding("hex"); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertNotEquals(hashCode1, hashCode2); - - ddsRequest.setResultEncoding("hex"); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - - ddsRequest2.setDialogID(156); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertNotEquals(hashCode1, hashCode2); - - ddsRequest.setDialogID(156); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - } - - @Test - public void testEquals() { - EncodeType encodeType = EncodeType.HEX; - DdsRequest ddsRequest2 = new DdsRequest(); - assertTrue(ddsRequest.equals(ddsRequest2)); - - ddsRequest2.setResultEncoding(encodeType.name()); - assertFalse(ddsRequest.equals(ddsRequest2)); - - ddsRequest.setResultEncoding(encodeType.name()); - assertTrue(ddsRequest.equals(ddsRequest2)); - - ddsRequest2.setDialogID(156); - assertFalse(ddsRequest.equals(ddsRequest2)); - - ddsRequest.setDialogID(156); - assertTrue(ddsRequest.equals(ddsRequest2)); - assertTrue(ddsRequest.equals(ddsRequest)); - - ddsRequest2.setResultEncoding(EncodeType.BASE64.name()); - assertFalse(ddsRequest.equals(ddsRequest2)); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.dds.DdsRequest.EncodeType; +import us.dot.its.jpo.ode.dds.DdsRequest.SystemName; + +public class DdsRequestTest { + + private DdsRequest ddsRequest; + + @Before + public void setUp() throws Exception { + ddsRequest = new DdsRequest(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDialogEnum() { + Dialog dialog = Dialog.ASD; + + assertEquals(Dialog.ISD, Dialog.getById(162)); + assertEquals(156, dialog.getId()); + assertNull(Dialog.getById(999)); + } + + @Test + public void testSystemNameEnum() { + SystemName systemName = SystemName.SDC; + assertEquals("SDC 2.3", systemName.getName()); + } + + @Test + public void testDialogId() { + ddsRequest.setDialogID(156); + assertEquals(156, ddsRequest.getDialogID()); + } + + @Test + public void testResultEncoding() { + String encodingType = "hex"; + ddsRequest.setResultEncoding(encodingType); + assertEquals(encodingType, ddsRequest.getResultEncoding()); + } + + @Test + public void testHashCode() { + int hashCode1, hashCode2; + DdsRequest ddsRequest2 = new DdsRequest(); + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + + ddsRequest2.setResultEncoding("hex"); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertNotEquals(hashCode1, hashCode2); + + ddsRequest.setResultEncoding("hex"); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + + ddsRequest2.setDialogID(156); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertNotEquals(hashCode1, hashCode2); + + ddsRequest.setDialogID(156); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + } + + @Test + public void testEquals() { + EncodeType encodeType = EncodeType.HEX; + DdsRequest ddsRequest2 = new DdsRequest(); + assertTrue(ddsRequest.equals(ddsRequest2)); + + ddsRequest2.setResultEncoding(encodeType.name()); + assertFalse(ddsRequest.equals(ddsRequest2)); + + ddsRequest.setResultEncoding(encodeType.name()); + assertTrue(ddsRequest.equals(ddsRequest2)); + + ddsRequest2.setDialogID(156); + assertFalse(ddsRequest.equals(ddsRequest2)); + + ddsRequest.setDialogID(156); + assertTrue(ddsRequest.equals(ddsRequest2)); + assertTrue(ddsRequest.equals(ddsRequest)); + + ddsRequest2.setResultEncoding(EncodeType.BASE64.name()); + assertFalse(ddsRequest.equals(ddsRequest2)); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java index d6f0ed2e7..d743b10dc 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.DecodeException; -import org.junit.Test; - -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessageDecoderTest { - - @Test - public void testGetResponseTag() { - assertEquals(StatusTag.CLOSED, DdsStatusMessageDecoder.getResponseTag("CLOSED")); - assertEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("DEPOSITED")); - assertNotEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("OPENED")); - assertNull(DdsStatusMessageDecoder.getResponseTag("WRONT_TAG")); - } - - @Test - public void testParseFullMsg() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - String msg = "DEPOSITED:1"; - String[] msgs = ddsStatusMessageDecoder.parseFullMsg(msg); - assertEquals("DEPOSITED", msgs[0]); - assertEquals("1", msgs[1]); - } - - @Test - public void testWillDecode() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - assertFalse(ddsStatusMessageDecoder.willDecode("DEPOSITED:1")); - assertTrue(ddsStatusMessageDecoder.willDecode("START:1")); - } - - @Test - public void testDecode() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - DdsMessage ddsMessage; - try { - ddsMessage = ddsStatusMessageDecoder.decode("DEPOSITED:1"); - String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("CONNECTED:testConnectionDetail"); - expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); - expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("STOP:recordCount=2"); - expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("ERROR:sampleError"); - expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - } catch (DecodeException e) { - e.printStackTrace(); - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.DecodeException; +import org.junit.Test; + +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessageDecoderTest { + + @Test + public void testGetResponseTag() { + assertEquals(StatusTag.CLOSED, DdsStatusMessageDecoder.getResponseTag("CLOSED")); + assertEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("DEPOSITED")); + assertNotEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("OPENED")); + assertNull(DdsStatusMessageDecoder.getResponseTag("WRONT_TAG")); + } + + @Test + public void testParseFullMsg() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + String msg = "DEPOSITED:1"; + String[] msgs = ddsStatusMessageDecoder.parseFullMsg(msg); + assertEquals("DEPOSITED", msgs[0]); + assertEquals("1", msgs[1]); + } + + @Test + public void testWillDecode() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + assertFalse(ddsStatusMessageDecoder.willDecode("DEPOSITED:1")); + assertTrue(ddsStatusMessageDecoder.willDecode("START:1")); + } + + @Test + public void testDecode() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + DdsMessage ddsMessage; + try { + ddsMessage = ddsStatusMessageDecoder.decode("DEPOSITED:1"); + String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("CONNECTED:testConnectionDetail"); + expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); + expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("STOP:recordCount=2"); + expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("ERROR:sampleError"); + expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + } catch (DecodeException e) { + e.printStackTrace(); + } + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java index b062e9c87..bbf2c39bb 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -import mockit.Mocked; -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessageTest { - - private static final String UPER = "UPER"; - - @Test - public void testConstructor1() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - - assertNull(ddsStatusMessage.getTag()); - assertNull(ddsStatusMessage.getEncoding()); - assertNull(ddsStatusMessage.getDialog()); - } - - @Test - public void testConstructor2(@Mocked StatusTag tag, @Mocked Dialog dialog) { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, UPER, dialog); - assertEquals(ddsStatusMessage.getTag(), tag); - assertEquals(UPER, ddsStatusMessage.getEncoding()); - assertEquals(ddsStatusMessage.getDialog(), dialog); - - ddsStatusMessage.setTag(null); - ddsStatusMessage.setDialog(null); - ddsStatusMessage.setEncoding(null); - - assertNull(ddsStatusMessage.getTag()); - assertNull(ddsStatusMessage.getEncoding()); - assertNull(ddsStatusMessage.getDialog()); - } - - - @Test - public void testRecordCount() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - assertEquals(0, ddsStatusMessage.getRecordCount()); - ddsStatusMessage.setRecordCount(5); - assertEquals(5, ddsStatusMessage.getRecordCount()); - } - - @Test - public void testConnectionDetails() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - assertEquals(null, ddsStatusMessage.getConnectionDetails()); - ddsStatusMessage.setConnectionDetails("testConnectionString"); - assertEquals("testConnectionString", ddsStatusMessage.getConnectionDetails()); - } - - @Test - public void testToString() { - StatusTag tag = StatusTag.CONNECTED; - String encoding = "hex"; - Dialog dialog = Dialog.ASD; - long recordCount = 3; - String connectionDetails = "testConnectionString"; - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, encoding, dialog); - ddsStatusMessage.setConnectionDetails(connectionDetails); - ddsStatusMessage.setRecordCount(recordCount); - String ddsStatusMessageString = "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" - + recordCount + ", connectionDetails=" + connectionDetails + "]"; - assertEquals(ddsStatusMessageString, ddsStatusMessage.toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import mockit.Mocked; +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessageTest { + + private static final String UPER = "UPER"; + + @Test + public void testConstructor1() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + + assertNull(ddsStatusMessage.getTag()); + assertNull(ddsStatusMessage.getEncoding()); + assertNull(ddsStatusMessage.getDialog()); + } + + @Test + public void testConstructor2(@Mocked StatusTag tag, @Mocked Dialog dialog) { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, UPER, dialog); + assertEquals(ddsStatusMessage.getTag(), tag); + assertEquals(UPER, ddsStatusMessage.getEncoding()); + assertEquals(ddsStatusMessage.getDialog(), dialog); + + ddsStatusMessage.setTag(null); + ddsStatusMessage.setDialog(null); + ddsStatusMessage.setEncoding(null); + + assertNull(ddsStatusMessage.getTag()); + assertNull(ddsStatusMessage.getEncoding()); + assertNull(ddsStatusMessage.getDialog()); + } + + + @Test + public void testRecordCount() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + assertEquals(0, ddsStatusMessage.getRecordCount()); + ddsStatusMessage.setRecordCount(5); + assertEquals(5, ddsStatusMessage.getRecordCount()); + } + + @Test + public void testConnectionDetails() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + assertEquals(null, ddsStatusMessage.getConnectionDetails()); + ddsStatusMessage.setConnectionDetails("testConnectionString"); + assertEquals("testConnectionString", ddsStatusMessage.getConnectionDetails()); + } + + @Test + public void testToString() { + StatusTag tag = StatusTag.CONNECTED; + String encoding = "hex"; + Dialog dialog = Dialog.ASD; + long recordCount = 3; + String connectionDetails = "testConnectionString"; + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, encoding, dialog); + ddsStatusMessage.setConnectionDetails(connectionDetails); + ddsStatusMessage.setRecordCount(recordCount); + String ddsStatusMessageString = "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" + + recordCount + ", connectionDetails=" + connectionDetails + "]"; + assertEquals(ddsStatusMessageString, ddsStatusMessage.toString()); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java index 845ad213c..d3bf02796 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.DecodeException; -import org.junit.Test; - -public class DepositResponseDecoderTest { - - @Test - public void testWillDecode() { - DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); - assertTrue(depositResponseDecoder.willDecode("Any String")); - assertTrue(depositResponseDecoder.willDecode("Always returns true")); - } - - @Test - public void testDecode() { - DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); - DdsMessage ddsMessage; - try { - ddsMessage = depositResponseDecoder.decode("DEPOSITED:1"); - String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("CONNECTED:testConnectionDetail"); - expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); - expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("STOP:recordCount=2"); - expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("ERROR:sampleError"); - expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - } catch (DecodeException e) { - e.printStackTrace(); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.DecodeException; +import org.junit.Test; + +public class DepositResponseDecoderTest { + + @Test + public void testWillDecode() { + DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); + assertTrue(depositResponseDecoder.willDecode("Any String")); + assertTrue(depositResponseDecoder.willDecode("Always returns true")); + } + + @Test + public void testDecode() { + DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); + DdsMessage ddsMessage; + try { + ddsMessage = depositResponseDecoder.decode("DEPOSITED:1"); + String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("CONNECTED:testConnectionDetail"); + expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); + expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("STOP:recordCount=2"); + expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("ERROR:sampleError"); + expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + } catch (DecodeException e) { + e.printStackTrace(); + } + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java index 9462cde8f..c01ec286e 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.CloseReason; -import javax.websocket.Session; - -import org.junit.Test; - -import ch.qos.logback.classic.Logger; -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import us.dot.its.jpo.ode.model.OdeControlData; -import us.dot.its.jpo.ode.model.OdeStatus; -import us.dot.its.jpo.ode.model.StatusTag; -import us.dot.its.jpo.ode.wrapper.WebSocketClient; - -public class StatusMessageHandlerTest { - - @Mocked - WebSocketClient mockWebSocketClient; - - @Test - public void testOnMessage(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger) { - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onMessage(statusMsg); - - new Verifications() { - { - new OdeControlData(statusMsg); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnMessageException(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger) { - Exception e = new Exception(); - new Expectations() { - { - new OdeControlData(statusMsg); - result = e; - } - }; - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onMessage(statusMsg); - - new Verifications() { - { - logger.error("Error handling ControlMessage. ", e); - } - }; - } - - @Test - public void testOnClose(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onClose(session, reason); - - new Verifications() { - { - new OdeControlData(StatusTag.CLOSED); - controlData.setMessage(anyString); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnOpen(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onOpen(session, null); - - new Verifications() { - { - new OdeControlData(StatusTag.OPENED); - controlData.setMessage("WebSocket Connection to DDS Opened."); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnError(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onError(session, new Throwable()); - - new Verifications() { - { - new OdeControlData(StatusTag.ERROR); - controlData.setMessage(anyString); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void buildOdeMessage(@Mocked DdsStatusMessage message) { - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - OdeStatus status = (OdeStatus) statusMessageHandler.buildOdeMessage(message); - - assertEquals(status.getMessage(), message.toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.CloseReason; +import javax.websocket.Session; + +import org.junit.Test; + +import ch.qos.logback.classic.Logger; +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import us.dot.its.jpo.ode.model.OdeControlData; +import us.dot.its.jpo.ode.model.OdeStatus; +import us.dot.its.jpo.ode.model.StatusTag; +import us.dot.its.jpo.ode.wrapper.WebSocketClient; + +public class StatusMessageHandlerTest { + + @Mocked + WebSocketClient mockWebSocketClient; + + @Test + public void testOnMessage(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger) { + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onMessage(statusMsg); + + new Verifications() { + { + new OdeControlData(statusMsg); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnMessageException(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger) { + Exception e = new Exception(); + new Expectations() { + { + new OdeControlData(statusMsg); + result = e; + } + }; + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onMessage(statusMsg); + + new Verifications() { + { + logger.error("Error handling ControlMessage. ", e); + } + }; + } + + @Test + public void testOnClose(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onClose(session, reason); + + new Verifications() { + { + new OdeControlData(StatusTag.CLOSED); + controlData.setMessage(anyString); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnOpen(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onOpen(session, null); + + new Verifications() { + { + new OdeControlData(StatusTag.OPENED); + controlData.setMessage("WebSocket Connection to DDS Opened."); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnError(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onError(session, new Throwable()); + + new Verifications() { + { + new OdeControlData(StatusTag.ERROR); + controlData.setMessage(anyString); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void buildOdeMessage(@Mocked DdsStatusMessage message) { + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + OdeStatus status = (OdeStatus) statusMessageHandler.buildOdeMessage(message); + + assertEquals(status.getMessage(), message.toString()); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java index 30b6a3f03..4193d72b9 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java @@ -1,236 +1,236 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.node.ObjectNode; - -import us.dot.its.jpo.ode.util.JsonUtils; - -public class SerialIdTest { - - @Test - public void testNoArgConstructor() { - SerialId testSerialId = new SerialId(); - - assertNotNull(testSerialId.getStreamId()); - } - - @Test - public void testFourArgConstructorNullStreamId() { - // streamId = null - // bundleSize = 3 - // bundleId = 6L - // recordId = 12 - SerialId testSerialId = new SerialId(null, 3, 6L, 12); - - assertNotNull(testSerialId.getStreamId()); - assertTrue(testSerialId.getStreamId().endsWith("_null")); - assertEquals(3, testSerialId.getBundleSize()); // bundle size = bundle size - assertEquals(10L, testSerialId.getBundleId()); // bundle id = bundle id + (record id / bundle size) = 6L + ( 12 / - // 3) = 10L - assertEquals(0, testSerialId.getRecordId()); // record id = record id % bundle size = 12 % 3 = 0 - assertEquals(30L, testSerialId.getSerialNumber()); // serial number = (bundle id * bundle size) + record id = (6L - // * 3) + 12 = 30L - } - - @Test - public void testFourArgConstructorWithStreamId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - - assertEquals("bob_3.10.0#30", testSerialId.toString()); - } - - @Test - public void testSingleArgConstructor() throws Exception { - SerialId testSerialId = new SerialId("bob_3.10.0#30"); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - } - - @Test - public void testSingleArgConstructorInvalidSerialId() { - try { - new SerialId("bob_3.10.0"); - fail("Expected Exception for invalid length"); - } catch (Exception e) { - assertEquals("Invalid serialId! Expected length 5 but was 4", e.getMessage()); - } - } - - @Test - public void testFiveArgConstructor() { - SerialId testSerialId = new SerialId("allison", 6, 12L, 24, 15); - - assertEquals("allison", testSerialId.getStreamId()); - assertEquals(6, testSerialId.getBundleSize()); - assertEquals(12L, testSerialId.getBundleId()); - assertEquals(24, testSerialId.getRecordId()); - assertEquals(15L, testSerialId.getSerialNumber()); - - assertEquals("allison_6.12.24#15", testSerialId.toString()); - } - - @Test - public void testJsonNodeConstructor() { - ObjectNode testNode = JsonUtils.newNode(); - JsonUtils.addNode(testNode, "streamId", "bob"); - JsonUtils.addNode(testNode, "bundleSize", 3); - JsonUtils.addNode(testNode, "bundleId", 10); - JsonUtils.addNode(testNode, "recordId", 0); - JsonUtils.addNode(testNode, "serialNumber", 30); - - SerialId testSerialId = new SerialId(testNode); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - - assertEquals("bob_3.10.0#30", testSerialId.toString()); - } - - @Test - public void testNextRecordId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals(1, testSerialId.nextRecordId()); // nextRecordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 - } - - @Test - public void testNextSerialNumber() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals(31L, testSerialId.nextSerialNumber()); // nextSerialNumber = nextSerialNumber + 1 - } - - @Test - public void testNextSerialId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - // nextSerialId: - // bundleId = bundleId + ((recordId + 1) / bundleSize) = 10 + ((0 + 1) / 3) = 10 - // recordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 - - SerialId nextSerialId = testSerialId.nextSerialId(); - - assertEquals(10L, nextSerialId.getBundleId()); - assertEquals(1, nextSerialId.getRecordId()); - } - - @Test - public void testIsRightAfter() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); - - assertTrue(testSerialId1.isRightAfter(testSerialId0)); - assertFalse(testSerialId0.isRightAfter(testSerialId1)); - } - - @Test - public void testIsRightBefore() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); - - assertTrue(testSerialId0.isRightBefore(testSerialId1)); - assertFalse(testSerialId1.isRightBefore(testSerialId0)); - } - - @Test - public void testAddBundleId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - testSerialId.addBundleId(5L); - - assertEquals(15L, testSerialId.getBundleId()); - } - - @Test - public void testAddRecordId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - testSerialId.addRecordId(7); - - assertEquals(7, testSerialId.getRecordId()); - } - - @Test - public void testHashCode() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId2 = new SerialId("bob", 3, 6L, 16); - - assertEquals(testSerialId0.hashCode(), testSerialId1.hashCode()); - assertNotEquals(testSerialId0.hashCode(), testSerialId2.hashCode()); - - testSerialId2.setStreamId(null); - assertNotEquals(testSerialId1.hashCode(), testSerialId2.hashCode()); - } - - @Test - public void testEquals() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); - - assertTrue(testSerialId0.equals(testSerialId0)); - assertFalse(testSerialId0.equals(null)); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleId(7L); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleId(10L); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleSize(7); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleSize(3); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setRecordId(1); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setRecordId(0); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setStreamId(null); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId0.setStreamId(null); - assertTrue(testSerialId0.equals(testSerialId1)); - - testSerialId0.setStreamId("bob"); - assertFalse(testSerialId1.equals(testSerialId0)); - - testSerialId1.setStreamId("allison"); - assertFalse(testSerialId0.equals(testSerialId1)); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +import us.dot.its.jpo.ode.util.JsonUtils; + +public class SerialIdTest { + + @Test + public void testNoArgConstructor() { + SerialId testSerialId = new SerialId(); + + assertNotNull(testSerialId.getStreamId()); + } + + @Test + public void testFourArgConstructorNullStreamId() { + // streamId = null + // bundleSize = 3 + // bundleId = 6L + // recordId = 12 + SerialId testSerialId = new SerialId(null, 3, 6L, 12); + + assertNotNull(testSerialId.getStreamId()); + assertTrue(testSerialId.getStreamId().endsWith("_null")); + assertEquals(3, testSerialId.getBundleSize()); // bundle size = bundle size + assertEquals(10L, testSerialId.getBundleId()); // bundle id = bundle id + (record id / bundle size) = 6L + ( 12 / + // 3) = 10L + assertEquals(0, testSerialId.getRecordId()); // record id = record id % bundle size = 12 % 3 = 0 + assertEquals(30L, testSerialId.getSerialNumber()); // serial number = (bundle id * bundle size) + record id = (6L + // * 3) + 12 = 30L + } + + @Test + public void testFourArgConstructorWithStreamId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + + assertEquals("bob_3.10.0#30", testSerialId.toString()); + } + + @Test + public void testSingleArgConstructor() throws Exception { + SerialId testSerialId = new SerialId("bob_3.10.0#30"); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + } + + @Test + public void testSingleArgConstructorInvalidSerialId() { + try { + new SerialId("bob_3.10.0"); + fail("Expected Exception for invalid length"); + } catch (Exception e) { + assertEquals("Invalid serialId! Expected length 5 but was 4", e.getMessage()); + } + } + + @Test + public void testFiveArgConstructor() { + SerialId testSerialId = new SerialId("allison", 6, 12L, 24, 15); + + assertEquals("allison", testSerialId.getStreamId()); + assertEquals(6, testSerialId.getBundleSize()); + assertEquals(12L, testSerialId.getBundleId()); + assertEquals(24, testSerialId.getRecordId()); + assertEquals(15L, testSerialId.getSerialNumber()); + + assertEquals("allison_6.12.24#15", testSerialId.toString()); + } + + @Test + public void testJsonNodeConstructor() { + ObjectNode testNode = JsonUtils.newNode(); + JsonUtils.addNode(testNode, "streamId", "bob"); + JsonUtils.addNode(testNode, "bundleSize", 3); + JsonUtils.addNode(testNode, "bundleId", 10); + JsonUtils.addNode(testNode, "recordId", 0); + JsonUtils.addNode(testNode, "serialNumber", 30); + + SerialId testSerialId = new SerialId(testNode); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + + assertEquals("bob_3.10.0#30", testSerialId.toString()); + } + + @Test + public void testNextRecordId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals(1, testSerialId.nextRecordId()); // nextRecordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 + } + + @Test + public void testNextSerialNumber() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals(31L, testSerialId.nextSerialNumber()); // nextSerialNumber = nextSerialNumber + 1 + } + + @Test + public void testNextSerialId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + // nextSerialId: + // bundleId = bundleId + ((recordId + 1) / bundleSize) = 10 + ((0 + 1) / 3) = 10 + // recordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 + + SerialId nextSerialId = testSerialId.nextSerialId(); + + assertEquals(10L, nextSerialId.getBundleId()); + assertEquals(1, nextSerialId.getRecordId()); + } + + @Test + public void testIsRightAfter() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); + + assertTrue(testSerialId1.isRightAfter(testSerialId0)); + assertFalse(testSerialId0.isRightAfter(testSerialId1)); + } + + @Test + public void testIsRightBefore() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); + + assertTrue(testSerialId0.isRightBefore(testSerialId1)); + assertFalse(testSerialId1.isRightBefore(testSerialId0)); + } + + @Test + public void testAddBundleId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + testSerialId.addBundleId(5L); + + assertEquals(15L, testSerialId.getBundleId()); + } + + @Test + public void testAddRecordId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + testSerialId.addRecordId(7); + + assertEquals(7, testSerialId.getRecordId()); + } + + @Test + public void testHashCode() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId2 = new SerialId("bob", 3, 6L, 16); + + assertEquals(testSerialId0.hashCode(), testSerialId1.hashCode()); + assertNotEquals(testSerialId0.hashCode(), testSerialId2.hashCode()); + + testSerialId2.setStreamId(null); + assertNotEquals(testSerialId1.hashCode(), testSerialId2.hashCode()); + } + + @Test + public void testEquals() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); + + assertTrue(testSerialId0.equals(testSerialId0)); + assertFalse(testSerialId0.equals(null)); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleId(7L); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleId(10L); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleSize(7); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleSize(3); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setRecordId(1); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setRecordId(0); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setStreamId(null); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId0.setStreamId(null); + assertTrue(testSerialId0.equals(testSerialId1)); + + testSerialId0.setStreamId("bob"); + assertFalse(testSerialId1.equals(testSerialId0)); + + testSerialId1.setStreamId("allison"); + assertFalse(testSerialId0.equals(testSerialId1)); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java index c62e0eb74..e329df51a 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java @@ -74,6 +74,6 @@ public void testGettersAndSetters() { @Test public void testSnmpTimestampFromIso() throws ParseException { String snmpTS = SNMP.snmpTimestampFromIso("2017-05-04T21:55:00-05:00"); - assertEquals("050414111537", snmpTS); + assertEquals("07E105041537", snmpTS); } } diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java index 7a564eb73..6544f2ad0 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.KeyStore; - -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.integration.junit4.JMockit; - -@RunWith(JMockit.class) -public class SSLBuilderTest { - - @Mocked - KeyStore keystore; - - @Mocked - SSLContexts sslContexts; - - @Mocked - TrustSelfSignedStrategy trustSelfSignedStrategy; - - @Test - public void testBuildSSLContext() { - try { - final InputStream keystoreFile = - new ByteArrayInputStream("keystoreFile".getBytes()); - final String keystorePass = "keystorePass"; - - {// BEGIN test custom SSLConext - new Expectations() {{ - KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, keystorePass.toCharArray()); - SSLContexts.custom() - .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) - .build(); - }}; - - - SSLBuilder.buildSSLContext(keystoreFile, keystorePass); - -// new Verifications() {{ -// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; -// keystore.load(keystoreFile, keystorePass.toCharArray()); times = 1; -// SSLContexts.custom() -// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) -// .build(); times = 1; -// }}; - } // END test normal path - - {// BEGIN test default SSLContext - new Expectations() {{ - SSLContexts.createDefault(); - }}; - - SSLBuilder.buildSSLContext(null, keystorePass); - -// new Verifications() {{ -// SSLContexts.createDefault(); times = 1; -// }}; - }// END test default path - - {// BEGIN test null password - new Expectations() {{ - KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, "".toCharArray()); - SSLContexts.custom() - .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) - .build(); - }}; - - SSLBuilder.buildSSLContext(keystoreFile, null); - -// new Verifications() {{ -// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; -// keystore.load(keystoreFile, "".toCharArray()); times = 1; -// SSLContexts.custom() -// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) -// .build(); times = 1; -// }}; - }// END test null password - - } catch (Exception e) { - fail(e.toString()); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.security.KeyStore; + +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; + +@RunWith(JMockit.class) +public class SSLBuilderTest { + + @Mocked + KeyStore keystore; + + @Mocked + SSLContexts sslContexts; + + @Mocked + TrustSelfSignedStrategy trustSelfSignedStrategy; + + @Test + public void testBuildSSLContext() { + try { + final InputStream keystoreFile = + new ByteArrayInputStream("keystoreFile".getBytes()); + final String keystorePass = "keystorePass"; + + {// BEGIN test custom SSLConext + new Expectations() {{ + KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(keystoreFile, keystorePass.toCharArray()); + SSLContexts.custom() + .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) + .build(); + }}; + + + SSLBuilder.buildSSLContext(keystoreFile, keystorePass); + +// new Verifications() {{ +// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; +// keystore.load(keystoreFile, keystorePass.toCharArray()); times = 1; +// SSLContexts.custom() +// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) +// .build(); times = 1; +// }}; + } // END test normal path + + {// BEGIN test default SSLContext + new Expectations() {{ + SSLContexts.createDefault(); + }}; + + SSLBuilder.buildSSLContext(null, keystorePass); + +// new Verifications() {{ +// SSLContexts.createDefault(); times = 1; +// }}; + }// END test default path + + {// BEGIN test null password + new Expectations() {{ + KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(keystoreFile, "".toCharArray()); + SSLContexts.custom() + .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) + .build(); + }}; + + SSLBuilder.buildSSLContext(keystoreFile, null); + +// new Verifications() {{ +// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; +// keystore.load(keystoreFile, "".toCharArray()); times = 1; +// SSLContexts.custom() +// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) +// .build(); times = 1; +// }}; + }// END test null password + + } catch (Exception e) { + fail(e.toString()); + } + } + +} diff --git a/jpo-ode-core/src/test/resources/CVMessages/.gitignore b/jpo-ode-core/src/test/resources/CVMessages/.gitignore index 153e27add..b835b6985 100644 --- a/jpo-ode-core/src/test/resources/CVMessages/.gitignore +++ b/jpo-ode-core/src/test/resources/CVMessages/.gitignore @@ -1 +1 @@ -/VehicleSituationDataServiceResponse.uper +/VehicleSituationDataServiceResponse.uper diff --git a/jpo-ode-core/src/test/resources/logback-test.xml b/jpo-ode-core/src/test/resources/logback-test.xml index a7a69c483..de5097a2d 100644 --- a/jpo-ode-core/src/test/resources/logback-test.xml +++ b/jpo-ode-core/src/test/resources/logback-test.xml @@ -1,10 +1,10 @@ - - - - %msg%n - - - - - + + + + %msg%n + + + + + \ No newline at end of file diff --git a/jpo-ode-plugins/LICENSE-2.0.html b/jpo-ode-plugins/LICENSE-2.0.html index d1055c8ad..16303d2c7 100644 --- a/jpo-ode-plugins/LICENSE-2.0.html +++ b/jpo-ode-plugins/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-plugins/pom.xml b/jpo-ode-plugins/pom.xml index b9997938d..f0cbfa9ff 100644 --- a/jpo-ode-plugins/pom.xml +++ b/jpo-ode-plugins/pom.xml @@ -11,7 +11,7 @@ usdot.jpo.ode jpo-ode - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT @@ -27,7 +27,7 @@ usdot.jpo.ode jpo-ode-common - 1.0.8-SNAPSHOT + 0.0.9-SNAPSHOT /)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,""),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:"space"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,"");this.tokens.push({type:"code",text:!this.options.pedantic?cap.replace(/\n+$/,""):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")};for(i=0;i ?/gm,"");this.token(cap,top,true);this.tokens.push({type:"blockquote_end"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:"list_start",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join("\n")+src;i=l-1}}loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==="\n";if(!loose)loose=next}this.tokens.push({type:loose?"loose_item_start":"list_item_start"});this.token(item,false,bq);this.tokens.push({type:"list_item_end"})}this.tokens.push({type:"list_end"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&(cap[1]==="pre"||cap[1]==="script"||cap[1]==="style"),text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(i=0;i])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)();inline.reflink=replace(inline.reflink)("inside",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error("Tokens array requires a `links` property.")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out="",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==="@"){text=cap[1].charAt(6)===":"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle("mailto:")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g," ");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue}if(src){throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=="!"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"â€").replace(/\.{3}/g,"…")};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out="",l=text.length,i=0,ch;for(;i.5){ch="x"+ch.toString(16)}out+="&#"+ch+";"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return"
    "+(escaped?code:escape(code,true))+"\n
    "}return'
    '+(escaped?code:escape(code,true))+"\n
    \n"};Renderer.prototype.blockquote=function(quote){return"
    \n"+quote+"
    \n"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return"'+text+"\n"};Renderer.prototype.hr=function(){return this.options.xhtml?"
    \n":"
    \n"};Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+"\n"};Renderer.prototype.listitem=function(text){return"
  • "+text+"
  • \n"};Renderer.prototype.paragraph=function(text){return"

    "+text+"

    \n"};Renderer.prototype.table=function(header,body){return"\n"+"\n"+header+"\n"+"\n"+body+"\n"+"
    \n"};Renderer.prototype.tablerow=function(content){return"\n"+content+"\n"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";var tag=flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">";return tag+content+"\n"};Renderer.prototype.strong=function(text){return""+text+""};Renderer.prototype.em=function(text){return""+text+""};Renderer.prototype.codespan=function(text){return""+text+""};Renderer.prototype.br=function(){return this.options.xhtml?"
    ":"
    "};Renderer.prototype.del=function(text){return""+text+""};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(prot.indexOf("javascript:")===0||prot.indexOf("vbscript:")===0){return""}}var out='
    ";return out};Renderer.prototype.image=function(href,title,text){var out=''+text+'":">";return out};Renderer.prototype.text=function(text){return text};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out="";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==="text"){body+="\n"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case"space":{return""}case"hr":{return this.renderer.hr()}case"heading":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case"code":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case"table":{var header="",body="",i,row,cell,flags,j;cell="";for(i=0;i/g,">").replace(/"/g,""").replace(/'/g,"'")}function unescape(html){return html.replace(/&([#\w]+);/g,function(_,n){n=n.toLowerCase();if(n==="colon")return":";if(n.charAt(0)==="#"){return n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1))}return""})}function replace(regex,opt){regex=regex.source;opt=opt||"";return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^\[])\^/g,"$1");regex=regex.replace(name,val);return self}}function noop(){}noop.exec=noop;function merge(obj){var i=1,target,key;for(;iAn error occurred:

    "+escape(e.message+"",true)+"
    "}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:"lang-",smartypants:false,headerPrefix:"",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=="undefined"&&typeof exports==="object"){module.exports=marked}else if(typeof define==="function"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!=="undefined"?window:global)}()); - - - - - - - - -
    -
    - -
    -
    -
    -

    ODE REST API

    -
    -
    -
    - -
    -
    -

    LogFile

    -
    -
    -
    -

    uploadObulog

    -

    File upload interface

    -
    -
    -
    -

    -

    Uploads an OBU log file to ODE upload folder to be processed and propaged

    -

    -
    -
    /upload/obulog
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/upload/obulog"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.LogFileApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class LogFileApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        LogFileApi apiInstance = new LogFileApi();
    -        File file = /path/to/file.txt; // File | The file to upload.
    -        try {
    -            array[Status] result = apiInstance.uploadObulog(file);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling LogFileApi#uploadObulog");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.LogFileApi;
    -
    -public class LogFileApiExample {
    -
    -    public static void main(String[] args) {
    -        LogFileApi apiInstance = new LogFileApi();
    -        File file = /path/to/file.txt; // File | The file to upload.
    -        try {
    -            array[Status] result = apiInstance.uploadObulog(file);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling LogFileApi#uploadObulog");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    File *file = /path/to/file.txt; // The file to upload. (optional)
    -
    -LogFileApi *apiInstance = [[LogFileApi alloc] init];
    -
    -// File upload interface
    -[apiInstance uploadObulogWith:file
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.LogFileApi()
    -
    -var opts = { 
    -  'file': /path/to/file.txt // {File} The file to upload.
    -};
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.uploadObulog(opts, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class uploadObulogExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new LogFileApi();
    -            var file = new File(); // File | The file to upload. (optional) 
    -
    -            try
    -            {
    -                // File upload interface
    -                array[Status] result = apiInstance.uploadObulog(file);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling LogFileApi.uploadObulog: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\LogFileApi();
    -$file = /path/to/file.txt; // File | The file to upload.
    -
    -try {
    -    $result = $api_instance->uploadObulog($file);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling LogFileApi->uploadObulog: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::LogFileApi;
    -
    -my $api_instance = WWW::SwaggerClient::LogFileApi->new();
    -my $file = /path/to/file.txt; # File | The file to upload.
    -
    -eval { 
    -    my $result = $api_instance->uploadObulog(file => $file);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling LogFileApi->uploadObulog: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.LogFileApi()
    -file = /path/to/file.txt # File | The file to upload. (optional)
    -
    -try: 
    -    # File upload interface
    -    api_response = api_instance.upload_obulog(file=file)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling LogFileApi->uploadObulog: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - -
    Form parameters
    - - - - - - - - - -
    NameDescription
    file - - -
    -
    -
    - - File - - -
    - The file to upload. -
    -
    -
    -
    -
    - - -

    Responses

    -

    Status: 200 - File uploaded successfully

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    PDM

    -
    -
    -
    -

    pdmPost

    -

    PDM Interface

    -
    -
    -
    -

    -

    Submits a Probe Data Management message to ODE for distribution to the specified RSUs.

    -

    -
    -
    /pdm
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/pdm"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.PDMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class PDMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        PDMApi apiInstance = new PDMApi();
    -        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    -        try {
    -            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling PDMApi#pdmPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.PDMApi;
    -
    -public class PDMApiExample {
    -
    -    public static void main(String[] args) {
    -        PDMApi apiInstance = new PDMApi();
    -        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    -        try {
    -            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling PDMApi#pdmPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    ProbeDataManagement *probeDataManagement = ; // PDM Message
    -
    -PDMApi *apiInstance = [[PDMApi alloc] init];
    -
    -// PDM Interface
    -[apiInstance pdmPostWith:probeDataManagement
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.PDMApi()
    -
    -var probeDataManagement = ; // {ProbeDataManagement} PDM Message
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.pdmPost(probeDataManagement, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class pdmPostExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new PDMApi();
    -            var probeDataManagement = new ProbeDataManagement(); // ProbeDataManagement | PDM Message
    -
    -            try
    -            {
    -                // PDM Interface
    -                array[Status] result = apiInstance.pdmPost(probeDataManagement);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling PDMApi.pdmPost: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\PDMApi();
    -$probeDataManagement = ; // ProbeDataManagement | PDM Message
    -
    -try {
    -    $result = $api_instance->pdmPost($probeDataManagement);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling PDMApi->pdmPost: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::PDMApi;
    -
    -my $api_instance = WWW::SwaggerClient::PDMApi->new();
    -my $probeDataManagement = WWW::SwaggerClient::Object::ProbeDataManagement->new(); # ProbeDataManagement | PDM Message
    -
    -eval { 
    -    my $result = $api_instance->pdmPost(probeDataManagement => $probeDataManagement);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling PDMApi->pdmPost: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.PDMApi()
    -probeDataManagement =  # ProbeDataManagement | PDM Message
    -
    -try: 
    -    # PDM Interface
    -    api_response = api_instance.pdm_post(probeDataManagement)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling PDMApi->pdmPost: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    probeDataManagement * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Probe Data Management message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    SNMP

    -
    -
    -
    -

    snmpGet

    -

    RSU SNMP Query

    -
    -
    -
    -

    -

    Check the health and status of RSU devices through SNMP communication. You should receive a detailed plain text response that looks like the following example. If the device is off, a 4 second timeout will occur and the ODE will indicate this with an "[ERROR] Empty response" message. (This specific OID returns the amount of time since the device was last powered on) "[1.3.6.1.2.1.1.3.0 = 0:05:12.59]"

    -

    -
    -
    /rsuHeartbeat
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X GET "https://yourhostname/rsuHeartbeat?ip=&oid="
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.SNMPApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class SNMPApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        SNMPApi apiInstance = new SNMPApi();
    -        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    -        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -        try {
    -            Status result = apiInstance.snmpGet(ip, oid);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling SNMPApi#snmpGet");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.SNMPApi;
    -
    -public class SNMPApiExample {
    -
    -    public static void main(String[] args) {
    -        SNMPApi apiInstance = new SNMPApi();
    -        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    -        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -        try {
    -            Status result = apiInstance.snmpGet(ip, oid);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling SNMPApi#snmpGet");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    BigDecimal *ip = 8.14; // IP address of an RSU
    -BigDecimal *oid = 8.14; // OID of the attribute you wish to check on
    -
    -SNMPApi *apiInstance = [[SNMPApi alloc] init];
    -
    -// RSU SNMP Query
    -[apiInstance snmpGetWith:ip
    -    oid:oid
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.SNMPApi()
    -
    -var ip = 8.14; // {BigDecimal} IP address of an RSU
    -
    -var oid = 8.14; // {BigDecimal} OID of the attribute you wish to check on
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.snmpGet(ip, oid, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class snmpGetExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new SNMPApi();
    -            var ip = 8.14;  // BigDecimal | IP address of an RSU
    -            var oid = 8.14;  // BigDecimal | OID of the attribute you wish to check on
    -
    -            try
    -            {
    -                // RSU SNMP Query
    -                Status result = apiInstance.snmpGet(ip, oid);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling SNMPApi.snmpGet: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\SNMPApi();
    -$ip = 8.14; // BigDecimal | IP address of an RSU
    -$oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    -
    -try {
    -    $result = $api_instance->snmpGet($ip, $oid);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling SNMPApi->snmpGet: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::SNMPApi;
    -
    -my $api_instance = WWW::SwaggerClient::SNMPApi->new();
    -my $ip = 8.14; # BigDecimal | IP address of an RSU
    -my $oid = 8.14; # BigDecimal | OID of the attribute you wish to check on
    -
    -eval { 
    -    my $result = $api_instance->snmpGet(ip => $ip, oid => $oid);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling SNMPApi->snmpGet: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.SNMPApi()
    -ip = 8.14 # BigDecimal | IP address of an RSU
    -oid = 8.14 # BigDecimal | OID of the attribute you wish to check on
    -
    -try: 
    -    # RSU SNMP Query
    -    api_response = api_instance.snmp_get(ip, oid)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling SNMPApi->snmpGet: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - - -
    Query parameters
    - - - - - - - - - - - - - -
    NameDescription
    ip* - - -
    -
    -
    - - BigDecimal - - - (string) - - -
    - IP address of an RSU -
    -
    -
    - Required -
    -
    -
    -
    oid* - - -
    -
    -
    - - BigDecimal - - - (string) - - -
    - OID of the attribute you wish to check on -
    -
    -
    - Required -
    -
    -
    -
    - -

    Responses

    -

    Status: 200 - OID responses

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Value input error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -

    TIM

    -
    -
    -
    -

    timDelete

    -

    Delete a TIM message on an RSU.

    -
    -
    -
    -

    -

    Sets the status of a designated message index on an RSU to 6.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X DELETE "https://yourhostname/tim?index="
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    -        try {
    -            Status result = apiInstance.timDelete(index);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timDelete");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    -        try {
    -            Status result = apiInstance.timDelete(index);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timDelete");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    BigDecimal *index = 8.14; // Index of message to be deleted
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Delete a TIM message on an RSU.
    -[apiInstance timDeleteWith:index
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var index = 8.14; // {BigDecimal} Index of message to be deleted
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timDelete(index, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timDeleteExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var index = 8.14;  // BigDecimal | Index of message to be deleted
    -
    -            try
    -            {
    -                // Delete a TIM message on an RSU.
    -                Status result = apiInstance.timDelete(index);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timDelete: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$index = 8.14; // BigDecimal | Index of message to be deleted
    -
    -try {
    -    $result = $api_instance->timDelete($index);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timDelete: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $index = 8.14; # BigDecimal | Index of message to be deleted
    -
    -eval { 
    -    my $result = $api_instance->timDelete(index => $index);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timDelete: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -index = 8.14 # BigDecimal | Index of message to be deleted
    -
    -try: 
    -    # Delete a TIM message on an RSU.
    -    api_response = api_instance.tim_delete(index)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timDelete: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - - - -
    Query parameters
    - - - - - - - - - -
    NameDescription
    index* - - -
    -
    -
    - - BigDecimal - - - (integer) - - -
    - Index of message to be deleted -
    -
    -
    - Required -
    -
    -
    -
    - -

    Responses

    -

    Status: 200 - Deleted index

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Error in body request

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 408 - Timeout

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Misc error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timPost

    -

    Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.

    -
    -
    -
    -

    -

    Submits a TIM message to ODE for distribution to the specified RSUs and SDW.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/tim"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPost(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPost(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPost");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -[apiInstance timPostWith:travelerInputData
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timPost(travelerInputData, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timPostExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -            try
    -            {
    -                // Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -                array[Status] result = apiInstance.timPost(travelerInputData);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timPost: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try {
    -    $result = $api_instance->timPost($travelerInputData);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timPost: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -eval { 
    -    my $result = $api_instance->timPost(travelerInputData => $travelerInputData);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timPost: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try: 
    -    # Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    -    api_response = api_instance.tim_post(travelerInputData)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timPost: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    travelerInputData * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timPut

    -

    Used to update an existing TIM already present on an RSU.

    -
    -
    -
    -

    -

    Update a Traveler Information Message (TIM) that has already been deposited to an RSU. Parameters and response codes are identical to the POST request. Will also deposit the new message to the SDW, if the SDW field is present.

    -

    -
    -
    /tim
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X PUT "https://yourhostname/tim"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPut(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPut");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -        try {
    -            array[Status] result = apiInstance.timPut(travelerInputData);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timPut");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Used to update an existing TIM already present on an RSU.
    -[apiInstance timPutWith:travelerInputData
    -              completionHandler: ^(array[Status] output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timPut(travelerInputData, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timPutExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -            try
    -            {
    -                // Used to update an existing TIM already present on an RSU.
    -                array[Status] result = apiInstance.timPut(travelerInputData);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timPut: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try {
    -    $result = $api_instance->timPut($travelerInputData);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timPut: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -eval { 
    -    my $result = $api_instance->timPut(travelerInputData => $travelerInputData);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timPut: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    -
    -try: 
    -    # Used to update an existing TIM already present on an RSU.
    -    api_response = api_instance.tim_put(travelerInputData)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timPut: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    travelerInputData * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    timQuery

    -

    Query an RSU for set TIMs

    -
    -
    -
    -

    -

    Query an RSU for set TIMs

    -

    -
    -
    /tim/query
    -

    -

    Usage and SDK Samples

    -

    - - -
    -
    -
    curl -X POST "https://yourhostname/tim/query"
    -
    -
    -
    import io.swagger.client.*;
    -import io.swagger.client.auth.*;
    -import io.swagger.client.model.*;
    -import io.swagger.client.api.TIMApi;
    -
    -import java.io.File;
    -import java.util.*;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        
    -        TIMApi apiInstance = new TIMApi();
    -        RSU rSU = ; // RSU | 
    -        try {
    -            Status result = apiInstance.timQuery(rSU);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timQuery");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    import io.swagger.client.api.TIMApi;
    -
    -public class TIMApiExample {
    -
    -    public static void main(String[] args) {
    -        TIMApi apiInstance = new TIMApi();
    -        RSU rSU = ; // RSU | 
    -        try {
    -            Status result = apiInstance.timQuery(rSU);
    -            System.out.println(result);
    -        } catch (ApiException e) {
    -            System.err.println("Exception when calling TIMApi#timQuery");
    -            e.printStackTrace();
    -        }
    -    }
    -}
    -
    - -
    -
    RSU *rSU = ; // 
    -
    -TIMApi *apiInstance = [[TIMApi alloc] init];
    -
    -// Query an RSU for set TIMs
    -[apiInstance timQueryWith:rSU
    -              completionHandler: ^(Status output, NSError* error) {
    -                            if (output) {
    -                                NSLog(@"%@", output);
    -                            }
    -                            if (error) {
    -                                NSLog(@"Error: %@", error);
    -                            }
    -                        }];
    -
    -
    - -
    -
    var OdeRestApi = require('ode_rest_api');
    -
    -var api = new OdeRestApi.TIMApi()
    -
    -var rSU = ; // {RSU} 
    -
    -
    -var callback = function(error, data, response) {
    -  if (error) {
    -    console.error(error);
    -  } else {
    -    console.log('API called successfully. Returned data: ' + data);
    -  }
    -};
    -api.timQuery(rSU, callback);
    -
    -
    - - -
    -
    using System;
    -using System.Diagnostics;
    -using IO.Swagger.Api;
    -using IO.Swagger.Client;
    -using IO.Swagger.Model;
    -
    -namespace Example
    -{
    -    public class timQueryExample
    -    {
    -        public void main()
    -        {
    -            
    -            var apiInstance = new TIMApi();
    -            var rSU = new RSU(); // RSU | 
    -
    -            try
    -            {
    -                // Query an RSU for set TIMs
    -                Status result = apiInstance.timQuery(rSU);
    -                Debug.WriteLine(result);
    -            }
    -            catch (Exception e)
    -            {
    -                Debug.Print("Exception when calling TIMApi.timQuery: " + e.Message );
    -            }
    -        }
    -    }
    -}
    -
    -
    - -
    -
    <?php
    -require_once(__DIR__ . '/vendor/autoload.php');
    -
    -$api_instance = new Swagger\Client\Api\TIMApi();
    -$rSU = ; // RSU | 
    -
    -try {
    -    $result = $api_instance->timQuery($rSU);
    -    print_r($result);
    -} catch (Exception $e) {
    -    echo 'Exception when calling TIMApi->timQuery: ', $e->getMessage(), PHP_EOL;
    -}
    -?>
    -
    - -
    -
    use Data::Dumper;
    -use WWW::SwaggerClient::Configuration;
    -use WWW::SwaggerClient::TIMApi;
    -
    -my $api_instance = WWW::SwaggerClient::TIMApi->new();
    -my $rSU = WWW::SwaggerClient::Object::RSU->new(); # RSU | 
    -
    -eval { 
    -    my $result = $api_instance->timQuery(rSU => $rSU);
    -    print Dumper($result);
    -};
    -if ($@) {
    -    warn "Exception when calling TIMApi->timQuery: $@\n";
    -}
    -
    - -
    -
    from __future__ import print_statement
    -import time
    -import swagger_client
    -from swagger_client.rest import ApiException
    -from pprint import pprint
    -
    -# create an instance of the API class
    -api_instance = swagger_client.TIMApi()
    -rSU =  # RSU | 
    -
    -try: 
    -    # Query an RSU for set TIMs
    -    api_response = api_instance.tim_query(rSU)
    -    pprint(api_response)
    -except ApiException as e:
    -    print("Exception when calling TIMApi->timQuery: %s\n" % e)
    -
    -
    - -

    Parameters

    - - - -
    Body parameters
    - - - - - - - - - -
    NameDescription
    rSU * - - - -
    -
    - - - -

    Responses

    -

    Status: 200 - List of messages in JSON form

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 400 - Error in body request

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 408 - Timeout

    - - - -
    -
    -
    - -
    - -
    -
    - -

    Status: 500 - Misc error

    - - - -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    - -
    -
    - Generated 2018-04-30T22:35:56.953Z -
    -
    -
    -
    -
    - - - - - - - - - - - - - - + + + + + ODE REST API + + + + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +

    ODE REST API

    +
    +
    +
    + +
    +
    +

    LogFile

    +
    +
    +
    +

    uploadObulog

    +

    File upload interface

    +
    +
    +
    +

    +

    Uploads an OBU log file to ODE upload folder to be processed and propaged

    +

    +
    +
    /upload/obulog
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/upload/obulog"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.LogFileApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class LogFileApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        LogFileApi apiInstance = new LogFileApi();
    +        File file = /path/to/file.txt; // File | The file to upload.
    +        try {
    +            array[Status] result = apiInstance.uploadObulog(file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling LogFileApi#uploadObulog");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.LogFileApi;
    +
    +public class LogFileApiExample {
    +
    +    public static void main(String[] args) {
    +        LogFileApi apiInstance = new LogFileApi();
    +        File file = /path/to/file.txt; // File | The file to upload.
    +        try {
    +            array[Status] result = apiInstance.uploadObulog(file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling LogFileApi#uploadObulog");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    File *file = /path/to/file.txt; // The file to upload. (optional)
    +
    +LogFileApi *apiInstance = [[LogFileApi alloc] init];
    +
    +// File upload interface
    +[apiInstance uploadObulogWith:file
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.LogFileApi()
    +
    +var opts = { 
    +  'file': /path/to/file.txt // {File} The file to upload.
    +};
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.uploadObulog(opts, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class uploadObulogExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new LogFileApi();
    +            var file = new File(); // File | The file to upload. (optional) 
    +
    +            try
    +            {
    +                // File upload interface
    +                array[Status] result = apiInstance.uploadObulog(file);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling LogFileApi.uploadObulog: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\LogFileApi();
    +$file = /path/to/file.txt; // File | The file to upload.
    +
    +try {
    +    $result = $api_instance->uploadObulog($file);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling LogFileApi->uploadObulog: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::LogFileApi;
    +
    +my $api_instance = WWW::SwaggerClient::LogFileApi->new();
    +my $file = /path/to/file.txt; # File | The file to upload.
    +
    +eval { 
    +    my $result = $api_instance->uploadObulog(file => $file);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling LogFileApi->uploadObulog: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.LogFileApi()
    +file = /path/to/file.txt # File | The file to upload. (optional)
    +
    +try: 
    +    # File upload interface
    +    api_response = api_instance.upload_obulog(file=file)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling LogFileApi->uploadObulog: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + +
    Form parameters
    + + + + + + + + + +
    NameDescription
    file + + +
    +
    +
    + + File + + +
    + The file to upload. +
    +
    +
    +
    +
    + + +

    Responses

    +

    Status: 200 - File uploaded successfully

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    PDM

    +
    +
    +
    +

    pdmPost

    +

    PDM Interface

    +
    +
    +
    +

    +

    Submits a Probe Data Management message to ODE for distribution to the specified RSUs.

    +

    +
    +
    /pdm
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/pdm"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.PDMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PDMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        PDMApi apiInstance = new PDMApi();
    +        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    +        try {
    +            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PDMApi#pdmPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.PDMApi;
    +
    +public class PDMApiExample {
    +
    +    public static void main(String[] args) {
    +        PDMApi apiInstance = new PDMApi();
    +        ProbeDataManagement probeDataManagement = ; // ProbeDataManagement | PDM Message
    +        try {
    +            array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PDMApi#pdmPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    ProbeDataManagement *probeDataManagement = ; // PDM Message
    +
    +PDMApi *apiInstance = [[PDMApi alloc] init];
    +
    +// PDM Interface
    +[apiInstance pdmPostWith:probeDataManagement
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.PDMApi()
    +
    +var probeDataManagement = ; // {ProbeDataManagement} PDM Message
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.pdmPost(probeDataManagement, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class pdmPostExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new PDMApi();
    +            var probeDataManagement = new ProbeDataManagement(); // ProbeDataManagement | PDM Message
    +
    +            try
    +            {
    +                // PDM Interface
    +                array[Status] result = apiInstance.pdmPost(probeDataManagement);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling PDMApi.pdmPost: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\PDMApi();
    +$probeDataManagement = ; // ProbeDataManagement | PDM Message
    +
    +try {
    +    $result = $api_instance->pdmPost($probeDataManagement);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PDMApi->pdmPost: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PDMApi;
    +
    +my $api_instance = WWW::SwaggerClient::PDMApi->new();
    +my $probeDataManagement = WWW::SwaggerClient::Object::ProbeDataManagement->new(); # ProbeDataManagement | PDM Message
    +
    +eval { 
    +    my $result = $api_instance->pdmPost(probeDataManagement => $probeDataManagement);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PDMApi->pdmPost: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PDMApi()
    +probeDataManagement =  # ProbeDataManagement | PDM Message
    +
    +try: 
    +    # PDM Interface
    +    api_response = api_instance.pdm_post(probeDataManagement)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PDMApi->pdmPost: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    probeDataManagement * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Probe Data Management message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    SNMP

    +
    +
    +
    +

    snmpGet

    +

    RSU SNMP Query

    +
    +
    +
    +

    +

    Check the health and status of RSU devices through SNMP communication. You should receive a detailed plain text response that looks like the following example. If the device is off, a 4 second timeout will occur and the ODE will indicate this with an "[ERROR] Empty response" message. (This specific OID returns the amount of time since the device was last powered on) "[1.3.6.1.2.1.1.3.0 = 0:05:12.59]"

    +

    +
    +
    /rsuHeartbeat
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X GET "https://yourhostname/rsuHeartbeat?ip=&oid="
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.SNMPApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class SNMPApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        SNMPApi apiInstance = new SNMPApi();
    +        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    +        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +        try {
    +            Status result = apiInstance.snmpGet(ip, oid);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling SNMPApi#snmpGet");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.SNMPApi;
    +
    +public class SNMPApiExample {
    +
    +    public static void main(String[] args) {
    +        SNMPApi apiInstance = new SNMPApi();
    +        BigDecimal ip = 8.14; // BigDecimal | IP address of an RSU
    +        BigDecimal oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +        try {
    +            Status result = apiInstance.snmpGet(ip, oid);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling SNMPApi#snmpGet");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    BigDecimal *ip = 8.14; // IP address of an RSU
    +BigDecimal *oid = 8.14; // OID of the attribute you wish to check on
    +
    +SNMPApi *apiInstance = [[SNMPApi alloc] init];
    +
    +// RSU SNMP Query
    +[apiInstance snmpGetWith:ip
    +    oid:oid
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.SNMPApi()
    +
    +var ip = 8.14; // {BigDecimal} IP address of an RSU
    +
    +var oid = 8.14; // {BigDecimal} OID of the attribute you wish to check on
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.snmpGet(ip, oid, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class snmpGetExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new SNMPApi();
    +            var ip = 8.14;  // BigDecimal | IP address of an RSU
    +            var oid = 8.14;  // BigDecimal | OID of the attribute you wish to check on
    +
    +            try
    +            {
    +                // RSU SNMP Query
    +                Status result = apiInstance.snmpGet(ip, oid);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling SNMPApi.snmpGet: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\SNMPApi();
    +$ip = 8.14; // BigDecimal | IP address of an RSU
    +$oid = 8.14; // BigDecimal | OID of the attribute you wish to check on
    +
    +try {
    +    $result = $api_instance->snmpGet($ip, $oid);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling SNMPApi->snmpGet: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::SNMPApi;
    +
    +my $api_instance = WWW::SwaggerClient::SNMPApi->new();
    +my $ip = 8.14; # BigDecimal | IP address of an RSU
    +my $oid = 8.14; # BigDecimal | OID of the attribute you wish to check on
    +
    +eval { 
    +    my $result = $api_instance->snmpGet(ip => $ip, oid => $oid);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling SNMPApi->snmpGet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.SNMPApi()
    +ip = 8.14 # BigDecimal | IP address of an RSU
    +oid = 8.14 # BigDecimal | OID of the attribute you wish to check on
    +
    +try: 
    +    # RSU SNMP Query
    +    api_response = api_instance.snmp_get(ip, oid)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling SNMPApi->snmpGet: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + + +
    Query parameters
    + + + + + + + + + + + + + +
    NameDescription
    ip* + + +
    +
    +
    + + BigDecimal + + + (string) + + +
    + IP address of an RSU +
    +
    +
    + Required +
    +
    +
    +
    oid* + + +
    +
    +
    + + BigDecimal + + + (string) + + +
    + OID of the attribute you wish to check on +
    +
    +
    + Required +
    +
    +
    +
    + +

    Responses

    +

    Status: 200 - OID responses

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Value input error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +

    TIM

    +
    +
    +
    +

    timDelete

    +

    Delete a TIM message on an RSU.

    +
    +
    +
    +

    +

    Sets the status of a designated message index on an RSU to 6.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X DELETE "https://yourhostname/tim?index="
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    +        try {
    +            Status result = apiInstance.timDelete(index);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timDelete");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        BigDecimal index = 8.14; // BigDecimal | Index of message to be deleted
    +        try {
    +            Status result = apiInstance.timDelete(index);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timDelete");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    BigDecimal *index = 8.14; // Index of message to be deleted
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Delete a TIM message on an RSU.
    +[apiInstance timDeleteWith:index
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var index = 8.14; // {BigDecimal} Index of message to be deleted
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timDelete(index, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timDeleteExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var index = 8.14;  // BigDecimal | Index of message to be deleted
    +
    +            try
    +            {
    +                // Delete a TIM message on an RSU.
    +                Status result = apiInstance.timDelete(index);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timDelete: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$index = 8.14; // BigDecimal | Index of message to be deleted
    +
    +try {
    +    $result = $api_instance->timDelete($index);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timDelete: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $index = 8.14; # BigDecimal | Index of message to be deleted
    +
    +eval { 
    +    my $result = $api_instance->timDelete(index => $index);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timDelete: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +index = 8.14 # BigDecimal | Index of message to be deleted
    +
    +try: 
    +    # Delete a TIM message on an RSU.
    +    api_response = api_instance.tim_delete(index)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timDelete: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + + + +
    Query parameters
    + + + + + + + + + +
    NameDescription
    index* + + +
    +
    +
    + + BigDecimal + + + (integer) + + +
    + Index of message to be deleted +
    +
    +
    + Required +
    +
    +
    +
    + +

    Responses

    +

    Status: 200 - Deleted index

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Error in body request

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 408 - Timeout

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Misc error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timPost

    +

    Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.

    +
    +
    +
    +

    +

    Submits a TIM message to ODE for distribution to the specified RSUs and SDW.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/tim"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPost(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPost(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPost");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +[apiInstance timPostWith:travelerInputData
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timPost(travelerInputData, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timPostExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +            try
    +            {
    +                // Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +                array[Status] result = apiInstance.timPost(travelerInputData);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timPost: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try {
    +    $result = $api_instance->timPost($travelerInputData);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timPost: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +eval { 
    +    my $result = $api_instance->timPost(travelerInputData => $travelerInputData);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timPost: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try: 
    +    # Submit Traveler Information Message (TIM) for broadcast to Connected Vehicles.
    +    api_response = api_instance.tim_post(travelerInputData)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timPost: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    travelerInputData * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timPut

    +

    Used to update an existing TIM already present on an RSU.

    +
    +
    +
    +

    +

    Update a Traveler Information Message (TIM) that has already been deposited to an RSU. Parameters and response codes are identical to the POST request. Will also deposit the new message to the SDW, if the SDW field is present.

    +

    +
    +
    /tim
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X PUT "https://yourhostname/tim"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPut(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPut");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        TravelerInputData travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +        try {
    +            array[Status] result = apiInstance.timPut(travelerInputData);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timPut");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    TravelerInputData *travelerInputData = ; // Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Used to update an existing TIM already present on an RSU.
    +[apiInstance timPutWith:travelerInputData
    +              completionHandler: ^(array[Status] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var travelerInputData = ; // {TravelerInputData} Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timPut(travelerInputData, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timPutExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var travelerInputData = new TravelerInputData(); // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +            try
    +            {
    +                // Used to update an existing TIM already present on an RSU.
    +                array[Status] result = apiInstance.timPut(travelerInputData);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timPut: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$travelerInputData = ; // TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try {
    +    $result = $api_instance->timPut($travelerInputData);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timPut: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $travelerInputData = WWW::SwaggerClient::Object::TravelerInputData->new(); # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +eval { 
    +    my $result = $api_instance->timPut(travelerInputData => $travelerInputData);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timPut: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +travelerInputData =  # TravelerInputData | Message containing the parameters for a Traveler Information Message including delivery information.
    +
    +try: 
    +    # Used to update an existing TIM already present on an RSU.
    +    api_response = api_instance.tim_put(travelerInputData)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timPut: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    travelerInputData * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - Traveleer Information Message was submitted successfully. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Bad Request. Issued if request is invalid or failed to be executed. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Internal Server Error. See the response body or ODE User Guide for details.

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    timQuery

    +

    Query an RSU for set TIMs

    +
    +
    +
    +

    +

    Query an RSU for set TIMs

    +

    +
    +
    /tim/query
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    curl -X POST "https://yourhostname/tim/query"
    +
    +
    +
    import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import io.swagger.client.api.TIMApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        TIMApi apiInstance = new TIMApi();
    +        RSU rSU = ; // RSU | 
    +        try {
    +            Status result = apiInstance.timQuery(rSU);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timQuery");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    import io.swagger.client.api.TIMApi;
    +
    +public class TIMApiExample {
    +
    +    public static void main(String[] args) {
    +        TIMApi apiInstance = new TIMApi();
    +        RSU rSU = ; // RSU | 
    +        try {
    +            Status result = apiInstance.timQuery(rSU);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling TIMApi#timQuery");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    + +
    +
    RSU *rSU = ; // 
    +
    +TIMApi *apiInstance = [[TIMApi alloc] init];
    +
    +// Query an RSU for set TIMs
    +[apiInstance timQueryWith:rSU
    +              completionHandler: ^(Status output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +
    + +
    +
    var OdeRestApi = require('ode_rest_api');
    +
    +var api = new OdeRestApi.TIMApi()
    +
    +var rSU = ; // {RSU} 
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.timQuery(rSU, callback);
    +
    +
    + + +
    +
    using System;
    +using System.Diagnostics;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
    +
    +namespace Example
    +{
    +    public class timQueryExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new TIMApi();
    +            var rSU = new RSU(); // RSU | 
    +
    +            try
    +            {
    +                // Query an RSU for set TIMs
    +                Status result = apiInstance.timQuery(rSU);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling TIMApi.timQuery: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +
    + +
    +
    <?php
    +require_once(__DIR__ . '/vendor/autoload.php');
    +
    +$api_instance = new Swagger\Client\Api\TIMApi();
    +$rSU = ; // RSU | 
    +
    +try {
    +    $result = $api_instance->timQuery($rSU);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling TIMApi->timQuery: ', $e->getMessage(), PHP_EOL;
    +}
    +?>
    +
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::TIMApi;
    +
    +my $api_instance = WWW::SwaggerClient::TIMApi->new();
    +my $rSU = WWW::SwaggerClient::Object::RSU->new(); # RSU | 
    +
    +eval { 
    +    my $result = $api_instance->timQuery(rSU => $rSU);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling TIMApi->timQuery: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.TIMApi()
    +rSU =  # RSU | 
    +
    +try: 
    +    # Query an RSU for set TIMs
    +    api_response = api_instance.tim_query(rSU)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling TIMApi->timQuery: %s\n" % e)
    +
    +
    + +

    Parameters

    + + + +
    Body parameters
    + + + + + + + + + +
    NameDescription
    rSU * + + + +
    +
    + + + +

    Responses

    +

    Status: 200 - List of messages in JSON form

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 400 - Error in body request

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 408 - Timeout

    + + + +
    +
    +
    + +
    + +
    +
    + +

    Status: 500 - Misc error

    + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    + Generated 2018-04-30T22:35:56.953Z +
    +
    +
    +
    +
    + + + + + + + + + + + + + + diff --git a/docs/timEndpointCurl.sh b/docs/timEndpointCurl.sh index 368dba948..222f38294 100755 --- a/docs/timEndpointCurl.sh +++ b/docs/timEndpointCurl.sh @@ -1,235 +1,235 @@ -curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 4c014aac-3597-a40d-e992-271d377d6d4c" -d '{ - "timContent": { - "msgcnt": "1", - "timestamp": "op", - "packetID": "op", - "urlB": "op", - "travelerDataFrame": [{ - "header": { - "sspindex": "1", - "travelerInfoType": "1", - "msgId": { - "FurtherInfoID": "1", - "RoadSignID": { - "position3D": { - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }, - "HeadingSlice": "1010011010010100", - "MUTCDCode": "op", - "MsgCRC": "op" - } - }, - "DYear": "op", - "MinuteOfTheYear": "0", - "MinutesDuration": "0", - "SignPriority": "0" - }, - "region": { - "sspindex": "0", - "GeographicalPath": [{ - "name": "op", - "id": "op", - "anchor": "op", - "laneWidth": "op", - "diretionality": "op", - "closedPath": "op", - "direction": "op", - "description": [{ - "path": [{ - "scale": "op", - "offset": [{ - "xy": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }], - "computed": [{ - "referenceLaneID": "1", - "offsetXaxis": [{ - "small": "1", - "large": "1" - }], - "offsetYaxis": [{ - "small": "1", - "large": "1" - }] - }] - }], - "ll": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }] - }] - }] - }], - "geometry": [{ - "direction": "1001101100100100", - "circle": [{ - "center": [{ - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }], - "radius": "3", - "units": "4" - }] - }], - "oldRegion": [{ - "direction": "1001101100100100", - "area": [{ - "shapePointSet": [{ - "nodes": [{ - "delta": [{ - "node-LL1": [{ - "lon": "20", - "lat": "21" - }], - "node-LL2": [{ - "lon": "20", - "lat": "21" - }], - "node-LL3": [{ - "lon": "20", - "lat": "21" - }], - "node-LL4": [{ - "lon": "20", - "lat": "21" - }], - "node-LL5": [{ - "lon": "20", - "lat": "21" - }], - "node-LL6": [{ - "lon": "20", - "lat": "21" - }] - }], - "attributes": "op" - }], - "computed": [{ - "referenceLaneID": "1", - "offsetXaxis": [{ - "small": "1", - "large": "1" - }], - "offsetYaxis": [{ - "small": "1", - "large": "1" - }] - }] - }], - "circle": [{ - "center": [{ - "latitude": "1", - "longitude": "1", - "elevation": "1", - "regional": "op" - }], - "radius": "3", - "units": "4" - }], - "regionPointSet": [{ - "nodeList": [{ - "xOffset": "1", - "yOffset": "1" - }] - }] - }] - }] - }] - }] - }, - "content": { - "sspMsgRights1": "1", - "sspMsgRights2": "2", - "contentType": { - "advisory": [{ - "ITISCodes": "268", - "ITIStext": "Speed Limit" - } ], - "workZone": [], - "genericSign": [], - "speedLimit": [], - "exitService": [] - }, - "URL-Short": "op", - "regional": "op" - } - }], - "regional": "op" - }, - "RSUs": [{ - "target": "127.0.0.1", - "username": "v3user", - "password": "password", - "retries": "1", - "timeout": "2000" - }], - "snmp": { - "rsuid": "8300", - "msgid": "31", - "mode": "1", - "channel": "178", - "interval": "1", - "deliverystart": "010114111530", - "deliverystop": "010114130000", - "enable": "1", - "status": "4" - } -}' "http://localhost:8080/tim" +curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 4c014aac-3597-a40d-e992-271d377d6d4c" -d '{ + "timContent": { + "msgcnt": "1", + "timestamp": "op", + "packetID": "op", + "urlB": "op", + "travelerDataFrame": [{ + "header": { + "sspindex": "1", + "travelerInfoType": "1", + "msgId": { + "FurtherInfoID": "1", + "RoadSignID": { + "position3D": { + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }, + "HeadingSlice": "1010011010010100", + "MUTCDCode": "op", + "MsgCRC": "op" + } + }, + "DYear": "op", + "MinuteOfTheYear": "0", + "MinutesDuration": "0", + "SignPriority": "0" + }, + "region": { + "sspindex": "0", + "GeographicalPath": [{ + "name": "op", + "id": "op", + "anchor": "op", + "laneWidth": "op", + "diretionality": "op", + "closedPath": "op", + "direction": "op", + "description": [{ + "path": [{ + "scale": "op", + "offset": [{ + "xy": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }], + "computed": [{ + "referenceLaneID": "1", + "offsetXaxis": [{ + "small": "1", + "large": "1" + }], + "offsetYaxis": [{ + "small": "1", + "large": "1" + }] + }] + }], + "ll": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }] + }] + }] + }], + "geometry": [{ + "direction": "1001101100100100", + "circle": [{ + "center": [{ + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }], + "radius": "3", + "units": "4" + }] + }], + "oldRegion": [{ + "direction": "1001101100100100", + "area": [{ + "shapePointSet": [{ + "nodes": [{ + "delta": [{ + "node-LL1": [{ + "lon": "20", + "lat": "21" + }], + "node-LL2": [{ + "lon": "20", + "lat": "21" + }], + "node-LL3": [{ + "lon": "20", + "lat": "21" + }], + "node-LL4": [{ + "lon": "20", + "lat": "21" + }], + "node-LL5": [{ + "lon": "20", + "lat": "21" + }], + "node-LL6": [{ + "lon": "20", + "lat": "21" + }] + }], + "attributes": "op" + }], + "computed": [{ + "referenceLaneID": "1", + "offsetXaxis": [{ + "small": "1", + "large": "1" + }], + "offsetYaxis": [{ + "small": "1", + "large": "1" + }] + }] + }], + "circle": [{ + "center": [{ + "latitude": "1", + "longitude": "1", + "elevation": "1", + "regional": "op" + }], + "radius": "3", + "units": "4" + }], + "regionPointSet": [{ + "nodeList": [{ + "xOffset": "1", + "yOffset": "1" + }] + }] + }] + }] + }] + }] + }, + "content": { + "sspMsgRights1": "1", + "sspMsgRights2": "2", + "contentType": { + "advisory": [{ + "ITISCodes": "268", + "ITIStext": "Speed Limit" + } ], + "workZone": [], + "genericSign": [], + "speedLimit": [], + "exitService": [] + }, + "URL-Short": "op", + "regional": "op" + } + }], + "regional": "op" + }, + "RSUs": [{ + "target": "127.0.0.1", + "username": "v3user", + "password": "password", + "retries": "1", + "timeout": "2000" + }], + "snmp": { + "rsuid": "8300", + "msgid": "31", + "mode": "1", + "channel": "178", + "interval": "1", + "deliverystart": "010114111530", + "deliverystop": "010114130000", + "enable": "1", + "status": "4" + } +}' "http://localhost:8080/tim" diff --git a/docs/timEndpointPython.py b/docs/timEndpointPython.py index e4927cb0a..73232755e 100644 --- a/docs/timEndpointPython.py +++ b/docs/timEndpointPython.py @@ -1,14 +1,14 @@ -import requests - -url = "http://localhost:8080/tim" - -payload = "{\r\n\t\"timContent\": {\r\n\t\t\"msgcnt\": \"1\",\r\n\t\t\"timestamp\": \"op\",\r\n\t\t\"packetID\": \"op\",\r\n\t\t\"urlB\": \"op\",\r\n\t\t\"travelerDataFrame\": [{\r\n\t\t\t\"header\": {\r\n\t\t\t\t\"sspindex\": \"1\",\r\n\t\t\t\t\"travelerInfoType\": \"1\",\r\n\t\t\t\t\"msgId\": {\r\n\t\t\t\t\t\"FurtherInfoID\": \"1\",\r\n\t\t\t\t\t\"RoadSignID\": {\r\n\t\t\t\t\t\t\"position3D\": {\r\n\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\"HeadingSlice\": \"1010011010010100\",\r\n\t\t\t\t\t\t\"MUTCDCode\": \"op\",\r\n\t\t\t\t\t\t\"MsgCRC\": \"op\"\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\"DYear\": \"op\",\r\n\t\t\t\t\"MinuteOfTheYear\": \"0\",\r\n\t\t\t\t\"MinutesDuration\": \"0\",\r\n\t\t\t\t\"SignPriority\": \"0\"\r\n\t\t\t},\r\n\t\t\t\"region\": {\r\n\t\t\t\t\"sspindex\": \"0\",\r\n\t\t\t\t\"GeographicalPath\": [{\r\n\t\t\t\t\t\"name\": \"op\",\r\n\t\t\t\t\t\"id\": \"op\",\r\n\t\t\t\t\t\"anchor\": \"op\",\r\n\t\t\t\t\t\"laneWidth\": \"op\",\r\n\t\t\t\t\t\"diretionality\": \"op\",\r\n\t\t\t\t\t\"closedPath\": \"op\",\r\n\t\t\t\t\t\"direction\": \"op\",\r\n\t\t\t\t\t\"description\": [{\r\n\t\t\t\t\t\t\"path\": [{\r\n\t\t\t\t\t\t\t\"scale\": \"op\",\r\n\t\t\t\t\t\t\t\"offset\": [{\r\n\t\t\t\t\t\t\t\t\"xy\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"ll\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"geometry\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"oldRegion\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"area\": [{\r\n\t\t\t\t\t\t\t\t\"shapePointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"regionPointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodeList\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"xOffset\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"yOffset\": \"1\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}]\r\n\t\t\t\t\t}]\r\n\t\t\t\t}]\r\n\t\t\t},\r\n\t\t\t\"content\": {\r\n\t\t\t\t\"sspMsgRights1\": \"1\",\r\n\t\t\t\t\"sspMsgRights2\": \"2\",\r\n\t\t\t\t\"contentType\": {\r\n\t\t\t\t\t\"advisory\": [{\r\n\t\t\t\t\t\t\"ITISCodes\": \"268\",\r\n\t\t\t\t\t\t\"ITIStext\": \"Speed Limit\"\r\n\t\t\t\t\t} ],\r\n\t\t\t\t\t\"workZone\": [],\r\n\t\t\t\t\t\"genericSign\": [],\r\n\t\t\t\t\t\"speedLimit\": [],\r\n\t\t\t\t\t\"exitService\": []\r\n\t\t\t\t},\r\n\t\t\t\t\"URL-Short\": \"op\",\r\n\t\t\t\t\"regional\": \"op\"\r\n\t\t\t}\r\n\t\t}],\r\n\t\t\"regional\": \"op\"\r\n\t},\r\n\t\"RSUs\": [{\r\n\t\t\"target\": \"127.0.0.1\",\r\n\t\t\"username\": \"v3user\",\r\n\t\t\"password\": \"password\",\r\n\t\t\"retries\": \"1\",\r\n\t\t\"timeout\": \"2000\"\r\n\t}], \r\n\t\"snmp\": {\r\n\t\t\"rsuid\": \"8300\",\r\n\t\t\"msgid\": \"31\",\r\n\t\t\"mode\": \"1\",\r\n\t\t\"channel\": \"178\",\r\n\t\t\"interval\": \"1\",\r\n\t\t\"deliverystart\": \"010114111530\",\r\n\t\t\"deliverystop\": \"010114130000\",\r\n\t\t\"enable\": \"1\",\r\n\t\t\"status\": \"4\"\r\n\t}\r\n}" -headers = { - 'content-type': "application/json", - 'cache-control': "no-cache", - 'postman-token': "e3aeeabb-569d-e3e9-0816-2b271aace18d" - } - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) +import requests + +url = "http://localhost:8080/tim" + +payload = "{\r\n\t\"timContent\": {\r\n\t\t\"msgcnt\": \"1\",\r\n\t\t\"timestamp\": \"op\",\r\n\t\t\"packetID\": \"op\",\r\n\t\t\"urlB\": \"op\",\r\n\t\t\"travelerDataFrame\": [{\r\n\t\t\t\"header\": {\r\n\t\t\t\t\"sspindex\": \"1\",\r\n\t\t\t\t\"travelerInfoType\": \"1\",\r\n\t\t\t\t\"msgId\": {\r\n\t\t\t\t\t\"FurtherInfoID\": \"1\",\r\n\t\t\t\t\t\"RoadSignID\": {\r\n\t\t\t\t\t\t\"position3D\": {\r\n\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\"HeadingSlice\": \"1010011010010100\",\r\n\t\t\t\t\t\t\"MUTCDCode\": \"op\",\r\n\t\t\t\t\t\t\"MsgCRC\": \"op\"\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\"DYear\": \"op\",\r\n\t\t\t\t\"MinuteOfTheYear\": \"0\",\r\n\t\t\t\t\"MinutesDuration\": \"0\",\r\n\t\t\t\t\"SignPriority\": \"0\"\r\n\t\t\t},\r\n\t\t\t\"region\": {\r\n\t\t\t\t\"sspindex\": \"0\",\r\n\t\t\t\t\"GeographicalPath\": [{\r\n\t\t\t\t\t\"name\": \"op\",\r\n\t\t\t\t\t\"id\": \"op\",\r\n\t\t\t\t\t\"anchor\": \"op\",\r\n\t\t\t\t\t\"laneWidth\": \"op\",\r\n\t\t\t\t\t\"diretionality\": \"op\",\r\n\t\t\t\t\t\"closedPath\": \"op\",\r\n\t\t\t\t\t\"direction\": \"op\",\r\n\t\t\t\t\t\"description\": [{\r\n\t\t\t\t\t\t\"path\": [{\r\n\t\t\t\t\t\t\t\"scale\": \"op\",\r\n\t\t\t\t\t\t\t\"offset\": [{\r\n\t\t\t\t\t\t\t\t\"xy\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"ll\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"geometry\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\"oldRegion\": [{\r\n\t\t\t\t\t\t\t\"direction\": \"1001101100100100\",\r\n\t\t\t\t\t\t\t\"area\": [{\r\n\t\t\t\t\t\t\t\t\"shapePointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodes\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"delta\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL1\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL2\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL3\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL4\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL5\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\t\"node-LL6\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lon\": \"20\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"lat\": \"21\"\r\n\t\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"attributes\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"computed\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"referenceLaneID\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"offsetXaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\t\"offsetYaxis\": [{\r\n\t\t\t\t\t\t\t\t\t\t\t\"small\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\t\"large\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"circle\": [{\r\n\t\t\t\t\t\t\t\t\t\"center\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"latitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"longitude\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"elevation\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"regional\": \"op\"\r\n\t\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\t\"radius\": \"3\",\r\n\t\t\t\t\t\t\t\t\t\"units\": \"4\"\r\n\t\t\t\t\t\t\t\t}],\r\n\t\t\t\t\t\t\t\t\"regionPointSet\": [{\r\n\t\t\t\t\t\t\t\t\t\"nodeList\": [{\r\n\t\t\t\t\t\t\t\t\t\t\"xOffset\": \"1\",\r\n\t\t\t\t\t\t\t\t\t\t\"yOffset\": \"1\"\r\n\t\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t\t}]\r\n\t\t\t\t\t\t}]\r\n\t\t\t\t\t}]\r\n\t\t\t\t}]\r\n\t\t\t},\r\n\t\t\t\"content\": {\r\n\t\t\t\t\"sspMsgRights1\": \"1\",\r\n\t\t\t\t\"sspMsgRights2\": \"2\",\r\n\t\t\t\t\"contentType\": {\r\n\t\t\t\t\t\"advisory\": [{\r\n\t\t\t\t\t\t\"ITISCodes\": \"268\",\r\n\t\t\t\t\t\t\"ITIStext\": \"Speed Limit\"\r\n\t\t\t\t\t} ],\r\n\t\t\t\t\t\"workZone\": [],\r\n\t\t\t\t\t\"genericSign\": [],\r\n\t\t\t\t\t\"speedLimit\": [],\r\n\t\t\t\t\t\"exitService\": []\r\n\t\t\t\t},\r\n\t\t\t\t\"URL-Short\": \"op\",\r\n\t\t\t\t\"regional\": \"op\"\r\n\t\t\t}\r\n\t\t}],\r\n\t\t\"regional\": \"op\"\r\n\t},\r\n\t\"RSUs\": [{\r\n\t\t\"target\": \"127.0.0.1\",\r\n\t\t\"username\": \"v3user\",\r\n\t\t\"password\": \"password\",\r\n\t\t\"retries\": \"1\",\r\n\t\t\"timeout\": \"2000\"\r\n\t}], \r\n\t\"snmp\": {\r\n\t\t\"rsuid\": \"8300\",\r\n\t\t\"msgid\": \"31\",\r\n\t\t\"mode\": \"1\",\r\n\t\t\"channel\": \"178\",\r\n\t\t\"interval\": \"1\",\r\n\t\t\"deliverystart\": \"010114111530\",\r\n\t\t\"deliverystop\": \"010114130000\",\r\n\t\t\"enable\": \"1\",\r\n\t\t\"status\": \"4\"\r\n\t}\r\n}" +headers = { + 'content-type': "application/json", + 'cache-control': "no-cache", + 'postman-token': "e3aeeabb-569d-e3e9-0816-2b271aace18d" + } + +response = requests.request("POST", url, data=payload, headers=headers) + +print(response.text) diff --git a/jpo-ode-common/LICENSE-2.0.html b/jpo-ode-common/LICENSE-2.0.html index 16303d2c7..d1055c8ad 100644 --- a/jpo-ode-common/LICENSE-2.0.html +++ b/jpo-ode-common/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-common/pom.xml b/jpo-ode-common/pom.xml index 63e6af4ad..da1882b32 100644 --- a/jpo-ode-common/pom.xml +++ b/jpo-ode-common/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT jpo-ode-common diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java index d87c7692d..96cf0a25a 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacket.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Arrays; - -import us.dot.its.jpo.ode.util.CodecUtils; -import us.dot.its.jpo.ode.util.CrcCccitt; - -public class InetPacket { - - private static final int MAGIC_NUMBER = 982451653; - private static final int MIN_BUNDLE_LENGTH = 4 + 4 + 1 + 4 + 2; // magic + port + type + ip4 + CRC - - private InetPoint point; - private byte[] payload; - - public InetPacket(String host, int port, byte[] payload) throws UnknownHostException { - this(InetAddress.getByName( host ), port, payload); - } - - public InetPacket(InetAddress ipAddress, int port, byte[] payload) { - this(new InetPoint(ipAddress.getAddress(), port), payload); - } - - public InetPacket(InetPoint point, byte[] payload) { - this.point = point; - if ( !parseBundle(payload) ) - this.payload = payload; - } - - public InetPacket(DatagramPacket packet) { - point = new InetPoint(packet.getAddress().getAddress(), packet.getPort()); - byte[] data = Arrays.copyOfRange(packet.getData(), packet.getOffset(), packet.getLength()); - if ( !parseBundle(data) ) - payload = data; - } - - public InetPacket(byte[] bundle) { - if ( !parseBundle(bundle) ) - payload = bundle; - } - - public InetPoint getPoint() { - return point; - } - - public byte[] getPayload() { - return payload; - } - - public byte[] getBundle() { - if ( point == null ) - return payload; - int payloadLength = payload != null ? payload.length : 0; - int headerLength = MIN_BUNDLE_LENGTH - 4 + point.address.length; - byte [] bundle = new byte[headerLength + payloadLength]; - ByteBuffer buffer = ByteBuffer.allocate(headerLength).order(ByteOrder.BIG_ENDIAN); - buffer.putInt(MAGIC_NUMBER); - buffer.putInt(point.port); - buffer.put((byte)(point.address.length == 16 ? 1 : 0)); - buffer.put(point.address); - byte[] header = buffer.array(); - assert(header.length == headerLength); - CrcCccitt.setMsgCRC(header); - System.arraycopy(header, 0, bundle, 0, headerLength); - if ( payload != null ) - System.arraycopy(payload, 0, bundle, headerLength, payloadLength); - return bundle; - } - - public boolean parseBundle(byte[] bundle) { - if ( bundle == null || bundle.length < MIN_BUNDLE_LENGTH ) - return false; - ByteBuffer buffer = ByteBuffer.wrap(bundle); - int magic = buffer.getInt(); - if ( magic != MAGIC_NUMBER ) - return false; - int port = buffer.getInt(); - byte type = buffer.get(); - int addressLength = type == 1 ? 16 : 4; - if ( buffer.remaining() < addressLength + 2 ) - return false; - if ( !CrcCccitt.isValidMsgCRC(bundle, 0, MIN_BUNDLE_LENGTH - 4 + addressLength) ) - return false; - byte[] address = new byte[addressLength]; - buffer.get(address,0,addressLength); - buffer.getShort(); - point = new InetPoint(address, port, true); - int payloadLength = bundle.length - MIN_BUNDLE_LENGTH + 4 - addressLength; - payload = new byte[payloadLength]; - buffer.get(payload,0,payloadLength); - return true; - } - - public String toHexString() { - return CodecUtils.toHex(getBundle()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +import us.dot.its.jpo.ode.util.CodecUtils; +import us.dot.its.jpo.ode.util.CrcCccitt; + +public class InetPacket { + + private static final int MAGIC_NUMBER = 982451653; + private static final int MIN_BUNDLE_LENGTH = 4 + 4 + 1 + 4 + 2; // magic + port + type + ip4 + CRC + + private InetPoint point; + private byte[] payload; + + public InetPacket(String host, int port, byte[] payload) throws UnknownHostException { + this(InetAddress.getByName( host ), port, payload); + } + + public InetPacket(InetAddress ipAddress, int port, byte[] payload) { + this(new InetPoint(ipAddress.getAddress(), port), payload); + } + + public InetPacket(InetPoint point, byte[] payload) { + this.point = point; + if ( !parseBundle(payload) ) + this.payload = payload; + } + + public InetPacket(DatagramPacket packet) { + point = new InetPoint(packet.getAddress().getAddress(), packet.getPort()); + byte[] data = Arrays.copyOfRange(packet.getData(), packet.getOffset(), packet.getLength()); + if ( !parseBundle(data) ) + payload = data; + } + + public InetPacket(byte[] bundle) { + if ( !parseBundle(bundle) ) + payload = bundle; + } + + public InetPoint getPoint() { + return point; + } + + public byte[] getPayload() { + return payload; + } + + public byte[] getBundle() { + if ( point == null ) + return payload; + int payloadLength = payload != null ? payload.length : 0; + int headerLength = MIN_BUNDLE_LENGTH - 4 + point.address.length; + byte [] bundle = new byte[headerLength + payloadLength]; + ByteBuffer buffer = ByteBuffer.allocate(headerLength).order(ByteOrder.BIG_ENDIAN); + buffer.putInt(MAGIC_NUMBER); + buffer.putInt(point.port); + buffer.put((byte)(point.address.length == 16 ? 1 : 0)); + buffer.put(point.address); + byte[] header = buffer.array(); + assert(header.length == headerLength); + CrcCccitt.setMsgCRC(header); + System.arraycopy(header, 0, bundle, 0, headerLength); + if ( payload != null ) + System.arraycopy(payload, 0, bundle, headerLength, payloadLength); + return bundle; + } + + public boolean parseBundle(byte[] bundle) { + if ( bundle == null || bundle.length < MIN_BUNDLE_LENGTH ) + return false; + ByteBuffer buffer = ByteBuffer.wrap(bundle); + int magic = buffer.getInt(); + if ( magic != MAGIC_NUMBER ) + return false; + int port = buffer.getInt(); + byte type = buffer.get(); + int addressLength = type == 1 ? 16 : 4; + if ( buffer.remaining() < addressLength + 2 ) + return false; + if ( !CrcCccitt.isValidMsgCRC(bundle, 0, MIN_BUNDLE_LENGTH - 4 + addressLength) ) + return false; + byte[] address = new byte[addressLength]; + buffer.get(address,0,addressLength); + buffer.getShort(); + point = new InetPoint(address, port, true); + int payloadLength = bundle.length - MIN_BUNDLE_LENGTH + 4 - addressLength; + payload = new byte[payloadLength]; + buffer.get(payload,0,payloadLength); + return true; + } + + public String toHexString() { + return CodecUtils.toHex(getBundle()); + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java index a1f36b5d6..3058b4774 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketException.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -public class InetPacketException extends Exception { - - private static final long serialVersionUID = 1L; - - public InetPacketException(String message) { - super(message); - } - - public InetPacketException(String message, Throwable cause) { - super(message, cause); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +public class InetPacketException extends Exception { + + private static final long serialVersionUID = 1L; + + public InetPacketException(String message) { + super(message); + } + + public InetPacketException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java index f8e352ca9..ced6cc3b5 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPacketSender.java @@ -1,160 +1,160 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.SocketException; - -import org.apache.log4j.Logger; - -/** - * Sender/Forwarder helper class for use by Forwarder, Transport, and Data Sink that need to send packets around - */ -public class InetPacketSender { - - private static final String INVALID_PARAMETERS_MSG = "Invalid Parameters. Parameters destination point and payload can not be null"; - - private static final Logger log = Logger.getLogger(InetPacketSender.class); - - /** - * Inet address and port to forward packets to - */ - private InetPoint frwdPoint; - - /** - * Specifies whether outbound IPv4 messages should be send directly or forwarded. Default is send directly. - * To force forwarding IPv4 messages, set this variable to true. - */ - private boolean forwardAll; - - public InetPacketSender() {} - - /** - * Creates an instance of the forwarder/sender helper class. - * @param frwdPoint is the destination to use for forwarding - */ - public InetPacketSender(InetPoint frwdPoint) { - this.frwdPoint = frwdPoint; - } - - /** - * Forward packet. Intended client is the forwarder that received a packet - * @param inbound UDP packet - * @throws InetPacketException - */ - public void forward(DatagramPacket packet) throws InetPacketException { - if ( packet == null ) { - log.warn("Ignoring forward request for null packet"); - return; - } - if ( frwdPoint == null ) - throw new InetPacketException("Couldn't forward packet. Reason: Forwarding destination is not defined."); - send(frwdPoint, new InetPacket(packet).getBundle()); - } - - /** - * Send packet. Intended client is the forwarder that sends outbound packet - * @param packet outbound packet that contains destination+payload bundle - * @throws InetPacketException - */ - public void send(DatagramPacket packet) throws InetPacketException { - if ( packet == null ) { - log.warn("Ignoring send request for null packet"); - return; - } - InetPacket p = new InetPacket(packet); - InetPoint point = p.getPoint(); - if ( point == null ) - throw new InetPacketException("Couldn't send packet. Reason: Destination is not defined in the packet (not a bundle?)"); - send(point, p.getPayload()); - } - - /** - * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder - * @param dstPoint destination address and port for forwarder to forward to - * @param payload data to forward - * @throws InetPacketException - */ - public void forward(InetPoint dstPoint, byte[] payload) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - if ( frwdPoint == null ) - log.warn("Couldn't forward packet. Reason: Forwarding destination is not defined."); - if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll()) ) { - send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); - } else { - log.debug("Using direct send instead of forwarding"); - send(dstPoint, payload); - } - } - - /** - * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder or direct - * @param dstPoint destination address and port of the final destination - * @param payload data to forward or send - * @param fromForwarder whether the original request came through a forwarder - * @throws InetPacketException - */ - public void forward(InetPoint dstPoint, byte[] payload, boolean fromForwarder) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll() || fromForwarder) ) { - send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); - } else { - log.debug("Using direct send instead of forwarding"); - send(dstPoint, payload); - } - } - - /** - * Send payload to the destination specified. Intended clients are Transport or Data Sink sending directly to the client - * @param dstPoint destination address and port to send to - * @param payload data to send - * @throws InetPacketException - */ - public void send(InetPoint dstPoint, byte[] payload) throws InetPacketException { - if ( dstPoint == null || payload == null ) - throw new InetPacketException(INVALID_PARAMETERS_MSG); - try(DatagramSocket sock = new DatagramSocket()) { - DatagramPacket packet = new DatagramPacket(payload, payload.length, dstPoint.getInetAddress(), dstPoint.port); - sock.send(packet); - } catch (SocketException ex) { - throw new InetPacketException("Couldn't send packet because socket closed.", ex); - } catch (IOException ex) { - throw new InetPacketException("Couldn't send packet due to IO exception.", ex); - } - } - - /** - * Reports whether outbound IPv4 messages should be send directly or forwarded. - * @return true if IPv4 packets are forwarded in addition to IPv6 packets - */ - public boolean isForwardAll() { - return forwardAll; - } - - /** - * - * @param forwardAll Directs how to handle IPv4 messages. - * Specify true to force forwarding IPv4 messages, and false to always send them directly. - */ - public void setForwardAll(boolean forwardAll) { - this.forwardAll = forwardAll; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.SocketException; + +import org.apache.log4j.Logger; + +/** + * Sender/Forwarder helper class for use by Forwarder, Transport, and Data Sink that need to send packets around + */ +public class InetPacketSender { + + private static final String INVALID_PARAMETERS_MSG = "Invalid Parameters. Parameters destination point and payload can not be null"; + + private static final Logger log = Logger.getLogger(InetPacketSender.class); + + /** + * Inet address and port to forward packets to + */ + private InetPoint frwdPoint; + + /** + * Specifies whether outbound IPv4 messages should be send directly or forwarded. Default is send directly. + * To force forwarding IPv4 messages, set this variable to true. + */ + private boolean forwardAll; + + public InetPacketSender() {} + + /** + * Creates an instance of the forwarder/sender helper class. + * @param frwdPoint is the destination to use for forwarding + */ + public InetPacketSender(InetPoint frwdPoint) { + this.frwdPoint = frwdPoint; + } + + /** + * Forward packet. Intended client is the forwarder that received a packet + * @param inbound UDP packet + * @throws InetPacketException + */ + public void forward(DatagramPacket packet) throws InetPacketException { + if ( packet == null ) { + log.warn("Ignoring forward request for null packet"); + return; + } + if ( frwdPoint == null ) + throw new InetPacketException("Couldn't forward packet. Reason: Forwarding destination is not defined."); + send(frwdPoint, new InetPacket(packet).getBundle()); + } + + /** + * Send packet. Intended client is the forwarder that sends outbound packet + * @param packet outbound packet that contains destination+payload bundle + * @throws InetPacketException + */ + public void send(DatagramPacket packet) throws InetPacketException { + if ( packet == null ) { + log.warn("Ignoring send request for null packet"); + return; + } + InetPacket p = new InetPacket(packet); + InetPoint point = p.getPoint(); + if ( point == null ) + throw new InetPacketException("Couldn't send packet. Reason: Destination is not defined in the packet (not a bundle?)"); + send(point, p.getPayload()); + } + + /** + * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder + * @param dstPoint destination address and port for forwarder to forward to + * @param payload data to forward + * @throws InetPacketException + */ + public void forward(InetPoint dstPoint, byte[] payload) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + if ( frwdPoint == null ) + log.warn("Couldn't forward packet. Reason: Forwarding destination is not defined."); + if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll()) ) { + send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); + } else { + log.debug("Using direct send instead of forwarding"); + send(dstPoint, payload); + } + } + + /** + * Forward payload to be sent to dstPoint. Intended clients are Transport or Data Sink sending via forwarder or direct + * @param dstPoint destination address and port of the final destination + * @param payload data to forward or send + * @param fromForwarder whether the original request came through a forwarder + * @throws InetPacketException + */ + public void forward(InetPoint dstPoint, byte[] payload, boolean fromForwarder) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + if ( frwdPoint != null && (dstPoint.isIPv6Address() || isForwardAll() || fromForwarder) ) { + send(frwdPoint, new InetPacket(dstPoint, payload).getBundle()); + } else { + log.debug("Using direct send instead of forwarding"); + send(dstPoint, payload); + } + } + + /** + * Send payload to the destination specified. Intended clients are Transport or Data Sink sending directly to the client + * @param dstPoint destination address and port to send to + * @param payload data to send + * @throws InetPacketException + */ + public void send(InetPoint dstPoint, byte[] payload) throws InetPacketException { + if ( dstPoint == null || payload == null ) + throw new InetPacketException(INVALID_PARAMETERS_MSG); + try(DatagramSocket sock = new DatagramSocket()) { + DatagramPacket packet = new DatagramPacket(payload, payload.length, dstPoint.getInetAddress(), dstPoint.port); + sock.send(packet); + } catch (SocketException ex) { + throw new InetPacketException("Couldn't send packet because socket closed.", ex); + } catch (IOException ex) { + throw new InetPacketException("Couldn't send packet due to IO exception.", ex); + } + } + + /** + * Reports whether outbound IPv4 messages should be send directly or forwarded. + * @return true if IPv4 packets are forwarded in addition to IPv6 packets + */ + public boolean isForwardAll() { + return forwardAll; + } + + /** + * + * @param forwardAll Directs how to handle IPv4 messages. + * Specify true to force forwarding IPv4 messages, and false to always send them directly. + */ + public void setForwardAll(boolean forwardAll) { + this.forwardAll = forwardAll; + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java index e91361c1c..c63db8ed5 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/inet/InetPoint.java @@ -1,73 +1,73 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPoint { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public final byte[] address; - public final int port; - public final boolean forward; - - public InetPoint(String host, int port, boolean forward) throws UnknownHostException { - this(InetAddress.getByName(host).getAddress(), port, forward); - } - - public InetPoint(byte[] address, int port) { - this(address, port, false); - } - - public InetPoint(byte[] address, int port, boolean forward ) { - if (address == null) { - throw new IllegalArgumentException("IP Address is required"); - } - this.address = address; - this.port = port; - this.forward = forward; - } - - public InetAddress getInetAddress() throws UnknownHostException { - return InetAddress.getByAddress(address); - } - - public boolean isIPv6Address() { - return address.length == 16; - } - - @Override - public String toString() { - String host = "?"; - try { - host = InetAddress.getByAddress(address).getHostAddress(); - } catch (UnknownHostException e) { - logger.error("Error", e); - } - return String.format("%s { port = %d (0x%x); address = %s (%s, %s); forward = %s }", - getClass().getSimpleName(), - port, port, - CodecUtils.toHex(address), address.length == 4 ? "IPv4" : "IPv6", host, - forward ? "true" : "false" - ); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPoint { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public final byte[] address; + public final int port; + public final boolean forward; + + public InetPoint(String host, int port, boolean forward) throws UnknownHostException { + this(InetAddress.getByName(host).getAddress(), port, forward); + } + + public InetPoint(byte[] address, int port) { + this(address, port, false); + } + + public InetPoint(byte[] address, int port, boolean forward ) { + if (address == null) { + throw new IllegalArgumentException("IP Address is required"); + } + this.address = address; + this.port = port; + this.forward = forward; + } + + public InetAddress getInetAddress() throws UnknownHostException { + return InetAddress.getByAddress(address); + } + + public boolean isIPv6Address() { + return address.length == 16; + } + + @Override + public String toString() { + String host = "?"; + try { + host = InetAddress.getByAddress(address).getHostAddress(); + } catch (UnknownHostException e) { + logger.error("Error", e); + } + return String.format("%s { port = %d (0x%x); address = %s (%s, %s); forward = %s }", + getClass().getSimpleName(), + port, port, + CodecUtils.toHex(address), address.length == 4 ? "IPv4" : "IPv6", host, + forward ? "true" : "false" + ); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java index 285dfe951..43d0d1b89 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeHexByteArray.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.util.CodecUtils; - -public class OdeHexByteArray extends OdeObject { - - private static final long serialVersionUID = 6106562581659367345L; - - private String bytes; - - public OdeHexByteArray() { - super(); - } - - public OdeHexByteArray(String bytes) { - super(); - this.bytes = bytes; - } - - public OdeHexByteArray(byte[] bytes) { - setBytes(bytes); - } - - public String getBytes() { - return bytes; - } - - public void setBytes(String bytes) { - this.bytes = bytes; - } - - public void setBytes(byte[] bytes) { - this.bytes = CodecUtils.toHex(bytes); - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.util.CodecUtils; + +public class OdeHexByteArray extends OdeObject { + + private static final long serialVersionUID = 6106562581659367345L; + + private String bytes; + + public OdeHexByteArray() { + super(); + } + + public OdeHexByteArray(String bytes) { + super(); + this.bytes = bytes; + } + + public OdeHexByteArray(byte[] bytes) { + setBytes(bytes); + } + + public String getBytes() { + return bytes; + } + + public void setBytes(String bytes) { + this.bytes = bytes; + } + + public void setBytes(byte[] bytes) { + this.bytes = CodecUtils.toHex(bytes); + } + + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java index 3233878be..e0e7b15d5 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/model/OdeObject.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.io.Serializable; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import us.dot.its.jpo.ode.util.JsonUtils; -import us.dot.its.jpo.ode.util.XmlUtils; -import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException; - -public class OdeObject implements Serializable { - private static final long serialVersionUID = 7514526408925039533L; - - public String toJson() { - return JsonUtils.toJson(this, false); - } - - public String toJson(boolean verbose) { - return JsonUtils.toJson(this, verbose); - } - - public String toXml() throws XmlUtilsException, JsonProcessingException { - return XmlUtils.toXmlStatic(this); - } - - @Override - public String toString() { - return this.toJson(true); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.io.Serializable; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import us.dot.its.jpo.ode.util.JsonUtils; +import us.dot.its.jpo.ode.util.XmlUtils; +import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException; + +public class OdeObject implements Serializable { + private static final long serialVersionUID = 7514526408925039533L; + + public String toJson() { + return JsonUtils.toJson(this, false); + } + + public String toJson(boolean verbose) { + return JsonUtils.toJson(this, verbose); + } + + public String toXml() throws XmlUtilsException, JsonProcessingException { + return XmlUtils.toXmlStatic(this); + } + + @Override + public String toString() { + return this.toJson(true); + } + +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java index c8ad2dccf..a93135061 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CodecUtils.java @@ -1,281 +1,281 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Arrays; - -import javax.xml.bind.DatatypeConverter; - -public class CodecUtils { - - private CodecUtils() { - } - - /** - * Converts an array of shorts to a byte array. - *

    - * Example: (short) 5 will be stored as {0, 5} since 5 = 00000000 00000101 - *

    - *

    - * Example: (short) 257 will be stored as {1, 1} since 257 = 00000001 00000001 - *

    - * - * @param shorts array of 16 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 16 bit integers - */ - public static byte[] shortsToBytes(short[] shorts, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(shorts.length * 2).order(bo); - for (short num : shorts) { - buffer.putShort(num); - } - return buffer.array(); - } - - /** - * Converts a single short to a byte array length 2. See - * {@link #shortsToBytes(short[])} - * - * @param number a 16 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 16 bit integer number - */ - public static byte[] shortToBytes(short number, ByteOrder bo) { - short[] shorts = new short[] { number }; - return shortsToBytes(shorts, bo); - } - - /** - * Converts an array of bytes to an array of shorts and returns the first - * element. See {@link #bytesToShorts(byte[])} - * - * @param bytes - * @return array of shorts - */ - public static short bytesToShort(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToShorts(bytes, offset, length, bo)[0]; - } - - /** - * Converts an array of bytes to an array of shorts. - *

    - * Example: {(byte) 1, (byte) 1} will return {(short) 257} since 257 = - * 00000001 00000001 - *

    - * - * @param bytes - * @return array of shorts - */ - public static short[] bytesToShorts(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfShorts = length / 2; - short[] shorts = new short[numberOfShorts]; - for (int i = 0; i < numberOfShorts; i++) { - shorts[i] = buffer.getShort(); - } - return shorts; - } - - /** - * Combines byte arrays. - * - * @param bytes - * @return combined array - * @throws IOException - */ - - public static byte[] mergeBytes(byte[]... bytes) throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - for (byte[] bArray : bytes) { - outputStream.write(bArray); - } - return outputStream.toByteArray(); - } - - /** - * Converts an array of integers to a byte array. - *

    - * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000101 - *

    - *

    - * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000001 00000001 - *

    - * - * @param ints array of 32 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 32 bit integers - */ - public static byte[] intsToBytes(int[] ints, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(ints.length * 4).order(bo); - for (int num : ints) { - buffer.putInt(num); - } - return buffer.array(); - } - - /** - * Converts a single int to a byte array length 4. See - * {@link #shortsToBytes(short[])} - * - * @param number a 32 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 32 bit integer number - */ - public static byte[] intToBytes(int number, ByteOrder bo) { - int[] ints = new int[] { number }; - return intsToBytes(ints, bo); - } - - public static int bytesToInt(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToInts(bytes, offset, length, bo)[0]; - } - - public static int[] bytesToInts(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfInts = length / 4; - int[] ints = new int[numberOfInts]; - for (int i = 0; i < numberOfInts; i++) { - ints[i] = buffer.getInt(); - } - return ints; - } - - /** - * Converts an array of longs to a byte array. - *

    - * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 - *

    - *

    - * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000001 - *

    - * - * @param longs array of 64 bit integers to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the array of 64 bit integers - */ - public static byte[] longsToBytes(long[] longs, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(longs.length * 8).order(bo); - for (long num : longs) { - buffer.putLong(num); - } - return buffer.array(); - } - - /** - * Converts a single long to a byte array length 8 in a 64 bit machine. See - * {@link #shortsToBytes(short[])} - * - * @param number a 64 bit integer to be converted to byte array - * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN - * @return byte array equivalent of the given 64 bit integer number - */ - public static byte[] longToBytes(long number, ByteOrder bo) { - long[] longs = new long[] { number }; - return longsToBytes(longs, bo); - } - - public static long bytesToLong(byte[] bytes, int offset, int length, ByteOrder bo) { - return bytesToLongs(bytes, offset, length, bo)[0]; - } - - public static long[] bytesToLongs(byte[] bytes, int offset, int length, ByteOrder bo) { - ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); - buffer.put(bytes, offset, length); - buffer.flip(); - int numberOfLongs = length / 8; - long[] longs = new long[numberOfLongs]; - for (int i = 0; i < numberOfLongs; i++) { - longs[i] = buffer.getLong(); - } - return longs; - } - - public static String toHex(byte[] bytes) { - return bytes != null ? DatatypeConverter.printHexBinary(bytes) : ""; - } - - public static String toHex(byte b) { - return DatatypeConverter.printHexBinary(new byte[]{b}); - } - - public static byte[] fromHex(String hex) { - return DatatypeConverter.parseHexBinary(hex); - } - - public static String toBase64(byte[] bytes) { - return bytes != null ? DatatypeConverter.printBase64Binary(bytes) : ""; - } - - public static byte[] fromBase64(String base64) { - return DatatypeConverter.parseBase64Binary(base64); - } - - /** - * @param strShort - * String representation of a short integer value in binary or hex - * format. If the string is in binary format, the length must be - * exactly 16 1s and zeros. If Hex format, the length must be - * exactly 4 Hex digits. - * - * @return a byte array equivalent of strShort - */ - public static byte[] shortStringToByteArray(String strShort) { - - byte[] byteArrayValue = null; - - int radix = radixOf(strShort); - - if (radix == 0) { - byteArrayValue = new byte[2]; // NOSONAR - } else { - byteArrayValue = Arrays - .copyOfRange(ByteBuffer.allocate(4).putInt(Integer.parseUnsignedInt(strShort, radix)).array(), 2, 4); - } - - return byteArrayValue; - } - - /** - * @param strShort - * String representation of a short integer value in binary or hex - * format. If strShort is in binary format, the length must be - * exactly 16 ones and zeros. If strShort is in Hex format, the - * length must be exactly 4 Hex digits. - * @return The radix of the strShort: Currently supporting only binary and - * hex, therefore the return value is either 2 or 16 - */ - private static int radixOf(String strShort) { - int radix = 0; - if (strShort == null || strShort.length() == 0) { - radix = 0; - } else if (strShort.length() == 16) { - radix = 2; - } else if (strShort.length() == 4) { - radix = 16; - } else { - throw new IllegalArgumentException("Short String length is invalid: " + strShort.length()); - } - return radix; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +import javax.xml.bind.DatatypeConverter; + +public class CodecUtils { + + private CodecUtils() { + } + + /** + * Converts an array of shorts to a byte array. + *

    + * Example: (short) 5 will be stored as {0, 5} since 5 = 00000000 00000101 + *

    + *

    + * Example: (short) 257 will be stored as {1, 1} since 257 = 00000001 00000001 + *

    + * + * @param shorts array of 16 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 16 bit integers + */ + public static byte[] shortsToBytes(short[] shorts, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(shorts.length * 2).order(bo); + for (short num : shorts) { + buffer.putShort(num); + } + return buffer.array(); + } + + /** + * Converts a single short to a byte array length 2. See + * {@link #shortsToBytes(short[])} + * + * @param number a 16 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 16 bit integer number + */ + public static byte[] shortToBytes(short number, ByteOrder bo) { + short[] shorts = new short[] { number }; + return shortsToBytes(shorts, bo); + } + + /** + * Converts an array of bytes to an array of shorts and returns the first + * element. See {@link #bytesToShorts(byte[])} + * + * @param bytes + * @return array of shorts + */ + public static short bytesToShort(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToShorts(bytes, offset, length, bo)[0]; + } + + /** + * Converts an array of bytes to an array of shorts. + *

    + * Example: {(byte) 1, (byte) 1} will return {(short) 257} since 257 = + * 00000001 00000001 + *

    + * + * @param bytes + * @return array of shorts + */ + public static short[] bytesToShorts(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfShorts = length / 2; + short[] shorts = new short[numberOfShorts]; + for (int i = 0; i < numberOfShorts; i++) { + shorts[i] = buffer.getShort(); + } + return shorts; + } + + /** + * Combines byte arrays. + * + * @param bytes + * @return combined array + * @throws IOException + */ + + public static byte[] mergeBytes(byte[]... bytes) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + for (byte[] bArray : bytes) { + outputStream.write(bArray); + } + return outputStream.toByteArray(); + } + + /** + * Converts an array of integers to a byte array. + *

    + * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000101 + *

    + *

    + * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000001 00000001 + *

    + * + * @param ints array of 32 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 32 bit integers + */ + public static byte[] intsToBytes(int[] ints, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(ints.length * 4).order(bo); + for (int num : ints) { + buffer.putInt(num); + } + return buffer.array(); + } + + /** + * Converts a single int to a byte array length 4. See + * {@link #shortsToBytes(short[])} + * + * @param number a 32 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 32 bit integer number + */ + public static byte[] intToBytes(int number, ByteOrder bo) { + int[] ints = new int[] { number }; + return intsToBytes(ints, bo); + } + + public static int bytesToInt(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToInts(bytes, offset, length, bo)[0]; + } + + public static int[] bytesToInts(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfInts = length / 4; + int[] ints = new int[numberOfInts]; + for (int i = 0; i < numberOfInts; i++) { + ints[i] = buffer.getInt(); + } + return ints; + } + + /** + * Converts an array of longs to a byte array. + *

    + * Example: (int) 5 will be stored as {0, 5} since 5 = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000101 + *

    + *

    + * Example: (int) 257 will be stored as {1, 1} since 257 = 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000001 + *

    + * + * @param longs array of 64 bit integers to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the array of 64 bit integers + */ + public static byte[] longsToBytes(long[] longs, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(longs.length * 8).order(bo); + for (long num : longs) { + buffer.putLong(num); + } + return buffer.array(); + } + + /** + * Converts a single long to a byte array length 8 in a 64 bit machine. See + * {@link #shortsToBytes(short[])} + * + * @param number a 64 bit integer to be converted to byte array + * @param bo Byte order ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIAN + * @return byte array equivalent of the given 64 bit integer number + */ + public static byte[] longToBytes(long number, ByteOrder bo) { + long[] longs = new long[] { number }; + return longsToBytes(longs, bo); + } + + public static long bytesToLong(byte[] bytes, int offset, int length, ByteOrder bo) { + return bytesToLongs(bytes, offset, length, bo)[0]; + } + + public static long[] bytesToLongs(byte[] bytes, int offset, int length, ByteOrder bo) { + ByteBuffer buffer = ByteBuffer.allocate(length).order(bo); + buffer.put(bytes, offset, length); + buffer.flip(); + int numberOfLongs = length / 8; + long[] longs = new long[numberOfLongs]; + for (int i = 0; i < numberOfLongs; i++) { + longs[i] = buffer.getLong(); + } + return longs; + } + + public static String toHex(byte[] bytes) { + return bytes != null ? DatatypeConverter.printHexBinary(bytes) : ""; + } + + public static String toHex(byte b) { + return DatatypeConverter.printHexBinary(new byte[]{b}); + } + + public static byte[] fromHex(String hex) { + return DatatypeConverter.parseHexBinary(hex); + } + + public static String toBase64(byte[] bytes) { + return bytes != null ? DatatypeConverter.printBase64Binary(bytes) : ""; + } + + public static byte[] fromBase64(String base64) { + return DatatypeConverter.parseBase64Binary(base64); + } + + /** + * @param strShort + * String representation of a short integer value in binary or hex + * format. If the string is in binary format, the length must be + * exactly 16 1s and zeros. If Hex format, the length must be + * exactly 4 Hex digits. + * + * @return a byte array equivalent of strShort + */ + public static byte[] shortStringToByteArray(String strShort) { + + byte[] byteArrayValue = null; + + int radix = radixOf(strShort); + + if (radix == 0) { + byteArrayValue = new byte[2]; // NOSONAR + } else { + byteArrayValue = Arrays + .copyOfRange(ByteBuffer.allocate(4).putInt(Integer.parseUnsignedInt(strShort, radix)).array(), 2, 4); + } + + return byteArrayValue; + } + + /** + * @param strShort + * String representation of a short integer value in binary or hex + * format. If strShort is in binary format, the length must be + * exactly 16 ones and zeros. If strShort is in Hex format, the + * length must be exactly 4 Hex digits. + * @return The radix of the strShort: Currently supporting only binary and + * hex, therefore the return value is either 2 or 16 + */ + private static int radixOf(String strShort) { + int radix = 0; + if (strShort == null || strShort.length() == 0) { + radix = 0; + } else if (strShort.length() == 16) { + radix = 2; + } else if (strShort.length() == 4) { + radix = 16; + } else { + throw new IllegalArgumentException("Short String length is invalid: " + strShort.length()); + } + return radix; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java index 04ad4e17e..0a4e7f3ed 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CommonUtils.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -public class CommonUtils { - - private CommonUtils() {} - - /** - * Wrapper method for System.getenv() - * @param name Variable name - */ - public static String getEnvironmentVariable(String name) { - return System.getenv(name); - } - - public static long getPidOfProcess(Process p) { - long pid = -1; - - try { - if (p.getClass().getName().equals("java.lang.UNIXProcess")) { //NOSONAR - Field f = p.getClass().getDeclaredField("pid"); - f.setAccessible(true); - pid = f.getLong(p); - f.setAccessible(false); - } - } catch (Exception e) { - pid = -1; - } - return pid; - } - - public static List getClasspath() { - ArrayList classpath = new ArrayList<>(); - - ClassLoader cl = ClassLoader.getSystemClassLoader(); - - URL[] urls = ((URLClassLoader)cl).getURLs(); - - for(URL url: urls){ - classpath.add(url); - } - - return classpath; - } - - public static String enumToString(Class clazz, String enumNameOrOrdinal) { - - String enumName = null; - try { - Object[] enumConstants = clazz.getEnumConstants(); - if (enumConstants != null) { - int enumOrdinal = Integer.parseInt(enumNameOrOrdinal); - enumName = enumConstants[enumOrdinal].toString(); - } - } catch (NumberFormatException e) { - enumName = enumNameOrOrdinal; - } - return enumName; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +public class CommonUtils { + + private CommonUtils() {} + + /** + * Wrapper method for System.getenv() + * @param name Variable name + */ + public static String getEnvironmentVariable(String name) { + return System.getenv(name); + } + + public static long getPidOfProcess(Process p) { + long pid = -1; + + try { + if (p.getClass().getName().equals("java.lang.UNIXProcess")) { //NOSONAR + Field f = p.getClass().getDeclaredField("pid"); + f.setAccessible(true); + pid = f.getLong(p); + f.setAccessible(false); + } + } catch (Exception e) { + pid = -1; + } + return pid; + } + + public static List getClasspath() { + ArrayList classpath = new ArrayList<>(); + + ClassLoader cl = ClassLoader.getSystemClassLoader(); + + URL[] urls = ((URLClassLoader)cl).getURLs(); + + for(URL url: urls){ + classpath.add(url); + } + + return classpath; + } + + public static String enumToString(Class clazz, String enumNameOrOrdinal) { + + String enumName = null; + try { + Object[] enumConstants = clazz.getEnumConstants(); + if (enumConstants != null) { + int enumOrdinal = Integer.parseInt(enumNameOrOrdinal); + enumName = enumConstants[enumOrdinal].toString(); + } + } catch (NumberFormatException e) { + enumName = enumNameOrOrdinal; + } + return enumName; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java index 587fdab75..d4d6160c7 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/CrcCccitt.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -public class CrcCccitt { - // CRC-CCITT polynomial: x^16 + x^12 + x^5 + 1 - final private static int ccittPolynomial = 0x1021; - final private static int ccittTableSize = 256; - final private static int[] ccittTable = new int[ccittTableSize]; - - static { - for (int i = 0; i < ccittTableSize; i++) { - int checkSum = i << 8; - for (int j = 0; j < 8; j++) - checkSum = (checkSum & 0x8000) == 0x8000 ? (checkSum << 1) ^ ccittPolynomial : (checkSum << 1); - ccittTable[i] = checkSum & 0xFFFF; - } - } - - public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC) { - return calculateCrcCccitt(msgIncludingMsgCRC) == 0; - } - - - public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC, int offset, int count) { - return calculateCrcCccitt(msgIncludingMsgCRC, offset, count) == 0; - } - - // update last two bytes of the message with CRC of all preceding bytes - public static void setMsgCRC(byte[] msg) { - if ( msg != null && msg.length > 2) { - int checkSum = calculateCrcCccitt(msg, 0, msg.length-2); - ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); - buffer.putShort((short)checkSum); - byte[] crcBytes = buffer.array(); - System.arraycopy(crcBytes, 0, msg, msg.length-2, 2); - } - } - - public static int calculateCrcCccitt(byte[] msg) { - return msg != null ? calculateCrcCccitt(msg, 0, msg.length) : 0; - } - - public static int calculateCrcCccitt(byte[] msg, int offset, int count) { - int checkSum = 0; - if ( msg != null && offset >= 0 ) { - final int size = Math.min(msg.length, count); - for( int i = 0; i < size; i++ ) { - checkSum = (ccittTable[((checkSum >> 8) & 0xFF) ^ (msg[i+offset] & 0xFF)] ^ (checkSum << 8)) & 0xFFFF; - } - } - return checkSum; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class CrcCccitt { + // CRC-CCITT polynomial: x^16 + x^12 + x^5 + 1 + final private static int ccittPolynomial = 0x1021; + final private static int ccittTableSize = 256; + final private static int[] ccittTable = new int[ccittTableSize]; + + static { + for (int i = 0; i < ccittTableSize; i++) { + int checkSum = i << 8; + for (int j = 0; j < 8; j++) + checkSum = (checkSum & 0x8000) == 0x8000 ? (checkSum << 1) ^ ccittPolynomial : (checkSum << 1); + ccittTable[i] = checkSum & 0xFFFF; + } + } + + public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC) { + return calculateCrcCccitt(msgIncludingMsgCRC) == 0; + } + + + public static boolean isValidMsgCRC(byte[] msgIncludingMsgCRC, int offset, int count) { + return calculateCrcCccitt(msgIncludingMsgCRC, offset, count) == 0; + } + + // update last two bytes of the message with CRC of all preceding bytes + public static void setMsgCRC(byte[] msg) { + if ( msg != null && msg.length > 2) { + int checkSum = calculateCrcCccitt(msg, 0, msg.length-2); + ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); + buffer.putShort((short)checkSum); + byte[] crcBytes = buffer.array(); + System.arraycopy(crcBytes, 0, msg, msg.length-2, 2); + } + } + + public static int calculateCrcCccitt(byte[] msg) { + return msg != null ? calculateCrcCccitt(msg, 0, msg.length) : 0; + } + + public static int calculateCrcCccitt(byte[] msg, int offset, int count) { + int checkSum = 0; + if ( msg != null && offset >= 0 ) { + final int size = Math.min(msg.length, count); + for( int i = 0; i < size; i++ ) { + checkSum = (ccittTable[((checkSum >> 8) & 0xFF) ^ (msg[i+offset] & 0xFF)] ^ (checkSum << 8)) & 0xFFFF; + } + } + return checkSum; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java index 65cefb459..40a1ab62f 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/DateTimeUtils.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.text.ParseException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; - -public class DateTimeUtils { - - private DateTimeUtils() { - } - - public static String now() { - return nowZDT().format(DateTimeFormatter.ISO_INSTANT); - } - - public static ZonedDateTime nowZDT() { - return ZonedDateTime.now(ZoneId.of("UTC")); - } - - public static String isoDateTime(ZonedDateTime zonedDateTime) { - return zonedDateTime.format(DateTimeFormatter.ISO_INSTANT); - } - - public static ZonedDateTime - isoDateTime(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millisec) { - return ZonedDateTime.of(year, month, dayOfMonth, hourOfDay, minute, second, millisec * 1000000, ZoneOffset.UTC); - } - - public static ZonedDateTime isoDateTime(String s) throws ParseException { - return ZonedDateTime.parse(s); - } - - public static ZonedDateTime isoDateTime(Date date) { - return ZonedDateTime.from(date.toInstant().atZone(ZoneId.of("UTC"))); - } - - public static ZonedDateTime isoDateTime(long epockMillis) { - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(epockMillis), ZoneId.of("UTC")); - } - - public static boolean - isBetweenTimesInclusive(ZonedDateTime dateTime, ZonedDateTime startDateTime, ZonedDateTime endDateTime) { - - if (dateTime == null) - return true; - - if (startDateTime == null) { - if (endDateTime == null) {// Both startDate and endDate are null, so - // it's false - return true; - } else {// We only have the endDate, so any dateTime not after the - // endDateTime is true - return !dateTime.isAfter(endDateTime); - } - } else { - if (endDateTime == null) {// We only have the startDateTime, so any - // dateTime not before the startDateTime is - // true - return !dateTime.isBefore(startDateTime); - } else {// We have both startDateTime and endDateTime, so any dateTime - // not before the startDate and not after endDateTime is true - return !dateTime.isBefore(startDateTime) && !dateTime.isAfter(endDateTime); - } - } - } - - public static long difference(ZonedDateTime t1, ZonedDateTime t2) { - return t2.toInstant().toEpochMilli() - t1.toInstant().toEpochMilli(); - } - - public static Long elapsedTime(ZonedDateTime zonedDateTime) { - return difference(zonedDateTime, ZonedDateTime.now()); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.text.ParseException; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +public class DateTimeUtils { + + private DateTimeUtils() { + } + + public static String now() { + return nowZDT().format(DateTimeFormatter.ISO_INSTANT); + } + + public static ZonedDateTime nowZDT() { + return ZonedDateTime.now(ZoneId.of("UTC")); + } + + public static String isoDateTime(ZonedDateTime zonedDateTime) { + return zonedDateTime.format(DateTimeFormatter.ISO_INSTANT); + } + + public static ZonedDateTime + isoDateTime(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millisec) { + return ZonedDateTime.of(year, month, dayOfMonth, hourOfDay, minute, second, millisec * 1000000, ZoneOffset.UTC); + } + + public static ZonedDateTime isoDateTime(String s) throws ParseException { + return ZonedDateTime.parse(s); + } + + public static ZonedDateTime isoDateTime(Date date) { + return ZonedDateTime.from(date.toInstant().atZone(ZoneId.of("UTC"))); + } + + public static ZonedDateTime isoDateTime(long epockMillis) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(epockMillis), ZoneId.of("UTC")); + } + + public static boolean + isBetweenTimesInclusive(ZonedDateTime dateTime, ZonedDateTime startDateTime, ZonedDateTime endDateTime) { + + if (dateTime == null) + return true; + + if (startDateTime == null) { + if (endDateTime == null) {// Both startDate and endDate are null, so + // it's false + return true; + } else {// We only have the endDate, so any dateTime not after the + // endDateTime is true + return !dateTime.isAfter(endDateTime); + } + } else { + if (endDateTime == null) {// We only have the startDateTime, so any + // dateTime not before the startDateTime is + // true + return !dateTime.isBefore(startDateTime); + } else {// We have both startDateTime and endDateTime, so any dateTime + // not before the startDate and not after endDateTime is true + return !dateTime.isBefore(startDateTime) && !dateTime.isAfter(endDateTime); + } + } + } + + public static long difference(ZonedDateTime t1, ZonedDateTime t2) { + return t2.toInstant().toEpochMilli() - t1.toInstant().toEpochMilli(); + } + + public static Long elapsedTime(ZonedDateTime zonedDateTime) { + return difference(zonedDateTime, ZonedDateTime.now()); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java index 92696439b..d404b3118 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/FormattedTimer.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -/** - * Timer class with formatting - * - */ -public class FormattedTimer { - /** */ - private long timerStart = 0L; - /** */ - - - /** - * Starts the timer - */ - public FormattedTimer() { - this.timerStart = System.currentTimeMillis(); - } - - /** - * Formats the time lapsed to "{HH} hours {mm} minutes {ss.sss} seconds". - * - * @param time - * @return - */ - protected String format(long time) { - - float seconds; - int minutes; - int hours; - - StringBuilder sb = new StringBuilder(); - float timeInSeconds = ((float) (time)) / 1000; - hours = (int) (timeInSeconds / 3600); - timeInSeconds = timeInSeconds - (hours * 3600); - minutes = (int) (timeInSeconds / 60); - timeInSeconds = timeInSeconds - (minutes * 60); - seconds = timeInSeconds; - sb.append(hours); - sb.append(" hours "); - sb.append(minutes); - sb.append(" minutes "); - sb.append(seconds); - sb.append(" seconds"); - return sb.toString(); - } - - /** - * @return the formatted time lapsed - */ - public String getFormattedTimer() { - return format(System.currentTimeMillis() - timerStart); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +/** + * Timer class with formatting + * + */ +public class FormattedTimer { + /** */ + private long timerStart = 0L; + /** */ + + + /** + * Starts the timer + */ + public FormattedTimer() { + this.timerStart = System.currentTimeMillis(); + } + + /** + * Formats the time lapsed to "{HH} hours {mm} minutes {ss.sss} seconds". + * + * @param time + * @return + */ + protected String format(long time) { + + float seconds; + int minutes; + int hours; + + StringBuilder sb = new StringBuilder(); + float timeInSeconds = ((float) (time)) / 1000; + hours = (int) (timeInSeconds / 3600); + timeInSeconds = timeInSeconds - (hours * 3600); + minutes = (int) (timeInSeconds / 60); + timeInSeconds = timeInSeconds - (minutes * 60); + seconds = timeInSeconds; + sb.append(hours); + sb.append(" hours "); + sb.append(minutes); + sb.append(" minutes "); + sb.append(seconds); + sb.append(" seconds"); + return sb.toString(); + } + + /** + * @return the formatted time lapsed + */ + public String getFormattedTimer() { + return format(System.currentTimeMillis() - timerStart); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java index f15cd6b45..dc6e87b2c 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java @@ -1,342 +1,342 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; - -public class GeoUtils { - public static final double ERROR_MARGIN = 0.0001; - public static final QELLIPSOID ellipsoid = new QELLIPSOID(6378206.4, 6356583.8, 0.08227185423947); - - public static final double EARTH_RADIUS_M = 6370997.0; - public static final double EARTH_RADIUS_MI = 3963.2263272; - - public static final ProjParams proj = new ProjParams(0.0); - - private GeoUtils() { - } - - public static class QELLIPSOID { - private double dEqRadius = 6378206.4; - private double dPolRadius = 6356583.8; - private double dEccentricity = 0.08227185423947; - - public QELLIPSOID() { - super(); - } - - public QELLIPSOID(double dEqRadius, double dPolRadius, double dEccentricity) { - this(); - this.dEqRadius = dEqRadius; - this.dPolRadius = dPolRadius; - this.dEccentricity = dEccentricity; - } - - public double getdEqRadius() { - return dEqRadius; - } - - public void setdEqRadius(double dEqRadius) { - this.dEqRadius = dEqRadius; - } - - public double getdPolRadius() { - return dPolRadius; - } - - public void setdPolRadius(double dPolRadius) { - this.dPolRadius = dPolRadius; - } - - public double getdEccentricity() { - return dEccentricity; - } - - public void setdEccentricity(double dEccentricity) { - this.dEccentricity = dEccentricity; - } - - } - - public static class ProjParams { - private double dCentralMeridian; - - public ProjParams() { - super(); - } - - public ProjParams(double dCentralMeridian) { - this(); - this.dCentralMeridian = dCentralMeridian; - } - - } - - public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) { - if (dest == null) { - dest = new Point2D.Double(); - } - - double apx = p.getX() - l.getX1(); - double apy = p.getY() - l.getY1(); - double abx = l.getX2() - l.getX1(); - double aby = l.getY2() - l.getY1(); - - double ab2 = abx * abx + aby * aby; - double ap_ab = apx * abx + apy * aby; - double t = ap_ab / ab2; - if (clampToSegment) { - if (t < 0) { - t = 0; - } else if (t > 1) { - t = 1; - } - } - dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t); - return dest; - } - - public static double lineLength(Point2D a, Point2D b) { - double abx = Math.abs(b.getX() - a.getX()); - double aby = Math.abs(b.getY() - a.getY()); - return Math.sqrt(abx * abx + aby * aby); - } - - public static double distanceToLine(Line2D l, Point2D p) { - - return l.ptLineDist(p); - } - - public static double distanceToLine2(Line2D l, Point2D p) { - - Point2D p2 = nearestPointOnLine(l, p, true, null); - return p.distance(p2); - } - - public static double distanceToLine3(Line2D l, Point2D p) - // Calculate the distance between the point (nX, nY) and the line through - // the - // points (nP1X, nP1Y), (nP2X, nP2Y). - { - double dDist = 0; - - if (l.getX1() == l.getX2()) - // Vertical line - dDist = p.getX() - l.getX1(); - else if (l.getY1() == l.getY2()) - // Horizontal line - dDist = p.getY() - l.getY1(); - else { - // Figure out the slope and Y intercept of the line - double dM1 = ((double) l.getY2() - l.getY1()) / ((double) l.getX2() - l.getX1()); - double dB1 = l.getY1() - (dM1 * l.getX1()); - // Figure out the slope and Y intercept of the perpendicular line - // through the third point - double dM2 = -(1 / dM1); - double dB2 = p.getY() - (dM2 * p.getX()); - - // Find the intersection of the two lines - double dXInt, dYInt; - dXInt = (dB2 - dB1) / (dM1 - dM2); - dYInt = (dM2 * dXInt) + dB2; - - // Now calulate the distance between the point and the intesection - // of - // the two lines. - dDist = Math.sqrt(Math.pow(dXInt - p.getX(), 2) + Math.pow(dYInt - p.getY(), 2)); - } - - return Math.abs(dDist); - } - - /** - * This function returns a Point2D that is offset to a point 'a' by distance - * 'k' and perpendicular to the line 'a-b' - * - * b / dest / *--- m ----- / | / l k / | a - * - * @param a - * @param b - * @param k - * @param dest - * @return - */ - public static Point2D pointOffset(Point2D a, Point2D b, double k, Point2D dest) { - if (dest == null) { - dest = new Point2D.Double(); - } - - double tanAlpha = (b.getY() - a.getY()) / (b.getX() - a.getX()); - double alpha = Math.atan(tanAlpha); - double sinAlpha = Math.sin(alpha); - double cosAlpha = Math.cos(alpha); - - double destX; - double destY; - if (b.getX() < a.getX()) { - destX = (a.getX() + k * sinAlpha); - destY = (a.getY() - k * cosAlpha); - } else { - destX = (a.getX() - k * sinAlpha); - destY = (a.getY() + k * cosAlpha); - } - - dest.setLocation(destX, destY); - return dest; - } - - public static double DEG2RAD(double deg) { - return ((double) deg * (Math.PI / 180.0)); - } - - public static double RAD2DEG(double rad) { - return ((double) rad * (180.0 / Math.PI)); - } - - public static Point2D latLngToMap(double dLat, double dLng) { - Point2D p = new Point2D.Double(); - - // Calculate map x - double px = ellipsoid.dEqRadius * DEG2RAD(dLng - proj.dCentralMeridian); - - double onePlusESine, oneMinusESine, tangent; - double eSine; - double divPowerE; - double lnValue; - - eSine = ellipsoid.dEccentricity * Math.sin(DEG2RAD(dLat)); - - onePlusESine = 1 + eSine; - oneMinusESine = 1 - eSine; - - divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); - - tangent = Math.tan(DEG2RAD((45.0 + dLat / 2.0))); - - lnValue = tangent * divPowerE; - double py = ellipsoid.dEqRadius * Math.log(lnValue); - - p.setLocation(px, py); - return p; - } - - public static Point2D mapToLatLng(Point2D d) { - // Calculate the lat - double t; - double onePlusESine, oneMinusESine; - double arcTangent; - double divPowerE; - double error = 0.0; - Point2D p = new Point2D.Double(); - - t = Math.exp(-(d.getY() / ellipsoid.dEqRadius)); - // Initial value far the lat - - double lat0 = 90 - 2 * RAD2DEG(Math.atan(t)); - - int i = 0; - do { - onePlusESine = 1 + (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); - oneMinusESine = 1 - (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); - - divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); - arcTangent = RAD2DEG(Math.atan(t * divPowerE)); - double lat = 90 - (2 * arcTangent); - error = Math.abs(lat - lat0); - lat0 = lat; - i++; // to avoid infinite loop; - } while (error > ERROR_MARGIN && i < 5); - - // Calculate the longitude - double lng = RAD2DEG(d.getY() / ellipsoid.dEqRadius) + proj.dCentralMeridian; - p.setLocation(lat0, lng); - - return p; - } - - public static double distance(Point2D a, Point2D b) { - return a.distance(b); - } - - public static double distanceLatLng(double dLat1, double dLng1, double dLat2, double dLng2, - LengthUtils.UnitOfMeasure u) { - double cd; - - // special case - if (dLat1 == dLat2 && dLng1 == dLng2) - return 0.0; - - double dDiff = dLng1 - dLng2; - int nSegs = (int) (Math.abs(dDiff) / 180.0); - double dDistance = 0; - - if (nSegs > 0 && dLat1 == dLat2) { - // if the span is bigger than 180 degrees, adjust the distance - cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) - + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(180.0)); - - cd = EARTH_RADIUS_M * Math.acos(cd); // This is in miles - dDistance = nSegs * cd; - dDiff = Math.abs(dDiff) - 180.0 * nSegs; - } - - cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) - + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(dDiff)); - - cd = EARTH_RADIUS_M * Math.acos(cd); // This is in meters - - cd += dDistance; - - switch (u) { - case KM: - cd = LengthUtils.MILES2KM(cd); - break; - case YARD: - cd = (LengthUtils.MILES2KM(cd) * 1000.0) / 0.9; // 90cm = 1 yard - break; - case MILE: - cd = LengthUtils.METERS2MILES(cd) * 1000.0; - break; - case NAUTICAL_MILE: - cd = LengthUtils.MILES2KNOTS(cd); - break; - case M: - default: - // already cd is in meters. we don't have to convert. - break; - } - - return cd; - } - - public static double distanceXY(double aLat, double aLng, double bLat, double bLng) { - - Point2D a = GeoUtils.latLngToMap(aLat, aLng); - Point2D b = GeoUtils.latLngToMap(bLat, bLng); - - return a.distance(b); - } - - public static boolean isPointWithinBounds(Point2D p, Line2D l, double tolerance) { - // Make sure the point p is inside the bounding rectangle of the segment - // a-b - return ((p.getX() >= (Math.min(l.getX1(), l.getX2()) - tolerance)) - && (p.getX() <= (Math.max(l.getX1(), l.getX2()) + tolerance)) - && (p.getY() >= (Math.min(l.getY1(), l.getY2()) - tolerance)) - && (p.getY() <= (Math.max(l.getY1(), l.getY2()) + tolerance))); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; + +public class GeoUtils { + public static final double ERROR_MARGIN = 0.0001; + public static final QELLIPSOID ellipsoid = new QELLIPSOID(6378206.4, 6356583.8, 0.08227185423947); + + public static final double EARTH_RADIUS_M = 6370997.0; + public static final double EARTH_RADIUS_MI = 3963.2263272; + + public static final ProjParams proj = new ProjParams(0.0); + + private GeoUtils() { + } + + public static class QELLIPSOID { + private double dEqRadius = 6378206.4; + private double dPolRadius = 6356583.8; + private double dEccentricity = 0.08227185423947; + + public QELLIPSOID() { + super(); + } + + public QELLIPSOID(double dEqRadius, double dPolRadius, double dEccentricity) { + this(); + this.dEqRadius = dEqRadius; + this.dPolRadius = dPolRadius; + this.dEccentricity = dEccentricity; + } + + public double getdEqRadius() { + return dEqRadius; + } + + public void setdEqRadius(double dEqRadius) { + this.dEqRadius = dEqRadius; + } + + public double getdPolRadius() { + return dPolRadius; + } + + public void setdPolRadius(double dPolRadius) { + this.dPolRadius = dPolRadius; + } + + public double getdEccentricity() { + return dEccentricity; + } + + public void setdEccentricity(double dEccentricity) { + this.dEccentricity = dEccentricity; + } + + } + + public static class ProjParams { + private double dCentralMeridian; + + public ProjParams() { + super(); + } + + public ProjParams(double dCentralMeridian) { + this(); + this.dCentralMeridian = dCentralMeridian; + } + + } + + public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) { + if (dest == null) { + dest = new Point2D.Double(); + } + + double apx = p.getX() - l.getX1(); + double apy = p.getY() - l.getY1(); + double abx = l.getX2() - l.getX1(); + double aby = l.getY2() - l.getY1(); + + double ab2 = abx * abx + aby * aby; + double ap_ab = apx * abx + apy * aby; + double t = ap_ab / ab2; + if (clampToSegment) { + if (t < 0) { + t = 0; + } else if (t > 1) { + t = 1; + } + } + dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t); + return dest; + } + + public static double lineLength(Point2D a, Point2D b) { + double abx = Math.abs(b.getX() - a.getX()); + double aby = Math.abs(b.getY() - a.getY()); + return Math.sqrt(abx * abx + aby * aby); + } + + public static double distanceToLine(Line2D l, Point2D p) { + + return l.ptLineDist(p); + } + + public static double distanceToLine2(Line2D l, Point2D p) { + + Point2D p2 = nearestPointOnLine(l, p, true, null); + return p.distance(p2); + } + + public static double distanceToLine3(Line2D l, Point2D p) + // Calculate the distance between the point (nX, nY) and the line through + // the + // points (nP1X, nP1Y), (nP2X, nP2Y). + { + double dDist = 0; + + if (l.getX1() == l.getX2()) + // Vertical line + dDist = p.getX() - l.getX1(); + else if (l.getY1() == l.getY2()) + // Horizontal line + dDist = p.getY() - l.getY1(); + else { + // Figure out the slope and Y intercept of the line + double dM1 = ((double) l.getY2() - l.getY1()) / ((double) l.getX2() - l.getX1()); + double dB1 = l.getY1() - (dM1 * l.getX1()); + // Figure out the slope and Y intercept of the perpendicular line + // through the third point + double dM2 = -(1 / dM1); + double dB2 = p.getY() - (dM2 * p.getX()); + + // Find the intersection of the two lines + double dXInt, dYInt; + dXInt = (dB2 - dB1) / (dM1 - dM2); + dYInt = (dM2 * dXInt) + dB2; + + // Now calulate the distance between the point and the intesection + // of + // the two lines. + dDist = Math.sqrt(Math.pow(dXInt - p.getX(), 2) + Math.pow(dYInt - p.getY(), 2)); + } + + return Math.abs(dDist); + } + + /** + * This function returns a Point2D that is offset to a point 'a' by distance + * 'k' and perpendicular to the line 'a-b' + * + * b / dest / *--- m ----- / | / l k / | a + * + * @param a + * @param b + * @param k + * @param dest + * @return + */ + public static Point2D pointOffset(Point2D a, Point2D b, double k, Point2D dest) { + if (dest == null) { + dest = new Point2D.Double(); + } + + double tanAlpha = (b.getY() - a.getY()) / (b.getX() - a.getX()); + double alpha = Math.atan(tanAlpha); + double sinAlpha = Math.sin(alpha); + double cosAlpha = Math.cos(alpha); + + double destX; + double destY; + if (b.getX() < a.getX()) { + destX = (a.getX() + k * sinAlpha); + destY = (a.getY() - k * cosAlpha); + } else { + destX = (a.getX() - k * sinAlpha); + destY = (a.getY() + k * cosAlpha); + } + + dest.setLocation(destX, destY); + return dest; + } + + public static double DEG2RAD(double deg) { + return ((double) deg * (Math.PI / 180.0)); + } + + public static double RAD2DEG(double rad) { + return ((double) rad * (180.0 / Math.PI)); + } + + public static Point2D latLngToMap(double dLat, double dLng) { + Point2D p = new Point2D.Double(); + + // Calculate map x + double px = ellipsoid.dEqRadius * DEG2RAD(dLng - proj.dCentralMeridian); + + double onePlusESine, oneMinusESine, tangent; + double eSine; + double divPowerE; + double lnValue; + + eSine = ellipsoid.dEccentricity * Math.sin(DEG2RAD(dLat)); + + onePlusESine = 1 + eSine; + oneMinusESine = 1 - eSine; + + divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); + + tangent = Math.tan(DEG2RAD((45.0 + dLat / 2.0))); + + lnValue = tangent * divPowerE; + double py = ellipsoid.dEqRadius * Math.log(lnValue); + + p.setLocation(px, py); + return p; + } + + public static Point2D mapToLatLng(Point2D d) { + // Calculate the lat + double t; + double onePlusESine, oneMinusESine; + double arcTangent; + double divPowerE; + double error = 0.0; + Point2D p = new Point2D.Double(); + + t = Math.exp(-(d.getY() / ellipsoid.dEqRadius)); + // Initial value far the lat + + double lat0 = 90 - 2 * RAD2DEG(Math.atan(t)); + + int i = 0; + do { + onePlusESine = 1 + (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); + oneMinusESine = 1 - (ellipsoid.dEccentricity * Math.sin(DEG2RAD(lat0))); + + divPowerE = Math.pow((oneMinusESine / onePlusESine), (ellipsoid.dEccentricity / 2.0)); + arcTangent = RAD2DEG(Math.atan(t * divPowerE)); + double lat = 90 - (2 * arcTangent); + error = Math.abs(lat - lat0); + lat0 = lat; + i++; // to avoid infinite loop; + } while (error > ERROR_MARGIN && i < 5); + + // Calculate the longitude + double lng = RAD2DEG(d.getY() / ellipsoid.dEqRadius) + proj.dCentralMeridian; + p.setLocation(lat0, lng); + + return p; + } + + public static double distance(Point2D a, Point2D b) { + return a.distance(b); + } + + public static double distanceLatLng(double dLat1, double dLng1, double dLat2, double dLng2, + LengthUtils.UnitOfMeasure u) { + double cd; + + // special case + if (dLat1 == dLat2 && dLng1 == dLng2) + return 0.0; + + double dDiff = dLng1 - dLng2; + int nSegs = (int) (Math.abs(dDiff) / 180.0); + double dDistance = 0; + + if (nSegs > 0 && dLat1 == dLat2) { + // if the span is bigger than 180 degrees, adjust the distance + cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) + + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(180.0)); + + cd = EARTH_RADIUS_M * Math.acos(cd); // This is in miles + dDistance = nSegs * cd; + dDiff = Math.abs(dDiff) - 180.0 * nSegs; + } + + cd = Math.sin(DEG2RAD(dLat1)) * Math.sin(DEG2RAD(dLat2)) + + Math.cos(DEG2RAD(dLat1)) * Math.cos(DEG2RAD(dLat2)) * Math.cos(DEG2RAD(dDiff)); + + cd = EARTH_RADIUS_M * Math.acos(cd); // This is in meters + + cd += dDistance; + + switch (u) { + case KM: + cd = LengthUtils.MILES2KM(cd); + break; + case YARD: + cd = (LengthUtils.MILES2KM(cd) * 1000.0) / 0.9; // 90cm = 1 yard + break; + case MILE: + cd = LengthUtils.METERS2MILES(cd) * 1000.0; + break; + case NAUTICAL_MILE: + cd = LengthUtils.MILES2KNOTS(cd); + break; + case M: + default: + // already cd is in meters. we don't have to convert. + break; + } + + return cd; + } + + public static double distanceXY(double aLat, double aLng, double bLat, double bLng) { + + Point2D a = GeoUtils.latLngToMap(aLat, aLng); + Point2D b = GeoUtils.latLngToMap(bLat, bLng); + + return a.distance(b); + } + + public static boolean isPointWithinBounds(Point2D p, Line2D l, double tolerance) { + // Make sure the point p is inside the bounding rectangle of the segment + // a-b + return ((p.getX() >= (Math.min(l.getX1(), l.getX2()) - tolerance)) + && (p.getX() <= (Math.max(l.getX1(), l.getX2()) + tolerance)) + && (p.getY() >= (Math.min(l.getY1(), l.getY2()) - tolerance)) + && (p.getY() <= (Math.max(l.getY1(), l.getY2()) + tolerance))); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java index 3cc01bb5d..1b77fa493 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/JsonUtils.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class JsonUtils { - - public static class JsonUtilsException extends Exception { - - private static final long serialVersionUID = 1L; - - public JsonUtilsException(String string, Exception e) { - super(string, e); - } - - } - - private static Gson gsonCompact; - private static Gson gsonVerbose; - private static ObjectMapper mapper; - private static Logger logger; - - private JsonUtils() { - logger = LoggerFactory.getLogger(JsonUtils.class); - } - - static { - gsonCompact = new GsonBuilder().create(); - gsonVerbose = new GsonBuilder().serializeNulls().create(); - mapper = new ObjectMapper(); - } - - public static String toJson(Object o, boolean verbose) { - - // convert java object to JSON format, - // and returned as JSON formatted string - return verbose ? gsonVerbose.toJson(o) : gsonCompact.toJson(o); - } - - public static Object fromJson(String s, Class clazz) { - return gsonCompact.fromJson(s, clazz); - } - - public static Object jacksonFromJson(String s, Class clazz) throws JsonUtilsException { - try { - return mapper.readValue(s, clazz); - } catch (IOException e) { - throw new JsonUtilsException("Error deserializing JSON tree to " + clazz.getName(), e); - } - } - - public static String newJson(String key, Object value) { - return newObjectNode(key, value).toString(); - } - - public static ObjectNode cloneObjectNode(ObjectNode src) { - return src.deepCopy(); - } - - public static ObjectNode newObjectNode(String key, Object value) { - ObjectNode json = mapper.createObjectNode(); - json.putPOJO(key, value); - return json; - } - - public static ObjectNode addNode(ObjectNode tree, String fieldName, Object fieldValue) { - tree.putPOJO(fieldName, fieldValue); - return tree; - } - - public static JsonNode getJsonNode(String tree, String fieldName) { - JsonNode node = null; - try { - JsonNode jsonNode = mapper.readTree(tree); - node = jsonNode.get(fieldName); - - } catch (IOException e) { - logger.error("IOException", e); - } - return node; - } - - public static ObjectNode newNode() { - return mapper.createObjectNode(); - } - - public static ArrayNode newArrayNode() { - return mapper.createArrayNode(); - } - - public static ObjectNode toObjectNode(String tree) throws JsonUtilsException { - ObjectNode jsonNode; - try { - jsonNode = (ObjectNode) mapper.readTree(tree); - } catch (Exception e) { - throw new JsonUtilsException("Error converting JSON tree to ObjectNode", e); - } - return jsonNode; - } - - public static JSONObject toJSONObject(String json) throws JsonUtilsException { - try { - return new JSONObject(json); - } catch (Exception e) { - throw new JsonUtilsException("Error decoding " + json + "to JSONObject", e); - } - } - - public static boolean isValid(String tree) throws IOException { - try { - ObjectNode jsonNode = (ObjectNode) mapper.readTree(tree); - return jsonNode != null; - } catch (JsonProcessingException jpe) { - return false; - } - } - - public static HashMap jsonNodeToHashMap(JsonNode jsonNode) { - HashMap nodeProps = new HashMap(); - Iterator> iter = jsonNode.fields(); - - while (iter.hasNext()) { - Entry element = iter.next(); - nodeProps.put(element.getKey(), element.getValue()); - } - return nodeProps; - } - - /** - * Takes in a key, value pair and returns a valid JSON string such as - * {"error":"message"} - * - * @param key - * @param value - * @return - */ - public static String jsonKeyValue(String key, String value) { - return "{\"" + key + "\":\"" + value + "\"}"; - } - - public static BigDecimal decimalValue(JsonNode v) { - BigDecimal result; - if (v.isTextual()) { - result = new BigDecimal(v.textValue()); - } else { - result = v.decimalValue(); - } - return result; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class JsonUtils { + + public static class JsonUtilsException extends Exception { + + private static final long serialVersionUID = 1L; + + public JsonUtilsException(String string, Exception e) { + super(string, e); + } + + } + + private static Gson gsonCompact; + private static Gson gsonVerbose; + private static ObjectMapper mapper; + private static Logger logger; + + private JsonUtils() { + logger = LoggerFactory.getLogger(JsonUtils.class); + } + + static { + gsonCompact = new GsonBuilder().create(); + gsonVerbose = new GsonBuilder().serializeNulls().create(); + mapper = new ObjectMapper(); + } + + public static String toJson(Object o, boolean verbose) { + + // convert java object to JSON format, + // and returned as JSON formatted string + return verbose ? gsonVerbose.toJson(o) : gsonCompact.toJson(o); + } + + public static Object fromJson(String s, Class clazz) { + return gsonCompact.fromJson(s, clazz); + } + + public static Object jacksonFromJson(String s, Class clazz) throws JsonUtilsException { + try { + return mapper.readValue(s, clazz); + } catch (IOException e) { + throw new JsonUtilsException("Error deserializing JSON tree to " + clazz.getName(), e); + } + } + + public static String newJson(String key, Object value) { + return newObjectNode(key, value).toString(); + } + + public static ObjectNode cloneObjectNode(ObjectNode src) { + return src.deepCopy(); + } + + public static ObjectNode newObjectNode(String key, Object value) { + ObjectNode json = mapper.createObjectNode(); + json.putPOJO(key, value); + return json; + } + + public static ObjectNode addNode(ObjectNode tree, String fieldName, Object fieldValue) { + tree.putPOJO(fieldName, fieldValue); + return tree; + } + + public static JsonNode getJsonNode(String tree, String fieldName) { + JsonNode node = null; + try { + JsonNode jsonNode = mapper.readTree(tree); + node = jsonNode.get(fieldName); + + } catch (IOException e) { + logger.error("IOException", e); + } + return node; + } + + public static ObjectNode newNode() { + return mapper.createObjectNode(); + } + + public static ArrayNode newArrayNode() { + return mapper.createArrayNode(); + } + + public static ObjectNode toObjectNode(String tree) throws JsonUtilsException { + ObjectNode jsonNode; + try { + jsonNode = (ObjectNode) mapper.readTree(tree); + } catch (Exception e) { + throw new JsonUtilsException("Error converting JSON tree to ObjectNode", e); + } + return jsonNode; + } + + public static JSONObject toJSONObject(String json) throws JsonUtilsException { + try { + return new JSONObject(json); + } catch (Exception e) { + throw new JsonUtilsException("Error decoding " + json + "to JSONObject", e); + } + } + + public static boolean isValid(String tree) throws IOException { + try { + ObjectNode jsonNode = (ObjectNode) mapper.readTree(tree); + return jsonNode != null; + } catch (JsonProcessingException jpe) { + return false; + } + } + + public static HashMap jsonNodeToHashMap(JsonNode jsonNode) { + HashMap nodeProps = new HashMap(); + Iterator> iter = jsonNode.fields(); + + while (iter.hasNext()) { + Entry element = iter.next(); + nodeProps.put(element.getKey(), element.getValue()); + } + return nodeProps; + } + + /** + * Takes in a key, value pair and returns a valid JSON string such as + * {"error":"message"} + * + * @param key + * @param value + * @return + */ + public static String jsonKeyValue(String key, String value) { + return "{\"" + key + "\":\"" + value + "\"}"; + } + + public static BigDecimal decimalValue(JsonNode v) { + BigDecimal result; + if (v.isTextual()) { + result = new BigDecimal(v.textValue()); + } else { + result = v.decimalValue(); + } + return result; + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java index 224a01e54..9143f1ff5 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/LengthUtils.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -public class LengthUtils { - public enum UnitOfMeasure { - MM, CM, M, KM, INCH, FOOT, YARD, MILE, NAUTICAL_MILE - } - - public static double MILES2KM(double m) {return ((double)m * 1.609347);} - - public static double KM2MILES(double m) {return ((double)m / 1.609347);} - - public static double MILES2METERS(double m) {return ((double)m * 1609.347);} - public static double METERS2MILES(double m) {return ((double)m / 1609.347);} - - public static double MILES2KNOTS(double m) {return ((double)m / 1.150568);} - public static double KNOTS2MILES(double m) {return ((double)m * 1.150568);} - - public static double MILES2YARDS(double m) {return ((double)m * 1760.0);} - public static double YARDS2MILES(double m) {return ((double)m / 1760.0);} -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +public class LengthUtils { + public enum UnitOfMeasure { + MM, CM, M, KM, INCH, FOOT, YARD, MILE, NAUTICAL_MILE + } + + public static double MILES2KM(double m) {return ((double)m * 1.609347);} + + public static double KM2MILES(double m) {return ((double)m / 1.609347);} + + public static double MILES2METERS(double m) {return ((double)m * 1609.347);} + public static double METERS2MILES(double m) {return ((double)m / 1609.347);} + + public static double MILES2KNOTS(double m) {return ((double)m / 1.150568);} + public static double KNOTS2MILES(double m) {return ((double)m * 1.150568);} + + public static double MILES2YARDS(double m) {return ((double)m * 1760.0);} + public static double YARDS2MILES(double m) {return ((double)m / 1760.0);} +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java index d3b1b2976..85849305a 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/SerializableObjectPool.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.Serializable; -import java.util.Enumeration; -import java.util.Hashtable; - -public abstract class SerializableObjectPool implements Serializable { - private static final long serialVersionUID = 914977959079989774L; - - private long expirationTime; - - private Hashtable locked, unlocked; - - public SerializableObjectPool() { - expirationTime = 30000; // 30 seconds - locked = new Hashtable(); - unlocked = new Hashtable(); - } - - protected abstract T create(); - - public abstract boolean validate(T o); - - public abstract void expire(T o); - - public synchronized T checkOut() { - long now = System.currentTimeMillis(); - T t; - if (unlocked.size() > 0) { - Enumeration e = unlocked.keys(); - while (e.hasMoreElements()) { - t = e.nextElement(); - if ((now - unlocked.get(t)) > expirationTime) { - // object has expired - unlocked.remove(t); - expire(t); - t = null; //NOSONAR - } else { - if (validate(t)) { - unlocked.remove(t); - locked.put(t, now); - return (t); - } else { - // object failed validation - unlocked.remove(t); - expire(t); - t = null; //NOSONAR - } - } - } - } - // no objects available, create a new one - t = create(); - locked.put(t, now); - return (t); - } - - public synchronized void checkIn(T t) { - locked.remove(t); - unlocked.put(t, System.currentTimeMillis()); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.Serializable; +import java.util.Enumeration; +import java.util.Hashtable; + +public abstract class SerializableObjectPool implements Serializable { + private static final long serialVersionUID = 914977959079989774L; + + private long expirationTime; + + private Hashtable locked, unlocked; + + public SerializableObjectPool() { + expirationTime = 30000; // 30 seconds + locked = new Hashtable(); + unlocked = new Hashtable(); + } + + protected abstract T create(); + + public abstract boolean validate(T o); + + public abstract void expire(T o); + + public synchronized T checkOut() { + long now = System.currentTimeMillis(); + T t; + if (unlocked.size() > 0) { + Enumeration e = unlocked.keys(); + while (e.hasMoreElements()) { + t = e.nextElement(); + if ((now - unlocked.get(t)) > expirationTime) { + // object has expired + unlocked.remove(t); + expire(t); + t = null; //NOSONAR + } else { + if (validate(t)) { + unlocked.remove(t); + locked.put(t, now); + return (t); + } else { + // object failed validation + unlocked.remove(t); + expire(t); + t = null; //NOSONAR + } + } + } + } + // no objects available, create a new one + t = create(); + locked.put(t, now); + return (t); + } + + public synchronized void checkIn(T t) { + locked.remove(t); + unlocked.put(t, System.currentTimeMillis()); + } +} diff --git a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java index 2334843c6..1014ee942 100644 --- a/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java +++ b/jpo-ode-common/src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java @@ -1,49 +1,49 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.io.IOException; - -import javax.websocket.Session; - -public class WebSocketUtils { - - /** - * @param session - * @param message - * @throws IOException - */ - public static void send(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getBasicRemote().sendText(message); - } - } - - public static void sendSync(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getBasicRemote().sendText(message); - } - } - - public static void sendAsync(Session session, String message) throws IOException { - if (session != null) - synchronized (session) { - session.getAsyncRemote().sendText(message); - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.io.IOException; + +import javax.websocket.Session; + +public class WebSocketUtils { + + /** + * @param session + * @param message + * @throws IOException + */ + public static void send(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getBasicRemote().sendText(message); + } + } + + public static void sendSync(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getBasicRemote().sendText(message); + } + } + + public static void sendAsync(Session session, String message) throws IOException { + if (session != null) + synchronized (session) { + session.getAsyncRemote().sendText(message); + } + } +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java index 5359e8b5c..e01d0c2ad 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketFunctionalTest.java @@ -1,116 +1,116 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.junit.Ignore; -import org.junit.Test; - -import mockit.Capturing; -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPacketFunctionalTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - private static boolean isVerbose = false; - - @Test - public void testConstrcutor() throws UnknownHostException { - InetPacket pkt = new InetPacket("bah.com", 1111, null); - - assertNull(pkt.getPayload()); - } - - @Test @Ignore - public void test() throws UnknownHostException { - test("127.0.0.1", 12, "01234567890".getBytes()); - test("::1", 47561, "0123456789001234567890".getBytes()); - test("1080:0:0:0:8:800:200C:417A", 345, "".getBytes()); - test("1080:0:0:0:8:800:200C:417A", 345, null); - test("1.0.0", 47561, "".getBytes()); - test("::FFFF:129.144.52.38", 4756, "0".getBytes()); - test("1080::8:800:200C:417A", 4756, new byte[] { (byte)0, (byte)1 }); - test("2001:0:9d38:90d7:3ce3:339d:f5c3:c42b", 11111, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); - test(null, 22222, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); - test("fdf8:f53b:82e4::53", 11111, new byte[] { (byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe }); - } - - public void test(String address, int port, byte[] payload) throws UnknownHostException { - if ( payload == null ) - return; - if ( isVerbose ) - System.out.println("---------- Test ----------"); - DatagramPacket packet = new DatagramPacket(payload, payload.length, InetAddress.getByName(address), port); - InetPacket pbOut = new InetPacket(packet); - test(address, port, payload, pbOut); - } - - public void test(String address, int port, byte[] payload, InetPacket pbOut) throws UnknownHostException { - InetPacket pbIn = new InetPacket(pbOut.getBundle()); - if ( isVerbose ) { - print("From params", pbOut); - print("From bundle", pbIn); - } - InetPoint pointIn = pbIn.getPoint(); - assertNotNull(pointIn); - InetPoint pointOut = pbOut.getPoint(); - assertEquals(pointOut.port, pointIn.port); - assertArrayEquals(pointOut.address, pointIn.address); - byte[] pbOutPayload = pbOut.getPayload(); - byte[] pyInPayload = pbIn.getPayload(); - if ( pbOutPayload != null && pbOutPayload != null ) - assertTrue(Arrays.equals(pbOutPayload, pyInPayload)); - else if (pbOutPayload != null || pbOutPayload != null) - assertTrue(false); - assertTrue(Arrays.equals(pbOut.getBundle(), pbIn.getBundle())); - } - - void print(String header, InetPacket pb) throws UnknownHostException { - assertNotNull(pb); - InetPoint point = pb.getPoint(); - if( point != null ) { - System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port ); - System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, - CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress() ); - System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false" ); - } else { - System.out.printf("%s: Inet point is null\n", header); - } - byte[] p = pb.getPayload(); - System.out.printf("%s payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); - System.out.printf("%s bundle: %s\n", header, pb.toHexString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; + +import org.junit.Ignore; +import org.junit.Test; + +import mockit.Capturing; +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPacketFunctionalTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + private static boolean isVerbose = false; + + @Test + public void testConstrcutor() throws UnknownHostException { + InetPacket pkt = new InetPacket("bah.com", 1111, null); + + assertNull(pkt.getPayload()); + } + + @Test @Ignore + public void test() throws UnknownHostException { + test("127.0.0.1", 12, "01234567890".getBytes()); + test("::1", 47561, "0123456789001234567890".getBytes()); + test("1080:0:0:0:8:800:200C:417A", 345, "".getBytes()); + test("1080:0:0:0:8:800:200C:417A", 345, null); + test("1.0.0", 47561, "".getBytes()); + test("::FFFF:129.144.52.38", 4756, "0".getBytes()); + test("1080::8:800:200C:417A", 4756, new byte[] { (byte)0, (byte)1 }); + test("2001:0:9d38:90d7:3ce3:339d:f5c3:c42b", 11111, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); + test(null, 22222, new byte[] { (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef }); + test("fdf8:f53b:82e4::53", 11111, new byte[] { (byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe }); + } + + public void test(String address, int port, byte[] payload) throws UnknownHostException { + if ( payload == null ) + return; + if ( isVerbose ) + System.out.println("---------- Test ----------"); + DatagramPacket packet = new DatagramPacket(payload, payload.length, InetAddress.getByName(address), port); + InetPacket pbOut = new InetPacket(packet); + test(address, port, payload, pbOut); + } + + public void test(String address, int port, byte[] payload, InetPacket pbOut) throws UnknownHostException { + InetPacket pbIn = new InetPacket(pbOut.getBundle()); + if ( isVerbose ) { + print("From params", pbOut); + print("From bundle", pbIn); + } + InetPoint pointIn = pbIn.getPoint(); + assertNotNull(pointIn); + InetPoint pointOut = pbOut.getPoint(); + assertEquals(pointOut.port, pointIn.port); + assertArrayEquals(pointOut.address, pointIn.address); + byte[] pbOutPayload = pbOut.getPayload(); + byte[] pyInPayload = pbIn.getPayload(); + if ( pbOutPayload != null && pbOutPayload != null ) + assertTrue(Arrays.equals(pbOutPayload, pyInPayload)); + else if (pbOutPayload != null || pbOutPayload != null) + assertTrue(false); + assertTrue(Arrays.equals(pbOut.getBundle(), pbIn.getBundle())); + } + + void print(String header, InetPacket pb) throws UnknownHostException { + assertNotNull(pb); + InetPoint point = pb.getPoint(); + if( point != null ) { + System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port ); + System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, + CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress() ); + System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false" ); + } else { + System.out.printf("%s: Inet point is null\n", header); + } + byte[] p = pb.getPayload(); + System.out.printf("%s payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); + System.out.printf("%s bundle: %s\n", header, pb.toHexString()); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java index 53a52aa82..b192d6f71 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java @@ -1,480 +1,480 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.apache.log4j.Logger; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import mockit.Capturing; -import us.dot.its.jpo.ode.util.CodecUtils; - -public class InetPacketSenderTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - static final private boolean isDebugOutput = false; - - private static Logger log = Logger.getLogger(InetPacketSenderTest.class); - - private static final int DEFAULT_MAX_PACKET_SIZE = 65535; - - private static final String TRANSPORT_HOST = "localhost"; - private static final int TRANSPORT_PORT = 46751; - - private static final String FORWARDER_HOST = "localhost"; - private static final int FORWARDER_PORT = 46752; - - private static final String CLIENT_HOST_IPV4 = "localhost"; - private static final String CLIENT_HOST_IPV6 = "::1"; - private static final int CLIENT_PORT = 46753; - - private static final byte[] PAYLOAD = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xca, - (byte) 0xfe, (byte) 0xba, (byte) 0xbe }; - - AssertionError assertionError = null; - - private enum TestCase { - TestForwardPacketInbound, TestSendPacketOutbound, TestIPv6ForwardOutbound, TestIPv4ForwardOutboundForward, TestIPv4ForwardOutboundSend, TestIPv6SendOutbound, TestIPv4SendOutbound, - }; - - @BeforeClass - public static void init() { - } - - @Test - public void testForwardPacketInboundIPV4() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Forwarder forwards incoming IPV4 packet to transport - testForwardPacketInbound(CLIENT_HOST_IPV4); - } - - @Test - public void testForwardPacketInboundIPV6() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Forwarder forwards incoming IPV6 packet to transport - testForwardPacketInbound(CLIENT_HOST_IPV6); - } - - public void testForwardPacketInbound(String hostname) - throws UnknownHostException, InetPacketException, InterruptedException { - startUdpListener(TRANSPORT_PORT, TestCase.TestForwardPacketInbound); - InetPoint transport = new InetPoint(getAddressBytes(TRANSPORT_HOST), TRANSPORT_PORT); - InetPacketSender sender = new InetPacketSender(transport); - DatagramPacket packet = new DatagramPacket(PAYLOAD, PAYLOAD.length, InetAddress.getByName(hostname), CLIENT_PORT); - sender.forward(packet); - checkBackgroundThreadAssertion(); - } - - @Test @Ignore - public void testSendPacketOutboundIPv4() throws UnknownHostException, InterruptedException, InetPacketException { - // Use case: Forwarder sends outgoing IPv4 packet out - testSendPacketOutbound(CLIENT_HOST_IPV4); - } - - @Test @Ignore - public void testSendPacketOutboundIPv6() throws UnknownHostException, InterruptedException, InetPacketException { - // Use case: Forwarder sends outgoing IPv6 packet out - testSendPacketOutbound(CLIENT_HOST_IPV6); - } - - public void testSendPacketOutbound(String hostname) - throws UnknownHostException, InetPacketException, InterruptedException { - startUdpListener(CLIENT_PORT, TestCase.TestSendPacketOutbound); - InetPoint client = new InetPoint(getAddressBytes(hostname), CLIENT_PORT); - byte[] bundle = new InetPacket(client, PAYLOAD).getBundle(); - InetPacketSender sender = new InetPacketSender(); - DatagramPacket packet = new DatagramPacket(bundle, bundle.length, InetAddress.getByName(FORWARDER_HOST), - FORWARDER_PORT); - sender.send(packet); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv6ForwardOutbound() throws UnknownHostException, InetPacketException, InterruptedException { - // Use case: Transport or Data Sink send IPv6 message out via forwarder - startUdpListener(FORWARDER_PORT, TestCase.TestIPv6ForwardOutbound); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4ForwardOutboundForward() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out via forwarder - startUdpListener(FORWARDER_PORT, TestCase.TestIPv4ForwardOutboundForward); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - sender.setForwardAll(true); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4ForwardOutboundSend() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out via forwarder - // but it's being send out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv4ForwardOutboundSend); - InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); - InetPacketSender sender = new InetPacketSender(forwarder); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.forward(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv6SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv6 message out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv6SendOutbound); - InetPacketSender sender = new InetPacketSender(); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); - sender.send(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - @Test - public void testIPv4SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { - // Use case: Transport or Data Sink send IPv4 message out directly - startUdpListener(CLIENT_PORT, TestCase.TestIPv4SendOutbound); - InetPacketSender sender = new InetPacketSender(); - InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); - sender.send(client, PAYLOAD); - checkBackgroundThreadAssertion(); - } - - private static byte[] getAddressBytes(String host) throws UnknownHostException { - return InetAddress.getByName(host).getAddress(); - } - - private void startUdpListener(int port, TestCase tc) { - final int listenPort = port; - final TestCase testCase = tc; - - Thread listener = new Thread(new Runnable() { - @Override - public void run() { - DatagramSocket socket = null; - try { - socket = new DatagramSocket(listenPort); - DatagramPacket datagramPacket = new DatagramPacket(new byte[DEFAULT_MAX_PACKET_SIZE], - DEFAULT_MAX_PACKET_SIZE); - socket.setSoTimeout(1000); - socket.receive(datagramPacket); - validatePacket(datagramPacket); - } catch (SocketTimeoutException ex) { - log.error( - String.format("Caught socket timeout exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), - ex); - } catch (SocketException ex) { - log.error(String.format("Caught socket exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), ex); - } catch (IOException ex) { - log.error( - String.format("Caught IO exception exception while recieving message on port %d. Max size is %d", - listenPort, DEFAULT_MAX_PACKET_SIZE), - ex); - } finally { - if (socket != null && !socket.isClosed()) { - socket.close(); - socket = null; - } - } - } - - private void validatePacket(DatagramPacket packet) throws UnknownHostException { - assertNotNull(packet); - - final byte[] data = packet.getData(); - assertNotNull(data); - - final int length = packet.getLength(); - assertTrue(length > 0); - - final int offset = packet.getOffset(); - - byte[] packetData = Arrays.copyOfRange(data, offset, length); - - try { - switch (testCase) { - case TestForwardPacketInbound: - validateForwardPacketInbound(packetData); - validateForwardPacketInbound(packet); - break; - case TestSendPacketOutbound: - validateSendPacketOutbound(packetData); - validateSendPacketOutbound(packet); - break; - case TestIPv6ForwardOutbound: - validateIPv6ForwardOutbound(packetData); - validateIPv6ForwardOutbound(packet); - break; - case TestIPv4ForwardOutboundForward: - validateIPv4ForwardOutboundForward(packetData); - validateIPv4ForwardOutboundForward(packet); - break; - case TestIPv4ForwardOutboundSend: - validateIPv4ForwardOutboundSend(packetData); - validateIPv4ForwardOutboundSend(packet); - break; - case TestIPv6SendOutbound: - validateIPv6SendOutbound(packetData); - validateIPv6SendOutbound(packet); - break; - case TestIPv4SendOutbound: - validateIPv4SendOutbound(packetData); - validateIPv4SendOutbound(packet); - break; - } - } catch (AssertionError ex) { - assertionError = ex; - } - } - - private void validateForwardPacketInbound(byte[] payload) throws UnknownHostException { - validateForwardPacketInbound("Payload", new InetPacket(payload)); - } - - private void validateForwardPacketInbound(DatagramPacket packet) throws UnknownHostException { - validateForwardPacketInbound("Packet", new InetPacket(packet)); - } - - private void validateForwardPacketInbound(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("ForwardPacketInbound", p); - assertEquals(TRANSPORT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV6), point.address); - else - assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV4), point.address); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(PAYLOAD, p.getPayload()); - } - - private void validateSendPacketOutbound(byte[] payload) throws UnknownHostException { - InetPacket p = new InetPacket(payload); - assertNotNull(p); - if (isDebugOutput) - print("SendPacketOutbound Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateSendPacketOutbound(DatagramPacket packet) throws UnknownHostException { - InetPacket p = new InetPacket(packet); - assertNotNull(p); - if (isDebugOutput) - print("SendPacketOutbound Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv6ForwardOutbound(byte[] payload) throws UnknownHostException { - validateIPv6ForwardOutbound("Payload", new InetPacket(payload)); - } - - private void validateIPv6ForwardOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPv6ForwardOutbound("Packet", new InetPacket(packet)); - } - - private void validateIPv6ForwardOutbound(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPv6ForwardOutbound " + tail, p); - assertEquals(FORWARDER_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - assertTrue(point.isIPv6Address()); - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundForward(byte[] payload) throws UnknownHostException { - validateIPv4ForwardOutboundForward("Payload", new InetPacket(payload)); - } - - private void validateIPv4ForwardOutboundForward(DatagramPacket packet) throws UnknownHostException { - validateIPv4ForwardOutboundForward("Packet", new InetPacket(packet)); - } - - private void validateIPv4ForwardOutboundForward(String tail, InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundForward " + tail, p); - assertEquals(FORWARDER_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - assertFalse(point.isIPv6Address()); - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertEquals(CLIENT_PORT, point.port); - assertTrue(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundSend(byte[] payload) throws UnknownHostException { - InetPacket p = new InetPacket(payload); - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundSend Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv4ForwardOutboundSend(DatagramPacket packet) throws UnknownHostException { - InetPacket p = new InetPacket(packet); - assertNotNull(p); - if (isDebugOutput) - print("IPv4ForwardOutboundSend Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPv6SendOutbound(byte[] payload) throws UnknownHostException { - validateIPvXSendOutboundPayload(new InetPacket(payload)); - } - - private void validateIPv4SendOutbound(byte[] payload) throws UnknownHostException { - validateIPvXSendOutboundPayload(new InetPacket(payload)); - } - - private void validateIPv6SendOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPvXSendOutboundPacket(new InetPacket(packet)); - } - - private void validateIPv4SendOutbound(DatagramPacket packet) throws UnknownHostException { - validateIPvXSendOutboundPacket(new InetPacket(packet)); - } - - private void validateIPvXSendOutboundPayload(InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPvXSendOutbound Payload", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNull(point); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void validateIPvXSendOutboundPacket(InetPacket p) throws UnknownHostException { - assertNotNull(p); - if (isDebugOutput) - print("IPvXSendOutbound Packet", p); - assertEquals(CLIENT_PORT, listenPort); - InetPoint point = p.getPoint(); - assertNotNull(point); - byte[] srcAddress = point.address; - assertNotNull(srcAddress); - if (point.isIPv6Address()) - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); - else - assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); - assertFalse(point.forward); - assertArrayEquals(p.getPayload(), PAYLOAD); - } - - private void print(String header, InetPacket pb) throws UnknownHostException { - assertNotNull(pb); - InetPoint point = pb.getPoint(); - if (point != null) { - System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port); - System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, - CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress()); - System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false"); - } else { - System.out.printf("%s: Inet point is null\n", header); - } - byte[] p = pb.getPayload(); - System.out.printf("%s: payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); - System.out.printf("%s: bundle: %s\n", header, pb.toHexString()); - } - }); - listener.start(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - } - } - - void checkBackgroundThreadAssertion() { - try { - Thread.sleep(1500); - } catch (InterruptedException unused) { - } - - if (assertionError != null) - throw assertionError; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.Arrays; + +import org.apache.log4j.Logger; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import mockit.Capturing; +import us.dot.its.jpo.ode.util.CodecUtils; + +public class InetPacketSenderTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + static final private boolean isDebugOutput = false; + + private static Logger log = Logger.getLogger(InetPacketSenderTest.class); + + private static final int DEFAULT_MAX_PACKET_SIZE = 65535; + + private static final String TRANSPORT_HOST = "localhost"; + private static final int TRANSPORT_PORT = 46751; + + private static final String FORWARDER_HOST = "localhost"; + private static final int FORWARDER_PORT = 46752; + + private static final String CLIENT_HOST_IPV4 = "localhost"; + private static final String CLIENT_HOST_IPV6 = "::1"; + private static final int CLIENT_PORT = 46753; + + private static final byte[] PAYLOAD = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xca, + (byte) 0xfe, (byte) 0xba, (byte) 0xbe }; + + AssertionError assertionError = null; + + private enum TestCase { + TestForwardPacketInbound, TestSendPacketOutbound, TestIPv6ForwardOutbound, TestIPv4ForwardOutboundForward, TestIPv4ForwardOutboundSend, TestIPv6SendOutbound, TestIPv4SendOutbound, + }; + + @BeforeClass + public static void init() { + } + + @Test + public void testForwardPacketInboundIPV4() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Forwarder forwards incoming IPV4 packet to transport + testForwardPacketInbound(CLIENT_HOST_IPV4); + } + + @Test + public void testForwardPacketInboundIPV6() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Forwarder forwards incoming IPV6 packet to transport + testForwardPacketInbound(CLIENT_HOST_IPV6); + } + + public void testForwardPacketInbound(String hostname) + throws UnknownHostException, InetPacketException, InterruptedException { + startUdpListener(TRANSPORT_PORT, TestCase.TestForwardPacketInbound); + InetPoint transport = new InetPoint(getAddressBytes(TRANSPORT_HOST), TRANSPORT_PORT); + InetPacketSender sender = new InetPacketSender(transport); + DatagramPacket packet = new DatagramPacket(PAYLOAD, PAYLOAD.length, InetAddress.getByName(hostname), CLIENT_PORT); + sender.forward(packet); + checkBackgroundThreadAssertion(); + } + + @Test @Ignore + public void testSendPacketOutboundIPv4() throws UnknownHostException, InterruptedException, InetPacketException { + // Use case: Forwarder sends outgoing IPv4 packet out + testSendPacketOutbound(CLIENT_HOST_IPV4); + } + + @Test @Ignore + public void testSendPacketOutboundIPv6() throws UnknownHostException, InterruptedException, InetPacketException { + // Use case: Forwarder sends outgoing IPv6 packet out + testSendPacketOutbound(CLIENT_HOST_IPV6); + } + + public void testSendPacketOutbound(String hostname) + throws UnknownHostException, InetPacketException, InterruptedException { + startUdpListener(CLIENT_PORT, TestCase.TestSendPacketOutbound); + InetPoint client = new InetPoint(getAddressBytes(hostname), CLIENT_PORT); + byte[] bundle = new InetPacket(client, PAYLOAD).getBundle(); + InetPacketSender sender = new InetPacketSender(); + DatagramPacket packet = new DatagramPacket(bundle, bundle.length, InetAddress.getByName(FORWARDER_HOST), + FORWARDER_PORT); + sender.send(packet); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv6ForwardOutbound() throws UnknownHostException, InetPacketException, InterruptedException { + // Use case: Transport or Data Sink send IPv6 message out via forwarder + startUdpListener(FORWARDER_PORT, TestCase.TestIPv6ForwardOutbound); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4ForwardOutboundForward() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out via forwarder + startUdpListener(FORWARDER_PORT, TestCase.TestIPv4ForwardOutboundForward); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + sender.setForwardAll(true); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4ForwardOutboundSend() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out via forwarder + // but it's being send out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv4ForwardOutboundSend); + InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); + InetPacketSender sender = new InetPacketSender(forwarder); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.forward(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv6SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv6 message out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv6SendOutbound); + InetPacketSender sender = new InetPacketSender(); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); + sender.send(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + @Test + public void testIPv4SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { + // Use case: Transport or Data Sink send IPv4 message out directly + startUdpListener(CLIENT_PORT, TestCase.TestIPv4SendOutbound); + InetPacketSender sender = new InetPacketSender(); + InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); + sender.send(client, PAYLOAD); + checkBackgroundThreadAssertion(); + } + + private static byte[] getAddressBytes(String host) throws UnknownHostException { + return InetAddress.getByName(host).getAddress(); + } + + private void startUdpListener(int port, TestCase tc) { + final int listenPort = port; + final TestCase testCase = tc; + + Thread listener = new Thread(new Runnable() { + @Override + public void run() { + DatagramSocket socket = null; + try { + socket = new DatagramSocket(listenPort); + DatagramPacket datagramPacket = new DatagramPacket(new byte[DEFAULT_MAX_PACKET_SIZE], + DEFAULT_MAX_PACKET_SIZE); + socket.setSoTimeout(1000); + socket.receive(datagramPacket); + validatePacket(datagramPacket); + } catch (SocketTimeoutException ex) { + log.error( + String.format("Caught socket timeout exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), + ex); + } catch (SocketException ex) { + log.error(String.format("Caught socket exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), ex); + } catch (IOException ex) { + log.error( + String.format("Caught IO exception exception while recieving message on port %d. Max size is %d", + listenPort, DEFAULT_MAX_PACKET_SIZE), + ex); + } finally { + if (socket != null && !socket.isClosed()) { + socket.close(); + socket = null; + } + } + } + + private void validatePacket(DatagramPacket packet) throws UnknownHostException { + assertNotNull(packet); + + final byte[] data = packet.getData(); + assertNotNull(data); + + final int length = packet.getLength(); + assertTrue(length > 0); + + final int offset = packet.getOffset(); + + byte[] packetData = Arrays.copyOfRange(data, offset, length); + + try { + switch (testCase) { + case TestForwardPacketInbound: + validateForwardPacketInbound(packetData); + validateForwardPacketInbound(packet); + break; + case TestSendPacketOutbound: + validateSendPacketOutbound(packetData); + validateSendPacketOutbound(packet); + break; + case TestIPv6ForwardOutbound: + validateIPv6ForwardOutbound(packetData); + validateIPv6ForwardOutbound(packet); + break; + case TestIPv4ForwardOutboundForward: + validateIPv4ForwardOutboundForward(packetData); + validateIPv4ForwardOutboundForward(packet); + break; + case TestIPv4ForwardOutboundSend: + validateIPv4ForwardOutboundSend(packetData); + validateIPv4ForwardOutboundSend(packet); + break; + case TestIPv6SendOutbound: + validateIPv6SendOutbound(packetData); + validateIPv6SendOutbound(packet); + break; + case TestIPv4SendOutbound: + validateIPv4SendOutbound(packetData); + validateIPv4SendOutbound(packet); + break; + } + } catch (AssertionError ex) { + assertionError = ex; + } + } + + private void validateForwardPacketInbound(byte[] payload) throws UnknownHostException { + validateForwardPacketInbound("Payload", new InetPacket(payload)); + } + + private void validateForwardPacketInbound(DatagramPacket packet) throws UnknownHostException { + validateForwardPacketInbound("Packet", new InetPacket(packet)); + } + + private void validateForwardPacketInbound(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("ForwardPacketInbound", p); + assertEquals(TRANSPORT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV6), point.address); + else + assertArrayEquals(getAddressBytes(CLIENT_HOST_IPV4), point.address); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(PAYLOAD, p.getPayload()); + } + + private void validateSendPacketOutbound(byte[] payload) throws UnknownHostException { + InetPacket p = new InetPacket(payload); + assertNotNull(p); + if (isDebugOutput) + print("SendPacketOutbound Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateSendPacketOutbound(DatagramPacket packet) throws UnknownHostException { + InetPacket p = new InetPacket(packet); + assertNotNull(p); + if (isDebugOutput) + print("SendPacketOutbound Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv6ForwardOutbound(byte[] payload) throws UnknownHostException { + validateIPv6ForwardOutbound("Payload", new InetPacket(payload)); + } + + private void validateIPv6ForwardOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPv6ForwardOutbound("Packet", new InetPacket(packet)); + } + + private void validateIPv6ForwardOutbound(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPv6ForwardOutbound " + tail, p); + assertEquals(FORWARDER_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + assertTrue(point.isIPv6Address()); + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundForward(byte[] payload) throws UnknownHostException { + validateIPv4ForwardOutboundForward("Payload", new InetPacket(payload)); + } + + private void validateIPv4ForwardOutboundForward(DatagramPacket packet) throws UnknownHostException { + validateIPv4ForwardOutboundForward("Packet", new InetPacket(packet)); + } + + private void validateIPv4ForwardOutboundForward(String tail, InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundForward " + tail, p); + assertEquals(FORWARDER_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + assertFalse(point.isIPv6Address()); + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertEquals(CLIENT_PORT, point.port); + assertTrue(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundSend(byte[] payload) throws UnknownHostException { + InetPacket p = new InetPacket(payload); + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundSend Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv4ForwardOutboundSend(DatagramPacket packet) throws UnknownHostException { + InetPacket p = new InetPacket(packet); + assertNotNull(p); + if (isDebugOutput) + print("IPv4ForwardOutboundSend Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPv6SendOutbound(byte[] payload) throws UnknownHostException { + validateIPvXSendOutboundPayload(new InetPacket(payload)); + } + + private void validateIPv4SendOutbound(byte[] payload) throws UnknownHostException { + validateIPvXSendOutboundPayload(new InetPacket(payload)); + } + + private void validateIPv6SendOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPvXSendOutboundPacket(new InetPacket(packet)); + } + + private void validateIPv4SendOutbound(DatagramPacket packet) throws UnknownHostException { + validateIPvXSendOutboundPacket(new InetPacket(packet)); + } + + private void validateIPvXSendOutboundPayload(InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPvXSendOutbound Payload", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNull(point); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void validateIPvXSendOutboundPacket(InetPacket p) throws UnknownHostException { + assertNotNull(p); + if (isDebugOutput) + print("IPvXSendOutbound Packet", p); + assertEquals(CLIENT_PORT, listenPort); + InetPoint point = p.getPoint(); + assertNotNull(point); + byte[] srcAddress = point.address; + assertNotNull(srcAddress); + if (point.isIPv6Address()) + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); + else + assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); + assertFalse(point.forward); + assertArrayEquals(p.getPayload(), PAYLOAD); + } + + private void print(String header, InetPacket pb) throws UnknownHostException { + assertNotNull(pb); + InetPoint point = pb.getPoint(); + if (point != null) { + System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port); + System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, + CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress()); + System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false"); + } else { + System.out.printf("%s: Inet point is null\n", header); + } + byte[] p = pb.getPayload(); + System.out.printf("%s: payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : ""); + System.out.printf("%s: bundle: %s\n", header, pb.toHexString()); + } + }); + listener.start(); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + } + + void checkBackgroundThreadAssertion() { + try { + Thread.sleep(1500); + } catch (InterruptedException unused) { + } + + if (assertionError != null) + throw assertionError; + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java index b0d22e447..b66bf931c 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketTest.java @@ -1,172 +1,172 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Before; -import org.junit.Test; - -import mockit.Capturing; -import mockit.Expectations; -import mockit.Mock; -import mockit.MockUp; -import mockit.Mocked; -import us.dot.its.jpo.ode.util.CrcCccitt; - -public class InetPacketTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - @Mocked - DatagramPacket mockDatagramPacket; - byte[] mockPayload; - - @Mocked InetAddress address; - - @Before - public void setup() { - new MockUp() { - @Mock - public InetAddress getByName(String host) { - return address; - } - }; - } - - - @Test - public void testStringConstructorCallsPointConstructor() { - try { - new InetPacket("testHost", 5, new byte[] { 1, 2, 3 }); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testDatagramPacketConstructor() { - new InetPacket(mockDatagramPacket); - } - - @Test - public void testByteConstructor() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - testPacket.getPoint(); - testPacket.getPayload(); - testPacket.getBundle(); - testPacket.toHexString(); - - } - - /* - * @Test public void testEvenNum() { boolean ans = false; boolean val; byte[] - * bundle = null; - * - * - * val = InetPacket.parseBundle(bundle); assertEquals(ans,val); } - */ - - @Test - public void parseBundleNulll() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = null; - - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleNotMagic() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMagic() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMagicother() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 1, 1, 1, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMaxLength() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void parseBundleMaxMaxLength() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 9, 8, 2, 4, 5, 1, 6, 5, 3 }; - assertFalse(testPacket.parseBundle(bundle)); - } - - @Test - public void setByteBuffer() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; - assertFalse(testPacket.parseBundle(bundle)); - - } - - @Test - public void parseBundleAddressLengthLessThanRemaining() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; - - assertFalse(testPacket.parseBundle(bundle)); - - } - - @Test - public void parseBundleCrcCccittReturnsTrue() { - InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); - byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; - - new Expectations(CrcCccitt.class) { - { - CrcCccitt.isValidMsgCRC((byte[]) any, anyInt, anyInt); - result = true; - } - }; - assertTrue(testPacket.parseBundle(bundle)); - - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.junit.Before; +import org.junit.Test; + +import mockit.Capturing; +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import us.dot.its.jpo.ode.util.CrcCccitt; + +public class InetPacketTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + @Mocked + DatagramPacket mockDatagramPacket; + byte[] mockPayload; + + @Mocked InetAddress address; + + @Before + public void setup() { + new MockUp() { + @Mock + public InetAddress getByName(String host) { + return address; + } + }; + } + + + @Test + public void testStringConstructorCallsPointConstructor() { + try { + new InetPacket("testHost", 5, new byte[] { 1, 2, 3 }); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testDatagramPacketConstructor() { + new InetPacket(mockDatagramPacket); + } + + @Test + public void testByteConstructor() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + testPacket.getPoint(); + testPacket.getPayload(); + testPacket.getBundle(); + testPacket.toHexString(); + + } + + /* + * @Test public void testEvenNum() { boolean ans = false; boolean val; byte[] + * bundle = null; + * + * + * val = InetPacket.parseBundle(bundle); assertEquals(ans,val); } + */ + + @Test + public void parseBundleNulll() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = null; + + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleNotMagic() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMagic() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMagicother() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 1, 1, 1, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMaxLength() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void parseBundleMaxMaxLength() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 9, 8, 2, 4, 5, 1, 6, 5, 3 }; + assertFalse(testPacket.parseBundle(bundle)); + } + + @Test + public void setByteBuffer() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; + assertFalse(testPacket.parseBundle(bundle)); + + } + + @Test + public void parseBundleAddressLengthLessThanRemaining() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; + + assertFalse(testPacket.parseBundle(bundle)); + + } + + @Test + public void parseBundleCrcCccittReturnsTrue() { + InetPacket testPacket = new InetPacket(new byte[] { 1, 2, 3 }); + byte[] bundle = new byte[] { 58, (byte) 143, 5, (byte) 197, 1, 2, 3, 4, 9, 1, 1, 1, 1, 1, 1, 1, 1 }; + + new Expectations(CrcCccitt.class) { + { + CrcCccitt.isValidMsgCRC((byte[]) any, anyInt, anyInt); + result = true; + } + }; + assertTrue(testPacket.parseBundle(bundle)); + + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java index 5aa56eabc..082541092 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPointTest.java @@ -1,141 +1,141 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.inet; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Test; - -import mockit.Capturing; -import mockit.Expectations; - -public class InetPointTest { - - @Capturing - DatagramSocket capturingDatagramSocket; - - @Capturing - DatagramPacket capturingDatagramPacket; - - @Capturing - Thread capturingThread; - - @Capturing - InetAddress capturingInetAddress; - - @Test - public void testStringConstructorCreatesAddress() { - try { - new Expectations() { - { - InetAddress.getByName(anyString).getAddress(); - } - }; - - new InetPoint("hostString123", 5, true); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test(expected = IllegalArgumentException.class) - public void testStringConstructorFailsNullAddress() { - try { - new Expectations() { - { - InetAddress.getByName(anyString).getAddress(); - result = null; - } - }; - new InetPoint("hostString123", 5, true); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testByteConstructorCreatesAddress() { - new InetPoint(new byte[] { 1, 2, 3 }, 5, true); - } - - @Test(expected = IllegalArgumentException.class) - public void testByteConstructorFailsNullAddress() { - new InetPoint((byte[]) null, 5, true); - } - - @Test - public void testBBytePortConstructorCreatesAddress() { - new InetPoint(new byte[] { 1, 2, 3 }, 5); - } - - @Test(expected = IllegalArgumentException.class) - public void testBytePortConstructorFailsNullAddress() { - new InetPoint((byte[]) null, 5); - } - - @Test - public void getInetAddressCallsGetAddress() { - try { - new Expectations() { - { - InetAddress.getByAddress((byte[]) any); - } - }; - new InetPoint(new byte[] { 1, 2, 3 }, 5).getInetAddress(); - } catch (UnknownHostException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void testAddressLength16IsIpv6() { - assertTrue(new InetPoint(new byte[16], 5).isIPv6Address()); - } - - @Test - public void testAddressLength4IsNotIpv6() { - assertFalse(new InetPoint(new byte[4], 5).isIPv6Address()); - } - - @Test - public void testToStringMethodIPV6() { - assertEquals( - "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", - new InetPoint(new byte[16], 5).toString()); - } - - @Test - public void testToStringException() { - assertEquals( - "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", - new InetPoint(new byte[16], 5).toString()); - } - - @Test - public void testToStringMethodIPV4() { - assertEquals("InetPoint { port = 5 (0x5); address = 00000000 (IPv4, null); forward = false }", - new InetPoint(new byte[4], 5).toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.inet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.junit.Test; + +import mockit.Capturing; +import mockit.Expectations; + +public class InetPointTest { + + @Capturing + DatagramSocket capturingDatagramSocket; + + @Capturing + DatagramPacket capturingDatagramPacket; + + @Capturing + Thread capturingThread; + + @Capturing + InetAddress capturingInetAddress; + + @Test + public void testStringConstructorCreatesAddress() { + try { + new Expectations() { + { + InetAddress.getByName(anyString).getAddress(); + } + }; + + new InetPoint("hostString123", 5, true); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testStringConstructorFailsNullAddress() { + try { + new Expectations() { + { + InetAddress.getByName(anyString).getAddress(); + result = null; + } + }; + new InetPoint("hostString123", 5, true); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testByteConstructorCreatesAddress() { + new InetPoint(new byte[] { 1, 2, 3 }, 5, true); + } + + @Test(expected = IllegalArgumentException.class) + public void testByteConstructorFailsNullAddress() { + new InetPoint((byte[]) null, 5, true); + } + + @Test + public void testBBytePortConstructorCreatesAddress() { + new InetPoint(new byte[] { 1, 2, 3 }, 5); + } + + @Test(expected = IllegalArgumentException.class) + public void testBytePortConstructorFailsNullAddress() { + new InetPoint((byte[]) null, 5); + } + + @Test + public void getInetAddressCallsGetAddress() { + try { + new Expectations() { + { + InetAddress.getByAddress((byte[]) any); + } + }; + new InetPoint(new byte[] { 1, 2, 3 }, 5).getInetAddress(); + } catch (UnknownHostException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void testAddressLength16IsIpv6() { + assertTrue(new InetPoint(new byte[16], 5).isIPv6Address()); + } + + @Test + public void testAddressLength4IsNotIpv6() { + assertFalse(new InetPoint(new byte[4], 5).isIPv6Address()); + } + + @Test + public void testToStringMethodIPV6() { + assertEquals( + "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", + new InetPoint(new byte[16], 5).toString()); + } + + @Test + public void testToStringException() { + assertEquals( + "InetPoint { port = 5 (0x5); address = 00000000000000000000000000000000 (IPv6, null); forward = false }", + new InetPoint(new byte[16], 5).toString()); + } + + @Test + public void testToStringMethodIPV4() { + assertEquals("InetPoint { port = 5 (0x5); address = 00000000 (IPv4, null); forward = false }", + new InetPoint(new byte[4], 5).toString()); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java index 9e44a234c..8bb3e482b 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CodecUtilsTest.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.Arrays; - -import org.junit.Test; - -public class CodecUtilsTest { - - @Test - public void testShortsToBytes() { - - byte[] expectedValue = new byte[] { 0, 5, 0, -2, 1, 1 }; - - byte[] actualValue = CodecUtils.shortsToBytes(new short[] { (short) 5, (short) 254, (short) 257 }, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testShortToBytes() { - byte[] expectedValue = new byte[] { 1, 37 }; - - byte[] actualValue = CodecUtils.shortToBytes((short) 293, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testBytesToShorts() { - short[] expectedValue = new short[] { (short) 513 }; - - short[] actualValue = CodecUtils.bytesToShorts(new byte[] { 2, 1 }, 0, 2, ByteOrder.BIG_ENDIAN); - - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - - @Test - public void testBytesToShort() { - short expectedValue = (short) 258; - - short actualValue = CodecUtils.bytesToShort(new byte[] { 1, 2, 5, 2 }, 0, 4, ByteOrder.BIG_ENDIAN); - - assertEquals(expectedValue, actualValue); - } - - @Test - public void testMergeBytes() { - - byte[] expectedValue = new byte[] { 1, 1, 2, 3, 5, 8 }; - - try { - byte[] actualValue = CodecUtils.mergeBytes(new byte[] { 1 }, new byte[] { 1, 2 }, new byte[] { 3, 5, 8 }); - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } catch (IOException e) { - fail("Unexpected exception: " + e); - } - } - - @Test - public void bytesToLongs() { - // 598273498 decimal == 23A8EDDA hex == 0, 0, 0, 0, 35, 168, 237, 218 - // 54 decimal = 0, 0, 0, 0, 0, 0, 0, 54 - long[] expectedValue = new long[] { (long) 598273498, (long) 54 }; - long[] actualValue = CodecUtils.bytesToLongs( - new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 35, (byte) 168, (byte) 237, (byte) 218, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 54 }, - 0, 16, ByteOrder.BIG_ENDIAN); - assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.nio.ByteOrder; +import java.util.Arrays; + +import org.junit.Test; + +public class CodecUtilsTest { + + @Test + public void testShortsToBytes() { + + byte[] expectedValue = new byte[] { 0, 5, 0, -2, 1, 1 }; + + byte[] actualValue = CodecUtils.shortsToBytes(new short[] { (short) 5, (short) 254, (short) 257 }, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testShortToBytes() { + byte[] expectedValue = new byte[] { 1, 37 }; + + byte[] actualValue = CodecUtils.shortToBytes((short) 293, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testBytesToShorts() { + short[] expectedValue = new short[] { (short) 513 }; + + short[] actualValue = CodecUtils.bytesToShorts(new byte[] { 2, 1 }, 0, 2, ByteOrder.BIG_ENDIAN); + + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + + @Test + public void testBytesToShort() { + short expectedValue = (short) 258; + + short actualValue = CodecUtils.bytesToShort(new byte[] { 1, 2, 5, 2 }, 0, 4, ByteOrder.BIG_ENDIAN); + + assertEquals(expectedValue, actualValue); + } + + @Test + public void testMergeBytes() { + + byte[] expectedValue = new byte[] { 1, 1, 2, 3, 5, 8 }; + + try { + byte[] actualValue = CodecUtils.mergeBytes(new byte[] { 1 }, new byte[] { 1, 2 }, new byte[] { 3, 5, 8 }); + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } catch (IOException e) { + fail("Unexpected exception: " + e); + } + } + + @Test + public void bytesToLongs() { + // 598273498 decimal == 23A8EDDA hex == 0, 0, 0, 0, 35, 168, 237, 218 + // 54 decimal = 0, 0, 0, 0, 0, 0, 0, 54 + long[] expectedValue = new long[] { (long) 598273498, (long) 54 }; + long[] actualValue = CodecUtils.bytesToLongs( + new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 35, (byte) 168, (byte) 237, (byte) 218, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 54 }, + 0, 16, ByteOrder.BIG_ENDIAN); + assertEquals(Arrays.toString(expectedValue), Arrays.toString(actualValue)); + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java index 2dd4b18a3..148d13118 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/CrcCccittTest.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import static org.junit.Assert.*; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class CrcCccittTest { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCalculateCrcCccitt() { - testCalculateCrcCccitt(0x0000, ""); - testCalculateCrcCccitt(0x2672, "1"); - testCalculateCrcCccitt(0x31c3, "123456789"); - testCalculateCrcCccitt(0x69df, "The generating polynomial used is the CRC-CCITT commonly expressed as x^16 + x^12 + x^5 + 1. An initial seed value of zero shall be used."); - testCalculateCrcCccitt(0xd4f9, "MsgCRC ::= OCTET STRING (SIZE(2)) -- created with the CRC-CCITT polynomial"); - } - - @Test - public void testCalculateCrcCccitt2() { - int checkSum = CrcCccitt.calculateCrcCccitt(null); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt(null, 1, 10); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("".getBytes(), 1, 10); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), -1, 1); - assertEquals(0, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("1".getBytes(), 0, 10); - assertEquals(0x2672, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), 0, 1); - assertEquals(0x2672, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 1, 9); - assertEquals(0x31c3, checkSum); - checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 5, 4); - assertEquals(0xccf0, checkSum); - } - - @Test - public void testSetMsgCRC() { - byte[] msg = "12345678900".getBytes(); - int checkSum = CrcCccitt.calculateCrcCccitt(msg,0,msg.length-2); - assertEquals(0x31c3, checkSum); - CrcCccitt.setMsgCRC(msg); - assertEquals((byte)0x31, msg[msg.length-2]); - assertEquals((byte)0xc3, msg[msg.length-1]); - assertTrue(CrcCccitt.isValidMsgCRC(msg)); - } - - public void testCalculateCrcCccitt(int expectedCheckSum, String text ) { - byte[] textBytes = text.getBytes(); - int checkSum = CrcCccitt.calculateCrcCccitt(textBytes); - assertEquals(expectedCheckSum, checkSum); - ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); - buffer.putShort((short)checkSum); - byte[] crcBytes = buffer.array(); - byte[] msg = new byte[text.length()+2]; - System.arraycopy(textBytes, 0, msg, 0, textBytes.length); - System.arraycopy(crcBytes, 0, msg, textBytes.length, 2); - boolean isValid = CrcCccitt.isValidMsgCRC(msg); - assertTrue(isValid); - //System.out.printf("0x%04x: %s: %3d %s\n", checkSum, isValid ? "valid" : "invalid", text.length(), text); - System.arraycopy("12".getBytes(), 0, msg, textBytes.length, 2); - isValid = CrcCccitt.isValidMsgCRC(msg); - assertFalse(isValid); - if ( textBytes.length > 0 ) { - isValid = CrcCccitt.isValidMsgCRC(textBytes); - assertFalse(isValid); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import static org.junit.Assert.*; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CrcCccittTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCalculateCrcCccitt() { + testCalculateCrcCccitt(0x0000, ""); + testCalculateCrcCccitt(0x2672, "1"); + testCalculateCrcCccitt(0x31c3, "123456789"); + testCalculateCrcCccitt(0x69df, "The generating polynomial used is the CRC-CCITT commonly expressed as x^16 + x^12 + x^5 + 1. An initial seed value of zero shall be used."); + testCalculateCrcCccitt(0xd4f9, "MsgCRC ::= OCTET STRING (SIZE(2)) -- created with the CRC-CCITT polynomial"); + } + + @Test + public void testCalculateCrcCccitt2() { + int checkSum = CrcCccitt.calculateCrcCccitt(null); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt(null, 1, 10); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("".getBytes(), 1, 10); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), -1, 1); + assertEquals(0, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("1".getBytes(), 0, 10); + assertEquals(0x2672, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("123".getBytes(), 0, 1); + assertEquals(0x2672, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 1, 9); + assertEquals(0x31c3, checkSum); + checkSum = CrcCccitt.calculateCrcCccitt("0123456789abcdef".getBytes(), 5, 4); + assertEquals(0xccf0, checkSum); + } + + @Test + public void testSetMsgCRC() { + byte[] msg = "12345678900".getBytes(); + int checkSum = CrcCccitt.calculateCrcCccitt(msg,0,msg.length-2); + assertEquals(0x31c3, checkSum); + CrcCccitt.setMsgCRC(msg); + assertEquals((byte)0x31, msg[msg.length-2]); + assertEquals((byte)0xc3, msg[msg.length-1]); + assertTrue(CrcCccitt.isValidMsgCRC(msg)); + } + + public void testCalculateCrcCccitt(int expectedCheckSum, String text ) { + byte[] textBytes = text.getBytes(); + int checkSum = CrcCccitt.calculateCrcCccitt(textBytes); + assertEquals(expectedCheckSum, checkSum); + ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN); + buffer.putShort((short)checkSum); + byte[] crcBytes = buffer.array(); + byte[] msg = new byte[text.length()+2]; + System.arraycopy(textBytes, 0, msg, 0, textBytes.length); + System.arraycopy(crcBytes, 0, msg, textBytes.length, 2); + boolean isValid = CrcCccitt.isValidMsgCRC(msg); + assertTrue(isValid); + //System.out.printf("0x%04x: %s: %3d %s\n", checkSum, isValid ? "valid" : "invalid", text.length(), text); + System.arraycopy("12".getBytes(), 0, msg, textBytes.length, 2); + isValid = CrcCccitt.isValidMsgCRC(msg); + assertFalse(isValid); + if ( textBytes.length > 0 ) { + isValid = CrcCccitt.isValidMsgCRC(textBytes); + assertFalse(isValid); + } + } + +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java index fe1849670..a04bd8e7a 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/DateTimeUtilsTest.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.text.ParseException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - -import org.junit.Test; - -import junit.framework.TestCase; -import us.dot.its.jpo.ode.util.DateTimeUtils; - -public class DateTimeUtilsTest extends TestCase { - - @Test - public void testIsoDateTime() throws ParseException { - ZonedDateTime expectedDate = ZonedDateTime.now(ZoneOffset.UTC); - String sExpectedDate = DateTimeUtils.isoDateTime(expectedDate); - String sdate = DateTimeUtils.isoDateTime( - expectedDate.getYear(), - expectedDate.getMonthValue(), - expectedDate.getDayOfMonth(), - expectedDate.getHour(), - expectedDate.getMinute(), - expectedDate.getSecond(), - expectedDate.getNano()/1000000).format(DateTimeFormatter.ISO_INSTANT); - - assertEquals(sExpectedDate.substring(0, 18), sdate.substring(0, 18)); - ZonedDateTime date2 = DateTimeUtils.isoDateTime("2015-11-30T16:06:15.679Z"); - assertNotNull(date2); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.text.ParseException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import org.junit.Test; + +import junit.framework.TestCase; +import us.dot.its.jpo.ode.util.DateTimeUtils; + +public class DateTimeUtilsTest extends TestCase { + + @Test + public void testIsoDateTime() throws ParseException { + ZonedDateTime expectedDate = ZonedDateTime.now(ZoneOffset.UTC); + String sExpectedDate = DateTimeUtils.isoDateTime(expectedDate); + String sdate = DateTimeUtils.isoDateTime( + expectedDate.getYear(), + expectedDate.getMonthValue(), + expectedDate.getDayOfMonth(), + expectedDate.getHour(), + expectedDate.getMinute(), + expectedDate.getSecond(), + expectedDate.getNano()/1000000).format(DateTimeFormatter.ISO_INSTANT); + + assertEquals(sExpectedDate.substring(0, 18), sdate.substring(0, 18)); + ZonedDateTime date2 = DateTimeUtils.isoDateTime("2015-11-30T16:06:15.679Z"); + assertNotNull(date2); + } +} diff --git a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java index 01e066a03..527e31523 100644 --- a/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java +++ b/jpo-ode-common/src/test/java/us/dot/its/jpo/ode/util/GeoUtilsTest.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.util; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; - -import org.junit.Test; - -import junit.framework.TestCase; -import us.dot.its.jpo.ode.util.GeoUtils; -import us.dot.its.jpo.ode.util.LengthUtils; - -public class GeoUtilsTest extends TestCase { - - public void testNearestPointOnLine() { - } - - @Test - public void testPointOffset() { - assertOffset(5.0, 5.0, 10.0, 5.0, 5.0, 8.0); //0 deg - assertOffset(5.0, 5.0, 10.0, 10.0, 2.878, 7.121); //45 deg - assertOffset(5.0, 5.0, 5.0, 10.0, 2.0, 5.0); //90 deg - assertOffset(5.0, 5.0, 0.0, 10.0, 2.878, 2.878); //135 deg - assertOffset(5.0, 5.0, 0.0, 5.0, 5.0, 2.0); //180 deg - assertOffset(5.0, 5.0, 0.0, 0.0, 7.121, 2.878); //225 deg - assertOffset(5.0, 5.0, 5.0, 0.0, 8.0, 5.0); //270 deg - assertOffset(5.0, 5.0, 10.0, 0.0, 7.121, 7.121); //315 deg - } - - @Test - public void assertOffset(double ax, double ay, double bx, double by, double ox, double oy) { - Point2D a = new Point2D.Double(ax, ay); - Point2D b = new Point2D.Double(bx, by); - double k = 3d; - double scale = 1000d; - - Point2D p1 = GeoUtils.pointOffset(a , b , k, null); - long p1x = (long) (p1.getX() * scale); - long p1y = (long) (p1.getY() * scale); - - assertEquals((long) (ox * scale), p1x); - assertEquals((long) (oy * scale), p1y); - } - - @Test - public void testDistanceInMapCoordinates() { - double aLat = 43.652969118285434; - double aLng = -85.94707489013672; - double bLat = 40.96538194577475; - double bLng = -81.03858947753906; - double pLat = 42.0; - double pLng = -83.5; - - Point2D a = GeoUtils.latLngToMap(aLat, aLng); - Point2D b = GeoUtils.latLngToMap(bLat, bLng); - Point2D p = GeoUtils.latLngToMap(pLat, pLng); - Line2D l = new Line2D.Double(a, b); - - double distanceInMeters = GeoUtils.distanceLatLng(aLat, aLng, bLat, bLng, - LengthUtils.UnitOfMeasure.M); - assertEquals(502073, Math.round(distanceInMeters)); - - double distanceInMapCoord = GeoUtils.distance(a, b); - assertEquals(679050, Math.round(distanceInMapCoord)); - - double d1 = GeoUtils.distanceToLine(l, p); - double d2 = GeoUtils.distanceToLine2(l, p); - double d3 = GeoUtils.distanceToLine3(l, p); - - assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); - assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); - } - - @Test - public void testDistanceInLatLng() { - double aLat = 43.652969118285434; - double aLng = -85.94707489013672; - double bLat = 40.96538194577475; - double bLng = -81.03858947753906; - double pLat = 42.0; - double pLng = -83.5; - - Point2D a = new Point2D.Double(aLat, aLng); - Point2D b = new Point2D.Double(bLat, bLng); - Point2D p = new Point2D.Double(pLat, pLng); - Line2D l = new Line2D.Double(a, b); - - double d1 = GeoUtils.distanceToLine(l, p); - double d2 = GeoUtils.distanceToLine2(l, p); - double d3 = GeoUtils.distanceToLine3(l, p); - - assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); - assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.util; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; + +import org.junit.Test; + +import junit.framework.TestCase; +import us.dot.its.jpo.ode.util.GeoUtils; +import us.dot.its.jpo.ode.util.LengthUtils; + +public class GeoUtilsTest extends TestCase { + + public void testNearestPointOnLine() { + } + + @Test + public void testPointOffset() { + assertOffset(5.0, 5.0, 10.0, 5.0, 5.0, 8.0); //0 deg + assertOffset(5.0, 5.0, 10.0, 10.0, 2.878, 7.121); //45 deg + assertOffset(5.0, 5.0, 5.0, 10.0, 2.0, 5.0); //90 deg + assertOffset(5.0, 5.0, 0.0, 10.0, 2.878, 2.878); //135 deg + assertOffset(5.0, 5.0, 0.0, 5.0, 5.0, 2.0); //180 deg + assertOffset(5.0, 5.0, 0.0, 0.0, 7.121, 2.878); //225 deg + assertOffset(5.0, 5.0, 5.0, 0.0, 8.0, 5.0); //270 deg + assertOffset(5.0, 5.0, 10.0, 0.0, 7.121, 7.121); //315 deg + } + + @Test + public void assertOffset(double ax, double ay, double bx, double by, double ox, double oy) { + Point2D a = new Point2D.Double(ax, ay); + Point2D b = new Point2D.Double(bx, by); + double k = 3d; + double scale = 1000d; + + Point2D p1 = GeoUtils.pointOffset(a , b , k, null); + long p1x = (long) (p1.getX() * scale); + long p1y = (long) (p1.getY() * scale); + + assertEquals((long) (ox * scale), p1x); + assertEquals((long) (oy * scale), p1y); + } + + @Test + public void testDistanceInMapCoordinates() { + double aLat = 43.652969118285434; + double aLng = -85.94707489013672; + double bLat = 40.96538194577475; + double bLng = -81.03858947753906; + double pLat = 42.0; + double pLng = -83.5; + + Point2D a = GeoUtils.latLngToMap(aLat, aLng); + Point2D b = GeoUtils.latLngToMap(bLat, bLng); + Point2D p = GeoUtils.latLngToMap(pLat, pLng); + Line2D l = new Line2D.Double(a, b); + + double distanceInMeters = GeoUtils.distanceLatLng(aLat, aLng, bLat, bLng, + LengthUtils.UnitOfMeasure.M); + assertEquals(502073, Math.round(distanceInMeters)); + + double distanceInMapCoord = GeoUtils.distance(a, b); + assertEquals(679050, Math.round(distanceInMapCoord)); + + double d1 = GeoUtils.distanceToLine(l, p); + double d2 = GeoUtils.distanceToLine2(l, p); + double d3 = GeoUtils.distanceToLine3(l, p); + + assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); + assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); + } + + @Test + public void testDistanceInLatLng() { + double aLat = 43.652969118285434; + double aLng = -85.94707489013672; + double bLat = 40.96538194577475; + double bLng = -81.03858947753906; + double pLat = 42.0; + double pLng = -83.5; + + Point2D a = new Point2D.Double(aLat, aLng); + Point2D b = new Point2D.Double(bLat, bLng); + Point2D p = new Point2D.Double(pLat, pLng); + Line2D l = new Line2D.Double(a, b); + + double d1 = GeoUtils.distanceToLine(l, p); + double d2 = GeoUtils.distanceToLine2(l, p); + double d3 = GeoUtils.distanceToLine3(l, p); + + assertEquals(d1, d2, GeoUtils.ERROR_MARGIN); + assertEquals(d1, d3, GeoUtils.ERROR_MARGIN); + } + +} diff --git a/jpo-ode-common/src/test/resources/logback-test.xml b/jpo-ode-common/src/test/resources/logback-test.xml index de5097a2d..a7a69c483 100644 --- a/jpo-ode-common/src/test/resources/logback-test.xml +++ b/jpo-ode-common/src/test/resources/logback-test.xml @@ -1,10 +1,10 @@ - - - - %msg%n - - - - - + + + + %msg%n + + + + + \ No newline at end of file diff --git a/jpo-ode-consumer-example/README.md b/jpo-ode-consumer-example/README.md index 53dae2f6f..311d14ad4 100644 --- a/jpo-ode-consumer-example/README.md +++ b/jpo-ode-consumer-example/README.md @@ -1,68 +1,68 @@ -# Kafka Consumer Example - -This project is intended to serve as a sample consumer application to subscribe to a Kafka topic of streams. After the ODE is up and running, this example project will showcase how you can build a Java application to subscribe to the outputs of a Kafka Stream. - -## Quick Run - - -The sample project needs to be compiled with assembly to ensure that that resulting jar is runnable with the Kafka libraries. It will produce a jar under `target/` with a "with-dependencies" tag. - -``` -mvn clean compile assembly:single install -``` - -To run the jar, be sure to include the topic at the end and group id at the end. If this is not a distributed system, the group can be any string. - -``` -java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar - -usage: Consumer Example - -b,--bootstrap-server Endpoint ('ip:port') - -g,--group Consumer Group - -t,--topic Topic Name - -type,--type string|byte message type -``` - -Example Usage As Of: 1/11/17 - -``` -java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar --bootstrap-server localhost:9092 -g group1 -t topic.J2735Bsm -type byte -``` - -It should return the following confirmation - -``` -Subscribed to topic topic.J2735Bsm -``` -Triggering an upload into the ODE, the output should be seen decoded into JSON in the console. - -![CLI-output](images/cli-output.png) - -## Additional Resources - -With the Kafka installed locally on a machine, here are a few additional commands that may be helpful while debugging Kafka topics. - -[Kafka Install Instructions](https://www.cloudera.com/documentation/kafka/latest/topics/kafka_installing.html#concept_ngx_4l4_4r) - -The IP used is the location of the Kafka endpoints. - -####Create, alter, list, and describe topics. - -``` -kafka-topics --zookeeper 192.168.1.151:2181 --list -sink1 -t1 -t2 -``` - -####Read data from a Kafka topic and write it to standard output. - -``` -kafka-console-consumer --zookeeper 192.168.1.151:2181 --topic topic.J2735Bsm -``` - -####Read data from standard output and write it to a Kafka topic. - -``` -kafka-console-producer --broker-list 192.168.1.151:9092 --topic topic.J2735Bsm -``` +# Kafka Consumer Example + +This project is intended to serve as a sample consumer application to subscribe to a Kafka topic of streams. After the ODE is up and running, this example project will showcase how you can build a Java application to subscribe to the outputs of a Kafka Stream. + +## Quick Run + + +The sample project needs to be compiled with assembly to ensure that that resulting jar is runnable with the Kafka libraries. It will produce a jar under `target/` with a "with-dependencies" tag. + +``` +mvn clean compile assembly:single install +``` + +To run the jar, be sure to include the topic at the end and group id at the end. If this is not a distributed system, the group can be any string. + +``` +java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar + +usage: Consumer Example + -b,--bootstrap-server Endpoint ('ip:port') + -g,--group Consumer Group + -t,--topic Topic Name + -type,--type string|byte message type +``` + +Example Usage As Of: 1/11/17 + +``` +java -jar target/consumer-example-0.0.1-SNAPSHOT-jar-with-dependencies.jar --bootstrap-server localhost:9092 -g group1 -t topic.J2735Bsm -type byte +``` + +It should return the following confirmation + +``` +Subscribed to topic topic.J2735Bsm +``` +Triggering an upload into the ODE, the output should be seen decoded into JSON in the console. + +![CLI-output](images/cli-output.png) + +## Additional Resources + +With the Kafka installed locally on a machine, here are a few additional commands that may be helpful while debugging Kafka topics. + +[Kafka Install Instructions](https://www.cloudera.com/documentation/kafka/latest/topics/kafka_installing.html#concept_ngx_4l4_4r) + +The IP used is the location of the Kafka endpoints. + +####Create, alter, list, and describe topics. + +``` +kafka-topics --zookeeper 192.168.1.151:2181 --list +sink1 +t1 +t2 +``` + +####Read data from a Kafka topic and write it to standard output. + +``` +kafka-console-consumer --zookeeper 192.168.1.151:2181 --topic topic.J2735Bsm +``` + +####Read data from standard output and write it to a Kafka topic. + +``` +kafka-console-producer --broker-list 192.168.1.151:9092 --topic topic.J2735Bsm +``` diff --git a/jpo-ode-consumer-example/pom.xml b/jpo-ode-consumer-example/pom.xml index 8ad267598..8d3f26391 100644 --- a/jpo-ode-consumer-example/pom.xml +++ b/jpo-ode-consumer-example/pom.xml @@ -1,64 +1,64 @@ - - 4.0.0 - - com.consumerexample - 0.0.1-SNAPSHOT - consumer-example - jar - consumer-example - - - junit - junit - 4.12 - test - - - - org.apache.kafka - kafka-clients - 0.10.1.0 - - - usdot.jpo.ode - jpo-ode-core - 0.0.1-SNAPSHOT - - - - commons-cli - commons-cli - 1.3 - - - - org.apache.commons - commons-lang3 - 3.0 - - - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.4 - - - - com.consumerexample.app.ConsumerExample - - - - jar-with-dependencies - - - - - - - + + 4.0.0 + + com.consumerexample + 0.0.1-SNAPSHOT + consumer-example + jar + consumer-example + + + junit + junit + 4.12 + test + + + + org.apache.kafka + kafka-clients + 0.10.1.0 + + + usdot.jpo.ode + jpo-ode-core + 0.0.1-SNAPSHOT + + + + commons-cli + commons-cli + 1.3 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.4 + + + + com.consumerexample.app.ConsumerExample + + + + jar-with-dependencies + + + + + + + diff --git a/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java b/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java index 74967e502..b63be9aab 100644 --- a/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java +++ b/jpo-ode-consumer-example/src/main/java/com/consumerexample/app/ConsumerExample.java @@ -1,111 +1,111 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 com.consumerexample.app; - -import java.util.Properties; -import java.util.Arrays; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.commons.cli.*; -import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; -import us.dot.its.jpo.ode.util.SerializationUtils; - -public class ConsumerExample { - - public static void main( String[] args ){ - - // Option parsing - Options options = new Options(); - - Option bootstrap_server = new Option("b", "bootstrap-server", true, "Endpoint ('ip:port')"); - bootstrap_server.setRequired(true); - options.addOption(bootstrap_server); - - Option topic_option = new Option("t", "topic", true, "Topic Name"); - topic_option.setRequired(true); - options.addOption(topic_option); - - Option group_option = new Option("g", "group", true, "Consumer Group"); - group_option.setRequired(true); - options.addOption(group_option); - - Option type_option = new Option("type", "type", true, "string|byte message type"); - type_option.setRequired(true); - options.addOption(type_option); - - CommandLineParser parser = new DefaultParser(); - HelpFormatter formatter = new HelpFormatter(); - CommandLine cmd; - - try { - cmd = parser.parse(options, args); - } catch (ParseException e) { - System.out.println(e.getMessage()); - formatter.printHelp("Consumer Example", options); - - System.exit(1); - return; - } - - String endpoint = cmd.getOptionValue("bootstrap-server"); - String topic = cmd.getOptionValue("topic"); - String group = cmd.getOptionValue("group"); - String type = cmd.getOptionValue("type"); - - // Properties for the kafka topic - Properties props = new Properties(); - props.put("bootstrap.servers", endpoint); - props.put("group.id", group); - props.put("enable.auto.commit", "false"); - props.put("auto.commit.interval.ms", "1000"); - props.put("session.timeout.ms", "30000"); - props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - if (type.equals("byte")){ - props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); - } else { - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - } - - if (type.equals("byte")) { - KafkaConsumer byteArrayConsumer = new KafkaConsumer(props); - - byteArrayConsumer.subscribe(Arrays.asList(topic)); - System.out.println("Subscribed to topic " + topic); - while (true) { - ConsumerRecords records = byteArrayConsumer.poll(100); - for (ConsumerRecord record : records) { - // Serialize the record value - SerializationUtils serializer = new SerializationUtils(); - J2735Bsm bsm = serializer.deserialize(record.value()); - System.out.println(bsm.toString()); - } - } - } else { - KafkaConsumer stringConsumer = new KafkaConsumer(props); - - stringConsumer.subscribe(Arrays.asList(topic)); - System.out.println("Subscribed to topic " + topic); - while (true) { - ConsumerRecords records = stringConsumer.poll(100); - for (ConsumerRecord record : records) { - System.out.println(record.value()); - } - } - - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 com.consumerexample.app; + +import java.util.Properties; +import java.util.Arrays; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.commons.cli.*; +import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; +import us.dot.its.jpo.ode.util.SerializationUtils; + +public class ConsumerExample { + + public static void main( String[] args ){ + + // Option parsing + Options options = new Options(); + + Option bootstrap_server = new Option("b", "bootstrap-server", true, "Endpoint ('ip:port')"); + bootstrap_server.setRequired(true); + options.addOption(bootstrap_server); + + Option topic_option = new Option("t", "topic", true, "Topic Name"); + topic_option.setRequired(true); + options.addOption(topic_option); + + Option group_option = new Option("g", "group", true, "Consumer Group"); + group_option.setRequired(true); + options.addOption(group_option); + + Option type_option = new Option("type", "type", true, "string|byte message type"); + type_option.setRequired(true); + options.addOption(type_option); + + CommandLineParser parser = new DefaultParser(); + HelpFormatter formatter = new HelpFormatter(); + CommandLine cmd; + + try { + cmd = parser.parse(options, args); + } catch (ParseException e) { + System.out.println(e.getMessage()); + formatter.printHelp("Consumer Example", options); + + System.exit(1); + return; + } + + String endpoint = cmd.getOptionValue("bootstrap-server"); + String topic = cmd.getOptionValue("topic"); + String group = cmd.getOptionValue("group"); + String type = cmd.getOptionValue("type"); + + // Properties for the kafka topic + Properties props = new Properties(); + props.put("bootstrap.servers", endpoint); + props.put("group.id", group); + props.put("enable.auto.commit", "false"); + props.put("auto.commit.interval.ms", "1000"); + props.put("session.timeout.ms", "30000"); + props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + if (type.equals("byte")){ + props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); + } else { + props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + } + + if (type.equals("byte")) { + KafkaConsumer byteArrayConsumer = new KafkaConsumer(props); + + byteArrayConsumer.subscribe(Arrays.asList(topic)); + System.out.println("Subscribed to topic " + topic); + while (true) { + ConsumerRecords records = byteArrayConsumer.poll(100); + for (ConsumerRecord record : records) { + // Serialize the record value + SerializationUtils serializer = new SerializationUtils(); + J2735Bsm bsm = serializer.deserialize(record.value()); + System.out.println(bsm.toString()); + } + } + } else { + KafkaConsumer stringConsumer = new KafkaConsumer(props); + + stringConsumer.subscribe(Arrays.asList(topic)); + System.out.println("Subscribed to topic " + topic); + while (true) { + ConsumerRecords records = stringConsumer.poll(100); + for (ConsumerRecord record : records) { + System.out.println(record.value()); + } + } + + } + } +} diff --git a/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java b/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java index 803e72531..866d78a56 100644 --- a/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java +++ b/jpo-ode-consumer-example/src/test/java/com/consumerexample/app/ConsumerExampleTest.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 com.consumerexample.app; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class ConsumerExampleTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public ConsumerExampleTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( ConsumerExampleTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 com.consumerexample.app; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class ConsumerExampleTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public ConsumerExampleTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( ConsumerExampleTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties b/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties index 5235dd160..c954cec91 100644 --- a/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties +++ b/jpo-ode-core/.mvn/wrapper/maven-wrapper.properties @@ -1 +1 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/jpo-ode-core/LICENSE-2.0.html b/jpo-ode-core/LICENSE-2.0.html index 16303d2c7..d1055c8ad 100644 --- a/jpo-ode-core/LICENSE-2.0.html +++ b/jpo-ode-core/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-core/mvnw b/jpo-ode-core/mvnw index 223618a5c..a1ba1bf55 100644 --- a/jpo-ode-core/mvnw +++ b/jpo-ode-core/mvnw @@ -1,233 +1,233 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" +#!/bin/sh +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" diff --git a/jpo-ode-core/mvnw.cmd b/jpo-ode-core/mvnw.cmd index beda8f144..2b934e89d 100644 --- a/jpo-ode-core/mvnw.cmd +++ b/jpo-ode-core/mvnw.cmd @@ -1,145 +1,145 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + exit /B %ERROR_CODE% \ No newline at end of file diff --git a/jpo-ode-core/pom.xml b/jpo-ode-core/pom.xml index acfc39dd3..7b3d02eb7 100644 --- a/jpo-ode-core/pom.xml +++ b/jpo-ode-core/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT jpo-ode-core @@ -23,12 +23,12 @@ usdot.jpo.ode jpo-ode-common - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT usdot.jpo.ode jpo-ode-plugins - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT org.apache.httpcomponents diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java index a35fda0fc..fb3a35c3d 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/context/AppContext.java @@ -1,149 +1,149 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.context; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.UUID; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -@Configuration -public class AppContext { - // CONSTANTS - public static final String ODE_HOSTNAME = "ODE_HOSTNAME"; - public static final String PAYLOAD_STRING = "payload"; - public static final String METADATA_STRING = "metadata"; - public static final String ODE_ASN1_DATA = "OdeAsn1Data"; - public static final String DATA_STRING = "data"; - public static final String ENCODINGS_STRING = "encodings"; - public static final String PAYLOAD_TYPE_STRING = "payloadType"; - public static final String DATA_TYPE_STRING = "dataType"; - public static final String SERIAL_ID_STRING = "serialId"; - public static final String SANITIZED_STRING = "Sanitized-"; - public static final String DEFAULT_KAFKA_PRODUCER_TYPE = "sync"; - - public static final int DEFAULT_SPARK_ROAD_SEGMENT_SNAPPING_TOLERANCE = 20; - public static final int DEFAULT_METRICS_GRAPHITE_PORT = 2003; - public static final int DEFAULT_METRICS_POLLING_RATE_SECONDS = 10; - - // Kafka Parameters - public static final String KAFKA_METADATA_BROKER_LIST = "kafka.metadata.broker.list"; - public static final String KAFKA_CONSUMER_THREADS = "kafka.consumer.threads"; - public static final String ZK_CONNECTION_STRINGS = "zk.connection.strings"; - public static final int DEFAULT_KAFKA_CONSUMER_THREADS = 1; - - public static final String TOKEN_KEY_RSA_PEM = "token.key.rsa.pem"; - - public static final String METRICS_PREFIX = "metrics.prefix"; - public static final String METRICS_POLLING_RATE_SECONDS = "metrics.polling.rate.seconds"; - public static final String METRICS_GRAPHITE_HOST = "metrics.graphite.host"; - public static final String METRICS_GRAPHITE_PORT = "metrics.graphite.port"; - - private static AppContext instance = null; - - @Autowired - Environment env; - - private String hostId; - - public AppContext() { - } - - public static AppContext getInstance() { - if (null == instance) { - synchronized (AppContext.class) { - if (null == instance) - instance = new AppContext(); - instance.init(); - } - } - return instance; - } - - private void init() { - String hostname; - - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - // Let's just use a random hostname - hostname = UUID.randomUUID().toString(); - } - hostId = hostname; - } - - public String getHostId() { - return hostId; - } - - public String getParam(String key) { - String result = null; - if (key != null) { - result = env.getProperty(key); - } - - return result; - } - - public String getParam(String key, String defaultValue) { - String result = getParam(key); - if (result != null) { - return result; - } else { - return defaultValue; - } - } - - public int getInt(String key, int defaultValue) { - String result = getParam(key); - if (result != null) { - return Integer.parseInt(result); - } else { - return defaultValue; - } - } - - public long getLong(String key, long defaultValue) { - String result = getParam(key); - if (result != null) { - return Long.parseLong(result); - } else { - return defaultValue; - } - } - - public double getDouble(String key, double defaultValue) { - String result = getParam(key); - if (result != null) { - return Double.parseDouble(result); - } else { - return defaultValue; - } - } - - public boolean getBoolean(String key, boolean defaultValue) { - String result = getParam(key); - if (result != null) { - return Boolean.parseBoolean(result); - } else { - return defaultValue; - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.context; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +@Configuration +public class AppContext { + // CONSTANTS + public static final String ODE_HOSTNAME = "ODE_HOSTNAME"; + public static final String PAYLOAD_STRING = "payload"; + public static final String METADATA_STRING = "metadata"; + public static final String ODE_ASN1_DATA = "OdeAsn1Data"; + public static final String DATA_STRING = "data"; + public static final String ENCODINGS_STRING = "encodings"; + public static final String PAYLOAD_TYPE_STRING = "payloadType"; + public static final String DATA_TYPE_STRING = "dataType"; + public static final String SERIAL_ID_STRING = "serialId"; + public static final String SANITIZED_STRING = "Sanitized-"; + public static final String DEFAULT_KAFKA_PRODUCER_TYPE = "sync"; + + public static final int DEFAULT_SPARK_ROAD_SEGMENT_SNAPPING_TOLERANCE = 20; + public static final int DEFAULT_METRICS_GRAPHITE_PORT = 2003; + public static final int DEFAULT_METRICS_POLLING_RATE_SECONDS = 10; + + // Kafka Parameters + public static final String KAFKA_METADATA_BROKER_LIST = "kafka.metadata.broker.list"; + public static final String KAFKA_CONSUMER_THREADS = "kafka.consumer.threads"; + public static final String ZK_CONNECTION_STRINGS = "zk.connection.strings"; + public static final int DEFAULT_KAFKA_CONSUMER_THREADS = 1; + + public static final String TOKEN_KEY_RSA_PEM = "token.key.rsa.pem"; + + public static final String METRICS_PREFIX = "metrics.prefix"; + public static final String METRICS_POLLING_RATE_SECONDS = "metrics.polling.rate.seconds"; + public static final String METRICS_GRAPHITE_HOST = "metrics.graphite.host"; + public static final String METRICS_GRAPHITE_PORT = "metrics.graphite.port"; + + private static AppContext instance = null; + + @Autowired + Environment env; + + private String hostId; + + public AppContext() { + } + + public static AppContext getInstance() { + if (null == instance) { + synchronized (AppContext.class) { + if (null == instance) + instance = new AppContext(); + instance.init(); + } + } + return instance; + } + + private void init() { + String hostname; + + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + // Let's just use a random hostname + hostname = UUID.randomUUID().toString(); + } + hostId = hostname; + } + + public String getHostId() { + return hostId; + } + + public String getParam(String key) { + String result = null; + if (key != null) { + result = env.getProperty(key); + } + + return result; + } + + public String getParam(String key, String defaultValue) { + String result = getParam(key); + if (result != null) { + return result; + } else { + return defaultValue; + } + } + + public int getInt(String key, int defaultValue) { + String result = getParam(key); + if (result != null) { + return Integer.parseInt(result); + } else { + return defaultValue; + } + } + + public long getLong(String key, long defaultValue) { + String result = getParam(key); + if (result != null) { + return Long.parseLong(result); + } else { + return defaultValue; + } + } + + public double getDouble(String key, double defaultValue) { + String result = getParam(key); + if (result != null) { + return Double.parseDouble(result); + } else { + return defaultValue; + } + } + + public boolean getBoolean(String key, boolean defaultValue) { + String result = getParam(key); + if (result != null) { + return Boolean.parseBoolean(result); + } else { + return defaultValue; + } + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java index c4df9b379..d47658251 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsDepRequest.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - - -/** - * "DEPOSIT: { \"systemDepositName\": \"%s\", \"encodeType\": \"%s\", \"encodedMsg\": \"%s\" }" - * - */ -public class DdsDepRequest extends DdsRequest { - - private static final long serialVersionUID = 6066887685895268828L; - - private String systemDepositName; - private String encodeType; - private String encodedMsg; - - - public String getSystemDepositName() { - return systemDepositName; - } - - public DdsDepRequest setSystemDepositName(String systemDepositName) { - this.systemDepositName = systemDepositName; - return this; - } - - public String getEncodeType() { - return encodeType; - } - - public DdsDepRequest setEncodeType(String encodeType) { - this.encodeType = encodeType; - return this; - } - - public String getEncodedMsg() { - return encodedMsg; - } - - public DdsDepRequest setEncodedMsg(String encodedMsg) { - this.encodedMsg = encodedMsg; - return this; - } - - @Override - public String toString() { - return "DEPOSIT:" + this.toJson(false); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((encodeType == null) ? 0 : encodeType.hashCode()); - result = prime * result - + ((encodedMsg == null) ? 0 : encodedMsg.hashCode()); - result = prime * result - + ((systemDepositName == null) ? 0 : systemDepositName.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; - DdsDepRequest other = (DdsDepRequest) obj; - if (encodeType == null) { - if (other.encodeType != null) - return false; - } else if (!encodeType.equals(other.encodeType)) - return false; - if (encodedMsg == null) { - if (other.encodedMsg != null) - return false; - } else if (!encodedMsg.equals(other.encodedMsg)) - return false; - if (systemDepositName == null) { - if (other.systemDepositName != null) - return false; - } else if (!systemDepositName.equals(other.systemDepositName)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + + +/** + * "DEPOSIT: { \"systemDepositName\": \"%s\", \"encodeType\": \"%s\", \"encodedMsg\": \"%s\" }" + * + */ +public class DdsDepRequest extends DdsRequest { + + private static final long serialVersionUID = 6066887685895268828L; + + private String systemDepositName; + private String encodeType; + private String encodedMsg; + + + public String getSystemDepositName() { + return systemDepositName; + } + + public DdsDepRequest setSystemDepositName(String systemDepositName) { + this.systemDepositName = systemDepositName; + return this; + } + + public String getEncodeType() { + return encodeType; + } + + public DdsDepRequest setEncodeType(String encodeType) { + this.encodeType = encodeType; + return this; + } + + public String getEncodedMsg() { + return encodedMsg; + } + + public DdsDepRequest setEncodedMsg(String encodedMsg) { + this.encodedMsg = encodedMsg; + return this; + } + + @Override + public String toString() { + return "DEPOSIT:" + this.toJson(false); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((encodeType == null) ? 0 : encodeType.hashCode()); + result = prime * result + + ((encodedMsg == null) ? 0 : encodedMsg.hashCode()); + result = prime * result + + ((systemDepositName == null) ? 0 : systemDepositName.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; + DdsDepRequest other = (DdsDepRequest) obj; + if (encodeType == null) { + if (other.encodeType != null) + return false; + } else if (!encodeType.equals(other.encodeType)) + return false; + if (encodedMsg == null) { + if (other.encodedMsg != null) + return false; + } else if (!encodedMsg.equals(other.encodedMsg)) + return false; + if (systemDepositName == null) { + if (other.systemDepositName != null) + return false; + } else if (!systemDepositName.equals(other.systemDepositName)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java index c5a4cbc66..765b3ce9d 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsRequest.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import us.dot.its.jpo.ode.model.BaseRequest; - -@SuppressWarnings("serial") -public class DdsRequest extends BaseRequest { - - public enum Dialog { - VSD (154), - ISD (162), - ASD (156), - ALL (-1); - - private final int id; - - Dialog(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public static Dialog getById(int id) { - Dialog result = null; - for (Dialog d : Dialog.values()) { - if (d.getId() == id) { - result = d; - break; - } - } - return result; - } - } - - public enum SystemName { - SDC ("SDC 2.3"), - SDW ("SDW 2.3"), - SDPC ("SDPC 2.3"); - - private final String name; - - SystemName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - - public enum EncodeType {BASE64, HEX} - - private int dialogID; - private String resultEncoding; - - public int getDialogID() { - return dialogID; - } - - public DdsRequest setDialogID(int dialogID) { - this.dialogID = dialogID; - return this; - } - - public String getResultEncoding() { - return resultEncoding; - } - - public DdsRequest setResultEncoding(String resultEncoding) { - this.resultEncoding = resultEncoding; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + dialogID; - result = prime * result + ((resultEncoding == null) ? 0 : resultEncoding.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; - DdsRequest other = (DdsRequest) obj; - if (dialogID != other.dialogID) - return false; - if (resultEncoding == null) { - if (other.resultEncoding != null) - return false; - } else if (!resultEncoding.equals(other.resultEncoding)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import us.dot.its.jpo.ode.model.BaseRequest; + +@SuppressWarnings("serial") +public class DdsRequest extends BaseRequest { + + public enum Dialog { + VSD (154), + ISD (162), + ASD (156), + ALL (-1); + + private final int id; + + Dialog(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public static Dialog getById(int id) { + Dialog result = null; + for (Dialog d : Dialog.values()) { + if (d.getId() == id) { + result = d; + break; + } + } + return result; + } + } + + public enum SystemName { + SDC ("SDC 2.3"), + SDW ("SDW 2.3"), + SDPC ("SDPC 2.3"); + + private final String name; + + SystemName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + + public enum EncodeType {BASE64, HEX} + + private int dialogID; + private String resultEncoding; + + public int getDialogID() { + return dialogID; + } + + public DdsRequest setDialogID(int dialogID) { + this.dialogID = dialogID; + return this; + } + + public String getResultEncoding() { + return resultEncoding; + } + + public DdsRequest setResultEncoding(String resultEncoding) { + this.resultEncoding = resultEncoding; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + dialogID; + result = prime * result + ((resultEncoding == null) ? 0 : resultEncoding.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; + DdsRequest other = (DdsRequest) obj; + if (dialogID != other.dialogID) + return false; + if (resultEncoding == null) { + if (other.resultEncoding != null) + return false; + } else if (!resultEncoding.equals(other.resultEncoding)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java index 7891043e3..cc08ff5e0 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/dds/DdsStatusMessage.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessage implements DdsMessage { - private StatusTag tag; - private String encoding; - private Dialog dialog; - private long recordCount; - private String connectionDetails; - - public DdsStatusMessage() { - super(); - } - - public DdsStatusMessage(StatusTag tag, String encoding, Dialog dialog) { - super(); - this.tag = tag; - this.encoding = encoding; - this.dialog = dialog; - } - - public StatusTag getTag() { - return tag; - } - - public DdsStatusMessage setTag(StatusTag tag) { - this.tag = tag; - return this; - } - - public String getEncoding() { - return encoding; - } - - public DdsStatusMessage setEncoding(String encoding) { - this.encoding = encoding; - return this; - } - - public Dialog getDialog() { - return dialog; - } - - public DdsStatusMessage setDialog(Dialog dialog) { - this.dialog = dialog; - return this; - } - - public long getRecordCount() { - return recordCount; - } - - public DdsStatusMessage setRecordCount(long recordCount) { - this.recordCount = recordCount; - return this; - } - - public String getConnectionDetails() { - return connectionDetails; - } - - public DdsStatusMessage setConnectionDetails(String connectionDetails) { - this.connectionDetails = connectionDetails; - return this; - } - - @Override - public String toString() { - return "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" - + recordCount + ", connectionDetails=" + connectionDetails + "]"; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessage implements DdsMessage { + private StatusTag tag; + private String encoding; + private Dialog dialog; + private long recordCount; + private String connectionDetails; + + public DdsStatusMessage() { + super(); + } + + public DdsStatusMessage(StatusTag tag, String encoding, Dialog dialog) { + super(); + this.tag = tag; + this.encoding = encoding; + this.dialog = dialog; + } + + public StatusTag getTag() { + return tag; + } + + public DdsStatusMessage setTag(StatusTag tag) { + this.tag = tag; + return this; + } + + public String getEncoding() { + return encoding; + } + + public DdsStatusMessage setEncoding(String encoding) { + this.encoding = encoding; + return this; + } + + public Dialog getDialog() { + return dialog; + } + + public DdsStatusMessage setDialog(Dialog dialog) { + this.dialog = dialog; + return this; + } + + public long getRecordCount() { + return recordCount; + } + + public DdsStatusMessage setRecordCount(long recordCount) { + this.recordCount = recordCount; + return this; + } + + public String getConnectionDetails() { + return connectionDetails; + } + + public DdsStatusMessage setConnectionDetails(String connectionDetails) { + this.connectionDetails = connectionDetails; + return this; + } + + @Override + public String toString() { + return "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" + + recordCount + ", connectionDetails=" + connectionDetails + "]"; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java index a4f4969f4..7dcd8ad2c 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/BaseRequest.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -@SuppressWarnings("serial") -public class BaseRequest extends OdeObject { - - public BaseRequest() { - super(); - } - - static BaseRequest create() { - return new BaseRequest(); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +@SuppressWarnings("serial") +public class BaseRequest extends OdeObject { + + public BaseRequest() { + super(); + } + + static BaseRequest create() { + return new BaseRequest(); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java index 69e6269a3..c38a99aad 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasKey.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public interface HasKey extends OdeFilterable { - String getKey(); -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public interface HasKey extends OdeFilterable { + String getKey(); +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java index 640f69d98..65b3eca2a 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/HasPosition.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.OdeGeoRegion; -import us.dot.its.jpo.ode.plugin.j2735.OdePosition3D; - -public interface HasPosition extends OdeFilterable { - OdePosition3D getPosition(); - boolean isWithinBounds(OdeGeoRegion region); -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.OdeGeoRegion; +import us.dot.its.jpo.ode.plugin.j2735.OdePosition3D; + +public interface HasPosition extends OdeFilterable { + OdePosition3D getPosition(); + boolean isWithinBounds(OdeGeoRegion region); +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java index edb52655d..296be0dcb 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAggregateData.java @@ -1,138 +1,138 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.math.BigDecimal; - -public final class OdeAggregateData extends OdeData implements HasKey { - - private static final long serialVersionUID = 1595406822366147861L; - - private String key; - private Long count; - private BigDecimal minSpeed; - private BigDecimal avgSpeed; - private BigDecimal maxSpeed; - - public OdeAggregateData() { - super(); - } - - public OdeAggregateData(String key, Long count, BigDecimal minSpeed, BigDecimal avgSpeed, BigDecimal maxSpeed) { - super(); - this.key = key; - this.count = count; - this.minSpeed = minSpeed; - this.avgSpeed = avgSpeed; - this.maxSpeed = maxSpeed; -} - -@Override - public String getKey() { - return key; - } - - public OdeAggregateData setKey(String key) { - this.key = key; - return this; - } - - public Long getCount() { - return count; - } - - public OdeAggregateData setCount(Long count) { - this.count = count; - return this; - } - - public BigDecimal getMinSpeed() { - return minSpeed; - } - - public OdeAggregateData setMinSpeed(BigDecimal minSpeed) { - this.minSpeed = minSpeed; - return this; - } - - public BigDecimal getAvgSpeed() { - return avgSpeed; - } - - public OdeAggregateData setAvgSpeed(BigDecimal avgSpeed) { - this.avgSpeed = avgSpeed; - return this; - } - - public BigDecimal getMaxSpeed() { - return maxSpeed; - } - - public void setMaxSpeed(BigDecimal maxSpeed) { - this.maxSpeed = maxSpeed; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((avgSpeed == null) ? 0 : avgSpeed.hashCode()); - result = prime * result + ((count == null) ? 0 : count.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((maxSpeed == null) ? 0 : maxSpeed.hashCode()); - result = prime * result + ((minSpeed == null) ? 0 : minSpeed.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeAggregateData other = (OdeAggregateData) obj; - if (avgSpeed == null) { - if (other.avgSpeed != null) - return false; - } else if (!avgSpeed.equals(other.avgSpeed)) - return false; - if (count == null) { - if (other.count != null) - return false; - } else if (!count.equals(other.count)) - return false; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) - return false; - if (maxSpeed == null) { - if (other.maxSpeed != null) - return false; - } else if (!maxSpeed.equals(other.maxSpeed)) - return false; - if (minSpeed == null) { - if (other.minSpeed != null) - return false; - } else if (!minSpeed.equals(other.minSpeed)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.math.BigDecimal; + +public final class OdeAggregateData extends OdeData implements HasKey { + + private static final long serialVersionUID = 1595406822366147861L; + + private String key; + private Long count; + private BigDecimal minSpeed; + private BigDecimal avgSpeed; + private BigDecimal maxSpeed; + + public OdeAggregateData() { + super(); + } + + public OdeAggregateData(String key, Long count, BigDecimal minSpeed, BigDecimal avgSpeed, BigDecimal maxSpeed) { + super(); + this.key = key; + this.count = count; + this.minSpeed = minSpeed; + this.avgSpeed = avgSpeed; + this.maxSpeed = maxSpeed; +} + +@Override + public String getKey() { + return key; + } + + public OdeAggregateData setKey(String key) { + this.key = key; + return this; + } + + public Long getCount() { + return count; + } + + public OdeAggregateData setCount(Long count) { + this.count = count; + return this; + } + + public BigDecimal getMinSpeed() { + return minSpeed; + } + + public OdeAggregateData setMinSpeed(BigDecimal minSpeed) { + this.minSpeed = minSpeed; + return this; + } + + public BigDecimal getAvgSpeed() { + return avgSpeed; + } + + public OdeAggregateData setAvgSpeed(BigDecimal avgSpeed) { + this.avgSpeed = avgSpeed; + return this; + } + + public BigDecimal getMaxSpeed() { + return maxSpeed; + } + + public void setMaxSpeed(BigDecimal maxSpeed) { + this.maxSpeed = maxSpeed; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((avgSpeed == null) ? 0 : avgSpeed.hashCode()); + result = prime * result + ((count == null) ? 0 : count.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((maxSpeed == null) ? 0 : maxSpeed.hashCode()); + result = prime * result + ((minSpeed == null) ? 0 : minSpeed.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeAggregateData other = (OdeAggregateData) obj; + if (avgSpeed == null) { + if (other.avgSpeed != null) + return false; + } else if (!avgSpeed.equals(other.avgSpeed)) + return false; + if (count == null) { + if (other.count != null) + return false; + } else if (!count.equals(other.count)) + return false; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (maxSpeed == null) { + if (other.maxSpeed != null) + return false; + } else if (!maxSpeed.equals(other.maxSpeed)) + return false; + if (minSpeed == null) { + if (other.minSpeed != null) + return false; + } else if (!minSpeed.equals(other.minSpeed)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java index 84f843fa3..be6e575ac 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsdPayload.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.DdsAdvisorySituationData; - -public class OdeAsdPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - - public OdeAsdPayload() { - this(new DdsAdvisorySituationData()); - } - - public OdeAsdPayload(DdsAdvisorySituationData asd) { - super(asd); - this.setData(asd); - } - - public DdsAdvisorySituationData getAsd() { - return (DdsAdvisorySituationData) getData(); - } - - public void setAsd(DdsAdvisorySituationData asd) { - setData(asd); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.DdsAdvisorySituationData; + +public class OdeAsdPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + + public OdeAsdPayload() { + this(new DdsAdvisorySituationData()); + } + + public OdeAsdPayload(DdsAdvisorySituationData asd) { + super(asd); + this.setData(asd); + } + + public DdsAdvisorySituationData getAsd() { + return (DdsAdvisorySituationData) getData(); + } + + public void setAsd(DdsAdvisorySituationData asd) { + setData(asd); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java index 52a2b0e4c..e48186239 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAsn1Data.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeAsn1Data extends OdeData { - private static final long serialVersionUID = 8844322473807845737L; - - public OdeAsn1Data() { - super(); - } - - public OdeAsn1Data(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeAsn1Data extends OdeData { + private static final long serialVersionUID = 8844322473807845737L; + + public OdeAsn1Data() { + super(); + } + + public OdeAsn1Data(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java index 156d9c34c..200af90e5 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeAuthorization.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeAuthorization extends OdeMessage{ - - private static final long serialVersionUID = -8496344900381434672L; - - private String token; - - public String getToken() { - return token; - } - - public OdeAuthorization setToken(String token) { - this.token = token; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((token == null) ? 0 : token.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeAuthorization other = (OdeAuthorization) obj; - if (token == null) { - if (other.token != null) - return false; - } else if (!token.equals(other.token)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeAuthorization extends OdeMessage{ + + private static final long serialVersionUID = -8496344900381434672L; + + private String token; + + public String getToken() { + return token; + } + + public OdeAuthorization setToken(String token) { + this.token = token; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((token == null) ? 0 : token.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeAuthorization other = (OdeAuthorization) obj; + if (token == null) { + if (other.token != null) + return false; + } else if (!token.equals(other.token)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java index 87c56b435..a16745cc6 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeControlData.java @@ -1,156 +1,156 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.dds.DdsStatusMessage; - -public class OdeControlData extends OdeMessage { - - private static final long serialVersionUID = 1L; - - private Long dataSourceBundleCount; - private Long receivedRecordCount; - private Long sentRecordCount; - private Long depositCount; - private StatusTag tag; - private String message; - - public OdeControlData() { - super(); - } - - public OdeControlData(StatusTag tag) { - super(); - setTag(tag); - } - - public OdeControlData(DdsStatusMessage controlMessage) { - setTag(controlMessage.getTag()); - if (controlMessage.getTag() == StatusTag.STOP) - setDataSourceBundleCount(controlMessage.getRecordCount()); - else if (controlMessage.getTag() == StatusTag.DEPOSITED) - setDepositCount(controlMessage.getRecordCount()); - } - - public Long getDataSourceBundleCount() { - return dataSourceBundleCount; - } - - public OdeControlData setDataSourceBundleCount(Long dataSourceBundleCount) { - this.dataSourceBundleCount = dataSourceBundleCount; - return this; - } - - public Long getReceivedRecordCount() { - return receivedRecordCount; - } - - public OdeControlData setReceivedRecordCount(Long receivedRecordCount) { - this.receivedRecordCount = receivedRecordCount; - return this; - } - - public Long getSentRecordCount() { - return sentRecordCount; - } - - public OdeControlData setSentRecordCount(Long sentRecordCount) { - this.sentRecordCount = sentRecordCount; - return this; - } - - public Long getDepositCount() { - return depositCount; - } - - public void setDepositCount(Long depositCount) { - this.depositCount = depositCount; - } - - public StatusTag getTag() { - return tag; - } - - public void setTag(StatusTag tag) { - this.tag = tag; - } - - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((dataSourceBundleCount == null) ? 0 - : dataSourceBundleCount.hashCode()); - result = prime * result - + ((depositCount == null) ? 0 : depositCount.hashCode()); - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result + ((receivedRecordCount == null) ? 0 - : receivedRecordCount.hashCode()); - result = prime * result - + ((sentRecordCount == null) ? 0 : sentRecordCount.hashCode()); - result = prime * result + ((tag == null) ? 0 : tag.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeControlData other = (OdeControlData) obj; - if (dataSourceBundleCount == null) { - if (other.dataSourceBundleCount != null) - return false; - } else if (!dataSourceBundleCount.equals(other.dataSourceBundleCount)) - return false; - if (depositCount == null) { - if (other.depositCount != null) - return false; - } else if (!depositCount.equals(other.depositCount)) - return false; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - if (receivedRecordCount == null) { - if (other.receivedRecordCount != null) - return false; - } else if (!receivedRecordCount.equals(other.receivedRecordCount)) - return false; - if (sentRecordCount == null) { - if (other.sentRecordCount != null) - return false; - } else if (!sentRecordCount.equals(other.sentRecordCount)) - return false; - if (tag != other.tag) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.dds.DdsStatusMessage; + +public class OdeControlData extends OdeMessage { + + private static final long serialVersionUID = 1L; + + private Long dataSourceBundleCount; + private Long receivedRecordCount; + private Long sentRecordCount; + private Long depositCount; + private StatusTag tag; + private String message; + + public OdeControlData() { + super(); + } + + public OdeControlData(StatusTag tag) { + super(); + setTag(tag); + } + + public OdeControlData(DdsStatusMessage controlMessage) { + setTag(controlMessage.getTag()); + if (controlMessage.getTag() == StatusTag.STOP) + setDataSourceBundleCount(controlMessage.getRecordCount()); + else if (controlMessage.getTag() == StatusTag.DEPOSITED) + setDepositCount(controlMessage.getRecordCount()); + } + + public Long getDataSourceBundleCount() { + return dataSourceBundleCount; + } + + public OdeControlData setDataSourceBundleCount(Long dataSourceBundleCount) { + this.dataSourceBundleCount = dataSourceBundleCount; + return this; + } + + public Long getReceivedRecordCount() { + return receivedRecordCount; + } + + public OdeControlData setReceivedRecordCount(Long receivedRecordCount) { + this.receivedRecordCount = receivedRecordCount; + return this; + } + + public Long getSentRecordCount() { + return sentRecordCount; + } + + public OdeControlData setSentRecordCount(Long sentRecordCount) { + this.sentRecordCount = sentRecordCount; + return this; + } + + public Long getDepositCount() { + return depositCount; + } + + public void setDepositCount(Long depositCount) { + this.depositCount = depositCount; + } + + public StatusTag getTag() { + return tag; + } + + public void setTag(StatusTag tag) { + this.tag = tag; + } + + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((dataSourceBundleCount == null) ? 0 + : dataSourceBundleCount.hashCode()); + result = prime * result + + ((depositCount == null) ? 0 : depositCount.hashCode()); + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((receivedRecordCount == null) ? 0 + : receivedRecordCount.hashCode()); + result = prime * result + + ((sentRecordCount == null) ? 0 : sentRecordCount.hashCode()); + result = prime * result + ((tag == null) ? 0 : tag.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeControlData other = (OdeControlData) obj; + if (dataSourceBundleCount == null) { + if (other.dataSourceBundleCount != null) + return false; + } else if (!dataSourceBundleCount.equals(other.dataSourceBundleCount)) + return false; + if (depositCount == null) { + if (other.depositCount != null) + return false; + } else if (!depositCount.equals(other.depositCount)) + return false; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (receivedRecordCount == null) { + if (other.receivedRecordCount != null) + return false; + } else if (!receivedRecordCount.equals(other.receivedRecordCount)) + return false; + if (sentRecordCount == null) { + if (other.sentRecordCount != null) + return false; + } else if (!sentRecordCount.equals(other.sentRecordCount)) + return false; + if (tag != other.tag) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java index f9f235425..3f0732dec 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeData.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeData extends OdeObject implements OdeFilterable { - private static final long serialVersionUID = -7711340868799607662L; - - private OdeMsgMetadata metadata; - private OdeMsgPayload payload; - - public OdeData() { - super(); - } - - public OdeData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(); - this.metadata = metadata; - this.payload = payload; - this.metadata.setPayloadType(payload.getClass().getName()); - } - - public OdeMsgMetadata getMetadata() { - return metadata; - } - - public void setMetadata(OdeMsgMetadata metadata) { - this.metadata = metadata; - } - - public OdeMsgPayload getPayload() { - return payload; - } - - public void setPayload(OdeMsgPayload payload) { - this.payload = payload; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.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; - OdeData other = (OdeData) obj; - if (metadata == null) { - if (other.metadata != null) - return false; - } else if (!metadata.equals(other.metadata)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeData extends OdeObject implements OdeFilterable { + private static final long serialVersionUID = -7711340868799607662L; + + private OdeMsgMetadata metadata; + private OdeMsgPayload payload; + + public OdeData() { + super(); + } + + public OdeData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(); + this.metadata = metadata; + this.payload = payload; + this.metadata.setPayloadType(payload.getClass().getName()); + } + + public OdeMsgMetadata getMetadata() { + return metadata; + } + + public void setMetadata(OdeMsgMetadata metadata) { + this.metadata = metadata; + } + + public OdeMsgPayload getPayload() { + return payload; + } + + public void setPayload(OdeMsgPayload payload) { + this.payload = payload; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.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; + OdeData other = (OdeData) obj; + if (metadata == null) { + if (other.metadata != null) + return false; + } else if (!metadata.equals(other.metadata)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java index 9db394e38..bf4929ebd 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDataType.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.databind.JsonNode; - -import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; - -public enum OdeDataType { - Status("status", OdeStatus.class), - Control("control", OdeControlData.class), - Authorization("auth", OdeAuthorization.class), - BasicSafetyMessage("bsm", J2735Bsm.class), - TravelerInformationMessage("tim", OdeTravelerInputData.class), - AggregateData("agg", OdeAggregateData.class), - AsnBase64("asnbase64", String.class), - AsnHex("asnhex", String.class), - OtherData("other", OdeMsgPayload.class), - Unknown("unknown", OdeMsgPayload.class); - - private static List shortNames = shortNamesAsList(); - - private final String shortName; - - private final Class clazz; - - private OdeDataType(String shortName, Class clazz) { - this.shortName = shortName; - this.clazz = clazz; - } - - public String getShortName() { - return shortName; - } - - public Class getClazz() { - return clazz; - } - - public static OdeDataType getByShortName(String shortName) { - OdeDataType result = null; - - for (OdeDataType value : OdeDataType.values()) { - if (shortName.equals(value.getShortName())) { - result = value; - break; - } - } - return result; - } - - public static OdeDataType getByClazz(Class clazz) { - OdeDataType result = null; - - for (OdeDataType value : OdeDataType.values()) { - if (clazz == value.getClazz()) { - result = value; - break; - } - } - return result; - } - - public static OdeDataType getByClassName(String className) throws ClassNotFoundException { - return getByClazz(Class.forName(className)); - } - - public static String shortNames() { - return shortNamesAsList().toString(); - } - - public static List shortNamesAsList() { - if (shortNames == null) { - shortNames = new ArrayList(); - for (OdeDataType value : OdeDataType.values()) { - shortNames.add(value.getShortName()); - } - } - return shortNames; - } - - public static OdeDataType getFromJsonNode(JsonNode data, String name) throws IOException { - OdeDataType odeDataType = null; - if (data != null) { - JsonNode dataType = data.get(name); - if (dataType != null) { - odeDataType = OdeDataType.getByShortName(dataType.textValue()); - } - } - return odeDataType; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.databind.JsonNode; + +import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm; + +public enum OdeDataType { + Status("status", OdeStatus.class), + Control("control", OdeControlData.class), + Authorization("auth", OdeAuthorization.class), + BasicSafetyMessage("bsm", J2735Bsm.class), + TravelerInformationMessage("tim", OdeTravelerInputData.class), + AggregateData("agg", OdeAggregateData.class), + AsnBase64("asnbase64", String.class), + AsnHex("asnhex", String.class), + OtherData("other", OdeMsgPayload.class), + Unknown("unknown", OdeMsgPayload.class); + + private static List shortNames = shortNamesAsList(); + + private final String shortName; + + private final Class clazz; + + private OdeDataType(String shortName, Class clazz) { + this.shortName = shortName; + this.clazz = clazz; + } + + public String getShortName() { + return shortName; + } + + public Class getClazz() { + return clazz; + } + + public static OdeDataType getByShortName(String shortName) { + OdeDataType result = null; + + for (OdeDataType value : OdeDataType.values()) { + if (shortName.equals(value.getShortName())) { + result = value; + break; + } + } + return result; + } + + public static OdeDataType getByClazz(Class clazz) { + OdeDataType result = null; + + for (OdeDataType value : OdeDataType.values()) { + if (clazz == value.getClazz()) { + result = value; + break; + } + } + return result; + } + + public static OdeDataType getByClassName(String className) throws ClassNotFoundException { + return getByClazz(Class.forName(className)); + } + + public static String shortNames() { + return shortNamesAsList().toString(); + } + + public static List shortNamesAsList() { + if (shortNames == null) { + shortNames = new ArrayList(); + for (OdeDataType value : OdeDataType.values()) { + shortNames.add(value.getShortName()); + } + } + return shortNames; + } + + public static OdeDataType getFromJsonNode(JsonNode data, String name) throws IOException { + OdeDataType odeDataType = null; + if (data != null) { + JsonNode dataType = data.get(name); + if (dataType != null) { + odeDataType = OdeDataType.getByShortName(dataType.textValue()); + } + } + return odeDataType; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java index c3d3cca40..d25ac9daf 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDepRequest.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeDepRequest extends OdeRequest { - - private static final long serialVersionUID = -6766743372518752149L; - - private String encodeType; - private String data; - - - public String getEncodeType() { - return encodeType; - } - - public void setEncodeType(String encodeType) { - this.encodeType = encodeType; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result - + ((encodeType == null) ? 0 : encodeType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeDepRequest other = (OdeDepRequest) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (encodeType == null) { - if (other.encodeType != null) - return false; - } else if (!encodeType.equals(other.encodeType)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeDepRequest extends OdeRequest { + + private static final long serialVersionUID = -6766743372518752149L; + + private String encodeType; + private String data; + + + public String getEncodeType() { + return encodeType; + } + + public void setEncodeType(String encodeType) { + this.encodeType = encodeType; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + + ((encodeType == null) ? 0 : encodeType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeDepRequest other = (OdeDepRequest) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (encodeType == null) { + if (other.encodeType != null) + return false; + } else if (!encodeType.equals(other.encodeType)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java index ed2d58f15..0eec5e2f2 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertData.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -/** - * Created by anthonychen on 11/4/17. - */ -public class OdeDriverAlertData extends OdeData { - - private static final long serialVersionUID = 2057040404896561615L; - - public OdeDriverAlertData() { - super(); - } - - public OdeDriverAlertData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +/** + * Created by anthonychen on 11/4/17. + */ +public class OdeDriverAlertData extends OdeData { + + private static final long serialVersionUID = 2057040404896561615L; + + public OdeDriverAlertData() { + super(); + } + + public OdeDriverAlertData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java index fcb44bc91..a596c9b4d 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeDriverAlertPayload.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -/** - * Created by anthonychen on 11/4/17. - */ -public class OdeDriverAlertPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - private String alert; - - public OdeDriverAlertPayload(String alert) { - this.alert = alert; - } - - public String getAlert() { - return this.alert; - } - - public void setAlert(String alert) { - this.alert = alert; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +/** + * Created by anthonychen on 11/4/17. + */ +public class OdeDriverAlertPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + private String alert; + + public OdeDriverAlertPayload(String alert) { + this.alert = alert; + } + + public String getAlert() { + return this.alert; + } + + public void setAlert(String alert) { + this.alert = alert; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java index 9ac25b5d5..6e4387902 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeException.java @@ -1,67 +1,67 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import com.fasterxml.jackson.databind.node.ObjectNode; - -import us.dot.its.jpo.ode.util.JsonUtils; - -public class OdeException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -4133732677963262764L; - - OdeStatus.Code code; - - public OdeException() { - super(); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException(Throwable cause) { - super(cause); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (String message) { - super(message); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (String message, Throwable cause) { - super(message, cause); - this.code = OdeStatus.Code.FAILURE; - } - - public OdeException (OdeStatus.Code code, String message) { - super(message); - this.code = code; - } - - public OdeException (OdeStatus.Code code, String message, Throwable cause) { - super(message, cause); - this.code = code; - } - - public String toJson() { - ObjectNode jsonObject = JsonUtils.newObjectNode("code", code.name()); - JsonUtils.addNode(jsonObject, "message", getMessage()); - JsonUtils.addNode(jsonObject, "cause", getCause().toString()); - return jsonObject.toString(); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +import us.dot.its.jpo.ode.util.JsonUtils; + +public class OdeException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -4133732677963262764L; + + OdeStatus.Code code; + + public OdeException() { + super(); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException(Throwable cause) { + super(cause); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (String message) { + super(message); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (String message, Throwable cause) { + super(message, cause); + this.code = OdeStatus.Code.FAILURE; + } + + public OdeException (OdeStatus.Code code, String message) { + super(message); + this.code = code; + } + + public OdeException (OdeStatus.Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public String toJson() { + ObjectNode jsonObject = JsonUtils.newObjectNode("code", code.name()); + JsonUtils.addNode(jsonObject, "message", getMessage()); + JsonUtils.addNode(jsonObject, "cause", getCause().toString()); + return jsonObject.toString(); + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java index 39816fde9..fd2ebbb34 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeFilterable.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public interface OdeFilterable { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public interface OdeFilterable { + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java index 456524dbd..8fa6eb858 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeLogMsgMetadataLocation.java @@ -1,81 +1,81 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeLogMsgMetadataLocation extends OdeObject { - - private static final long serialVersionUID = 3174683494132372801L; - - String latitude; - String longitude; - String elevation; - String speed; - String heading; - - public OdeLogMsgMetadataLocation() { - super(); - } - - public OdeLogMsgMetadataLocation(String latitude, String longitude, String elevation, String speed, String heading) { - super(); - this.latitude = latitude; - this.longitude = longitude; - this.elevation = elevation; - this.speed = speed; - this.heading = heading; - } - - public String getLatitude() { - return latitude; - } - - public void setLatitude(String latitude) { - this.latitude = latitude; - } - - public String getLongitude() { - return longitude; - } - - public void setLongitude(String longitude) { - this.longitude = longitude; - } - - public String getElevation() { - return elevation; - } - - public void setElevation(String elevation) { - this.elevation = elevation; - } - - public String getSpeed() { - return speed; - } - - public void setSpeed(String speed) { - this.speed = speed; - } - - public String getHeading() { - return heading; - } - - public void setHeading(String heading) { - this.heading = heading; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeLogMsgMetadataLocation extends OdeObject { + + private static final long serialVersionUID = 3174683494132372801L; + + String latitude; + String longitude; + String elevation; + String speed; + String heading; + + public OdeLogMsgMetadataLocation() { + super(); + } + + public OdeLogMsgMetadataLocation(String latitude, String longitude, String elevation, String speed, String heading) { + super(); + this.latitude = latitude; + this.longitude = longitude; + this.elevation = elevation; + this.speed = speed; + this.heading = heading; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + public String getElevation() { + return elevation; + } + + public void setElevation(String elevation) { + this.elevation = elevation; + } + + public String getSpeed() { + return speed; + } + + public void setSpeed(String speed) { + this.speed = speed; + } + + public String getHeading() { + return heading; + } + + public void setHeading(String heading) { + this.heading = heading; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java index 4391924fa..777de37e1 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMessage.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeMessage extends OdeObject { - - private static final long serialVersionUID = 6381260328835278701L; - - private Integer schemaVersion; - - public OdeMessage() { - super(); - this.schemaVersion = 3; - } - - public Integer getSchemaVersion() { - return schemaVersion; - } - - public void setSchemaVersion(Integer schemaVersion) { - this.schemaVersion = schemaVersion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((schemaVersion == null) ? 0 : schemaVersion.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; - OdeMessage other = (OdeMessage) obj; - if (schemaVersion == null) { - if (other.schemaVersion != null) - return false; - } else if (!schemaVersion.equals(other.schemaVersion)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeMessage extends OdeObject { + + private static final long serialVersionUID = 6381260328835278701L; + + private Integer schemaVersion; + + public OdeMessage() { + super(); + this.schemaVersion = 3; + } + + public Integer getSchemaVersion() { + return schemaVersion; + } + + public void setSchemaVersion(Integer schemaVersion) { + this.schemaVersion = schemaVersion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((schemaVersion == null) ? 0 : schemaVersion.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; + OdeMessage other = (OdeMessage) obj; + if (schemaVersion == null) { + if (other.schemaVersion != null) + return false; + } else if (!schemaVersion.equals(other.schemaVersion)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java index 41e91ca5e..3605f4959 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgMetadata.java @@ -1,181 +1,181 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.util.DateTimeUtils; - -public class OdeMsgMetadata extends OdeObject { - - public enum GeneratedBy { - TMC, OBU, RSU, TMC_VIA_SAT, TMC_VIA_SNMP, UNKNOWN - } - - private static final long serialVersionUID = 3979762143291085955L; - - private static int staticSchemaVersion; - - private String payloadType; - private SerialId serialId; - private String odeReceivedAt; - private int schemaVersion; - private String recordGeneratedAt; - private GeneratedBy recordGeneratedBy; - private boolean sanitized = false; - - public OdeMsgMetadata() { - this(OdeMsgPayload.class.getName(), new SerialId(), DateTimeUtils.now()); - } - - public OdeMsgMetadata(OdeMsgPayload payload) { - this(payload, new SerialId(), DateTimeUtils.now()); - } - - private OdeMsgMetadata(OdeMsgPayload payload, SerialId serialId, String receivedAt) { - this(payload.getClass().getName(), serialId, receivedAt); - } - - public OdeMsgMetadata(String payloadType, SerialId serialId, String receivedAt) { - super(); - this.schemaVersion = staticSchemaVersion; - this.payloadType = payloadType; - this.serialId = serialId; - this.odeReceivedAt = receivedAt; - } - - public String getPayloadType() { - return payloadType; - } - - public OdeMsgMetadata setPayloadType(OdeDataType payloadType) { - this.payloadType = payloadType.getShortName(); - return this; - } - - public OdeMsgMetadata setPayloadType(String payloadType) { - this.payloadType = payloadType; - return this; - } - - public SerialId getSerialId() { - return serialId; - } - - public void setSerialId(SerialId serialId) { - this.serialId = serialId; - } - - public String getOdeReceivedAt() { - return odeReceivedAt; - } - - public void setOdeReceivedAt(String receivedAt) { - this.odeReceivedAt = receivedAt; - } - - public int getSchemaVersion() { - return schemaVersion; - } - - public void setSchemaVersion(int aSchemaVersion) { - schemaVersion = aSchemaVersion; - } - - public String getRecordGeneratedAt() { - return recordGeneratedAt; - } - - public void setRecordGeneratedAt(String recordGeneratedAt) { - this.recordGeneratedAt = recordGeneratedAt; - } - - public GeneratedBy getRecordGeneratedBy() { - return recordGeneratedBy; - } - - public void setRecordGeneratedBy(GeneratedBy recordGeneratedBy) { - this.recordGeneratedBy = recordGeneratedBy; - } - - public boolean isSanitized() { - return sanitized; - } - - public void setSanitized(boolean sanitized) { - this.sanitized = sanitized; - } - - - public static int getStaticSchemaVersion() { - return staticSchemaVersion; - } - - public static void setStaticSchemaVersion(int aSchemaVersion) { - staticSchemaVersion = aSchemaVersion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((odeReceivedAt == null) ? 0 : odeReceivedAt.hashCode()); - result = prime * result + ((payloadType == null) ? 0 : payloadType.hashCode()); - result = prime * result + ((recordGeneratedAt == null) ? 0 : recordGeneratedAt.hashCode()); - result = prime * result + ((recordGeneratedBy == null) ? 0 : recordGeneratedBy.hashCode()); - result = prime * result + (sanitized ? 1231 : 1237); - result = prime * result + schemaVersion; - result = prime * result + ((serialId == null) ? 0 : serialId.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; - OdeMsgMetadata other = (OdeMsgMetadata) obj; - if (odeReceivedAt == null) { - if (other.odeReceivedAt != null) - return false; - } else if (!odeReceivedAt.equals(other.odeReceivedAt)) - return false; - if (payloadType == null) { - if (other.payloadType != null) - return false; - } else if (!payloadType.equals(other.payloadType)) - return false; - if (recordGeneratedAt == null) { - if (other.recordGeneratedAt != null) - return false; - } else if (!recordGeneratedAt.equals(other.recordGeneratedAt)) - return false; - if (recordGeneratedBy != other.recordGeneratedBy) - return false; - if (sanitized != other.sanitized) - return false; - if (schemaVersion != other.schemaVersion) - return false; - if (serialId == null) { - if (other.serialId != null) - return false; - } else if (!serialId.equals(other.serialId)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.util.DateTimeUtils; + +public class OdeMsgMetadata extends OdeObject { + + public enum GeneratedBy { + TMC, OBU, RSU, TMC_VIA_SAT, TMC_VIA_SNMP, UNKNOWN + } + + private static final long serialVersionUID = 3979762143291085955L; + + private static int staticSchemaVersion; + + private String payloadType; + private SerialId serialId; + private String odeReceivedAt; + private int schemaVersion; + private String recordGeneratedAt; + private GeneratedBy recordGeneratedBy; + private boolean sanitized = false; + + public OdeMsgMetadata() { + this(OdeMsgPayload.class.getName(), new SerialId(), DateTimeUtils.now()); + } + + public OdeMsgMetadata(OdeMsgPayload payload) { + this(payload, new SerialId(), DateTimeUtils.now()); + } + + private OdeMsgMetadata(OdeMsgPayload payload, SerialId serialId, String receivedAt) { + this(payload.getClass().getName(), serialId, receivedAt); + } + + public OdeMsgMetadata(String payloadType, SerialId serialId, String receivedAt) { + super(); + this.schemaVersion = staticSchemaVersion; + this.payloadType = payloadType; + this.serialId = serialId; + this.odeReceivedAt = receivedAt; + } + + public String getPayloadType() { + return payloadType; + } + + public OdeMsgMetadata setPayloadType(OdeDataType payloadType) { + this.payloadType = payloadType.getShortName(); + return this; + } + + public OdeMsgMetadata setPayloadType(String payloadType) { + this.payloadType = payloadType; + return this; + } + + public SerialId getSerialId() { + return serialId; + } + + public void setSerialId(SerialId serialId) { + this.serialId = serialId; + } + + public String getOdeReceivedAt() { + return odeReceivedAt; + } + + public void setOdeReceivedAt(String receivedAt) { + this.odeReceivedAt = receivedAt; + } + + public int getSchemaVersion() { + return schemaVersion; + } + + public void setSchemaVersion(int aSchemaVersion) { + schemaVersion = aSchemaVersion; + } + + public String getRecordGeneratedAt() { + return recordGeneratedAt; + } + + public void setRecordGeneratedAt(String recordGeneratedAt) { + this.recordGeneratedAt = recordGeneratedAt; + } + + public GeneratedBy getRecordGeneratedBy() { + return recordGeneratedBy; + } + + public void setRecordGeneratedBy(GeneratedBy recordGeneratedBy) { + this.recordGeneratedBy = recordGeneratedBy; + } + + public boolean isSanitized() { + return sanitized; + } + + public void setSanitized(boolean sanitized) { + this.sanitized = sanitized; + } + + + public static int getStaticSchemaVersion() { + return staticSchemaVersion; + } + + public static void setStaticSchemaVersion(int aSchemaVersion) { + staticSchemaVersion = aSchemaVersion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((odeReceivedAt == null) ? 0 : odeReceivedAt.hashCode()); + result = prime * result + ((payloadType == null) ? 0 : payloadType.hashCode()); + result = prime * result + ((recordGeneratedAt == null) ? 0 : recordGeneratedAt.hashCode()); + result = prime * result + ((recordGeneratedBy == null) ? 0 : recordGeneratedBy.hashCode()); + result = prime * result + (sanitized ? 1231 : 1237); + result = prime * result + schemaVersion; + result = prime * result + ((serialId == null) ? 0 : serialId.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; + OdeMsgMetadata other = (OdeMsgMetadata) obj; + if (odeReceivedAt == null) { + if (other.odeReceivedAt != null) + return false; + } else if (!odeReceivedAt.equals(other.odeReceivedAt)) + return false; + if (payloadType == null) { + if (other.payloadType != null) + return false; + } else if (!payloadType.equals(other.payloadType)) + return false; + if (recordGeneratedAt == null) { + if (other.recordGeneratedAt != null) + return false; + } else if (!recordGeneratedAt.equals(other.recordGeneratedAt)) + return false; + if (recordGeneratedBy != other.recordGeneratedBy) + return false; + if (sanitized != other.sanitized) + return false; + if (schemaVersion != other.schemaVersion) + return false; + if (serialId == null) { + if (other.serialId != null) + return false; + } else if (!serialId.equals(other.serialId)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java index 863eabd13..3bd5c32e4 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeMsgPayload.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeMsgPayload extends OdeObject { - private static final long serialVersionUID = -7711340868799607662L; - - private String dataType; - private OdeObject data; - - public OdeMsgPayload() { - super(); - } - - public OdeMsgPayload(OdeObject data) { - super(); - this.dataType = data.getClass().getName(); - this.data = data; - } - - public OdeMsgPayload(String dataType, OdeObject data) { - super(); - this.dataType = dataType; - this.data = data; - } - - public String getDataType() { - return dataType; - } - - public void setDataType(String dataType) { - this.dataType = dataType; - } - - public OdeObject getData() { - return data; - } - - public void setData(OdeObject data) { - this.data = data; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeMsgPayload other = (OdeMsgPayload) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (dataType == null) { - if (other.dataType != null) - return false; - } else if (!dataType.equals(other.dataType)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeMsgPayload extends OdeObject { + private static final long serialVersionUID = -7711340868799607662L; + + private String dataType; + private OdeObject data; + + public OdeMsgPayload() { + super(); + } + + public OdeMsgPayload(OdeObject data) { + super(); + this.dataType = data.getClass().getName(); + this.data = data; + } + + public OdeMsgPayload(String dataType, OdeObject data) { + super(); + this.dataType = dataType; + this.data = data; + } + + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + public OdeObject getData() { + return data; + } + + public void setData(OdeObject data) { + this.data = data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeMsgPayload other = (OdeMsgPayload) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (dataType == null) { + if (other.dataType != null) + return false; + } else if (!dataType.equals(other.dataType)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java index 8edf7b0c9..671f7b6d4 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePayloadViolation.java @@ -1,113 +1,113 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdePayloadViolation { - - private String fieldName; - private double fieldValue; - private double validMin; - private double validMax; - - public OdePayloadViolation() { - super(); - fieldName = null; - fieldValue = Double.NaN; - validMin = Double.NaN; - validMax = Double.NaN; - } - - public OdePayloadViolation(String fieldName, double value, double validMin, double validMax) { - super(); - this.fieldName = fieldName; - this.fieldValue = value; - this.validMin = validMin; - this.validMax = validMax; - } - - public String getFieldName() { - return fieldName; - } - - public OdePayloadViolation setFieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - public double getFieldValue() { - return fieldValue; - } - - public void setFieldValue(double fieldValue) { - this.fieldValue = fieldValue; - } - - public double getValidMin() { - return validMin; - } - - public OdePayloadViolation setValidMin(double validMin) { - this.validMin = validMin; - return this; - } - - public double getValidMax() { - return validMax; - } - - public OdePayloadViolation setValidMax(double validMax) { - this.validMax = validMax; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode()); - long temp; - temp = Double.doubleToLongBits(validMax); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(validMin); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(fieldValue); - result = prime * result + (int) (temp ^ (temp >>> 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; - OdePayloadViolation other = (OdePayloadViolation) obj; - if (fieldName == null) { - if (other.fieldName != null) - return false; - } else if (!fieldName.equals(other.fieldName)) - return false; - if (Double.doubleToLongBits(validMax) != Double.doubleToLongBits(other.validMax)) - return false; - if (Double.doubleToLongBits(validMin) != Double.doubleToLongBits(other.validMin)) - return false; - if (Double.doubleToLongBits(fieldValue) != Double.doubleToLongBits(other.fieldValue)) - return false; - return true; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdePayloadViolation { + + private String fieldName; + private double fieldValue; + private double validMin; + private double validMax; + + public OdePayloadViolation() { + super(); + fieldName = null; + fieldValue = Double.NaN; + validMin = Double.NaN; + validMax = Double.NaN; + } + + public OdePayloadViolation(String fieldName, double value, double validMin, double validMax) { + super(); + this.fieldName = fieldName; + this.fieldValue = value; + this.validMin = validMin; + this.validMax = validMax; + } + + public String getFieldName() { + return fieldName; + } + + public OdePayloadViolation setFieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + public double getFieldValue() { + return fieldValue; + } + + public void setFieldValue(double fieldValue) { + this.fieldValue = fieldValue; + } + + public double getValidMin() { + return validMin; + } + + public OdePayloadViolation setValidMin(double validMin) { + this.validMin = validMin; + return this; + } + + public double getValidMax() { + return validMax; + } + + public OdePayloadViolation setValidMax(double validMax) { + this.validMax = validMax; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode()); + long temp; + temp = Double.doubleToLongBits(validMax); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(validMin); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(fieldValue); + result = prime * result + (int) (temp ^ (temp >>> 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; + OdePayloadViolation other = (OdePayloadViolation) obj; + if (fieldName == null) { + if (other.fieldName != null) + return false; + } else if (!fieldName.equals(other.fieldName)) + return false; + if (Double.doubleToLongBits(validMax) != Double.doubleToLongBits(other.validMax)) + return false; + if (Double.doubleToLongBits(validMin) != Double.doubleToLongBits(other.validMin)) + return false; + if (Double.doubleToLongBits(fieldValue) != Double.doubleToLongBits(other.fieldValue)) + return false; + return true; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java index 91ca47302..630d83f77 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdePoint.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.math.BigDecimal; - -public class OdePoint extends OdeObject { - - private static final long serialVersionUID = 6030294798158488311L; - - private BigDecimal latitude; - private BigDecimal longitude; - public OdePoint() { - super(); - } - public OdePoint(BigDecimal latitude, BigDecimal longitude) { - super(); - this.latitude = latitude; - this.longitude = longitude; - } - public BigDecimal getLatitude() { - return latitude; - } - public OdePoint setLatitude(BigDecimal latitude) { - this.latitude = latitude; - return this; - } - public BigDecimal getLongitude() { - return longitude; - } - public OdePoint setLongitude(BigDecimal longitude) { - this.longitude = longitude; - return this; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((latitude == null) ? 0 : latitude.hashCode()); - result = prime * result - + ((longitude == null) ? 0 : longitude.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; - OdePoint other = (OdePoint) obj; - if (latitude == null) { - if (other.latitude != null) - return false; - } else if (!latitude.equals(other.latitude)) - return false; - if (longitude == null) { - if (other.longitude != null) - return false; - } else if (!longitude.equals(other.longitude)) - return false; - return true; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.math.BigDecimal; + +public class OdePoint extends OdeObject { + + private static final long serialVersionUID = 6030294798158488311L; + + private BigDecimal latitude; + private BigDecimal longitude; + public OdePoint() { + super(); + } + public OdePoint(BigDecimal latitude, BigDecimal longitude) { + super(); + this.latitude = latitude; + this.longitude = longitude; + } + public BigDecimal getLatitude() { + return latitude; + } + public OdePoint setLatitude(BigDecimal latitude) { + this.latitude = latitude; + return this; + } + public BigDecimal getLongitude() { + return longitude; + } + public OdePoint setLongitude(BigDecimal longitude) { + this.longitude = longitude; + return this; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((latitude == null) ? 0 : latitude.hashCode()); + result = prime * result + + ((longitude == null) ? 0 : longitude.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; + OdePoint other = (OdePoint) obj; + if (latitude == null) { + if (other.latitude != null) + return false; + } else if (!latitude.equals(other.latitude)) + return false; + if (longitude == null) { + if (other.longitude != null) + return false; + } else if (!longitude.equals(other.longitude)) + return false; + return true; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java index 98893a0ce..e83e3cbe3 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequest.java @@ -1,157 +1,157 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.context.AppContext; -import us.dot.its.jpo.ode.util.JsonUtils; - -@SuppressWarnings("serial") -public class OdeRequest extends BaseRequest { - public static class OdeRequestException extends OdeException { - - public OdeRequestException(String message) { - super(message); - } - - } - - public enum DataSource { - SDC, SDW, SDPC, TEST_UPLOAD, DEPOSIT_SDC, DEPOSIT_SDW - } - - private String id; - private DataSource dataSource; - private OdeRequestType requestType; - private OdeDataType dataType; - - public OdeRequest() { - super(); - } - - public OdeRequest(OdeRequest other) { - super(); - this.setDataSource(other.getDataSource()); - this.setDataType(other.getDataType()); - this.setId(other.getId()); - this.setRequestType(other.getRequestType()); - } - - public static OdeRequest create(String rtype, String dtype, String message) throws OdeRequestException { - OdeRequest odeRequest = null; - OdeRequestType requestType = OdeRequestType.getByShortName(rtype); - if (requestType == OdeRequestType.Deposit) { - odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeDepRequest.class); -// } else if (requestType == OdeRequestType.Subscription) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeSubRequest.class); -// } else if (requestType == OdeRequestType.Query) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeQryRequest.class); -// } else if (requestType == OdeRequestType.Test) { -// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeTstRequest.class); - } else { - OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_REQUEST_TYPE_ERROR).setMessage(String - .format("Invalid request type %s. Valid request types are %s.", rtype, OdeRequestType.shortNames())); - throw new OdeRequestException(status.toString()); - } - odeRequest.setRequestType(requestType); - - OdeDataType dataType = OdeDataType.getByShortName(dtype); - if (dataType == null) { - OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_DATA_TYPE_ERROR).setMessage( - String.format("Invalid data type %s. Valid data types are %s.", dtype, OdeDataType.shortNames())); - throw new OdeRequestException(status.toString()); - } - odeRequest.setDataType(dataType); - - odeRequest.setId(buildRequestId(odeRequest)); - return odeRequest; - } - - public static String buildRequestId(OdeRequest odeRequest) { - return AppContext.getInstance().getParam(AppContext.ODE_HOSTNAME) + odeRequest.getClass().getSimpleName() - + String.valueOf(odeRequest.hashCode()); - } - - public String getId() { - return id; - } - - public OdeRequest setId(String id) { - this.id = id; - return this; - } - - public OdeRequestType getRequestType() { - return requestType; - } - - public DataSource getDataSource() { - return dataSource; - } - - public OdeRequest setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - return this; - } - - public OdeRequest setRequestType(OdeRequestType requestType) { - this.requestType = requestType; - return this; - } - - public OdeDataType getDataType() { - return dataType; - } - - public OdeRequest setDataType(OdeDataType dataType) { - this.dataType = dataType; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((dataSource == null) ? 0 : dataSource.hashCode()); - result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((requestType == null) ? 0 : requestType.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; - OdeRequest other = (OdeRequest) obj; - if (dataSource != other.dataSource) - return false; - if (dataType != other.dataType) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (requestType != other.requestType) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.context.AppContext; +import us.dot.its.jpo.ode.util.JsonUtils; + +@SuppressWarnings("serial") +public class OdeRequest extends BaseRequest { + public static class OdeRequestException extends OdeException { + + public OdeRequestException(String message) { + super(message); + } + + } + + public enum DataSource { + SDC, SDW, SDPC, TEST_UPLOAD, DEPOSIT_SDC, DEPOSIT_SDW + } + + private String id; + private DataSource dataSource; + private OdeRequestType requestType; + private OdeDataType dataType; + + public OdeRequest() { + super(); + } + + public OdeRequest(OdeRequest other) { + super(); + this.setDataSource(other.getDataSource()); + this.setDataType(other.getDataType()); + this.setId(other.getId()); + this.setRequestType(other.getRequestType()); + } + + public static OdeRequest create(String rtype, String dtype, String message) throws OdeRequestException { + OdeRequest odeRequest = null; + OdeRequestType requestType = OdeRequestType.getByShortName(rtype); + if (requestType == OdeRequestType.Deposit) { + odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeDepRequest.class); +// } else if (requestType == OdeRequestType.Subscription) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeSubRequest.class); +// } else if (requestType == OdeRequestType.Query) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeQryRequest.class); +// } else if (requestType == OdeRequestType.Test) { +// odeRequest = (OdeRequest) JsonUtils.fromJson(message, OdeTstRequest.class); + } else { + OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_REQUEST_TYPE_ERROR).setMessage(String + .format("Invalid request type %s. Valid request types are %s.", rtype, OdeRequestType.shortNames())); + throw new OdeRequestException(status.toString()); + } + odeRequest.setRequestType(requestType); + + OdeDataType dataType = OdeDataType.getByShortName(dtype); + if (dataType == null) { + OdeStatus status = new OdeStatus().setCode(OdeStatus.Code.INVALID_DATA_TYPE_ERROR).setMessage( + String.format("Invalid data type %s. Valid data types are %s.", dtype, OdeDataType.shortNames())); + throw new OdeRequestException(status.toString()); + } + odeRequest.setDataType(dataType); + + odeRequest.setId(buildRequestId(odeRequest)); + return odeRequest; + } + + public static String buildRequestId(OdeRequest odeRequest) { + return AppContext.getInstance().getParam(AppContext.ODE_HOSTNAME) + odeRequest.getClass().getSimpleName() + + String.valueOf(odeRequest.hashCode()); + } + + public String getId() { + return id; + } + + public OdeRequest setId(String id) { + this.id = id; + return this; + } + + public OdeRequestType getRequestType() { + return requestType; + } + + public DataSource getDataSource() { + return dataSource; + } + + public OdeRequest setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + return this; + } + + public OdeRequest setRequestType(OdeRequestType requestType) { + this.requestType = requestType; + return this; + } + + public OdeDataType getDataType() { + return dataType; + } + + public OdeRequest setDataType(OdeDataType dataType) { + this.dataType = dataType; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((dataSource == null) ? 0 : dataSource.hashCode()); + result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((requestType == null) ? 0 : requestType.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; + OdeRequest other = (OdeRequest) obj; + if (dataSource != other.dataSource) + return false; + if (dataType != other.dataType) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (requestType != other.requestType) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java index 194405a4a..b57b1289d 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeRequestType.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import java.util.ArrayList; -import java.util.List; - -public enum OdeRequestType { - Subscription("sub"), Query("qry"), Test("tst"), Deposit("dep"); - - private static List shortNames = shortNamesAsList(); - private final String shortName; - - private OdeRequestType(String shortName) { - this.shortName = shortName; - } - - public String getShortName() { - return shortName; - } - - public static OdeRequestType getByShortName(String shortName) { - OdeRequestType result = null; - - for (OdeRequestType value : OdeRequestType.values()) { - if (shortName.equals(value.getShortName())) { - result = value; - break; - } - } - return result; - } - - public static String shortNames() { - return shortNamesAsList().toString(); - } - - public static List shortNamesAsList() { - if (shortNames == null) { - shortNames = new ArrayList(); - - for (OdeRequestType value : OdeRequestType.values()) { - shortNames.add(value.getShortName()); - } - } - return shortNames; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import java.util.ArrayList; +import java.util.List; + +public enum OdeRequestType { + Subscription("sub"), Query("qry"), Test("tst"), Deposit("dep"); + + private static List shortNames = shortNamesAsList(); + private final String shortName; + + private OdeRequestType(String shortName) { + this.shortName = shortName; + } + + public String getShortName() { + return shortName; + } + + public static OdeRequestType getByShortName(String shortName) { + OdeRequestType result = null; + + for (OdeRequestType value : OdeRequestType.values()) { + if (shortName.equals(value.getShortName())) { + result = value; + break; + } + } + return result; + } + + public static String shortNames() { + return shortNamesAsList().toString(); + } + + public static List shortNamesAsList() { + if (shortNames == null) { + shortNames = new ArrayList(); + + for (OdeRequestType value : OdeRequestType.values()) { + shortNames.add(value.getShortName()); + } + } + return shortNames; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java index 2a05312cd..96cabd54e 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeStatus.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - - -public class OdeStatus extends OdeMessage { - private static final long serialVersionUID = -8787345244306039604L; - - public static enum Code { - SUCCESS, FAILURE, - SOURCE_CONNECTION_ERROR, INVALID_REQUEST_TYPE_ERROR, - INVALID_DATA_TYPE_ERROR, COMMENT, DATA_TYPE_NOT_SUPPORTED - } - - Code code; - String message; - String requestId; - - public OdeStatus() { - super(); - } - - public OdeStatus(Code code, String message) { - super(); - this.code = code; - this.message = message; - } - - public Code getCode() { - return code; - } - - public OdeStatus setCode(Code code) { - this.code = code; - return this; - } - - public String getMessage() { - return message; - } - - public OdeStatus setMessage(String message) { - this.message = message; - return this; - } - - public String getRequestId() { - return requestId; - } - - public OdeStatus setRequestId(String requestId) { - this.requestId = requestId; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((code == null) ? 0 : code.hashCode()); - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result - + ((requestId == null) ? 0 : requestId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OdeStatus other = (OdeStatus) obj; - if (code != other.code) - return false; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - if (requestId == null) { - if (other.requestId != null) - return false; - } else if (!requestId.equals(other.requestId)) - return false; - return true; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + + +public class OdeStatus extends OdeMessage { + private static final long serialVersionUID = -8787345244306039604L; + + public static enum Code { + SUCCESS, FAILURE, + SOURCE_CONNECTION_ERROR, INVALID_REQUEST_TYPE_ERROR, + INVALID_DATA_TYPE_ERROR, COMMENT, DATA_TYPE_NOT_SUPPORTED + } + + Code code; + String message; + String requestId; + + public OdeStatus() { + super(); + } + + public OdeStatus(Code code, String message) { + super(); + this.code = code; + this.message = message; + } + + public Code getCode() { + return code; + } + + public OdeStatus setCode(Code code) { + this.code = code; + return this; + } + + public String getMessage() { + return message; + } + + public OdeStatus setMessage(String message) { + this.message = message; + return this; + } + + public String getRequestId() { + return requestId; + } + + public OdeStatus setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((code == null) ? 0 : code.hashCode()); + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + + ((requestId == null) ? 0 : requestId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OdeStatus other = (OdeStatus) obj; + if (code != other.code) + return false; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (requestId == null) { + if (other.requestId != null) + return false; + } else if (!requestId.equals(other.requestId)) + return false; + return true; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java index 10b38108e..1f1fac5f4 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimData.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class OdeTimData extends OdeData { - - private static final long serialVersionUID = 2057040404896561615L; - - - public OdeTimData() { - super(); - } - - - public OdeTimData(OdeMsgMetadata metadata, OdeMsgPayload payload) { - super(metadata, payload); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class OdeTimData extends OdeData { + + private static final long serialVersionUID = 2057040404896561615L; + + + public OdeTimData() { + super(); + } + + + public OdeTimData(OdeMsgMetadata metadata, OdeMsgPayload payload) { + super(metadata, payload); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java index a4adeffb9..b3ecd5565 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/OdeTimPayload.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import us.dot.its.jpo.ode.plugin.j2735.OdeTravelerInformationMessage; - -public class OdeTimPayload extends OdeMsgPayload { - - private static final long serialVersionUID = 7061315628111448390L; - - public OdeTimPayload() { - this(new OdeTravelerInformationMessage()); - } - - public OdeTimPayload(OdeTravelerInformationMessage tim) { - super(tim); - this.setData(tim); - } - - public OdeTravelerInformationMessage getTim() { - return (OdeTravelerInformationMessage) getData(); - } - - public void setTim(OdeTravelerInformationMessage tim) { - setData(tim); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import us.dot.its.jpo.ode.plugin.j2735.OdeTravelerInformationMessage; + +public class OdeTimPayload extends OdeMsgPayload { + + private static final long serialVersionUID = 7061315628111448390L; + + public OdeTimPayload() { + this(new OdeTravelerInformationMessage()); + } + + public OdeTimPayload(OdeTravelerInformationMessage tim) { + super(tim); + this.setData(tim); + } + + public OdeTravelerInformationMessage getTim() { + return (OdeTravelerInformationMessage) getData(); + } + + public void setTim(OdeTravelerInformationMessage tim) { + setData(tim); + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java index 491393108..a2ccd752b 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ReceivedMessageDetails.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public class ReceivedMessageDetails extends OdeObject { - - private static final long serialVersionUID = -122988228561853841L; - - private OdeLogMsgMetadataLocation locationData; - private RxSource rxSource; - - public ReceivedMessageDetails() { - super(); - } - - public ReceivedMessageDetails(OdeLogMsgMetadataLocation locationData, RxSource rxSource) { - super(); - this.setLocationData(locationData); - this.setRxSource(rxSource); - } - - public OdeLogMsgMetadataLocation getLocationData() { - return locationData; - } - - public void setLocationData(OdeLogMsgMetadataLocation locationData) { - this.locationData = locationData; - } - - public RxSource getRxSource() { - return rxSource; - } - - public void setRxSource(RxSource rxSource) { - this.rxSource = rxSource; - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public class ReceivedMessageDetails extends OdeObject { + + private static final long serialVersionUID = -122988228561853841L; + + private OdeLogMsgMetadataLocation locationData; + private RxSource rxSource; + + public ReceivedMessageDetails() { + super(); + } + + public ReceivedMessageDetails(OdeLogMsgMetadataLocation locationData, RxSource rxSource) { + super(); + this.setLocationData(locationData); + this.setRxSource(rxSource); + } + + public OdeLogMsgMetadataLocation getLocationData() { + return locationData; + } + + public void setLocationData(OdeLogMsgMetadataLocation locationData) { + this.locationData = locationData; + } + + public RxSource getRxSource() { + return rxSource; + } + + public void setRxSource(RxSource rxSource) { + this.rxSource = rxSource; + } +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java index fca8fa2fe..3491055bb 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/RxSource.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public enum RxSource { - RSU, - SAT, // XM satellite - RV, // for BSM rx - SNMP,// for SRM payload from back-end/ODE - NA, // Not applicable (for example, Distress Notification or Driver Alert - UNKNOWN -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public enum RxSource { + RSU, + SAT, // XM satellite + RV, // for BSM rx + SNMP,// for SRM payload from back-end/ODE + NA, // Not applicable (for example, Distress Notification or Driver Alert + UNKNOWN +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java index 1c4ef7416..7f7af7e07 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/StatusTag.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -public enum StatusTag { - CONNECTED, START, STOP, ERROR, DEPOSITED, CLOSED, OPENED -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +public enum StatusTag { + CONNECTED, START, STOP, ERROR, DEPOSITED, CLOSED, OPENED +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java index 051bf43e0..36050ccb4 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubPubTransformer.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -/** - * @author 572682 - * - * This abstract class provides a basic pipeline functionality through the messaging - * framework. The objects of this class subscribe to a topic, process received messages - * and publish the results to another topic. - * - * @param Message Key type - * @param Received Message Value Type - * @param

    Published Message Value Type - */ -public abstract class AbstractSubPubTransformer extends AbstractSubscriberProcessor { - - protected int messagesPublished = 0; - protected MessageProducer producer; - protected String outputTopic; - - public AbstractSubPubTransformer(MessageProducer producer, String outputTopic) { - super(); - this.producer = producer; - this.outputTopic = outputTopic; - } - - @Override - public Object call() { - @SuppressWarnings("unchecked") - P toBePublished = (P) super.call(); - - if (null != toBePublished) { - producer.send(outputTopic, getRecord().key(), toBePublished); - } - - return toBePublished; - } - - public MessageProducer getProducer() { - return producer; - } - - public void setProducer(MessageProducer producer) { - this.producer = producer; - } - - public String getOutputTopic() { - return outputTopic; - } - - public void setOutputTopic(String outputTopic) { - this.outputTopic = outputTopic; - } - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +/** + * @author 572682 + * + * This abstract class provides a basic pipeline functionality through the messaging + * framework. The objects of this class subscribe to a topic, process received messages + * and publish the results to another topic. + * + * @param Message Key type + * @param Received Message Value Type + * @param

    Published Message Value Type + */ +public abstract class AbstractSubPubTransformer extends AbstractSubscriberProcessor { + + protected int messagesPublished = 0; + protected MessageProducer producer; + protected String outputTopic; + + public AbstractSubPubTransformer(MessageProducer producer, String outputTopic) { + super(); + this.producer = producer; + this.outputTopic = outputTopic; + } + + @Override + public Object call() { + @SuppressWarnings("unchecked") + P toBePublished = (P) super.call(); + + if (null != toBePublished) { + producer.send(outputTopic, getRecord().key(), toBePublished); + } + + return toBePublished; + } + + public MessageProducer getProducer() { + return producer; + } + + public void setProducer(MessageProducer producer) { + this.producer = producer; + } + + public String getOutputTopic() { + return outputTopic; + } + + public void setOutputTopic(String outputTopic) { + this.outputTopic = outputTopic; + } + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java index 1249c47d2..0fda858a1 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/AbstractSubscriberProcessor.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import java.util.Arrays; -import java.util.concurrent.Executors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author 572682 - * - * This abstract class provides a basic service that subscribes to one - * or more topics and process the received messages in the derived - * classes. - * - * @param - * Message Key type - * @param - * Received Message Value Type - */ -public abstract class AbstractSubscriberProcessor extends MessageProcessor { - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - protected int messagesConsumed = 0; - - /** - * Starts a Kafka listener that runs call() every time a new msg arrives - * - * @param consumer - * @param inputTopics - */ - public void start(MessageConsumer consumer, String... inputTopics) { - logger.info("Subscribing to {}", Arrays.asList(inputTopics).toString()); - - Executors.newSingleThreadExecutor().submit(new Runnable() { - @Override - public void run() { - consumer.subscribe(inputTopics); - } - }); - } - - @Override - public Object call() { - messagesConsumed++; - - S consumedData = getRecord().value(); - - return process(consumedData); - } - - protected abstract Object process(S consumedData); - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import java.util.Arrays; +import java.util.concurrent.Executors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 572682 + * + * This abstract class provides a basic service that subscribes to one + * or more topics and process the received messages in the derived + * classes. + * + * @param + * Message Key type + * @param + * Received Message Value Type + */ +public abstract class AbstractSubscriberProcessor extends MessageProcessor { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + protected int messagesConsumed = 0; + + /** + * Starts a Kafka listener that runs call() every time a new msg arrives + * + * @param consumer + * @param inputTopics + */ + public void start(MessageConsumer consumer, String... inputTopics) { + logger.info("Subscribing to {}", Arrays.asList(inputTopics).toString()); + + Executors.newSingleThreadExecutor().submit(new Runnable() { + @Override + public void run() { + consumer.subscribe(inputTopics); + } + }); + } + + @Override + public Object call() { + messagesConsumed++; + + S consumedData = getRecord().value(); + + return process(consumedData); + } + + protected abstract Object process(S consumedData); + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java index 43b5f9d01..1c425b9d5 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java @@ -1,323 +1,323 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.cookie.Cookie; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This class provides an abstraction layer for making HTTP and HTTPS - * connections to an HTTP server. Follow the steps below to create an HTTP - * client and send HTTP requests to the HTTP server. - * - *

      - *
    1. Call {@link HttpClientFactory#build(SSLContext)} to create a factory - * instance. This factory can be used to create individual HTTP connections - * to an HTTP Server.
    2. - *
    3. Use the obtained factory from step 1 to create a {@link HttpClient} - * object by calling {@link HttpClientFactory#createHttpClient()} method.
    4. - *
    5. Use {@link HttpClient} object to send HTTP GET, POST and other requests - * to the server using {@link HttpClient#get(String, Map, Map)}, - * {@link HttpClient#post(String, Map, Map, String)} methods.
    6. - *
    7. Use the returned {@link HttpResponse} object to retrieve the various - * components of a response including: {@link HttpResponse#getBody()} and - * {@link HttpResponse#getStatusCode()}
    8. - *
    - */ -public class HttpClientFactory { - - private SSLConnectionSocketFactory sslSocketFactory; - - public class HttpClient { - private CloseableHttpClient closeableHttpClient; - private CookieStore cookieStore; - - private HttpClient() { - cookieStore = new BasicCookieStore(); - closeableHttpClient = HttpClientFactory.buildHttpClient(cookieStore, - sslSocketFactory); - } - - /** - * Sends HTTP GET request to server with the given - * headers and specified params. - * - * @param server - to which request will be sent - * @param headers - request headers - * @param params - request query parameters - * @return the server's response. - * @throws HttpException - in case of a problem or the connection was - * aborted or an http protocol error - */ - public HttpResponse get(String server, Map headers, - Map params) throws HttpException { - - try { - RequestBuilder builder = RequestBuilder.get().setUri(server); - - CloseableHttpResponse closeableresponse = executeRequest(headers, - params, builder); - - return new HttpResponse(Response.Status.fromStatusCode(closeableresponse - .getStatusLine().getStatusCode()), - EntityUtils.toString(closeableresponse.getEntity())); - - } catch (Throwable t) { - throw new HttpException(t); - } finally { - } - } - - /** - * Sends HTTP POST request to server with the given - * headers and specified params and body. - * - * @param server - to which request will be sent - * @param headers - request headers - * @param params - request query parameters - * @param body - the body of the post request - * @return the server's response. - * @throws HttpException - in case of a problem or the connection was - * aborted or an http protocol error - */ - public HttpResponse post(String server, Map headers, - Map params, String body) throws HttpException { - - try { - RequestBuilder builder = RequestBuilder.post().setUri(server); - - if (body != null) - builder.setEntity(new StringEntity(body)); - - CloseableHttpResponse closeableresponse = executeRequest(headers, - params, builder); - - return new HttpResponse(Response.Status.fromStatusCode(closeableresponse - .getStatusLine().getStatusCode()), - EntityUtils.toString(closeableresponse.getEntity())); - - } catch (Throwable t) { - throw new HttpException(t); - } finally { - } - } - - /** - * Executes a HTTP Client request using the given parameters. - * - * @param headers - request headers - * @param params - request query parameters - * @param builder - the {@link RequestBuilder} to be used for building the - * request. - * @return the {@link CloseableHttpResponse} returned by the server - * @throws IOException - in case of a problem or the connection was aborted - * @throws ClientProtocolException - in case of an http protocol error - * - */ - private CloseableHttpResponse executeRequest(Map headers, - Map params, RequestBuilder builder) - throws IOException, ClientProtocolException { - if (params != null) { - for (Map.Entry param : params.entrySet()) { - builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue())); - } - } - - HttpUriRequest request = builder.build(); - - if (headers != null) { - for (Map.Entry header : headers.entrySet()){ - request.setHeader(header.getKey(), header.getValue()); - } - } - - CloseableHttpResponse closeableresponse = - closeableHttpClient.execute(request); - return closeableresponse; - } - - /** - * Returns the cookies. - * - * @return - returning the cookie parameters from the HTTP connection. - */ - public Map getCookies() { - ConcurrentHashMap cookies = new ConcurrentHashMap(); - for (Cookie c : cookieStore.getCookies()) { - cookies.put(c.getName(), c.getValue()); - } - - return cookies; - } - - /** - * Closes the connection. - * - * @throws HttpException - in case an I/O error occurs - */ - public void close() throws HttpException { - try { - closeableHttpClient.close(); - } catch (Exception e) { - throw new HttpException(e); - } - } - } - - /** - * Encapsulates an HTTP Response containing the statusCode and - * body of the response which would be the resource returned - * by a REST call. - */ - public class HttpResponse { - private Response.Status statusCode; - private String body; - - /** - * General constructor. - * - * @param statucCode - response status code - * @param body - response body - */ - private HttpResponse(Response.Status statucCode, String body) { - super(); - this.statusCode = statucCode; - this.body = body; - } - - /** - * @return - status code - */ - public Response.Status getStatusCode() { - return statusCode; - } - - /** - * Sets the status code in the response object - * @param statucCode - the status code - * @return the response object. - */ - public HttpResponse setStatusCode(Response.Status statucCode) { - this.statusCode = statucCode; - return this; - } - - /** - * @return the response body. - */ - public String getBody() { - return body; - } - - /** - * Sets the response body/entity. - * - * @param body - the response body/entity. - * @return - the response object. - */ - public HttpResponse setBody(String body) { - this.body = body; - return this; - } - - } - - public class HttpException extends Exception { - - private static final long serialVersionUID = 1L; - - public HttpException(Throwable t) { - super(t); - } - } - - /** - * Builds {@link HttpClientFactory} object which is used to create {@link HttpClient} object. - * - * @param sslContext with which the client factory to be built. - * @return {@link HttpClientFactory} object - * @throws HttpException if building the socket factory fails. - */ - public static HttpClientFactory build(SSLContext sslContext) - throws HttpException { - HttpClientFactory factory = new HttpClientFactory(); - - try { - factory.sslSocketFactory = buildSSLConnectionSocketFactory(sslContext); - } catch (Throwable t) { - throw factory.new HttpException(t); - } - - return factory; - } - - /** - * Builds a {@link SSLConnectionSocketFactory} object - * - * @param sslContext with which the client factory to be built. - * @return SSL connection factory object that is used to create SSL socket - * connections. - */ - private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory( - SSLContext sslContext) { - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); -// , new String[] { "TLSv1" }, null, -// SSLConnectionSocketFactory.getDefaultHostnameVerifier()); - return sslsf; - } - - /** - * Creates a {@link CloseableHttpClient} object. - * @param cookieStore - * or null if no cookies required - * @param sslSocketFactory - * or null if not using SSL - * @return a {@link CloseableHttpClient} object - */ - private static CloseableHttpClient buildHttpClient(CookieStore cookieStore, - SSLConnectionSocketFactory sslSocketFactory) { - return HttpClients.custom().setDefaultCookieStore(cookieStore) - .setSSLSocketFactory(sslSocketFactory).build(); - } - - /** - * Creates a {@link HttpClient} object. - * @return a new {@link HttpClient} object - */ - public HttpClient createHttpClient() { - HttpClient httpClient = new HttpClient(); - - return httpClient; - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CookieStore; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.cookie.Cookie; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * This class provides an abstraction layer for making HTTP and HTTPS + * connections to an HTTP server. Follow the steps below to create an HTTP + * client and send HTTP requests to the HTTP server. + * + *
      + *
    1. Call {@link HttpClientFactory#build(SSLContext)} to create a factory + * instance. This factory can be used to create individual HTTP connections + * to an HTTP Server.
    2. + *
    3. Use the obtained factory from step 1 to create a {@link HttpClient} + * object by calling {@link HttpClientFactory#createHttpClient()} method.
    4. + *
    5. Use {@link HttpClient} object to send HTTP GET, POST and other requests + * to the server using {@link HttpClient#get(String, Map, Map)}, + * {@link HttpClient#post(String, Map, Map, String)} methods.
    6. + *
    7. Use the returned {@link HttpResponse} object to retrieve the various + * components of a response including: {@link HttpResponse#getBody()} and + * {@link HttpResponse#getStatusCode()}
    8. + *
    + */ +public class HttpClientFactory { + + private SSLConnectionSocketFactory sslSocketFactory; + + public class HttpClient { + private CloseableHttpClient closeableHttpClient; + private CookieStore cookieStore; + + private HttpClient() { + cookieStore = new BasicCookieStore(); + closeableHttpClient = HttpClientFactory.buildHttpClient(cookieStore, + sslSocketFactory); + } + + /** + * Sends HTTP GET request to server with the given + * headers and specified params. + * + * @param server - to which request will be sent + * @param headers - request headers + * @param params - request query parameters + * @return the server's response. + * @throws HttpException - in case of a problem or the connection was + * aborted or an http protocol error + */ + public HttpResponse get(String server, Map headers, + Map params) throws HttpException { + + try { + RequestBuilder builder = RequestBuilder.get().setUri(server); + + CloseableHttpResponse closeableresponse = executeRequest(headers, + params, builder); + + return new HttpResponse(Response.Status.fromStatusCode(closeableresponse + .getStatusLine().getStatusCode()), + EntityUtils.toString(closeableresponse.getEntity())); + + } catch (Throwable t) { + throw new HttpException(t); + } finally { + } + } + + /** + * Sends HTTP POST request to server with the given + * headers and specified params and body. + * + * @param server - to which request will be sent + * @param headers - request headers + * @param params - request query parameters + * @param body - the body of the post request + * @return the server's response. + * @throws HttpException - in case of a problem or the connection was + * aborted or an http protocol error + */ + public HttpResponse post(String server, Map headers, + Map params, String body) throws HttpException { + + try { + RequestBuilder builder = RequestBuilder.post().setUri(server); + + if (body != null) + builder.setEntity(new StringEntity(body)); + + CloseableHttpResponse closeableresponse = executeRequest(headers, + params, builder); + + return new HttpResponse(Response.Status.fromStatusCode(closeableresponse + .getStatusLine().getStatusCode()), + EntityUtils.toString(closeableresponse.getEntity())); + + } catch (Throwable t) { + throw new HttpException(t); + } finally { + } + } + + /** + * Executes a HTTP Client request using the given parameters. + * + * @param headers - request headers + * @param params - request query parameters + * @param builder - the {@link RequestBuilder} to be used for building the + * request. + * @return the {@link CloseableHttpResponse} returned by the server + * @throws IOException - in case of a problem or the connection was aborted + * @throws ClientProtocolException - in case of an http protocol error + * + */ + private CloseableHttpResponse executeRequest(Map headers, + Map params, RequestBuilder builder) + throws IOException, ClientProtocolException { + if (params != null) { + for (Map.Entry param : params.entrySet()) { + builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue())); + } + } + + HttpUriRequest request = builder.build(); + + if (headers != null) { + for (Map.Entry header : headers.entrySet()){ + request.setHeader(header.getKey(), header.getValue()); + } + } + + CloseableHttpResponse closeableresponse = + closeableHttpClient.execute(request); + return closeableresponse; + } + + /** + * Returns the cookies. + * + * @return - returning the cookie parameters from the HTTP connection. + */ + public Map getCookies() { + ConcurrentHashMap cookies = new ConcurrentHashMap(); + for (Cookie c : cookieStore.getCookies()) { + cookies.put(c.getName(), c.getValue()); + } + + return cookies; + } + + /** + * Closes the connection. + * + * @throws HttpException - in case an I/O error occurs + */ + public void close() throws HttpException { + try { + closeableHttpClient.close(); + } catch (Exception e) { + throw new HttpException(e); + } + } + } + + /** + * Encapsulates an HTTP Response containing the statusCode and + * body of the response which would be the resource returned + * by a REST call. + */ + public class HttpResponse { + private Response.Status statusCode; + private String body; + + /** + * General constructor. + * + * @param statucCode - response status code + * @param body - response body + */ + private HttpResponse(Response.Status statucCode, String body) { + super(); + this.statusCode = statucCode; + this.body = body; + } + + /** + * @return - status code + */ + public Response.Status getStatusCode() { + return statusCode; + } + + /** + * Sets the status code in the response object + * @param statucCode - the status code + * @return the response object. + */ + public HttpResponse setStatusCode(Response.Status statucCode) { + this.statusCode = statucCode; + return this; + } + + /** + * @return the response body. + */ + public String getBody() { + return body; + } + + /** + * Sets the response body/entity. + * + * @param body - the response body/entity. + * @return - the response object. + */ + public HttpResponse setBody(String body) { + this.body = body; + return this; + } + + } + + public class HttpException extends Exception { + + private static final long serialVersionUID = 1L; + + public HttpException(Throwable t) { + super(t); + } + } + + /** + * Builds {@link HttpClientFactory} object which is used to create {@link HttpClient} object. + * + * @param sslContext with which the client factory to be built. + * @return {@link HttpClientFactory} object + * @throws HttpException if building the socket factory fails. + */ + public static HttpClientFactory build(SSLContext sslContext) + throws HttpException { + HttpClientFactory factory = new HttpClientFactory(); + + try { + factory.sslSocketFactory = buildSSLConnectionSocketFactory(sslContext); + } catch (Throwable t) { + throw factory.new HttpException(t); + } + + return factory; + } + + /** + * Builds a {@link SSLConnectionSocketFactory} object + * + * @param sslContext with which the client factory to be built. + * @return SSL connection factory object that is used to create SSL socket + * connections. + */ + private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory( + SSLContext sslContext) { + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); +// , new String[] { "TLSv1" }, null, +// SSLConnectionSocketFactory.getDefaultHostnameVerifier()); + return sslsf; + } + + /** + * Creates a {@link CloseableHttpClient} object. + * @param cookieStore + * or null if no cookies required + * @param sslSocketFactory + * or null if not using SSL + * @return a {@link CloseableHttpClient} object + */ + private static CloseableHttpClient buildHttpClient(CookieStore cookieStore, + SSLConnectionSocketFactory sslSocketFactory) { + return HttpClients.custom().setDefaultCookieStore(cookieStore) + .setSSLSocketFactory(sslSocketFactory).build(); + } + + /** + * Creates a {@link HttpClient} object. + * @return a new {@link HttpClient} object + */ + public HttpClient createHttpClient() { + HttpClient httpClient = new HttpClient(); + + return httpClient; + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java index 75b9b03bf..571ef5eb6 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/SSLBuilder.java @@ -1,99 +1,99 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import java.io.InputStream; -import java.security.KeyStore; - -import javax.net.ssl.SSLContext; - -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; - -/** - * This class is used to build a SSL Context - */ -public class SSLBuilder { - - /** - * Creates SSL context. - * To create a custom SSLContext that accepts CA and self-signed certs, - * pass a valid keystoreStream and keystorePass. To create a default SSLContext - * pass null for keystoreStream; - * - * @param keystoreStream - * Input Stream of the keystore file. If null, a default SSL context - * will be created. - * @param keystorePass - * The password required to access the Keystore file. If null, - * blank is passed as password. - * - * @return SSLContext object - * @throws SSLException - * - if no Provider supports a KeyStoreSpi implementation for the specified type. - * - if an I/O error occurs - * - or any other causes will be attached to the exception. - */ - public static SSLContext buildSSLContext( - InputStream keystoreStream, - String keystorePass) throws SSLException { - - SSLContext sslcontext = null; - try { - if (keystoreStream != null) { // Create custom context - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - - - try { - keystore.load(keystoreStream, - keystorePass == null ? "".toCharArray() : - keystorePass.toCharArray()); - } finally { - keystoreStream.close(); - } - - // Trust own CA and all self-signed certs - sslcontext = SSLContexts.custom() - .loadTrustMaterial(keystore, new TrustSelfSignedStrategy()) - .build(); - } else { //get the default context - sslcontext = SSLContexts.createDefault(); - } - } catch (Exception e) { - throw new SSLException(e); - } - return sslcontext; - } - - /** - * The exception thrown when errors occur within this class - */ - public static class SSLException extends Exception { - - - private static final long serialVersionUID = 1L; - - public SSLException(String string) { - super(string); - } - - public SSLException(Exception e) { - super(e); - } - - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import java.io.InputStream; +import java.security.KeyStore; + +import javax.net.ssl.SSLContext; + +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; + +/** + * This class is used to build a SSL Context + */ +public class SSLBuilder { + + /** + * Creates SSL context. + * To create a custom SSLContext that accepts CA and self-signed certs, + * pass a valid keystoreStream and keystorePass. To create a default SSLContext + * pass null for keystoreStream; + * + * @param keystoreStream + * Input Stream of the keystore file. If null, a default SSL context + * will be created. + * @param keystorePass + * The password required to access the Keystore file. If null, + * blank is passed as password. + * + * @return SSLContext object + * @throws SSLException + * - if no Provider supports a KeyStoreSpi implementation for the specified type. + * - if an I/O error occurs + * - or any other causes will be attached to the exception. + */ + public static SSLContext buildSSLContext( + InputStream keystoreStream, + String keystorePass) throws SSLException { + + SSLContext sslcontext = null; + try { + if (keystoreStream != null) { // Create custom context + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + + + try { + keystore.load(keystoreStream, + keystorePass == null ? "".toCharArray() : + keystorePass.toCharArray()); + } finally { + keystoreStream.close(); + } + + // Trust own CA and all self-signed certs + sslcontext = SSLContexts.custom() + .loadTrustMaterial(keystore, new TrustSelfSignedStrategy()) + .build(); + } else { //get the default context + sslcontext = SSLContexts.createDefault(); + } + } catch (Exception e) { + throw new SSLException(e); + } + return sslcontext; + } + + /** + * The exception thrown when errors occur within this class + */ + public static class SSLException extends Exception { + + + private static final long serialVersionUID = 1L; + + public SSLException(String string) { + super(string); + } + + public SSLException(Exception e) { + super(e); + } + + } + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java index 23dd48ebf..ba627e6a3 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageDecoder.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import javax.websocket.Decoder; - -/** - * This interface abstracts the use of {@link Decoder.Text} from the rest of - * the application. - * - * @param - the type of object being decoded by this decoder. - */ -public interface WebSocketMessageDecoder extends Decoder.Text { - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import javax.websocket.Decoder; + +/** + * This interface abstracts the use of {@link Decoder.Text} from the rest of + * the application. + * + * @param - the type of object being decoded by this decoder. + */ +public interface WebSocketMessageDecoder extends Decoder.Text { + + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java index d61c59802..8d9a64ecf 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/WebSocketMessageHandler.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import javax.websocket.CloseReason; -import javax.websocket.EndpointConfig; -import javax.websocket.MessageHandler; -import javax.websocket.Session; - -/** - * This interface abstracts the use of {@link MessageHandler.Whole} from the - * rest of the application. - * - * @param - the type of message being handled by this message handler. - */ -public interface WebSocketMessageHandler extends MessageHandler.Whole { - - void onOpen(Session session, EndpointConfig config); - - void onClose(Session session, CloseReason reason); - - void onError(Session session, Throwable t); - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import javax.websocket.CloseReason; +import javax.websocket.EndpointConfig; +import javax.websocket.MessageHandler; +import javax.websocket.Session; + +/** + * This interface abstracts the use of {@link MessageHandler.Whole} from the + * rest of the application. + * + * @param - the type of message being handled by this message handler. + */ +public interface WebSocketMessageHandler extends MessageHandler.Whole { + + void onOpen(Session session, EndpointConfig config); + + void onClose(Session session, CloseReason reason); + + void onError(Session session, Throwable t); + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java index 9cdf91962..9cdc0df3a 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimDeserializer.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; - -import us.dot.its.jpo.ode.model.OdeTimData; - -public class OdeTimDeserializer extends MessagingDeserializer { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; + +import us.dot.its.jpo.ode.model.OdeTimData; + +public class OdeTimDeserializer extends MessagingDeserializer { + +} diff --git a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java index 08e468655..59e508f9e 100644 --- a/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java +++ b/jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/serdes/OdeTimSerializer.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; - -import us.dot.its.jpo.ode.model.OdeTimData; - -public class OdeTimSerializer extends MessagingSerializer { - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper.serdes; + +import us.dot.its.jpo.ode.model.OdeTimData; + +public class OdeTimSerializer extends MessagingSerializer { + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java index 0c644f6ab..5d5722f20 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/CASClientTest.java @@ -1,527 +1,527 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.core.Response.Status; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; -import us.dot.its.jpo.ode.dds.CASClient.CASException; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpClient; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpException; -import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpResponse; - -@RunWith(JMockit.class) -public class CASClientTest { - @Mocked HttpClientFactory mockHttpClientFactory; - @Mocked SSLContext sslContext; - @Mocked private HttpResponse mockResponse; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the following very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - * -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running us.dot.its.jpo.ode.asn1.j2735.CVMessageTest -Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.673 sec - in us.dot.its.jpo.ode.asn1.j2735.CVMessageTest -Running us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest -01:20:03.199 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehicleSituationDataServiceRequest.uper into object ServiceRequest -01:20:03.227 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehSitDataMessage.uper into object VehSitDataMessage -2017-05-29 05:20:03.239 UTC -2017-05-29 05:21:03.000 UTC -Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.25 sec - in us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest -Running us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest -Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec - in us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest -Running us.dot.its.jpo.ode.dds.CASClientTest -Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.521 sec - in us.dot.its.jpo.ode.dds.CASClientTest -Running us.dot.its.jpo.ode.dds.DdsClientTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsClientTest -us.dot.its.jpo.ode.dds.DdsClientTest Time elapsed: 0.01 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsDepRequestTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsDepRequestTest -us.dot.its.jpo.ode.dds.DdsDepRequestTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsRequestTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.002 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsRequestTest -us.dot.its.jpo.ode.dds.DdsRequestTest Time elapsed: 0.002 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.016 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest -us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest Time elapsed: 0.016 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DdsStatusMessageTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageTest -us.dot.its.jpo.ode.dds.DdsStatusMessageTest Time elapsed: 0.003 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.DepositResponseDecoderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DepositResponseDecoderTest -us.dot.its.jpo.ode.dds.DepositResponseDecoderTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.dds.StatusMessageHandlerTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.StatusMessageHandlerTest -us.dot.its.jpo.ode.dds.StatusMessageHandlerTest Time elapsed: 0.011 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.model.J2735GeoRegionTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in us.dot.its.jpo.ode.model.J2735GeoRegionTest -us.dot.its.jpo.ode.model.J2735GeoRegionTest Time elapsed: 0.001 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.snmp.SNMPTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.snmp.SNMPTest -us.dot.its.jpo.ode.snmp.SNMPTest Time elapsed: 0.01 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.DateTimeUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.DateTimeUtilsTest -us.dot.its.jpo.ode.util.DateTimeUtilsTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.GeoUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.GeoUtilsTest -us.dot.its.jpo.ode.util.GeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.JsonUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.JsonUtilsTest -us.dot.its.jpo.ode.util.JsonUtilsTest Time elapsed: 0.003 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.util.OdeGeoUtilsTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.OdeGeoUtilsTest -us.dot.its.jpo.ode.util.OdeGeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest -us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest Time elapsed: 0.005 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.HttpClientTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientTest -us.dot.its.jpo.ode.wrapper.HttpClientTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.SSLBuilderTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.015 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.SSLBuilderTest -us.dot.its.jpo.ode.wrapper.SSLBuilderTest Time elapsed: 0.015 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Running us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest -Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest -us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest Time elapsed: 0.013 sec <<< ERROR! -java.lang.NullPointerException - at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) - at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) - at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) - -Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0 - -Results : - -Tests in error: - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer - -Tests run: 26, Failures: 0, Errors: 17, Skipped: 0 - -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD FAILURE -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 7.387 s -[INFO] Finished at: 2017-05-29T01:20:05-04:00 -[INFO] Final Memory: 19M/227M -[INFO] ------------------------------------------------------------------------ -[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project jpo-ode-core: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process -[ERROR] org.apache.maven.surefire.testset.TestSetFailedException: java.lang.NullPointerException -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures(JUnit4RunListener.java:209) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:169) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) -[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) -[ERROR] Caused by: java.lang.NullPointerException -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.extractClassName(JUnit4RunListener.java:188) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.getClassName(JUnit4RunListener.java:157) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.createReportEntry(JUnit4RunListener.java:181) -[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.testFinished(JUnit4RunListener.java:143) -[ERROR] at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56) -[ERROR] at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190) -[ERROR] at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72) -[ERROR] at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187) -[ERROR] at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38) -[ERROR] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331) -[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) -[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) -[ERROR] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) -[ERROR] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) -[ERROR] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) -[ERROR] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) -[ERROR] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) -[ERROR] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) -[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) -[ERROR] ... 3 more -[ERROR] -[ERROR] -> [Help 1] -[ERROR] -[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. -[ERROR] Re-run Maven using the -X switch to enable full debug logging. -[ERROR] -[ERROR] For more information about the errors and possible solutions, please read the following articles: -[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException - * - */ -// @Mocked private Pattern mockPattern; -// @Mocked private Matcher mockMatcher; - - String casUser = "testUser"; - String casPass = "testPass"; - String casUrl = "testUrl"; - - @Test - public void testConfigure() { - CASClient casClient = null; - try { - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - } catch (CASException e) { - fail("Unexpected exception: " + e.toString()); - } - assertEquals(casClient.getDdsCasUrl(), casUrl); - assertEquals(casClient.getDdsCasUsername(), casUser); - } - - @Test(expected = CASException.class) - public void testConfigureException() - throws CASException, HttpException { - new Expectations() { - { - HttpClientFactory.build((SSLContext) any); - result = new Exception(); - } - }; - CASClient.configure(sslContext, casUrl, casUser, casPass); - } - - @SuppressWarnings("unchecked") - @Test - public void testLogin() throws HttpException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.OK; - result = Status.OK; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - - mockHttpClientFactory.createHttpClient().getCookies(); - result = cookies; - } - }; - - CASClient casClient; - String sessionId = ""; - try { - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - sessionId = casClient.login(websocketURL); - assertEquals(casClient.getSessionID(), sessionId); - assertEquals("1bif45f-testSessionId", sessionId); - } catch (CASException e) { - fail("Unexpected exception: " + e.toString()); - } - - new Verifications() { - { - HttpClient httpClient = mockHttpClientFactory.createHttpClient(); - minTimes = 3; - - httpClient.post(anyString, null, (Map) any, anyString); - minTimes = 2; - - httpClient.get(anyString, null, (Map) any); - minTimes = 1; - - httpClient.close(); - minTimes = 3; - - Pattern.compile(anyString); - } - }; - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetTicket1() throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.BAD_REQUEST; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetTicket2() throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = false; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - @Test(expected = CASException.class) - public void testLoginExceptionInGetServiceTicket() - throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.BAD_REQUEST; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - } - }; - - CASClient casClient; - - casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } - - - @Test(expected = CASException.class) - public void testLoginExceptionInGetServiceCall() - throws HttpException, CASException { - String websocketURL = "wss://url.websocket.com"; - Map cookies = new ConcurrentHashMap(); - cookies.put("JSESSIONID", "1bif45f-testSessionId"); - new Expectations() { - { - mockResponse.getStatusCode(); - result = Status.CREATED; - result = Status.OK; - result = Status.BAD_REQUEST; - - /* - * For some very odd reason, just having mocked objects of Pattern and Matcher causes - * surefile plug-in to report the followig very odd and strange errors on all - * subsequest test cases. Hence, we have to use real values so we don't have to mock - * which is a better approach anyway. - */ -// Pattern.compile(anyString); -// result = mockPattern; -// -// mockPattern.matcher(anyString); -// result = mockMatcher; -// -// mockMatcher.matches(); -// result = true; -// mockMatcher.group(1); -// result = "TGT-1234-11112222333334444-cas01"; - - mockResponse.getBody(); - result = "action=\"x/TGT-1234-11112222333334444-cas01\""; - result = "ST-1234-1111222233334444-cas01"; - - } - }; - - CASClient casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); - casClient.login(websocketURL); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.core.Response.Status; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; +import us.dot.its.jpo.ode.dds.CASClient.CASException; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpClient; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpException; +import us.dot.its.jpo.ode.wrapper.HttpClientFactory.HttpResponse; + +@RunWith(JMockit.class) +public class CASClientTest { + @Mocked HttpClientFactory mockHttpClientFactory; + @Mocked SSLContext sslContext; + @Mocked private HttpResponse mockResponse; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the following very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + * +------------------------------------------------------- + T E S T S +------------------------------------------------------- +Running us.dot.its.jpo.ode.asn1.j2735.CVMessageTest +Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.673 sec - in us.dot.its.jpo.ode.asn1.j2735.CVMessageTest +Running us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest +01:20:03.199 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehicleSituationDataServiceRequest.uper into object ServiceRequest +01:20:03.227 [main] INFO us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest - Decoded file VehSitDataMessage.uper into object VehSitDataMessage +2017-05-29 05:20:03.239 UTC +2017-05-29 05:21:03.000 UTC +Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.25 sec - in us.dot.its.jpo.ode.asn1.j2735.J2735UtilTest +Running us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest +Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec - in us.dot.its.jpo.ode.asn1.j2735.msg.ids.ConnectedVehicleMessageLookupTest +Running us.dot.its.jpo.ode.dds.CASClientTest +Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.521 sec - in us.dot.its.jpo.ode.dds.CASClientTest +Running us.dot.its.jpo.ode.dds.DdsClientTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsClientTest +us.dot.its.jpo.ode.dds.DdsClientTest Time elapsed: 0.01 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsDepRequestTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsDepRequestTest +us.dot.its.jpo.ode.dds.DdsDepRequestTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsRequestTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.002 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsRequestTest +us.dot.its.jpo.ode.dds.DdsRequestTest Time elapsed: 0.002 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.016 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest +us.dot.its.jpo.ode.dds.DdsStatusMessageDecoderTest Time elapsed: 0.016 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DdsStatusMessageTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DdsStatusMessageTest +us.dot.its.jpo.ode.dds.DdsStatusMessageTest Time elapsed: 0.003 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.DepositResponseDecoderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.DepositResponseDecoderTest +us.dot.its.jpo.ode.dds.DepositResponseDecoderTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.dds.StatusMessageHandlerTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE! - in us.dot.its.jpo.ode.dds.StatusMessageHandlerTest +us.dot.its.jpo.ode.dds.StatusMessageHandlerTest Time elapsed: 0.011 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.model.J2735GeoRegionTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in us.dot.its.jpo.ode.model.J2735GeoRegionTest +us.dot.its.jpo.ode.model.J2735GeoRegionTest Time elapsed: 0.001 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.snmp.SNMPTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE! - in us.dot.its.jpo.ode.snmp.SNMPTest +us.dot.its.jpo.ode.snmp.SNMPTest Time elapsed: 0.01 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.DateTimeUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.DateTimeUtilsTest +us.dot.its.jpo.ode.util.DateTimeUtilsTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.GeoUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.GeoUtilsTest +us.dot.its.jpo.ode.util.GeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.JsonUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.JsonUtilsTest +us.dot.its.jpo.ode.util.JsonUtilsTest Time elapsed: 0.003 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.util.OdeGeoUtilsTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.util.OdeGeoUtilsTest +us.dot.its.jpo.ode.util.OdeGeoUtilsTest Time elapsed: 0.004 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest +us.dot.its.jpo.ode.wrapper.HttpClientFactoryTest Time elapsed: 0.005 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.HttpClientTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.HttpClientTest +us.dot.its.jpo.ode.wrapper.HttpClientTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.SSLBuilderTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.015 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.SSLBuilderTest +us.dot.its.jpo.ode.wrapper.SSLBuilderTest Time elapsed: 0.015 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Running us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest +Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.013 sec <<< FAILURE! - in us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest +us.dot.its.jpo.ode.wrapper.WebSocketEndpointTest Time elapsed: 0.013 sec <<< ERROR! +java.lang.NullPointerException + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) + +Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0 + +Results : + +Tests in error: + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + JUnit4Provider.invoke:161->executeTestSet:238->executeWithRerun:274->execute:365 â•— NullPointer + +Tests run: 26, Failures: 0, Errors: 17, Skipped: 0 + +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD FAILURE +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 7.387 s +[INFO] Finished at: 2017-05-29T01:20:05-04:00 +[INFO] Final Memory: 19M/227M +[INFO] ------------------------------------------------------------------------ +[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project jpo-ode-core: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process +[ERROR] org.apache.maven.surefire.testset.TestSetFailedException: java.lang.NullPointerException +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures(JUnit4RunListener.java:209) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:169) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) +[ERROR] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) +[ERROR] Caused by: java.lang.NullPointerException +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.extractClassName(JUnit4RunListener.java:188) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.getClassName(JUnit4RunListener.java:157) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.createReportEntry(JUnit4RunListener.java:181) +[ERROR] at org.apache.maven.surefire.common.junit4.JUnit4RunListener.testFinished(JUnit4RunListener.java:143) +[ERROR] at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56) +[ERROR] at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190) +[ERROR] at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72) +[ERROR] at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187) +[ERROR] at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38) +[ERROR] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331) +[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) +[ERROR] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) +[ERROR] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) +[ERROR] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) +[ERROR] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) +[ERROR] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) +[ERROR] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) +[ERROR] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) +[ERROR] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) +[ERROR] ... 3 more +[ERROR] +[ERROR] -> [Help 1] +[ERROR] +[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. +[ERROR] Re-run Maven using the -X switch to enable full debug logging. +[ERROR] +[ERROR] For more information about the errors and possible solutions, please read the following articles: +[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException + * + */ +// @Mocked private Pattern mockPattern; +// @Mocked private Matcher mockMatcher; + + String casUser = "testUser"; + String casPass = "testPass"; + String casUrl = "testUrl"; + + @Test + public void testConfigure() { + CASClient casClient = null; + try { + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + } catch (CASException e) { + fail("Unexpected exception: " + e.toString()); + } + assertEquals(casClient.getDdsCasUrl(), casUrl); + assertEquals(casClient.getDdsCasUsername(), casUser); + } + + @Test(expected = CASException.class) + public void testConfigureException() + throws CASException, HttpException { + new Expectations() { + { + HttpClientFactory.build((SSLContext) any); + result = new Exception(); + } + }; + CASClient.configure(sslContext, casUrl, casUser, casPass); + } + + @SuppressWarnings("unchecked") + @Test + public void testLogin() throws HttpException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.OK; + result = Status.OK; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + + mockHttpClientFactory.createHttpClient().getCookies(); + result = cookies; + } + }; + + CASClient casClient; + String sessionId = ""; + try { + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + sessionId = casClient.login(websocketURL); + assertEquals(casClient.getSessionID(), sessionId); + assertEquals("1bif45f-testSessionId", sessionId); + } catch (CASException e) { + fail("Unexpected exception: " + e.toString()); + } + + new Verifications() { + { + HttpClient httpClient = mockHttpClientFactory.createHttpClient(); + minTimes = 3; + + httpClient.post(anyString, null, (Map) any, anyString); + minTimes = 2; + + httpClient.get(anyString, null, (Map) any); + minTimes = 1; + + httpClient.close(); + minTimes = 3; + + Pattern.compile(anyString); + } + }; + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetTicket1() throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.BAD_REQUEST; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetTicket2() throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = false; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + @Test(expected = CASException.class) + public void testLoginExceptionInGetServiceTicket() + throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.BAD_REQUEST; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + } + }; + + CASClient casClient; + + casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } + + + @Test(expected = CASException.class) + public void testLoginExceptionInGetServiceCall() + throws HttpException, CASException { + String websocketURL = "wss://url.websocket.com"; + Map cookies = new ConcurrentHashMap(); + cookies.put("JSESSIONID", "1bif45f-testSessionId"); + new Expectations() { + { + mockResponse.getStatusCode(); + result = Status.CREATED; + result = Status.OK; + result = Status.BAD_REQUEST; + + /* + * For some very odd reason, just having mocked objects of Pattern and Matcher causes + * surefile plug-in to report the followig very odd and strange errors on all + * subsequest test cases. Hence, we have to use real values so we don't have to mock + * which is a better approach anyway. + */ +// Pattern.compile(anyString); +// result = mockPattern; +// +// mockPattern.matcher(anyString); +// result = mockMatcher; +// +// mockMatcher.matches(); +// result = true; +// mockMatcher.group(1); +// result = "TGT-1234-11112222333334444-cas01"; + + mockResponse.getBody(); + result = "action=\"x/TGT-1234-11112222333334444-cas01\""; + result = "ST-1234-1111222233334444-cas01"; + + } + }; + + CASClient casClient = CASClient.configure(sslContext, casUrl, casUser, casPass); + casClient.login(websocketURL); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java index 61dc913c6..7d349d230 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsClientTest.java @@ -1,142 +1,142 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import java.io.InputStream; -import java.net.URI; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLContext; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; -import us.dot.its.jpo.ode.dds.CASClient.CASException; -import us.dot.its.jpo.ode.dds.DdsClient.DdsClientException; -import us.dot.its.jpo.ode.wrapper.SSLBuilder; -import us.dot.its.jpo.ode.wrapper.WebSocketEndpoint; -import us.dot.its.jpo.ode.wrapper.WebSocketMessageDecoder; -import us.dot.its.jpo.ode.wrapper.WebSocketMessageHandler; - -@RunWith(JMockit.class) -public class DdsClientTest { - @Mocked private WebSocketMessageHandler mockMessageHandler; - @Mocked private CASClient mockCasClient; - - String ddsCasUrl = "ddsCasUrl"; - String ddsCasUsername = "ddsCasUsername"; - String ddsCasPassword = "ddsCasPassword"; - String websocketURL = "ws://websocket.org"; - String keystoreFile = "keystoreFile"; - String keystorePass = "keystorePass"; - - @Ignore - @Test - public void testConstructor() { - try { - new Expectations() { - { - CASClient.configure((SSLContext) any, anyString, anyString, anyString); - } - }; - } catch (CASException e1) { - e1.printStackTrace(); - } - - try { - new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); - } catch (DdsClientException e) { - e.printStackTrace(); - } - - try { - new Verifications() { - { - new URI("websocketURL"); - minTimes = 1; - CASClient.class.getClassLoader().getResourceAsStream("keystoreFile"); - SSLBuilder.buildSSLContext((InputStream) any, "keystorePass"); - } - }; - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Ignore - @Test(expected = DdsClientException.class) - public void testConstructorException() - throws DdsClientException, CASException { - - new Expectations() { - { - CASClient.configure((SSLContext) any, anyString, anyString, anyString); - result = new Exception(); - } - }; - - new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); - } - - @SuppressWarnings("unchecked") - @Ignore - @Test - public void testLogin() { - try { - DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, - keystoreFile, keystorePass); - ddsClient.login(null, mockMessageHandler); - - new Verifications() { - { - mockCasClient.login(anyString); - new WebSocketEndpoint((URI) any, (SSLContext) any, null, - (Map>) any, (WebSocketMessageHandler) any, - (List>>) any); - } - }; - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Ignore - @SuppressWarnings("unchecked") - @Test(expected = DdsClientException.class) - public void testLoginException() - throws DdsClientException, CASException { - - new Expectations() { - { - mockCasClient.login(anyString); - new WebSocketEndpoint((URI) any, (SSLContext) any, null, (Map>) any, - (WebSocketMessageHandler) any, (List>>) any); - result = new DdsClientException(null); - } - }; - - DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, - keystoreFile, keystorePass); - ddsClient.login(null, mockMessageHandler); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import java.io.InputStream; +import java.net.URI; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLContext; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; +import us.dot.its.jpo.ode.dds.CASClient.CASException; +import us.dot.its.jpo.ode.dds.DdsClient.DdsClientException; +import us.dot.its.jpo.ode.wrapper.SSLBuilder; +import us.dot.its.jpo.ode.wrapper.WebSocketEndpoint; +import us.dot.its.jpo.ode.wrapper.WebSocketMessageDecoder; +import us.dot.its.jpo.ode.wrapper.WebSocketMessageHandler; + +@RunWith(JMockit.class) +public class DdsClientTest { + @Mocked private WebSocketMessageHandler mockMessageHandler; + @Mocked private CASClient mockCasClient; + + String ddsCasUrl = "ddsCasUrl"; + String ddsCasUsername = "ddsCasUsername"; + String ddsCasPassword = "ddsCasPassword"; + String websocketURL = "ws://websocket.org"; + String keystoreFile = "keystoreFile"; + String keystorePass = "keystorePass"; + + @Ignore + @Test + public void testConstructor() { + try { + new Expectations() { + { + CASClient.configure((SSLContext) any, anyString, anyString, anyString); + } + }; + } catch (CASException e1) { + e1.printStackTrace(); + } + + try { + new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); + } catch (DdsClientException e) { + e.printStackTrace(); + } + + try { + new Verifications() { + { + new URI("websocketURL"); + minTimes = 1; + CASClient.class.getClassLoader().getResourceAsStream("keystoreFile"); + SSLBuilder.buildSSLContext((InputStream) any, "keystorePass"); + } + }; + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Ignore + @Test(expected = DdsClientException.class) + public void testConstructorException() + throws DdsClientException, CASException { + + new Expectations() { + { + CASClient.configure((SSLContext) any, anyString, anyString, anyString); + result = new Exception(); + } + }; + + new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, keystoreFile, keystorePass); + } + + @SuppressWarnings("unchecked") + @Ignore + @Test + public void testLogin() { + try { + DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, + keystoreFile, keystorePass); + ddsClient.login(null, mockMessageHandler); + + new Verifications() { + { + mockCasClient.login(anyString); + new WebSocketEndpoint((URI) any, (SSLContext) any, null, + (Map>) any, (WebSocketMessageHandler) any, + (List>>) any); + } + }; + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Ignore + @SuppressWarnings("unchecked") + @Test(expected = DdsClientException.class) + public void testLoginException() + throws DdsClientException, CASException { + + new Expectations() { + { + mockCasClient.login(anyString); + new WebSocketEndpoint((URI) any, (SSLContext) any, null, (Map>) any, + (WebSocketMessageHandler) any, (List>>) any); + result = new DdsClientException(null); + } + }; + + DdsClient ddsClient = new DdsClient(ddsCasUrl, ddsCasUsername, ddsCasPassword, websocketURL, + keystoreFile, keystorePass); + ddsClient.login(null, mockMessageHandler); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java index f76f34079..256225340 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsDepRequestTest.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; -import org.junit.Test; - -public class DdsDepRequestTest { - - @Test - public void testSystemDepositName() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String depositName = "test deposit name"; - ddsDepRequest.setSystemDepositName(depositName); - assertEquals(depositName, ddsDepRequest.getSystemDepositName()); - } - - @Test - public void testEncodeType() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodeType = "hex"; - ddsDepRequest.setEncodeType(encodeType); - assertEquals(encodeType, ddsDepRequest.getEncodeType()); - assertNotEquals("base64", ddsDepRequest.getEncodeType()); - } - - @Test - public void testEncodedMsg() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodedMsg = "Sample Encode Msg"; - ddsDepRequest.setEncodedMsg(encodedMsg); - assertEquals(encodedMsg, ddsDepRequest.getEncodedMsg()); - assertNotEquals("invalid encoded msg", ddsDepRequest.getEncodedMsg()); - } - - @Test - public void testToString() { - DdsDepRequest ddsDepRequest = new DdsDepRequest(); - String encodedMsg = "testEncodeMsg"; - String encodeType = "hex"; - String depositName = "testDepositName"; - - ddsDepRequest.setEncodeType(encodedMsg); - ddsDepRequest.setEncodeType(encodeType); - ddsDepRequest.setSystemDepositName(depositName); - String expectedStr = "DEPOSIT:{\"systemDepositName\":\"testDepositName\",\"encodeType\":\"hex\",\"dialogID\":0}"; - assertEquals(ddsDepRequest.toString(), expectedStr); - } - - @Test - public void testHashCode() { - DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); - DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - String encodeType = "hex"; - ddsDepRequest1.setEncodeType(encodeType); - assertNotEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - ddsDepRequest2.setEncodeType(encodeType); - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - - String encodedMsg = "testEncodeMsg"; - ddsDepRequest1.setEncodedMsg(encodedMsg); - ddsDepRequest2.setEncodedMsg(encodedMsg); - - String depositName = "testDepositName"; - ddsDepRequest1.setSystemDepositName(depositName); - ddsDepRequest2.setSystemDepositName(depositName); - - assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); - } - - @Test - public void testEquals() { - DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); - DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); - Object randomObject = new Object(); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - assertTrue(ddsDepRequest1.equals(ddsDepRequest1)); - assertFalse(ddsDepRequest1.equals(randomObject)); - assertFalse(ddsDepRequest1.equals(null)); - - ddsDepRequest2.setEncodeType("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String encodeType = "hex"; - ddsDepRequest1.setEncodeType(encodeType); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodeType(encodeType); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodedMsg("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String encodedMsg = "testEncodeMsg"; - ddsDepRequest1.setEncodedMsg(encodedMsg); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setEncodedMsg(encodedMsg); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setSystemDepositName("NotNull"); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - String depositName = "testDepositName"; - ddsDepRequest1.setSystemDepositName(depositName); - assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); - - ddsDepRequest2.setSystemDepositName(depositName); - assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); - } - - - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class DdsDepRequestTest { + + @Test + public void testSystemDepositName() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String depositName = "test deposit name"; + ddsDepRequest.setSystemDepositName(depositName); + assertEquals(depositName, ddsDepRequest.getSystemDepositName()); + } + + @Test + public void testEncodeType() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodeType = "hex"; + ddsDepRequest.setEncodeType(encodeType); + assertEquals(encodeType, ddsDepRequest.getEncodeType()); + assertNotEquals("base64", ddsDepRequest.getEncodeType()); + } + + @Test + public void testEncodedMsg() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodedMsg = "Sample Encode Msg"; + ddsDepRequest.setEncodedMsg(encodedMsg); + assertEquals(encodedMsg, ddsDepRequest.getEncodedMsg()); + assertNotEquals("invalid encoded msg", ddsDepRequest.getEncodedMsg()); + } + + @Test + public void testToString() { + DdsDepRequest ddsDepRequest = new DdsDepRequest(); + String encodedMsg = "testEncodeMsg"; + String encodeType = "hex"; + String depositName = "testDepositName"; + + ddsDepRequest.setEncodeType(encodedMsg); + ddsDepRequest.setEncodeType(encodeType); + ddsDepRequest.setSystemDepositName(depositName); + String expectedStr = "DEPOSIT:{\"systemDepositName\":\"testDepositName\",\"encodeType\":\"hex\",\"dialogID\":0}"; + assertEquals(ddsDepRequest.toString(), expectedStr); + } + + @Test + public void testHashCode() { + DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); + DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + String encodeType = "hex"; + ddsDepRequest1.setEncodeType(encodeType); + assertNotEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + ddsDepRequest2.setEncodeType(encodeType); + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + + String encodedMsg = "testEncodeMsg"; + ddsDepRequest1.setEncodedMsg(encodedMsg); + ddsDepRequest2.setEncodedMsg(encodedMsg); + + String depositName = "testDepositName"; + ddsDepRequest1.setSystemDepositName(depositName); + ddsDepRequest2.setSystemDepositName(depositName); + + assertEquals(ddsDepRequest1.hashCode(), ddsDepRequest2.hashCode()); + } + + @Test + public void testEquals() { + DdsDepRequest ddsDepRequest1 = new DdsDepRequest(); + DdsDepRequest ddsDepRequest2 = new DdsDepRequest(); + Object randomObject = new Object(); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + assertTrue(ddsDepRequest1.equals(ddsDepRequest1)); + assertFalse(ddsDepRequest1.equals(randomObject)); + assertFalse(ddsDepRequest1.equals(null)); + + ddsDepRequest2.setEncodeType("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String encodeType = "hex"; + ddsDepRequest1.setEncodeType(encodeType); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodeType(encodeType); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodedMsg("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String encodedMsg = "testEncodeMsg"; + ddsDepRequest1.setEncodedMsg(encodedMsg); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setEncodedMsg(encodedMsg); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setSystemDepositName("NotNull"); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + String depositName = "testDepositName"; + ddsDepRequest1.setSystemDepositName(depositName); + assertFalse(ddsDepRequest1.equals(ddsDepRequest2)); + + ddsDepRequest2.setSystemDepositName(depositName); + assertTrue(ddsDepRequest1.equals(ddsDepRequest2)); + } + + + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java index b0464a5c2..dd2fac010 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsRequestTest.java @@ -1,123 +1,123 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.dds.DdsRequest.EncodeType; -import us.dot.its.jpo.ode.dds.DdsRequest.SystemName; - -public class DdsRequestTest { - - private DdsRequest ddsRequest; - - @Before - public void setUp() throws Exception { - ddsRequest = new DdsRequest(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testDialogEnum() { - Dialog dialog = Dialog.ASD; - - assertEquals(Dialog.ISD, Dialog.getById(162)); - assertEquals(156, dialog.getId()); - assertNull(Dialog.getById(999)); - } - - @Test - public void testSystemNameEnum() { - SystemName systemName = SystemName.SDC; - assertEquals("SDC 2.3", systemName.getName()); - } - - @Test - public void testDialogId() { - ddsRequest.setDialogID(156); - assertEquals(156, ddsRequest.getDialogID()); - } - - @Test - public void testResultEncoding() { - String encodingType = "hex"; - ddsRequest.setResultEncoding(encodingType); - assertEquals(encodingType, ddsRequest.getResultEncoding()); - } - - @Test - public void testHashCode() { - int hashCode1, hashCode2; - DdsRequest ddsRequest2 = new DdsRequest(); - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - - ddsRequest2.setResultEncoding("hex"); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertNotEquals(hashCode1, hashCode2); - - ddsRequest.setResultEncoding("hex"); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - - ddsRequest2.setDialogID(156); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertNotEquals(hashCode1, hashCode2); - - ddsRequest.setDialogID(156); - - hashCode1 = ddsRequest.hashCode(); - hashCode2 = ddsRequest2.hashCode(); - assertEquals(hashCode1, hashCode2); - } - - @Test - public void testEquals() { - EncodeType encodeType = EncodeType.HEX; - DdsRequest ddsRequest2 = new DdsRequest(); - assertTrue(ddsRequest.equals(ddsRequest2)); - - ddsRequest2.setResultEncoding(encodeType.name()); - assertFalse(ddsRequest.equals(ddsRequest2)); - - ddsRequest.setResultEncoding(encodeType.name()); - assertTrue(ddsRequest.equals(ddsRequest2)); - - ddsRequest2.setDialogID(156); - assertFalse(ddsRequest.equals(ddsRequest2)); - - ddsRequest.setDialogID(156); - assertTrue(ddsRequest.equals(ddsRequest2)); - assertTrue(ddsRequest.equals(ddsRequest)); - - ddsRequest2.setResultEncoding(EncodeType.BASE64.name()); - assertFalse(ddsRequest.equals(ddsRequest2)); - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.dds.DdsRequest.EncodeType; +import us.dot.its.jpo.ode.dds.DdsRequest.SystemName; + +public class DdsRequestTest { + + private DdsRequest ddsRequest; + + @Before + public void setUp() throws Exception { + ddsRequest = new DdsRequest(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDialogEnum() { + Dialog dialog = Dialog.ASD; + + assertEquals(Dialog.ISD, Dialog.getById(162)); + assertEquals(156, dialog.getId()); + assertNull(Dialog.getById(999)); + } + + @Test + public void testSystemNameEnum() { + SystemName systemName = SystemName.SDC; + assertEquals("SDC 2.3", systemName.getName()); + } + + @Test + public void testDialogId() { + ddsRequest.setDialogID(156); + assertEquals(156, ddsRequest.getDialogID()); + } + + @Test + public void testResultEncoding() { + String encodingType = "hex"; + ddsRequest.setResultEncoding(encodingType); + assertEquals(encodingType, ddsRequest.getResultEncoding()); + } + + @Test + public void testHashCode() { + int hashCode1, hashCode2; + DdsRequest ddsRequest2 = new DdsRequest(); + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + + ddsRequest2.setResultEncoding("hex"); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertNotEquals(hashCode1, hashCode2); + + ddsRequest.setResultEncoding("hex"); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + + ddsRequest2.setDialogID(156); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertNotEquals(hashCode1, hashCode2); + + ddsRequest.setDialogID(156); + + hashCode1 = ddsRequest.hashCode(); + hashCode2 = ddsRequest2.hashCode(); + assertEquals(hashCode1, hashCode2); + } + + @Test + public void testEquals() { + EncodeType encodeType = EncodeType.HEX; + DdsRequest ddsRequest2 = new DdsRequest(); + assertTrue(ddsRequest.equals(ddsRequest2)); + + ddsRequest2.setResultEncoding(encodeType.name()); + assertFalse(ddsRequest.equals(ddsRequest2)); + + ddsRequest.setResultEncoding(encodeType.name()); + assertTrue(ddsRequest.equals(ddsRequest2)); + + ddsRequest2.setDialogID(156); + assertFalse(ddsRequest.equals(ddsRequest2)); + + ddsRequest.setDialogID(156); + assertTrue(ddsRequest.equals(ddsRequest2)); + assertTrue(ddsRequest.equals(ddsRequest)); + + ddsRequest2.setResultEncoding(EncodeType.BASE64.name()); + assertFalse(ddsRequest.equals(ddsRequest2)); + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java index d743b10dc..d6f0ed2e7 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageDecoderTest.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.DecodeException; -import org.junit.Test; - -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessageDecoderTest { - - @Test - public void testGetResponseTag() { - assertEquals(StatusTag.CLOSED, DdsStatusMessageDecoder.getResponseTag("CLOSED")); - assertEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("DEPOSITED")); - assertNotEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("OPENED")); - assertNull(DdsStatusMessageDecoder.getResponseTag("WRONT_TAG")); - } - - @Test - public void testParseFullMsg() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - String msg = "DEPOSITED:1"; - String[] msgs = ddsStatusMessageDecoder.parseFullMsg(msg); - assertEquals("DEPOSITED", msgs[0]); - assertEquals("1", msgs[1]); - } - - @Test - public void testWillDecode() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - assertFalse(ddsStatusMessageDecoder.willDecode("DEPOSITED:1")); - assertTrue(ddsStatusMessageDecoder.willDecode("START:1")); - } - - @Test - public void testDecode() { - DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); - DdsMessage ddsMessage; - try { - ddsMessage = ddsStatusMessageDecoder.decode("DEPOSITED:1"); - String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("CONNECTED:testConnectionDetail"); - expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); - expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("STOP:recordCount=2"); - expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = ddsStatusMessageDecoder.decode("ERROR:sampleError"); - expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - } catch (DecodeException e) { - e.printStackTrace(); - } - } -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.DecodeException; +import org.junit.Test; + +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessageDecoderTest { + + @Test + public void testGetResponseTag() { + assertEquals(StatusTag.CLOSED, DdsStatusMessageDecoder.getResponseTag("CLOSED")); + assertEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("DEPOSITED")); + assertNotEquals(StatusTag.DEPOSITED, DdsStatusMessageDecoder.getResponseTag("OPENED")); + assertNull(DdsStatusMessageDecoder.getResponseTag("WRONT_TAG")); + } + + @Test + public void testParseFullMsg() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + String msg = "DEPOSITED:1"; + String[] msgs = ddsStatusMessageDecoder.parseFullMsg(msg); + assertEquals("DEPOSITED", msgs[0]); + assertEquals("1", msgs[1]); + } + + @Test + public void testWillDecode() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + assertFalse(ddsStatusMessageDecoder.willDecode("DEPOSITED:1")); + assertTrue(ddsStatusMessageDecoder.willDecode("START:1")); + } + + @Test + public void testDecode() { + DdsStatusMessageDecoder ddsStatusMessageDecoder = new DdsStatusMessageDecoder(); + DdsMessage ddsMessage; + try { + ddsMessage = ddsStatusMessageDecoder.decode("DEPOSITED:1"); + String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("CONNECTED:testConnectionDetail"); + expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); + expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("STOP:recordCount=2"); + expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = ddsStatusMessageDecoder.decode("ERROR:sampleError"); + expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + } catch (DecodeException e) { + e.printStackTrace(); + } + } +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java index bbf2c39bb..b062e9c87 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DdsStatusMessageTest.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -import mockit.Mocked; -import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; -import us.dot.its.jpo.ode.model.StatusTag; - -public class DdsStatusMessageTest { - - private static final String UPER = "UPER"; - - @Test - public void testConstructor1() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - - assertNull(ddsStatusMessage.getTag()); - assertNull(ddsStatusMessage.getEncoding()); - assertNull(ddsStatusMessage.getDialog()); - } - - @Test - public void testConstructor2(@Mocked StatusTag tag, @Mocked Dialog dialog) { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, UPER, dialog); - assertEquals(ddsStatusMessage.getTag(), tag); - assertEquals(UPER, ddsStatusMessage.getEncoding()); - assertEquals(ddsStatusMessage.getDialog(), dialog); - - ddsStatusMessage.setTag(null); - ddsStatusMessage.setDialog(null); - ddsStatusMessage.setEncoding(null); - - assertNull(ddsStatusMessage.getTag()); - assertNull(ddsStatusMessage.getEncoding()); - assertNull(ddsStatusMessage.getDialog()); - } - - - @Test - public void testRecordCount() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - assertEquals(0, ddsStatusMessage.getRecordCount()); - ddsStatusMessage.setRecordCount(5); - assertEquals(5, ddsStatusMessage.getRecordCount()); - } - - @Test - public void testConnectionDetails() { - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); - assertEquals(null, ddsStatusMessage.getConnectionDetails()); - ddsStatusMessage.setConnectionDetails("testConnectionString"); - assertEquals("testConnectionString", ddsStatusMessage.getConnectionDetails()); - } - - @Test - public void testToString() { - StatusTag tag = StatusTag.CONNECTED; - String encoding = "hex"; - Dialog dialog = Dialog.ASD; - long recordCount = 3; - String connectionDetails = "testConnectionString"; - DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, encoding, dialog); - ddsStatusMessage.setConnectionDetails(connectionDetails); - ddsStatusMessage.setRecordCount(recordCount); - String ddsStatusMessageString = "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" - + recordCount + ", connectionDetails=" + connectionDetails + "]"; - assertEquals(ddsStatusMessageString, ddsStatusMessage.toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import mockit.Mocked; +import us.dot.its.jpo.ode.dds.DdsRequest.Dialog; +import us.dot.its.jpo.ode.model.StatusTag; + +public class DdsStatusMessageTest { + + private static final String UPER = "UPER"; + + @Test + public void testConstructor1() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + + assertNull(ddsStatusMessage.getTag()); + assertNull(ddsStatusMessage.getEncoding()); + assertNull(ddsStatusMessage.getDialog()); + } + + @Test + public void testConstructor2(@Mocked StatusTag tag, @Mocked Dialog dialog) { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, UPER, dialog); + assertEquals(ddsStatusMessage.getTag(), tag); + assertEquals(UPER, ddsStatusMessage.getEncoding()); + assertEquals(ddsStatusMessage.getDialog(), dialog); + + ddsStatusMessage.setTag(null); + ddsStatusMessage.setDialog(null); + ddsStatusMessage.setEncoding(null); + + assertNull(ddsStatusMessage.getTag()); + assertNull(ddsStatusMessage.getEncoding()); + assertNull(ddsStatusMessage.getDialog()); + } + + + @Test + public void testRecordCount() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + assertEquals(0, ddsStatusMessage.getRecordCount()); + ddsStatusMessage.setRecordCount(5); + assertEquals(5, ddsStatusMessage.getRecordCount()); + } + + @Test + public void testConnectionDetails() { + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(); + assertEquals(null, ddsStatusMessage.getConnectionDetails()); + ddsStatusMessage.setConnectionDetails("testConnectionString"); + assertEquals("testConnectionString", ddsStatusMessage.getConnectionDetails()); + } + + @Test + public void testToString() { + StatusTag tag = StatusTag.CONNECTED; + String encoding = "hex"; + Dialog dialog = Dialog.ASD; + long recordCount = 3; + String connectionDetails = "testConnectionString"; + DdsStatusMessage ddsStatusMessage = new DdsStatusMessage(tag, encoding, dialog); + ddsStatusMessage.setConnectionDetails(connectionDetails); + ddsStatusMessage.setRecordCount(recordCount); + String ddsStatusMessageString = "DdsStatusMessage [tag=" + tag + ", encoding=" + encoding + ", dialog=" + dialog + ", recordCount=" + + recordCount + ", connectionDetails=" + connectionDetails + "]"; + assertEquals(ddsStatusMessageString, ddsStatusMessage.toString()); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java index d3bf02796..845ad213c 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/DepositResponseDecoderTest.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.DecodeException; -import org.junit.Test; - -public class DepositResponseDecoderTest { - - @Test - public void testWillDecode() { - DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); - assertTrue(depositResponseDecoder.willDecode("Any String")); - assertTrue(depositResponseDecoder.willDecode("Always returns true")); - } - - @Test - public void testDecode() { - DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); - DdsMessage ddsMessage; - try { - ddsMessage = depositResponseDecoder.decode("DEPOSITED:1"); - String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("CONNECTED:testConnectionDetail"); - expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); - expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("STOP:recordCount=2"); - expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - ddsMessage = depositResponseDecoder.decode("ERROR:sampleError"); - expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; - assertEquals(ddsMessage.toString(), expectedDdsMessage); - - } catch (DecodeException e) { - e.printStackTrace(); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.DecodeException; +import org.junit.Test; + +public class DepositResponseDecoderTest { + + @Test + public void testWillDecode() { + DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); + assertTrue(depositResponseDecoder.willDecode("Any String")); + assertTrue(depositResponseDecoder.willDecode("Always returns true")); + } + + @Test + public void testDecode() { + DepositResponseDecoder depositResponseDecoder = new DepositResponseDecoder(); + DdsMessage ddsMessage; + try { + ddsMessage = depositResponseDecoder.decode("DEPOSITED:1"); + String expectedDdsMessage = "DdsStatusMessage [tag=DEPOSITED, encoding=null, dialog=null, recordCount=1, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("CONNECTED:testConnectionDetail"); + expectedDdsMessage = "DdsStatusMessage [tag=CONNECTED, encoding=null, dialog=null, recordCount=0, connectionDetails=testConnectionDetail]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("START:{\"dialogID\":156, \"resultEncoding\":\"hex\"}"); + expectedDdsMessage = "DdsStatusMessage [tag=START, encoding=hex, dialog=ASD, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("STOP:recordCount=2"); + expectedDdsMessage = "DdsStatusMessage [tag=STOP, encoding=null, dialog=null, recordCount=2, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + ddsMessage = depositResponseDecoder.decode("ERROR:sampleError"); + expectedDdsMessage = "DdsStatusMessage [tag=ERROR, encoding=null, dialog=null, recordCount=0, connectionDetails=null]"; + assertEquals(ddsMessage.toString(), expectedDdsMessage); + + } catch (DecodeException e) { + e.printStackTrace(); + } + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java index c01ec286e..9462cde8f 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/dds/StatusMessageHandlerTest.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.dds; - -import static org.junit.Assert.*; - -import javax.websocket.CloseReason; -import javax.websocket.Session; - -import org.junit.Test; - -import ch.qos.logback.classic.Logger; -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import us.dot.its.jpo.ode.model.OdeControlData; -import us.dot.its.jpo.ode.model.OdeStatus; -import us.dot.its.jpo.ode.model.StatusTag; -import us.dot.its.jpo.ode.wrapper.WebSocketClient; - -public class StatusMessageHandlerTest { - - @Mocked - WebSocketClient mockWebSocketClient; - - @Test - public void testOnMessage(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger) { - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onMessage(statusMsg); - - new Verifications() { - { - new OdeControlData(statusMsg); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnMessageException(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger) { - Exception e = new Exception(); - new Expectations() { - { - new OdeControlData(statusMsg); - result = e; - } - }; - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onMessage(statusMsg); - - new Verifications() { - { - logger.error("Error handling ControlMessage. ", e); - } - }; - } - - @Test - public void testOnClose(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onClose(session, reason); - - new Verifications() { - { - new OdeControlData(StatusTag.CLOSED); - controlData.setMessage(anyString); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnOpen(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onOpen(session, null); - - new Verifications() { - { - new OdeControlData(StatusTag.OPENED); - controlData.setMessage("WebSocket Connection to DDS Opened."); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void testOnError(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, - @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { - - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - statusMessageHandler.onError(session, new Throwable()); - - new Verifications() { - { - new OdeControlData(StatusTag.ERROR); - controlData.setMessage(anyString); - logger.info(controlData.toJson(false)); - } - }; - } - - @Test - public void buildOdeMessage(@Mocked DdsStatusMessage message) { - StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); - OdeStatus status = (OdeStatus) statusMessageHandler.buildOdeMessage(message); - - assertEquals(status.getMessage(), message.toString()); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.dds; + +import static org.junit.Assert.*; + +import javax.websocket.CloseReason; +import javax.websocket.Session; + +import org.junit.Test; + +import ch.qos.logback.classic.Logger; +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import us.dot.its.jpo.ode.model.OdeControlData; +import us.dot.its.jpo.ode.model.OdeStatus; +import us.dot.its.jpo.ode.model.StatusTag; +import us.dot.its.jpo.ode.wrapper.WebSocketClient; + +public class StatusMessageHandlerTest { + + @Mocked + WebSocketClient mockWebSocketClient; + + @Test + public void testOnMessage(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger) { + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onMessage(statusMsg); + + new Verifications() { + { + new OdeControlData(statusMsg); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnMessageException(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger) { + Exception e = new Exception(); + new Expectations() { + { + new OdeControlData(statusMsg); + result = e; + } + }; + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onMessage(statusMsg); + + new Verifications() { + { + logger.error("Error handling ControlMessage. ", e); + } + }; + } + + @Test + public void testOnClose(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onClose(session, reason); + + new Verifications() { + { + new OdeControlData(StatusTag.CLOSED); + controlData.setMessage(anyString); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnOpen(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onOpen(session, null); + + new Verifications() { + { + new OdeControlData(StatusTag.OPENED); + controlData.setMessage("WebSocket Connection to DDS Opened."); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void testOnError(@Mocked DdsStatusMessage statusMsg, @Mocked OdeControlData controlData, + @Mocked final Logger logger, @Mocked Session session, @Mocked CloseReason reason) { + + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + statusMessageHandler.onError(session, new Throwable()); + + new Verifications() { + { + new OdeControlData(StatusTag.ERROR); + controlData.setMessage(anyString); + logger.info(controlData.toJson(false)); + } + }; + } + + @Test + public void buildOdeMessage(@Mocked DdsStatusMessage message) { + StatusMessageHandler statusMessageHandler = new StatusMessageHandler(mockWebSocketClient); + OdeStatus status = (OdeStatus) statusMessageHandler.buildOdeMessage(message); + + assertEquals(status.getMessage(), message.toString()); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java index 4193d72b9..30b6a3f03 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/model/SerialIdTest.java @@ -1,236 +1,236 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.node.ObjectNode; - -import us.dot.its.jpo.ode.util.JsonUtils; - -public class SerialIdTest { - - @Test - public void testNoArgConstructor() { - SerialId testSerialId = new SerialId(); - - assertNotNull(testSerialId.getStreamId()); - } - - @Test - public void testFourArgConstructorNullStreamId() { - // streamId = null - // bundleSize = 3 - // bundleId = 6L - // recordId = 12 - SerialId testSerialId = new SerialId(null, 3, 6L, 12); - - assertNotNull(testSerialId.getStreamId()); - assertTrue(testSerialId.getStreamId().endsWith("_null")); - assertEquals(3, testSerialId.getBundleSize()); // bundle size = bundle size - assertEquals(10L, testSerialId.getBundleId()); // bundle id = bundle id + (record id / bundle size) = 6L + ( 12 / - // 3) = 10L - assertEquals(0, testSerialId.getRecordId()); // record id = record id % bundle size = 12 % 3 = 0 - assertEquals(30L, testSerialId.getSerialNumber()); // serial number = (bundle id * bundle size) + record id = (6L - // * 3) + 12 = 30L - } - - @Test - public void testFourArgConstructorWithStreamId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - - assertEquals("bob_3.10.0#30", testSerialId.toString()); - } - - @Test - public void testSingleArgConstructor() throws Exception { - SerialId testSerialId = new SerialId("bob_3.10.0#30"); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - } - - @Test - public void testSingleArgConstructorInvalidSerialId() { - try { - new SerialId("bob_3.10.0"); - fail("Expected Exception for invalid length"); - } catch (Exception e) { - assertEquals("Invalid serialId! Expected length 5 but was 4", e.getMessage()); - } - } - - @Test - public void testFiveArgConstructor() { - SerialId testSerialId = new SerialId("allison", 6, 12L, 24, 15); - - assertEquals("allison", testSerialId.getStreamId()); - assertEquals(6, testSerialId.getBundleSize()); - assertEquals(12L, testSerialId.getBundleId()); - assertEquals(24, testSerialId.getRecordId()); - assertEquals(15L, testSerialId.getSerialNumber()); - - assertEquals("allison_6.12.24#15", testSerialId.toString()); - } - - @Test - public void testJsonNodeConstructor() { - ObjectNode testNode = JsonUtils.newNode(); - JsonUtils.addNode(testNode, "streamId", "bob"); - JsonUtils.addNode(testNode, "bundleSize", 3); - JsonUtils.addNode(testNode, "bundleId", 10); - JsonUtils.addNode(testNode, "recordId", 0); - JsonUtils.addNode(testNode, "serialNumber", 30); - - SerialId testSerialId = new SerialId(testNode); - - assertEquals("bob", testSerialId.getStreamId()); - assertEquals(3, testSerialId.getBundleSize()); - assertEquals(10L, testSerialId.getBundleId()); - assertEquals(0, testSerialId.getRecordId()); - assertEquals(30L, testSerialId.getSerialNumber()); - - assertEquals("bob_3.10.0#30", testSerialId.toString()); - } - - @Test - public void testNextRecordId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals(1, testSerialId.nextRecordId()); // nextRecordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 - } - - @Test - public void testNextSerialNumber() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - assertEquals(31L, testSerialId.nextSerialNumber()); // nextSerialNumber = nextSerialNumber + 1 - } - - @Test - public void testNextSerialId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - - // nextSerialId: - // bundleId = bundleId + ((recordId + 1) / bundleSize) = 10 + ((0 + 1) / 3) = 10 - // recordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 - - SerialId nextSerialId = testSerialId.nextSerialId(); - - assertEquals(10L, nextSerialId.getBundleId()); - assertEquals(1, nextSerialId.getRecordId()); - } - - @Test - public void testIsRightAfter() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); - - assertTrue(testSerialId1.isRightAfter(testSerialId0)); - assertFalse(testSerialId0.isRightAfter(testSerialId1)); - } - - @Test - public void testIsRightBefore() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); - - assertTrue(testSerialId0.isRightBefore(testSerialId1)); - assertFalse(testSerialId1.isRightBefore(testSerialId0)); - } - - @Test - public void testAddBundleId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - testSerialId.addBundleId(5L); - - assertEquals(15L, testSerialId.getBundleId()); - } - - @Test - public void testAddRecordId() { - SerialId testSerialId = new SerialId("bob", 3, 6L, 12); - testSerialId.addRecordId(7); - - assertEquals(7, testSerialId.getRecordId()); - } - - @Test - public void testHashCode() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId2 = new SerialId("bob", 3, 6L, 16); - - assertEquals(testSerialId0.hashCode(), testSerialId1.hashCode()); - assertNotEquals(testSerialId0.hashCode(), testSerialId2.hashCode()); - - testSerialId2.setStreamId(null); - assertNotEquals(testSerialId1.hashCode(), testSerialId2.hashCode()); - } - - @Test - public void testEquals() { - SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); - SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); - - assertTrue(testSerialId0.equals(testSerialId0)); - assertFalse(testSerialId0.equals(null)); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleId(7L); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleId(10L); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleSize(7); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setBundleSize(3); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setRecordId(1); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId1.setRecordId(0); - - assertTrue(testSerialId0.equals(testSerialId1)); - testSerialId1.setStreamId(null); - assertFalse(testSerialId0.equals(testSerialId1)); - testSerialId0.setStreamId(null); - assertTrue(testSerialId0.equals(testSerialId1)); - - testSerialId0.setStreamId("bob"); - assertFalse(testSerialId1.equals(testSerialId0)); - - testSerialId1.setStreamId("allison"); - assertFalse(testSerialId0.equals(testSerialId1)); - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +import us.dot.its.jpo.ode.util.JsonUtils; + +public class SerialIdTest { + + @Test + public void testNoArgConstructor() { + SerialId testSerialId = new SerialId(); + + assertNotNull(testSerialId.getStreamId()); + } + + @Test + public void testFourArgConstructorNullStreamId() { + // streamId = null + // bundleSize = 3 + // bundleId = 6L + // recordId = 12 + SerialId testSerialId = new SerialId(null, 3, 6L, 12); + + assertNotNull(testSerialId.getStreamId()); + assertTrue(testSerialId.getStreamId().endsWith("_null")); + assertEquals(3, testSerialId.getBundleSize()); // bundle size = bundle size + assertEquals(10L, testSerialId.getBundleId()); // bundle id = bundle id + (record id / bundle size) = 6L + ( 12 / + // 3) = 10L + assertEquals(0, testSerialId.getRecordId()); // record id = record id % bundle size = 12 % 3 = 0 + assertEquals(30L, testSerialId.getSerialNumber()); // serial number = (bundle id * bundle size) + record id = (6L + // * 3) + 12 = 30L + } + + @Test + public void testFourArgConstructorWithStreamId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + + assertEquals("bob_3.10.0#30", testSerialId.toString()); + } + + @Test + public void testSingleArgConstructor() throws Exception { + SerialId testSerialId = new SerialId("bob_3.10.0#30"); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + } + + @Test + public void testSingleArgConstructorInvalidSerialId() { + try { + new SerialId("bob_3.10.0"); + fail("Expected Exception for invalid length"); + } catch (Exception e) { + assertEquals("Invalid serialId! Expected length 5 but was 4", e.getMessage()); + } + } + + @Test + public void testFiveArgConstructor() { + SerialId testSerialId = new SerialId("allison", 6, 12L, 24, 15); + + assertEquals("allison", testSerialId.getStreamId()); + assertEquals(6, testSerialId.getBundleSize()); + assertEquals(12L, testSerialId.getBundleId()); + assertEquals(24, testSerialId.getRecordId()); + assertEquals(15L, testSerialId.getSerialNumber()); + + assertEquals("allison_6.12.24#15", testSerialId.toString()); + } + + @Test + public void testJsonNodeConstructor() { + ObjectNode testNode = JsonUtils.newNode(); + JsonUtils.addNode(testNode, "streamId", "bob"); + JsonUtils.addNode(testNode, "bundleSize", 3); + JsonUtils.addNode(testNode, "bundleId", 10); + JsonUtils.addNode(testNode, "recordId", 0); + JsonUtils.addNode(testNode, "serialNumber", 30); + + SerialId testSerialId = new SerialId(testNode); + + assertEquals("bob", testSerialId.getStreamId()); + assertEquals(3, testSerialId.getBundleSize()); + assertEquals(10L, testSerialId.getBundleId()); + assertEquals(0, testSerialId.getRecordId()); + assertEquals(30L, testSerialId.getSerialNumber()); + + assertEquals("bob_3.10.0#30", testSerialId.toString()); + } + + @Test + public void testNextRecordId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals(1, testSerialId.nextRecordId()); // nextRecordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 + } + + @Test + public void testNextSerialNumber() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + assertEquals(31L, testSerialId.nextSerialNumber()); // nextSerialNumber = nextSerialNumber + 1 + } + + @Test + public void testNextSerialId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + + // nextSerialId: + // bundleId = bundleId + ((recordId + 1) / bundleSize) = 10 + ((0 + 1) / 3) = 10 + // recordId = (recordId + 1) % bundleSize = (0 + 1) % 3 = 1 + + SerialId nextSerialId = testSerialId.nextSerialId(); + + assertEquals(10L, nextSerialId.getBundleId()); + assertEquals(1, nextSerialId.getRecordId()); + } + + @Test + public void testIsRightAfter() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); + + assertTrue(testSerialId1.isRightAfter(testSerialId0)); + assertFalse(testSerialId0.isRightAfter(testSerialId1)); + } + + @Test + public void testIsRightBefore() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 13); + + assertTrue(testSerialId0.isRightBefore(testSerialId1)); + assertFalse(testSerialId1.isRightBefore(testSerialId0)); + } + + @Test + public void testAddBundleId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + testSerialId.addBundleId(5L); + + assertEquals(15L, testSerialId.getBundleId()); + } + + @Test + public void testAddRecordId() { + SerialId testSerialId = new SerialId("bob", 3, 6L, 12); + testSerialId.addRecordId(7); + + assertEquals(7, testSerialId.getRecordId()); + } + + @Test + public void testHashCode() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId2 = new SerialId("bob", 3, 6L, 16); + + assertEquals(testSerialId0.hashCode(), testSerialId1.hashCode()); + assertNotEquals(testSerialId0.hashCode(), testSerialId2.hashCode()); + + testSerialId2.setStreamId(null); + assertNotEquals(testSerialId1.hashCode(), testSerialId2.hashCode()); + } + + @Test + public void testEquals() { + SerialId testSerialId0 = new SerialId("bob", 3, 6L, 12); + SerialId testSerialId1 = new SerialId("bob", 3, 6L, 12); + + assertTrue(testSerialId0.equals(testSerialId0)); + assertFalse(testSerialId0.equals(null)); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleId(7L); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleId(10L); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleSize(7); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setBundleSize(3); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setRecordId(1); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId1.setRecordId(0); + + assertTrue(testSerialId0.equals(testSerialId1)); + testSerialId1.setStreamId(null); + assertFalse(testSerialId0.equals(testSerialId1)); + testSerialId0.setStreamId(null); + assertTrue(testSerialId0.equals(testSerialId1)); + + testSerialId0.setStreamId("bob"); + assertFalse(testSerialId1.equals(testSerialId0)); + + testSerialId1.setStreamId("allison"); + assertFalse(testSerialId0.equals(testSerialId1)); + } + +} diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java index e329df51a..c62e0eb74 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/snmp/SNMPTest.java @@ -74,6 +74,6 @@ public void testGettersAndSetters() { @Test public void testSnmpTimestampFromIso() throws ParseException { String snmpTS = SNMP.snmpTimestampFromIso("2017-05-04T21:55:00-05:00"); - assertEquals("07E105041537", snmpTS); + assertEquals("050414111537", snmpTS); } } diff --git a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java index 6544f2ad0..7a564eb73 100644 --- a/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java +++ b/jpo-ode-core/src/test/java/us/dot/its/jpo/ode/wrapper/SSLBuilderTest.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright 2018 572682 - * - * Licensed 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 us.dot.its.jpo.ode.wrapper; - -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.KeyStore; - -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; -import org.junit.Test; -import org.junit.runner.RunWith; - -import mockit.Expectations; -import mockit.Mocked; -import mockit.integration.junit4.JMockit; - -@RunWith(JMockit.class) -public class SSLBuilderTest { - - @Mocked - KeyStore keystore; - - @Mocked - SSLContexts sslContexts; - - @Mocked - TrustSelfSignedStrategy trustSelfSignedStrategy; - - @Test - public void testBuildSSLContext() { - try { - final InputStream keystoreFile = - new ByteArrayInputStream("keystoreFile".getBytes()); - final String keystorePass = "keystorePass"; - - {// BEGIN test custom SSLConext - new Expectations() {{ - KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, keystorePass.toCharArray()); - SSLContexts.custom() - .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) - .build(); - }}; - - - SSLBuilder.buildSSLContext(keystoreFile, keystorePass); - -// new Verifications() {{ -// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; -// keystore.load(keystoreFile, keystorePass.toCharArray()); times = 1; -// SSLContexts.custom() -// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) -// .build(); times = 1; -// }}; - } // END test normal path - - {// BEGIN test default SSLContext - new Expectations() {{ - SSLContexts.createDefault(); - }}; - - SSLBuilder.buildSSLContext(null, keystorePass); - -// new Verifications() {{ -// SSLContexts.createDefault(); times = 1; -// }}; - }// END test default path - - {// BEGIN test null password - new Expectations() {{ - KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, "".toCharArray()); - SSLContexts.custom() - .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) - .build(); - }}; - - SSLBuilder.buildSSLContext(keystoreFile, null); - -// new Verifications() {{ -// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; -// keystore.load(keystoreFile, "".toCharArray()); times = 1; -// SSLContexts.custom() -// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) -// .build(); times = 1; -// }}; - }// END test null password - - } catch (Exception e) { - fail(e.toString()); - } - } - -} +/******************************************************************************* + * Copyright 2018 572682 + * + * Licensed 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 us.dot.its.jpo.ode.wrapper; + +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.security.KeyStore; + +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; + +@RunWith(JMockit.class) +public class SSLBuilderTest { + + @Mocked + KeyStore keystore; + + @Mocked + SSLContexts sslContexts; + + @Mocked + TrustSelfSignedStrategy trustSelfSignedStrategy; + + @Test + public void testBuildSSLContext() { + try { + final InputStream keystoreFile = + new ByteArrayInputStream("keystoreFile".getBytes()); + final String keystorePass = "keystorePass"; + + {// BEGIN test custom SSLConext + new Expectations() {{ + KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(keystoreFile, keystorePass.toCharArray()); + SSLContexts.custom() + .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) + .build(); + }}; + + + SSLBuilder.buildSSLContext(keystoreFile, keystorePass); + +// new Verifications() {{ +// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; +// keystore.load(keystoreFile, keystorePass.toCharArray()); times = 1; +// SSLContexts.custom() +// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) +// .build(); times = 1; +// }}; + } // END test normal path + + {// BEGIN test default SSLContext + new Expectations() {{ + SSLContexts.createDefault(); + }}; + + SSLBuilder.buildSSLContext(null, keystorePass); + +// new Verifications() {{ +// SSLContexts.createDefault(); times = 1; +// }}; + }// END test default path + + {// BEGIN test null password + new Expectations() {{ + KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(keystoreFile, "".toCharArray()); + SSLContexts.custom() + .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) + .build(); + }}; + + SSLBuilder.buildSSLContext(keystoreFile, null); + +// new Verifications() {{ +// KeyStore.getInstance(KeyStore.getDefaultType()); times = 1; +// keystore.load(keystoreFile, "".toCharArray()); times = 1; +// SSLContexts.custom() +// .loadTrustMaterial(keystore, withAny(trustSelfSignedStrategy)) +// .build(); times = 1; +// }}; + }// END test null password + + } catch (Exception e) { + fail(e.toString()); + } + } + +} diff --git a/jpo-ode-core/src/test/resources/CVMessages/.gitignore b/jpo-ode-core/src/test/resources/CVMessages/.gitignore index b835b6985..153e27add 100644 --- a/jpo-ode-core/src/test/resources/CVMessages/.gitignore +++ b/jpo-ode-core/src/test/resources/CVMessages/.gitignore @@ -1 +1 @@ -/VehicleSituationDataServiceResponse.uper +/VehicleSituationDataServiceResponse.uper diff --git a/jpo-ode-core/src/test/resources/logback-test.xml b/jpo-ode-core/src/test/resources/logback-test.xml index de5097a2d..a7a69c483 100644 --- a/jpo-ode-core/src/test/resources/logback-test.xml +++ b/jpo-ode-core/src/test/resources/logback-test.xml @@ -1,10 +1,10 @@ - - - - %msg%n - - - - - + + + + %msg%n + + + + + \ No newline at end of file diff --git a/jpo-ode-plugins/LICENSE-2.0.html b/jpo-ode-plugins/LICENSE-2.0.html index 16303d2c7..d1055c8ad 100644 --- a/jpo-ode-plugins/LICENSE-2.0.html +++ b/jpo-ode-plugins/LICENSE-2.0.html @@ -1,228 +1,228 @@ - - - - - - Apache License, Version 2.0 - - -
    - -

    Apache License
    - Version 2.0, January 2004
    - http://www.apache.org/licenses/

    -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND - DISTRIBUTION

    -

    1. - Definitions.

    -

    "License" shall mean the terms and conditions for use, - reproduction, and distribution as defined by Sections 1 through 9 - of this document.

    -

    "Licensor" shall mean the copyright owner or entity authorized - by the copyright owner that is granting the License.

    -

    "Legal Entity" shall mean the union of the acting entity and - all other entities that control, are controlled by, or are under - common control with that entity. For the purposes of this - definition, "control" means (i) the power, direct or indirect, to - cause the direction or management of such entity, whether by - contract or otherwise, or (ii) ownership of fifty percent (50%) - or more of the outstanding shares, or (iii) beneficial ownership - of such entity.

    -

    "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License.

    -

    "Source" form shall mean the preferred form for making - modifications, including but not limited to software source code, - documentation source, and configuration files.

    -

    "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types.

    -

    "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work (an - example is provided in the Appendix below).

    -

    "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and for - which the editorial revisions, annotations, elaborations, or - other modifications represent, as a whole, an original work of - authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely - link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof.

    -

    "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or - additions to that Work or Derivative Works thereof, that is - intentionally submitted to Licensor for inclusion in the Work by - the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the - purposes of this definition, "submitted" means any form of - electronic, verbal, or written communication sent to the Licensor - or its representatives, including but not limited to - communication on electronic mailing lists, source code control - systems, and issue tracking systems that are managed by, or on - behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is - conspicuously marked or otherwise designated in writing by the - copyright owner as "Not a Contribution."

    -

    "Contributor" shall mean Licensor and any individual or Legal - Entity on behalf of whom a Contribution has been received by - Licensor and subsequently incorporated within the Work.

    -

    2. Grant of - Copyright License. Subject to the terms and - conditions of this License, each Contributor hereby grants to You - a perpetual, worldwide, non-exclusive, no-charge, royalty-free, - irrevocable copyright license to reproduce, prepare Derivative - Works of, publicly display, publicly perform, sublicense, and - distribute the Work and such Derivative Works in Source or Object - form.

    -

    3. Grant of Patent - License. Subject to the terms and conditions of this - License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have - made, use, offer to sell, sell, import, and otherwise transfer - the Work, where such license applies only to those patent claims - licensable by such Contributor that are necessarily infringed by - their Contribution(s) alone or by combination of their - Contribution(s) with the Work to which such Contribution(s) was - submitted. If You institute patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging - that the Work or a Contribution incorporated within the Work - constitutes direct or contributory patent infringement, then any - patent licenses granted to You under this License for that Work - shall terminate as of the date such litigation is filed.

    -

    4. - Redistribution. You may reproduce and distribute - copies of the Work or Derivative Works thereof in any medium, - with or without modifications, and in Source or Object form, - provided that You meet the following conditions:

    -
      -
    1. You must give any other recipients of the Work or - Derivative Works a copy of this License; and
    2. -
    3. You must cause any modified files to carry prominent - notices stating that You changed the files; and
    4. -
    5. You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, excluding - those notices that do not pertain to any part of the Derivative - Works; and
    6. -
    7. If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute - must include a readable copy of the attribution notices - contained within such NOTICE file, excluding those notices that - do not pertain to any part of the Derivative Works, in at least - one of the following places: within a NOTICE text file - distributed as part of the Derivative Works; within the Source - form or documentation, if provided along with the Derivative - Works; or, within a display generated by the Derivative Works, - if and wherever such third-party notices normally appear. The - contents of the NOTICE file are for informational purposes only - and do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed as - modifying the License.
      -
      - You may add Your own copyright statement to Your modifications - and may provide additional or different license terms and - conditions for use, reproduction, or distribution of Your - modifications, or for any such Derivative Works as a whole, - provided Your use, reproduction, and distribution of the Work - otherwise complies with the conditions stated in this - License.
    8. -
    -

    5. - Submission of Contributions. Unless You explicitly - state otherwise, any Contribution intentionally submitted for - inclusion in the Work by You to the Licensor shall be under the - terms and conditions of this License, without any additional - terms or conditions. Notwithstanding the above, nothing herein - shall supersede or modify the terms of any separate license - agreement you may have executed with Licensor regarding such - Contributions.

    -

    6. - Trademarks. This License does not grant permission - to use the trade names, trademarks, service marks, or product - names of the Licensor, except as required for reasonable and - customary use in describing the origin of the Work and - reproducing the content of the NOTICE file.

    -

    7. Disclaimer - of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or - FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for - determining the appropriateness of using or redistributing the - Work and assume any risks associated with Your exercise of - permissions under this License.

    -

    8. Limitation - of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, - special, incidental, or consequential damages of any character - arising as a result of this License or out of the use or - inability to use the Work (including but not limited to damages - for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other commercial damages or losses), - even if such Contributor has been advised of the possibility of - such damages.

    -

    9. Accepting - Warranty or Additional Liability. While - redistributing the Work or Derivative Works thereof, You may - choose to offer, and charge a fee for, acceptance of support, - warranty, indemnity, or other liability obligations and/or rights - consistent with this License. However, in accepting such - obligations, You may act only on Your own behalf and on Your sole - responsibility, not on behalf of any other Contributor, and only - if You agree to indemnify, defend, and hold each Contributor - harmless for any liability incurred by, or claims asserted - against, such Contributor by reason of your accepting any such - warranty or additional liability.

    -

    END OF TERMS AND CONDITIONS

    -

    APPENDIX: How to apply the Apache License to your - work

    -

    To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a file - or class name and description of purpose be included on the same - "printed page" as the copyright notice for easier identification - within third-party archives.

    -
    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed 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.
    -    
    -
    -
    - - - + + + + + + Apache License, Version 2.0 + + +
    + +

    Apache License
    + Version 2.0, January 2004
    + http://www.apache.org/licenses/

    +

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND + DISTRIBUTION

    +

    1. + Definitions.

    +

    "License" shall mean the terms and conditions for use, + reproduction, and distribution as defined by Sections 1 through 9 + of this document.

    +

    "Licensor" shall mean the copyright owner or entity authorized + by the copyright owner that is granting the License.

    +

    "Legal Entity" shall mean the union of the acting entity and + all other entities that control, are controlled by, or are under + common control with that entity. For the purposes of this + definition, "control" means (i) the power, direct or indirect, to + cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) + or more of the outstanding shares, or (iii) beneficial ownership + of such entity.

    +

    "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License.

    +

    "Source" form shall mean the preferred form for making + modifications, including but not limited to software source code, + documentation source, and configuration files.

    +

    "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but not + limited to compiled object code, generated documentation, and + conversions to other media types.

    +

    "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work (an + example is provided in the Appendix below).

    +

    "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and for + which the editorial revisions, annotations, elaborations, or + other modifications represent, as a whole, an original work of + authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely + link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof.

    +

    "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or + additions to that Work or Derivative Works thereof, that is + intentionally submitted to Licensor for inclusion in the Work by + the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the + purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor + or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on + behalf of, the Licensor for the purpose of discussing and + improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the + copyright owner as "Not a Contribution."

    +

    "Contributor" shall mean Licensor and any individual or Legal + Entity on behalf of whom a Contribution has been received by + Licensor and subsequently incorporated within the Work.

    +

    2. Grant of + Copyright License. Subject to the terms and + conditions of this License, each Contributor hereby grants to You + a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative + Works of, publicly display, publicly perform, sublicense, and + distribute the Work and such Derivative Works in Source or Object + form.

    +

    3. Grant of Patent + License. Subject to the terms and conditions of this + License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims + licensable by such Contributor that are necessarily infringed by + their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging + that the Work or a Contribution incorporated within the Work + constitutes direct or contributory patent infringement, then any + patent licenses granted to You under this License for that Work + shall terminate as of the date such litigation is filed.

    +

    4. + Redistribution. You may reproduce and distribute + copies of the Work or Derivative Works thereof in any medium, + with or without modifications, and in Source or Object form, + provided that You meet the following conditions:

    +
      +
    1. You must give any other recipients of the Work or + Derivative Works a copy of this License; and
    2. +
    3. You must cause any modified files to carry prominent + notices stating that You changed the files; and
    4. +
    5. You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and
    6. +
    7. If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices that + do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source + form or documentation, if provided along with the Derivative + Works; or, within a display generated by the Derivative Works, + if and wherever such third-party notices normally appear. The + contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed as + modifying the License.
      +
      + You may add Your own copyright statement to Your modifications + and may provide additional or different license terms and + conditions for use, reproduction, or distribution of Your + modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work + otherwise complies with the conditions stated in this + License.
    8. +
    +

    5. + Submission of Contributions. Unless You explicitly + state otherwise, any Contribution intentionally submitted for + inclusion in the Work by You to the Licensor shall be under the + terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein + shall supersede or modify the terms of any separate license + agreement you may have executed with Licensor regarding such + Contributions.

    +

    6. + Trademarks. This License does not grant permission + to use the trade names, trademarks, service marks, or product + names of the Licensor, except as required for reasonable and + customary use in describing the origin of the Work and + reproducing the content of the NOTICE file.

    +

    7. Disclaimer + of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or + FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing the + Work and assume any risks associated with Your exercise of + permissions under this License.

    +

    8. Limitation + of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, + special, incidental, or consequential damages of any character + arising as a result of this License or out of the use or + inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or + malfunction, or any and all other commercial damages or losses), + even if such Contributor has been advised of the possibility of + such damages.

    +

    9. Accepting + Warranty or Additional Liability. While + redistributing the Work or Derivative Works thereof, You may + choose to offer, and charge a fee for, acceptance of support, + warranty, indemnity, or other liability obligations and/or rights + consistent with this License. However, in accepting such + obligations, You may act only on Your own behalf and on Your sole + responsibility, not on behalf of any other Contributor, and only + if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted + against, such Contributor by reason of your accepting any such + warranty or additional liability.

    +

    END OF TERMS AND CONDITIONS

    +

    APPENDIX: How to apply the Apache License to your + work

    +

    To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a file + or class name and description of purpose be included on the same + "printed page" as the copyright notice for easier identification + within third-party archives.

    +
    +
    Copyright [yyyy] [name of copyright owner]
    +
    +Licensed 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.
    +    
    +
    +
    + + + diff --git a/jpo-ode-plugins/pom.xml b/jpo-ode-plugins/pom.xml index f0cbfa9ff..b9997938d 100644 --- a/jpo-ode-plugins/pom.xml +++ b/jpo-ode-plugins/pom.xml @@ -11,7 +11,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT @@ -27,7 +27,7 @@ usdot.jpo.ode jpo-ode-common - 0.0.9-SNAPSHOT + 1.0.8-SNAPSHOT 1.4.1.11.3 = 4 - // rsuSRMTxChannel.3 = 3 - // --> 1.4.1.5.3 = 178 - // rsuSRMTxMode.3 = 1 - // --> 1.4.1.4.3 = 1 - // rsuSRMPsid.3 x "8300" - // --> 1.4.1.2.3 x "8300" - // rsuSRMDsrcMsgId.3 = 31 - // --> 1.4.1.3.3 = 31 - // rsuSRMTxInterval.3 = 1 - // --> 1.4.1.6.3 = 1 - // rsuSRMDeliveryStart.3 x "010114111530" - // --> 1.4.1.7.3 = "010114111530" - // rsuSRMDeliveryStop.3 x "010114130000" - // --> 1.4.1.8.3 = "010114130000" - // rsuSRMPayload.3 x "0EFF82445566778899000000AABBCCDDEEFF00E00EA0C12A00" - // --> 1.4.1.9.3 = "0EFF82445566778899000000AABBCCDDEEFF00E00EA0C12A00" - // rsuSRMEnable.3 = 1 - // --> 1.4.1.10.3 = 1 - ////////////////////////////// - - VariableBinding rsuSRMPsid = new VariableBinding(new OID("1.0.15628.4.1.4.1.2.".concat(Integer.toString(index))), new OctetString(DatatypeConverter.parseHexBinary(snmp.getRsuid()))); - VariableBinding rsuSRMDsrcMsgId = new VariableBinding(new OID("1.0.15628.4.1.4.1.3.".concat(Integer.toString(index))), new Integer32(snmp.getMsgid())); - VariableBinding rsuSRMTxMode = new VariableBinding(new OID("1.0.15628.4.1.4.1.4.".concat(Integer.toString(index))), new Integer32(snmp.getMode())); - VariableBinding rsuSRMTxChannel = new VariableBinding(new OID("1.0.15628.4.1.4.1.5.".concat(Integer.toString(index))), new Integer32(snmp.getChannel())); - VariableBinding rsuSRMTxInterval = new VariableBinding(new OID("1.0.15628.4.1.4.1.6.".concat(Integer.toString(index))), new Integer32(snmp.getInterval())); - VariableBinding rsuSRMDeliveryStart = new VariableBinding(new OID("1.0.15628.4.1.4.1.7.".concat(Integer.toString(index))), new OctetString(DatatypeConverter.parseHexBinary(SNMP.snmpTimestampFromIso(snmp.getDeliverystart())))); - VariableBinding rsuSRMDeliveryStop = new VariableBinding(new OID("1.0.15628.4.1.4.1.8.".concat(Integer.toString(index))), new OctetString(DatatypeConverter.parseHexBinary(SNMP.snmpTimestampFromIso(snmp.getDeliverystop())))); - VariableBinding rsuSRMPayload = new VariableBinding(new OID("1.0.15628.4.1.4.1.9.".concat(Integer.toString(index))), new OctetString(DatatypeConverter.parseHexBinary(payload))); - VariableBinding rsuSRMEnable = new VariableBinding(new OID("1.0.15628.4.1.4.1.10.".concat(Integer.toString(index))), new Integer32(snmp.getEnable())); - VariableBinding rsuSRMStatus = new VariableBinding(new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(index))), new Integer32(snmp.getStatus())); - - ScopedPDU pdu = new ScopedPDU(); - pdu.add(rsuSRMPsid); - pdu.add(rsuSRMDsrcMsgId); - pdu.add(rsuSRMTxMode); - pdu.add(rsuSRMTxChannel); - pdu.add(rsuSRMTxInterval); - pdu.add(rsuSRMDeliveryStart); - pdu.add(rsuSRMDeliveryStop); - pdu.add(rsuSRMPayload); - pdu.add(rsuSRMEnable); - if (verb == ServiceRequest.OdeInternal.RequestVerb.POST) { - pdu.add(rsuSRMStatus); - } - pdu.setType(PDU.SET); - - return pdu; - } -} + public static ScopedPDU createPDU(SNMP snmp, String payload, int index, RequestVerb verb) throws ParseException { + + ////////////////////////////// + // - OID examples - // + ////////////////////////////// + // rsuSRMStatus.3 = 4 + // --> 1.4.1.11.3 = 4 + // rsuSRMTxChannel.3 = 3 + // --> 1.4.1.5.3 = 178 + // rsuSRMTxMode.3 = 1 + // --> 1.4.1.4.3 = 1 + // rsuSRMPsid.3 x "8300" + // --> 1.4.1.2.3 x "8300" + // rsuSRMDsrcMsgId.3 = 31 + // --> 1.4.1.3.3 = 31 + // rsuSRMTxInterval.3 = 1 + // --> 1.4.1.6.3 = 1 + // rsuSRMDeliveryStart.3 x "010114111530" + // --> 1.4.1.7.3 = "010114111530" + // rsuSRMDeliveryStop.3 x "010114130000" + // --> 1.4.1.8.3 = "010114130000" + // rsuSRMPayload.3 x "0EFF82445566778899000000AABBCCDDEEFF00E00EA0C12A00" + // --> 1.4.1.9.3 = "0EFF82445566778899000000AABBCCDDEEFF00E00EA0C12A00" + // rsuSRMEnable.3 = 1 + // --> 1.4.1.10.3 = 1 + ////////////////////////////// + + VariableBinding rsuSRMPsid = SnmpSession.getPEncodedVariableBinding("1.0.15628.4.1.4.1.2.".concat(Integer.toString(index)), + snmp.getRsuid()); + VariableBinding rsuSRMDsrcMsgId = new VariableBinding( + new OID("1.0.15628.4.1.4.1.3.".concat(Integer.toString(index))), new Integer32(snmp.getMsgid())); + VariableBinding rsuSRMTxMode = new VariableBinding( + new OID("1.0.15628.4.1.4.1.4.".concat(Integer.toString(index))), new Integer32(snmp.getMode())); + VariableBinding rsuSRMTxChannel = new VariableBinding( + new OID("1.0.15628.4.1.4.1.5.".concat(Integer.toString(index))), new Integer32(snmp.getChannel())); + VariableBinding rsuSRMTxInterval = new VariableBinding( + new OID("1.0.15628.4.1.4.1.6.".concat(Integer.toString(index))), new Integer32(snmp.getInterval())); + VariableBinding rsuSRMDeliveryStart = new VariableBinding( + new OID("1.0.15628.4.1.4.1.7.".concat(Integer.toString(index))), + new OctetString(DatatypeConverter.parseHexBinary(SNMP.snmpTimestampFromIso(snmp.getDeliverystart())))); + VariableBinding rsuSRMDeliveryStop = new VariableBinding( + new OID("1.0.15628.4.1.4.1.8.".concat(Integer.toString(index))), + new OctetString(DatatypeConverter.parseHexBinary(SNMP.snmpTimestampFromIso(snmp.getDeliverystop())))); + VariableBinding rsuSRMPayload = new VariableBinding( + new OID("1.0.15628.4.1.4.1.9.".concat(Integer.toString(index))), + new OctetString(DatatypeConverter.parseHexBinary(payload))); + VariableBinding rsuSRMEnable = new VariableBinding( + new OID("1.0.15628.4.1.4.1.10.".concat(Integer.toString(index))), new Integer32(snmp.getEnable())); + VariableBinding rsuSRMStatus = new VariableBinding( + new OID("1.0.15628.4.1.4.1.11.".concat(Integer.toString(index))), new Integer32(snmp.getStatus())); + + ScopedPDU pdu = new ScopedPDU(); + pdu.add(rsuSRMPsid); + pdu.add(rsuSRMDsrcMsgId); + pdu.add(rsuSRMTxMode); + pdu.add(rsuSRMTxChannel); + pdu.add(rsuSRMTxInterval); + pdu.add(rsuSRMDeliveryStart); + pdu.add(rsuSRMDeliveryStop); + pdu.add(rsuSRMPayload); + pdu.add(rsuSRMEnable); + if (verb == ServiceRequest.OdeInternal.RequestVerb.POST) { + pdu.add(rsuSRMStatus); + } + pdu.setType(PDU.SET); + + return pdu; + } + + public static VariableBinding getPEncodedVariableBinding(String oid, String val) { + Integer intVal = Integer.parseInt(val, 16); + Integer additionValue = null; + + if (intVal >= 0 && intVal <= 127) { + // P = V + // here we must instantiate the OctetString directly with the hex string to avoid inadvertently creating the ASCII character codes + // for instance OctetString.fromString("20", 16) produces the space character (" ") rather than hex 20 + return new VariableBinding(new OID(oid), new OctetString(Integer.toHexString(intVal))); + } else if (intVal >= 128 && intVal <= 16511) { + // P = V + 0x7F80 + additionValue = 0x7F80; + } else if (intVal >= 016512 && intVal <= 2113663) { + // P = V + 0xBFBF80 + additionValue = 0xBFBF80; + } else if (intVal >= 2113664 && intVal <= 270549119) { + // P = V + 0xDFDFBF80 + additionValue = 0xDFDFBF80; + } + + if (additionValue != null) { + return new VariableBinding(new OID(oid), + OctetString.fromString(Integer.toHexString(intVal + additionValue), 16)); + } + return null; + } +} \ No newline at end of file diff --git a/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java b/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java index 79942d9c0..a6df840de 100644 --- a/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java +++ b/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java @@ -30,6 +30,7 @@ import org.snmp4j.TransportMapping; import org.snmp4j.UserTarget; import org.snmp4j.security.USM; +import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; import mockit.Expectations; @@ -43,8 +44,9 @@ public class SnmpSessionTest { RSU testProps; SnmpSession snmpSession; - @Injectable USM mockUSM; - + @Injectable + USM mockUSM; + @Before public void setUp() throws Exception { String testUsername = "testUser"; @@ -104,7 +106,7 @@ public void testGetSetMethods(@Mocked Snmp mockSnmp, @Mocked TransportMapping mo assertEquals(mockUserTarget, snmpSession.getTarget()); } - @Test(expected = IOException.class) + @Test(expected = IOException.class) public void testResponseEventUDPException(@Mocked Snmp mockSnmp, @Mocked TransportMapping mockTransportMapping, @Mocked UserTarget mockUserTarget, @Mocked PDU mockPDU) throws IOException { @@ -119,8 +121,8 @@ public void testResponseEventUDPException(@Mocked Snmp mockSnmp, @Mocked Transpo } @Test(expected = IOException.class) - public void testResponseEventSNMPException(@Mocked Snmp mockSnmp, - @Mocked UserTarget mockUserTarget, @Mocked PDU mockPDU) throws IOException { + public void testResponseEventSNMPException(@Mocked Snmp mockSnmp, @Mocked UserTarget mockUserTarget, + @Mocked PDU mockPDU) throws IOException { new Expectations() { { @@ -131,35 +133,51 @@ public void testResponseEventSNMPException(@Mocked Snmp mockSnmp, snmpSession.set(mockPDU, mockSnmp, mockUserTarget, false); } - @Test - public void shouldCreatePDU() throws ParseException { + @Test + public void shouldCreatePDU() throws ParseException { + + String expectedResult = "[1.0.15628.4.1.4.1.2.3 = 80:03, 1.0.15628.4.1.4.1.3.3 = 2, 1.0.15628.4.1.4.1.4.3 = 3, 1.0.15628.4.1.4.1.5.3 = 4, 1.0.15628.4.1.4.1.6.3 = 5, 1.0.15628.4.1.4.1.7.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.8.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.9.3 = 88, 1.0.15628.4.1.4.1.10.3 = 9, 1.0.15628.4.1.4.1.11.3 = 10]"; + String expectedResult2 = "[1.0.15628.4.1.4.1.2.3 = 80:03, 1.0.15628.4.1.4.1.3.3 = 2, 1.0.15628.4.1.4.1.4.3 = 3, 1.0.15628.4.1.4.1.5.3 = 4, 1.0.15628.4.1.4.1.6.3 = 5, 1.0.15628.4.1.4.1.7.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.8.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.9.3 = 88, 1.0.15628.4.1.4.1.10.3 = 9]"; - String expectedResult = "[1.0.15628.4.1.4.1.2.3 = 11, 1.0.15628.4.1.4.1.3.3 = 2, 1.0.15628.4.1.4.1.4.3 = 3, 1.0.15628.4.1.4.1.5.3 = 4, 1.0.15628.4.1.4.1.6.3 = 5, 1.0.15628.4.1.4.1.7.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.8.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.9.3 = 88, 1.0.15628.4.1.4.1.10.3 = 9, 1.0.15628.4.1.4.1.11.3 = 10]"; - String expectedResult2 = "[1.0.15628.4.1.4.1.2.3 = 11, 1.0.15628.4.1.4.1.3.3 = 2, 1.0.15628.4.1.4.1.4.3 = 3, 1.0.15628.4.1.4.1.5.3 = 4, 1.0.15628.4.1.4.1.6.3 = 5, 1.0.15628.4.1.4.1.7.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.8.3 = 07:e1:0c:02:11:2f, 1.0.15628.4.1.4.1.9.3 = 88, 1.0.15628.4.1.4.1.10.3 = 9]"; + String rsuSRMPsid = "00000083"; + int rsuSRMDsrcMsgId = 2; + int rsuSRMTxMode = 3; + int rsuSRMTxChannel = 4; + int rsuSRMTxInterval = 5; + String rsuSRMPayload = "88"; + int rsuSRMEnable = 9; + int rsuSRMStatus = 10; - - String rsuSRMPsid = "11"; - int rsuSRMDsrcMsgId = 2; - int rsuSRMTxMode = 3; - int rsuSRMTxChannel = 4; - int rsuSRMTxInterval = 5; - String rsuSRMPayload = "88"; - int rsuSRMEnable = 9; - int rsuSRMStatus = 10; + SNMP testParams = new SNMP(rsuSRMPsid, rsuSRMDsrcMsgId, rsuSRMTxMode, rsuSRMTxChannel, rsuSRMTxInterval, + "2017-12-02T17:47:11-05:00", "2017-12-02T17:47:11-05:00", rsuSRMEnable, rsuSRMStatus); - SNMP testParams = new SNMP( - rsuSRMPsid, rsuSRMDsrcMsgId, rsuSRMTxMode, rsuSRMTxChannel, - rsuSRMTxInterval, "2017-12-02T17:47:11-05:00", "2017-12-02T17:47:11-05:00", - rsuSRMEnable, rsuSRMStatus); + ScopedPDU result = SnmpSession.createPDU(testParams, rsuSRMPayload, 3, RequestVerb.POST); - ScopedPDU result = SnmpSession.createPDU(testParams, rsuSRMPayload, 3, RequestVerb.POST); + assertEquals("Incorrect type, expected PDU.SET (-93)", -93, result.getType()); + assertEquals(expectedResult, result.getVariableBindings().toString()); - assertEquals("Incorrect type, expected PDU.SET (-93)", -93, result.getType()); - assertEquals(expectedResult, result.getVariableBindings().toString()); + ScopedPDU result2 = SnmpSession.createPDU(testParams, rsuSRMPayload, 3, RequestVerb.GET); - ScopedPDU result2 = SnmpSession.createPDU(testParams, rsuSRMPayload, 3, RequestVerb.GET); + assertEquals("Incorrect type, expected PDU.SET (-93)", -93, result2.getType()); + assertEquals(expectedResult2, result2.getVariableBindings().toString()); + } - assertEquals("Incorrect type, expected PDU.SET (-93)", -93, result2.getType()); - assertEquals(expectedResult2, result2.getVariableBindings().toString()); - } -} + @Test + public void shouldProperlyPEncode(){ + String oid = "1.0.15628.4.1.4.1.2.3"; + String hex1="00000083"; + String hex2="00000020"; + String hex3="0020408E"; + String hex4 = "0020408F"; + + VariableBinding vb1 = SnmpSession.getPEncodedVariableBinding(oid, hex1); + VariableBinding vb2 = SnmpSession.getPEncodedVariableBinding(oid, hex2); + VariableBinding vb3 = SnmpSession.getPEncodedVariableBinding(oid, hex3); + VariableBinding vb4 = SnmpSession.getPEncodedVariableBinding(oid, hex4); + + assertEquals("P-Encoding failed for " + hex1,"80:03", vb1.toValueString()); + assertEquals("P-Encoding failed for " + hex2,"20", vb2.toValueString()); + assertEquals("P-Encoding failed for " + hex3,"e0:00:00:0e", vb3.toValueString()); + assertEquals("P-Encoding failed for " + hex4,"e0:00:00:0f", vb4.toValueString()); + } +} \ No newline at end of file From c7beceb4c38316359b9d0419596ae5428914439a Mon Sep 17 00:00:00 2001 From: "TRIHYDRO\\bpayne" Date: Wed, 31 Jul 2019 14:46:08 -0600 Subject: [PATCH 07/10] Unit test naming clarifications --- .../dot/its/jpo/ode/snmp/SnmpSessionTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java b/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java index a6df840de..23c3da503 100644 --- a/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java +++ b/jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/snmp/SnmpSessionTest.java @@ -165,19 +165,19 @@ public void shouldCreatePDU() throws ParseException { @Test public void shouldProperlyPEncode(){ String oid = "1.0.15628.4.1.4.1.2.3"; - String hex1="00000083"; - String hex2="00000020"; - String hex3="0020408E"; - String hex4 = "0020408F"; + String tim_hex="00000083"; + String bsm_hex="00000020"; + String data_log_transfer_hex="0020408E"; + String ota_update_hex = "0020408F"; - VariableBinding vb1 = SnmpSession.getPEncodedVariableBinding(oid, hex1); - VariableBinding vb2 = SnmpSession.getPEncodedVariableBinding(oid, hex2); - VariableBinding vb3 = SnmpSession.getPEncodedVariableBinding(oid, hex3); - VariableBinding vb4 = SnmpSession.getPEncodedVariableBinding(oid, hex4); + VariableBinding vb1 = SnmpSession.getPEncodedVariableBinding(oid, tim_hex); + VariableBinding vb2 = SnmpSession.getPEncodedVariableBinding(oid, bsm_hex); + VariableBinding vb3 = SnmpSession.getPEncodedVariableBinding(oid, data_log_transfer_hex); + VariableBinding vb4 = SnmpSession.getPEncodedVariableBinding(oid, ota_update_hex); - assertEquals("P-Encoding failed for " + hex1,"80:03", vb1.toValueString()); - assertEquals("P-Encoding failed for " + hex2,"20", vb2.toValueString()); - assertEquals("P-Encoding failed for " + hex3,"e0:00:00:0e", vb3.toValueString()); - assertEquals("P-Encoding failed for " + hex4,"e0:00:00:0f", vb4.toValueString()); + assertEquals("P-Encoding failed for " + tim_hex,"80:03", vb1.toValueString()); + assertEquals("P-Encoding failed for " + bsm_hex,"20", vb2.toValueString()); + assertEquals("P-Encoding failed for " + data_log_transfer_hex,"e0:00:00:0e", vb3.toValueString()); + assertEquals("P-Encoding failed for " + ota_update_hex,"e0:00:00:0f", vb4.toValueString()); } } \ No newline at end of file From b1a6cda6ed91f201cd312b02d837e5a39d71dfeb Mon Sep 17 00:00:00 2001 From: Brian Brotsos Date: Thu, 8 Aug 2019 14:35:35 -0400 Subject: [PATCH 08/10] Updated release files --- jpo-ode-common/pom.xml | 2 +- jpo-ode-core/pom.xml | 6 +++--- jpo-ode-plugins/pom.xml | 4 ++-- jpo-ode-svcs/pom.xml | 6 +++--- pom.xml | 4 ++-- release.properties | 40 ++++++++++++++++++++-------------------- 6 files changed, 31 insertions(+), 31 deletions(-) diff --git a/jpo-ode-common/pom.xml b/jpo-ode-common/pom.xml index 63e6af4ad..2de4c05a5 100644 --- a/jpo-ode-common/pom.xml +++ b/jpo-ode-common/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.9 jpo-ode-common diff --git a/jpo-ode-core/pom.xml b/jpo-ode-core/pom.xml index acfc39dd3..81c7ba65a 100644 --- a/jpo-ode-core/pom.xml +++ b/jpo-ode-core/pom.xml @@ -5,7 +5,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.9 jpo-ode-core @@ -23,12 +23,12 @@ usdot.jpo.ode jpo-ode-common - 0.0.9-SNAPSHOT + 1.0.9 usdot.jpo.ode jpo-ode-plugins - 0.0.9-SNAPSHOT + 1.0.9 org.apache.httpcomponents diff --git a/jpo-ode-plugins/pom.xml b/jpo-ode-plugins/pom.xml index f0cbfa9ff..12a31abbd 100644 --- a/jpo-ode-plugins/pom.xml +++ b/jpo-ode-plugins/pom.xml @@ -11,7 +11,7 @@ usdot.jpo.ode jpo-ode - 0.0.9-SNAPSHOT + 1.0.9 @@ -27,7 +27,7 @@ usdot.jpo.ode jpo-ode-common - 0.0.9-SNAPSHOT + 1.0.9 @@ -27,7 +27,7 @@ usdot.jpo.ode jpo-ode-common - 1.0.9 + 0.0.9-SNAPSHOT - src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java - src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java - src/main/java/us/dot/its/jpo/ode/util/* - src/main/java/us/dot/its/jpo/ode/inet/* - - - - - - org.json - json - - - com.google.code.gson - gson - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - - - javax.websocket - javax.websocket-client-api - 1.1 - - - com.esotericsoftware - kryo - 4.0.0 - - - + + + 4.0.0 + + + usdot.jpo.ode + jpo-ode + 1.0.9 + + + jpo-ode-common + jpo-ode-common + JPO ODE Common Components + jar + + + + src/main/java/us/dot/its/jpo/ode/util/GeoUtils.java + src/main/java/us/dot/its/jpo/ode/util/WebSocketUtils.java + src/main/java/us/dot/its/jpo/ode/util/* + src/main/java/us/dot/its/jpo/ode/inet/* + + + + + + org.json + json + + + com.google.code.gson + gson + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + javax.websocket + javax.websocket-client-api + 1.1 + + + com.esotericsoftware + kryo + 4.0.0 + + + diff --git a/jpo-ode-core/pom.xml b/jpo-ode-core/pom.xml index acfc39dd3..98749dea2 100644 --- a/jpo-ode-core/pom.xml +++ b/jpo-ode-core/pom.xml @@ -1,93 +1,93 @@ - - - 4.0.0 - - - usdot.jpo.ode - jpo-ode - 0.0.9-SNAPSHOT - - - jpo-ode-core - jpo-ode-core - JPO ODE Core Components - jar - - - - - src/main/java/us/dot/its/jpo/ode/dds/* - - - - - usdot.jpo.ode - jpo-ode-common - 0.0.9-SNAPSHOT - - - usdot.jpo.ode - jpo-ode-plugins - 0.0.9-SNAPSHOT - - - org.apache.httpcomponents - httpcore - - - org.apache.httpcomponents - httpclient - - - - io.dropwizard.metrics - metrics-core - - - io.dropwizard.metrics - metrics-graphite - - - com.sun.jersey - jersey-core - - - org.apache.kafka - kafka-clients - 0.10.1.0 - - - org.slf4j - slf4j-log4j12 - - - - - org.apache.kafka - kafka_2.11 - 0.10.1.0 - - - org.slf4j - slf4j-log4j12 - - - - - org.apache.kafka - kafka-streams - 0.10.1.0 - - - org.slf4j - slf4j-log4j12 - - - - - commons-io - commons-io - - - - + + + 4.0.0 + + + usdot.jpo.ode + jpo-ode + 1.0.9 + + + jpo-ode-core + jpo-ode-core + JPO ODE Core Components + jar + + + + + src/main/java/us/dot/its/jpo/ode/dds/* + + + + + usdot.jpo.ode + jpo-ode-common + 1.0.9 + + + usdot.jpo.ode + jpo-ode-plugins + 1.0.9 + + + org.apache.httpcomponents + httpcore + + + org.apache.httpcomponents + httpclient + + + + io.dropwizard.metrics + metrics-core + + + io.dropwizard.metrics + metrics-graphite + + + com.sun.jersey + jersey-core + + + org.apache.kafka + kafka-clients + 0.10.1.0 + + + org.slf4j + slf4j-log4j12 + + + + + org.apache.kafka + kafka_2.11 + 0.10.1.0 + + + org.slf4j + slf4j-log4j12 + + + + + org.apache.kafka + kafka-streams + 0.10.1.0 + + + org.slf4j + slf4j-log4j12 + + + + + commons-io + commons-io + + + + diff --git a/jpo-ode-plugins/pom.xml b/jpo-ode-plugins/pom.xml index f0cbfa9ff..4ed101132 100644 --- a/jpo-ode-plugins/pom.xml +++ b/jpo-ode-plugins/pom.xml @@ -1,48 +1,48 @@ - - - 4.0.0 - - jpo-ode-plugins - jar - - jpo-ode-plugins - JPO ODE Plugins Library - - - usdot.jpo.ode - jpo-ode - 0.0.9-SNAPSHOT - - - - - src/main/java/us/dot/its/jpo/ode/plugin/*.java, - src/main/java/us/dot/its/jpo/ode/plugin/ieee1609dot2/*.java, - src/main/java/us/dot/its/jpo/ode/plugin/j2735/J2735*.java, - src/main/java/us/dot/its/jpo/ode/plugin/j2735/OdeTravelerInformationMessage.java, - src/main/java/us/dot/its/jpo/ode/plugin/j2735/timstorage/*.java - - - - - usdot.jpo.ode - jpo-ode-common - 0.0.9-SNAPSHOT - - - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-core - - - + + + 4.0.0 + + jpo-ode-plugins + jar + + jpo-ode-plugins + JPO ODE Plugins Library + + + usdot.jpo.ode + jpo-ode + 1.0.9 + + + + + src/main/java/us/dot/its/jpo/ode/plugin/*.java, + src/main/java/us/dot/its/jpo/ode/plugin/ieee1609dot2/*.java, + src/main/java/us/dot/its/jpo/ode/plugin/j2735/J2735*.java, + src/main/java/us/dot/its/jpo/ode/plugin/j2735/OdeTravelerInformationMessage.java, + src/main/java/us/dot/its/jpo/ode/plugin/j2735/timstorage/*.java + + + + + usdot.jpo.ode + jpo-ode-common + 1.0.9 + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-core + + + diff --git a/jpo-ode-svcs/pom.xml b/jpo-ode-svcs/pom.xml index 874a624d8..b21c43b24 100644 --- a/jpo-ode-svcs/pom.xml +++ b/jpo-ode-svcs/pom.xml @@ -1,113 +1,113 @@ - - - 4.0.0 - - usdot.jpo.ode - jpo-ode - 0.0.9-SNAPSHOT - - jpo-ode-svcs - jar - jpo-ode-svcs - Services and web interface for US DOT ITS JPO ODE - - - src/main/**/OdeSvcsApplication.java - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-devtools - runtime - - - org.springframework.boot - spring-boot-starter-data-rest - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.restdocs - spring-restdocs-mockmvc - test - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-websocket - - - - org.webjars - webjars-locator - - - org.webjars - sockjs-client - 1.0.2 - - - org.webjars - stomp-websocket - 2.3.3 - - - org.webjars - jquery - - - org.webjars - materializecss - 1.0.0 - - - - usdot.jpo.ode - jpo-ode-core - 0.0.9-SNAPSHOT - - - usdot.jpo.ode - jpo-ode-plugins - 0.0.9-SNAPSHOT - - - org.springframework - spring-messaging - - - org.snmp4j - snmp4j - 1.10.1 - - - - ${project.artifactId} - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + + 4.0.0 + + usdot.jpo.ode + jpo-ode + 1.0.9 + + jpo-ode-svcs + jar + jpo-ode-svcs + Services and web interface for US DOT ITS JPO ODE + + + src/main/**/OdeSvcsApplication.java + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.webjars + webjars-locator + + + org.webjars + sockjs-client + 1.0.2 + + + org.webjars + stomp-websocket + 2.3.3 + + + org.webjars + jquery + + + org.webjars + materializecss + 1.0.0 + + + + usdot.jpo.ode + jpo-ode-core + 1.0.9 + + + usdot.jpo.ode + jpo-ode-plugins + 1.0.9 + + + org.springframework + spring-messaging + + + org.snmp4j + snmp4j + 1.10.1 + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/pom.xml b/pom.xml index 826711f3e..c8c402645 100644 --- a/pom.xml +++ b/pom.xml @@ -1,117 +1,117 @@ - - - 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 1.4.1.RELEASE - - - - - scm:git:https://github.com/usdot-jpo-ode/jpo-ode.git - HEAD - - - usdot.jpo.ode - jpo-ode - 0.0.9-SNAPSHOT - pom - - jpo-ode-common - jpo-ode-plugins - jpo-ode-core - jpo-ode-svcs - - - - - - - - UTF-8 - UTF-8 - 1.8 - - - ${project.build.directory}/${project.artifactId}-${project.version} - ${maven.build.timestamp} - yyyy-MM-dd'T'HH:mm:ss.SSSZ - - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.jmockit - jmockit - 1.40 - test - - - junit - junit - test - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Camden.SR1 - pom - import - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.1 - - - ${loader.path} - ${project.build.directory} - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - - - - - + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.4.1.RELEASE + + + + + scm:git:https://github.com/usdot-jpo-ode/jpo-ode.git + jpo-ode-1.0.9 + + + usdot.jpo.ode + jpo-ode + 1.0.9 + pom + + jpo-ode-common + jpo-ode-plugins + jpo-ode-core + jpo-ode-svcs + + + + + + + + UTF-8 + UTF-8 + 1.8 + + + ${project.build.directory}/${project.artifactId}-${project.version} + ${maven.build.timestamp} + yyyy-MM-dd'T'HH:mm:ss.SSSZ + + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.jmockit + jmockit + 1.40 + test + + + junit + junit + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR1 + pom + import + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + ${loader.path} + ${project.build.directory} + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 + + + + + +