├── .coveralls.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── NOTICE ├── README.md ├── apidocs ├── README.md └── swagger │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── index.html │ ├── oauth2-redirect.html │ ├── swagger-ui-bundle.js │ ├── swagger-ui-bundle.js.map │ ├── swagger-ui-standalone-preset.js │ ├── swagger-ui-standalone-preset.js.map │ ├── swagger-ui.css │ ├── swagger-ui.css.map │ ├── swagger-ui.js │ └── swagger-ui.js.map ├── deployment ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mapcode │ │ │ └── services │ │ │ ├── cli │ │ │ └── Main.java │ │ │ └── deployment │ │ │ ├── DeploymentModule.java │ │ │ └── StartupCheck.java │ └── webapp │ │ └── WEB-INF │ │ └── web.xml │ └── test │ └── java │ └── com │ └── mapcode │ └── services │ ├── cli │ └── MainTest.java │ └── deployment │ ├── DeploymentModuleTest.java │ └── StartupCheckTest.java ├── example ├── index.html └── monitorclient │ ├── MapcodeMonitor.css │ ├── MapcodeMonitor.js │ ├── cubism.v1.min.js │ ├── d3.v2.min.js │ ├── index.html │ ├── jolokia-cubism-min.js │ ├── jolokia-cubism.js │ ├── jolokia-min.js │ ├── jolokia-simple-min.js │ ├── jolokia-simple.js │ ├── jolokia.js │ └── json2-min.js ├── pom.xml ├── resources ├── pom.xml └── src │ └── main │ ├── external-resources-test │ ├── log4j.xml │ └── mapcode-secret.properties │ ├── external-resources │ └── README.md │ └── resources │ └── mapcode.properties └── service ├── pom.xml └── src ├── main └── java │ └── com │ └── mapcode │ └── services │ ├── ApiConstants.java │ ├── MapcodeResource.java │ ├── OnlyJsonResource.java │ ├── OnlyXmlResource.java │ ├── ResourcesModule.java │ ├── RootResource.java │ ├── dto │ ├── AlphabetDTO.java │ ├── AlphabetListDTO.java │ ├── AlphabetsDTO.java │ ├── MapcodeDTO.java │ ├── MapcodeListDTO.java │ ├── MapcodesDTO.java │ ├── PointDTO.java │ ├── RectangleDTO.java │ ├── TerritoriesDTO.java │ ├── TerritoryDTO.java │ ├── TerritoryListDTO.java │ └── VersionDTO.java │ ├── implementation │ ├── MapcodeResourceImpl.java │ ├── OnlyJsonResourceImpl.java │ ├── OnlyXmlResourceImpl.java │ ├── RootResourceImpl.java │ ├── SystemMetricsImpl.java │ └── TestAsyncResponse.java │ ├── jmx │ └── SystemMetricsAgent.java │ ├── metrics │ ├── SystemMetrics.java │ └── SystemMetricsCollector.java │ └── standalone │ ├── MainCommandLine.java │ ├── Server.java │ └── StandaloneModule.java └── test └── java └── com └── mapcode └── services ├── ApiAlphabetsTest.java ├── ApiCodesTest.java ├── ApiCoordsTest.java ├── ApiDTOTest.java ├── ApiOthersTest.java ├── ApiTerritoriesTest.java ├── LocalTestServer.java └── standalone ├── MainCommandLineTest.java └── StandaloneModuleTest.java /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-ci 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | deployment/src/main/webapp/swagger.json 2 | resources/src/main/external-resources/*.xml 3 | resources/src/main/external-resources/*.json 4 | resources/src/main/external-resources/*.properties 5 | out/ 6 | target/ 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | sudo: false 4 | 5 | jdk: 6 | - openjdk8 7 | 8 | install: 9 | - export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF8" 10 | - mvn install -DskipTests -Dgpg.skip 11 | 12 | script: 13 | - export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF8" 14 | - mvn verify -Dgpg.skip 15 | 16 | after_success: 17 | - export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF8" 18 | - mvn coveralls:report -Dgpg.skip 19 | 20 | cache: 21 | directories: 22 | - $HOME/.m2 23 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------------- 2 | MAPCODE JAVA LIBRARY 3 | ------------------------------------------------------------------------------- 4 | 5 | Original C library created by Pieter Geelen. Work on Java version 6 | of the Mapcode library by Rijn Buve (original port by Matthew Lowden). 7 | 8 | Copyright (C) 2014-2016 Stichting Mapcode Foundation (http://www.mapcode.com) 9 | -------------------------------------------------------------------------------- /apidocs/README.md: -------------------------------------------------------------------------------- 1 | The directory `swagger` contains a distribution of the Swagger web site files. 2 | Visit http://swagger.io for more information on where to obtain the latest 3 | version of these files. 4 | 5 | The contents of the directory `swagger` can be copied to a directory on 6 | a web server. 7 | 8 | Search for this line in `index.html` and change it to the correct base URI 9 | of your REST API web services: 10 | 11 | url: "http://api.mapcode.com/swagger.json", 12 | 13 | The fiel `swagger.json` contains the generated REST API definitions. 14 | You can build this file, simply by executing: 15 | 16 | mvn compile 17 | 18 | -------------------------------------------------------------------------------- /apidocs/swagger/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mapcode-foundation/mapcode-rest-service/85ee540739b3d95556577f16743dc288aacd29f0/apidocs/swagger/favicon-16x16.png -------------------------------------------------------------------------------- /apidocs/swagger/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mapcode-foundation/mapcode-rest-service/85ee540739b3d95556577f16743dc288aacd29f0/apidocs/swagger/favicon-32x32.png -------------------------------------------------------------------------------- /apidocs/swagger/index.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Swagger UI 23 | 24 | 25 | 26 | 27 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
85 | 86 | 87 | 88 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /apidocs/swagger/oauth2-redirect.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 70 | -------------------------------------------------------------------------------- /apidocs/swagger/swagger-ui-bundle.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"swagger-ui-bundle.js","sources":["webpack:///swagger-ui-bundle.js"],"mappings":"AAAA;;;;;AAsyKA;;;;;;AAmtEA;;;;;;;;;;;;;;;;;;;;;;;;;;AAkqTA;;;;;;;;;;;;;;AA+5JA;;;;;;;;;AAkwnBA;;;;;AA6kQA;;;;;;AA+gXA","sourceRoot":""} -------------------------------------------------------------------------------- /apidocs/swagger/swagger-ui-standalone-preset.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"swagger-ui-standalone-preset.js","sources":["webpack:///swagger-ui-standalone-preset.js"],"mappings":"AAAA;;;;;AA40CA;;;;;;AAmlFA","sourceRoot":""} -------------------------------------------------------------------------------- /apidocs/swagger/swagger-ui.css.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"swagger-ui.css","sources":[],"mappings":"","sourceRoot":""} -------------------------------------------------------------------------------- /apidocs/swagger/swagger-ui.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"swagger-ui.js","sources":["webpack:///swagger-ui.js"],"mappings":"AAAA;;;;;;AA46aA","sourceRoot":""} -------------------------------------------------------------------------------- /deployment/pom.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 21 | 4.0.0 22 | 23 | 24 | com.mapcode.rest 25 | mapcode-rest-service 26 | 2.4.18.2 27 | 28 | 29 | deployment 30 | war 31 | 32 | Deployment 33 | 34 | This is the deployment WAR with the entry point. 35 | 36 | 37 | 38 | 39 | ${project.groupId} 40 | resources 41 | 42 | 43 | 44 | ${project.groupId} 45 | service 46 | 47 | 48 | 49 | com.google.code.findbugs 50 | jsr305 51 | 52 | 53 | 54 | com.google.inject 55 | guice 56 | 57 | 58 | 59 | com.tomtom.speedtools 60 | guice 61 | 62 | 63 | 64 | com.tomtom.speedtools 65 | tracer 66 | 67 | 68 | 69 | javax.inject 70 | javax.inject 71 | 72 | 73 | 74 | junit 75 | junit 76 | test 77 | 78 | 79 | 80 | org.apache.logging.log4j 81 | log4j-api 82 | 83 | 84 | 85 | org.apache.logging.log4j 86 | log4j-core 87 | 88 | 89 | 90 | org.jolokia 91 | jolokia-core 92 | 93 | 94 | 95 | org.mockito 96 | mockito-core 97 | test 98 | 99 | 100 | 101 | org.slf4j 102 | slf4j-api 103 | 104 | 105 | 106 | org.slf4j 107 | slf4j-log4j12 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | src/main/webapp/WEB-INF 116 | true 117 | 118 | 119 | 120 | 121 | 122 | org.apache.maven.plugins 123 | maven-antrun-plugin 124 | ${maven-antrun-plugin.version} 125 | 126 | 127 | move-main-class 128 | compile 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | run 140 | 141 | 142 | 143 | 144 | 145 | 146 | org.apache.maven.plugins 147 | maven-war-plugin 148 | ${maven-war-plugin.version} 149 | 150 | true 151 | classes 152 | 153 | 154 | com.mapcode.services.cli.Main 155 | true 156 | WEB-INF/lib/ 157 | 158 | 159 | 160 | 161 | 162 | target/webapp 163 | 164 | 165 | 166 | 167 | 168 | 169 | org.apache.maven.plugins 170 | maven-remote-resources-plugin 171 | ${maven-remote-resources-plugin.version} 172 | 173 | 174 | 175 | process 176 | 177 | 178 | 179 | com.tomtom.speedtools:resources:${speedtools.version} 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | org.eclipse.jetty 188 | jetty-maven-plugin 189 | ${jetty-maven-plugin.version} 190 | 191 | 192 | ${maven.httpserver.root} 193 | 194 | 195 | ${maven.httpserver.port} 196 | 197 | 10 198 | stop 199 | 9999 200 | 201 | 202 | 203 | 204 | 205 | -------------------------------------------------------------------------------- /deployment/src/main/java/com/mapcode/services/cli/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.cli; 18 | 19 | import javax.annotation.Nonnull; 20 | import javax.annotation.Nullable; 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.lang.reflect.InvocationTargetException; 24 | import java.lang.reflect.Method; 25 | import java.net.*; 26 | import java.util.ArrayList; 27 | import java.util.Enumeration; 28 | import java.util.List; 29 | import java.util.jar.JarEntry; 30 | import java.util.jar.JarFile; 31 | import java.util.regex.Pattern; 32 | 33 | /** 34 | * Stub to load CLI main from war file. 35 | * You can start the application with the following command: 36 | * 37 | * java -jar war-file [arguments] 38 | * 39 | */ 40 | public final class Main { 41 | private static final String MAIN_CLASS_NAME = "com.mapcode.services.standalone.MainCommandLine"; 42 | private static final String MAIN_METHOD_NAME = "execute"; 43 | 44 | private Main() { 45 | // Prevent instantiation. 46 | } 47 | 48 | public static void main(@Nonnull final String... args) 49 | throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IOException { 50 | assert args != null; 51 | final List newUrls = new ArrayList<>(); 52 | URL.setURLStreamHandlerFactory(new NestedJarURLStreamHandlerFactory()); 53 | final String warFile = getWarFile(); 54 | try (final JarFile jarFile = new JarFile(warFile)) { 55 | 56 | for (final Enumeration entryEnum = jarFile.entries(); entryEnum.hasMoreElements(); ) { 57 | final JarEntry entry = entryEnum.nextElement(); 58 | if (entry.getName().endsWith(".jar")) { 59 | newUrls.add(new URL("jar:nestedjar:file:" + warFile + "~/" + entry.getName() + "!/")); 60 | } 61 | } 62 | } 63 | 64 | final URLClassLoader newClassLoader = new URLClassLoader(newUrls.toArray(new URL[newUrls.size()])); 65 | final Class mainClass = newClassLoader.loadClass(MAIN_CLASS_NAME); 66 | final Method method = mainClass.getMethod(MAIN_METHOD_NAME, String[].class); 67 | try { 68 | method.invoke(null, (Object) args); 69 | } catch (InvocationTargetException e) { 70 | throw new IllegalStateException("The program failed. An exception was thrown during execution.", 71 | e.getCause()); 72 | } 73 | } 74 | 75 | @Nonnull 76 | private static String getWarFile() { 77 | final URLClassLoader classLoader = (URLClassLoader) Main.class.getClassLoader(); 78 | for (final URL url : classLoader.getURLs()) { 79 | if (url.toString().endsWith(".war")) { 80 | return url.getFile(); 81 | } 82 | } 83 | throw new IllegalStateException("Should be run from the war file (using java -jar )."); 84 | } 85 | 86 | static class NestedJarURLConnection extends URLConnection { 87 | private final URLConnection connection; 88 | 89 | @SuppressWarnings("OverlyBroadThrowsClause") 90 | NestedJarURLConnection(@Nonnull final URL url) 91 | throws IOException { 92 | super(url); 93 | assert url != null; 94 | connection = new URL(url.getFile()).openConnection(); 95 | } 96 | 97 | @Override 98 | public void connect() throws IOException { 99 | if (!connected) { 100 | connection.connect(); 101 | connected = true; 102 | } 103 | } 104 | 105 | @Override 106 | @Nonnull 107 | public InputStream getInputStream() throws IOException { 108 | connect(); 109 | return connection.getInputStream(); 110 | } 111 | } 112 | 113 | static class NestedJarURLStreamHandlerFactory implements URLStreamHandlerFactory { 114 | 115 | @Nullable 116 | @Override 117 | public URLStreamHandler createURLStreamHandler(@Nonnull final String protocol) { 118 | assert protocol != null; 119 | if (protocol.equals("nestedjar")) { 120 | return new JarJarURLStreamHandler(); 121 | } 122 | return null; 123 | } 124 | } 125 | 126 | static class JarJarURLStreamHandler extends URLStreamHandler { 127 | 128 | private static final Pattern PATTERN = Pattern.compile("\\~/"); 129 | 130 | @Nonnull 131 | @Override 132 | protected URLConnection openConnection(@Nonnull final URL u) throws IOException { 133 | assert u != null; 134 | return new NestedJarURLConnection(u); 135 | } 136 | 137 | @Override 138 | protected void parseURL(@Nonnull final URL u, @Nonnull final String spec, final int start, final int limit) { 139 | assert u != null; 140 | assert spec != null; 141 | final String file = "jar:" + PATTERN.matcher(spec.substring(start, limit)).replaceFirst("!/"); 142 | setURL(u, "nestedjar", "", -1, null, null, file, null, null); 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /deployment/src/main/java/com/mapcode/services/deployment/DeploymentModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.deployment; 18 | 19 | import com.google.inject.Binder; 20 | import com.tomtom.speedtools.guice.GuiceConfigurationModule; 21 | import com.tomtom.speedtools.tracer.LoggingTraceHandler; 22 | import com.tomtom.speedtools.tracer.TracerFactory; 23 | import com.tomtom.speedtools.tracer.mongo.MongoDBTraceHandler; 24 | import com.tomtom.speedtools.tracer.mongo.MongoDBTraceProperties; 25 | import com.tomtom.speedtools.tracer.mongo.MongoDBTraceStream; 26 | 27 | import javax.annotation.Nonnull; 28 | 29 | 30 | /** 31 | * This class defines the deployment configuration for Google Guice. 32 | *

33 | * The deployment module "bootstraps" the whole Guice injection process. 34 | *

35 | * It bootstraps the Guice injection and specifies the property files to be read. It also needs to bind the tracer, so 36 | * they can be used early on in the app. Finally, it can bind a "startup check" (example provided) as an eager 37 | * singleton, so the system won't start unless a set of basic preconditions are fulfilled. 38 | *

39 | * The "speedtools.default.properties" is required, but its values may be overridden in other property files. 40 | */ 41 | public class DeploymentModule extends GuiceConfigurationModule { 42 | 43 | public DeploymentModule() { 44 | super( 45 | "classpath:speedtools.default.properties", // Default set required by SpeedTools. 46 | "classpath:mapcode.properties", // Specific for mapcode service. 47 | "classpath:mapcode-secret.properties"); // Secret properties (not in WAR file). 48 | } 49 | 50 | @Override 51 | public void configure(@Nonnull final Binder binder) { 52 | assert binder != null; 53 | 54 | super.configure(binder); 55 | 56 | // Bind these classes if you wish to use the SpeedTools MongoDB tracing framework. 57 | TracerFactory.setEnabled(true); 58 | binder.bind(MongoDBTraceProperties.class).asEagerSingleton(); 59 | binder.bind(MongoDBTraceStream.class); 60 | binder.bind(MongoDBTraceHandler.class).asEagerSingleton(); 61 | binder.bind(LoggingTraceHandler.class).asEagerSingleton(); 62 | 63 | // Bind start-up checking class (example). 64 | binder.bind(StartupCheck.class).asEagerSingleton(); 65 | } 66 | } 67 | 68 | -------------------------------------------------------------------------------- /deployment/src/main/java/com/mapcode/services/deployment/StartupCheck.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.deployment; 18 | 19 | import com.google.inject.Injector; 20 | import com.mapcode.services.jmx.SystemMetricsAgent; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import javax.annotation.Nonnull; 25 | import javax.inject.Inject; 26 | import java.nio.charset.Charset; 27 | 28 | /** 29 | * This class provides a safe start up of the system. It provides basic checks required before startup is allowed. It 30 | * is 31 | * abound as an eager Singleton by Guice in the {@link DeploymentModule} 32 | * by using "binder.bind(StartupCheck.class).asEagerSingleton()". This means the Singleton is instantiated right away. 33 | *

If any of the checks in the constructor of this class fail, an IllegalStateException is thrown and the 34 | * application will not continue to run. This prevents starting the system with, for example, incorrect database 35 | * information or an incompatible JRE. 36 | */ 37 | public final class StartupCheck { 38 | private static final Logger LOG = LoggerFactory.getLogger(StartupCheck.class); 39 | 40 | private static final String REQUIRED_ENCODING = "UTF-8"; 41 | 42 | @Inject 43 | StartupCheck(@Nonnull final Injector injector) { 44 | assert injector != null; 45 | 46 | /** 47 | * This method contains a number of checks that should be performed before the system 48 | * is started up. Not every application will need a 'StartupCheck' class, but if it does 49 | * it is good to know how to implement it safely in the SpeedTools framework. Hence the 50 | * inclusion in this example. 51 | * 52 | * A good example of a really useful StartupCheck is to check whether the database has 53 | * the expected format, especially for no-SQL databases. If the database format (or 54 | * schema, as you may wish to call it) is not what you think it is, you might ruin the 55 | * database. You should check this sort of stuff here. 56 | * 57 | * Another good one is checking the expected character set (see below) and the JRE version. 58 | */ 59 | 60 | // Check if we are using the correct JDK. 61 | LOG.info("check: Checking system start-up configuration."); 62 | final String javaVersion = System.getProperty("java.version"); 63 | check(javaVersion.startsWith("1.6.") || javaVersion.startsWith("1.7.") || javaVersion.startsWith("1.8.") || 64 | javaVersion.startsWith("11.") || javaVersion.startsWith("14.") || javaVersion.startsWith("17."), 65 | "The system requires JRE 1.6.x/1.7.x/1.8.x/11.x/14.x/17.x (found JRE " + javaVersion + ")."); 66 | 67 | // Check encoding. The default character encoding for JSON is UTF8. UTF16 and UTF32 are also supported. 68 | // This is to make sure that byte conversions that rely on default encoding do not cause unexpected behaviour. 69 | check(REQUIRED_ENCODING.equals(Charset.defaultCharset().name()), 70 | "The system default encoding must be UTF-8 (add '-Dfile.encoding=UTF-8' the JVM command line)." + 71 | " Current value=" + Charset.defaultCharset().name()); 72 | 73 | // Start JMX server. 74 | LOG.info("check: Get JMX agent."); 75 | final SystemMetricsAgent jmxAgent = injector.getInstance(SystemMetricsAgent.class); 76 | 77 | //noinspection OverlyBroadCatchBlock 78 | try { 79 | LOG.info("check: Register JMX agent."); 80 | jmxAgent.register(); 81 | } 82 | catch (final Exception e) { 83 | check(false, "Could not register the JMX agent: " + e.getMessage()); 84 | } 85 | 86 | LOG.info("Startup: System started successfully."); 87 | } 88 | 89 | private StartupCheck() { 90 | // Empty. 91 | } 92 | 93 | @SuppressWarnings("UseOfSystemOutOrSystemErr") 94 | private static void check(final boolean check, @Nonnull final String reason) { 95 | if (!check) { 96 | LOG.error("check: System did NOT start succesfully."); 97 | LOG.error("check: Reason: {}", reason); 98 | 99 | System.err.println(); 100 | System.err.println("======================================="); 101 | System.err.println("ERROR"); 102 | System.err.println("======================================="); 103 | System.err.println("System did NOT start successfully."); 104 | System.err.println("Reason: " + reason); 105 | System.err.println("======================================="); 106 | System.err.println(); 107 | throw new IllegalStateException("System did NOT start successfully. Reason: " + reason); 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /deployment/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 23 | 24 | Mapcode REST API Web Services 25 | 26 | 27 | resteasy.guice.modules 28 | 29 | com.tomtom.speedtools.rest.ServicesModule, 30 | com.mapcode.services.ResourcesModule, 31 | com.mapcode.services.deployment.DeploymentModule 32 | 33 | 34 | 35 | 36 | resteasy.use.builtin.providers 37 | true 38 | 39 | 40 | 41 | resteasy.providers 42 | 43 | io.swagger.jaxrs.listing.ApiListingResource, 44 | io.swagger.jaxrs.listing.SwaggerSerializers, 45 | com.tomtom.speedtools.rest.security.CorsFeature 46 | 47 | 48 | 49 | 52 | 53 | com.tomtom.speedtools.guice.LoggingGuiceResteasyBootstrapServletContextListener 54 | 55 | 56 | 59 | 60 | 61 | com.tomtom.speedtools.rest.Shutdown 62 | 63 | 64 | 65 | 66 | Mapcode 67 | org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher 68 | true 69 | 70 | 71 | 72 | Mapcode 73 | /mapcode/* 74 | 75 | 76 | 77 | Swagger 78 | io.swagger.jaxrs.config.DefaultJaxrsConfig 79 | 80 | api.version 81 | ${pom.version} 82 | 83 | 2 84 | 85 | 86 | 87 | Swagger 88 | /swagger/* 89 | 90 | 91 | 92 | JolokiaAgent 93 | org.jolokia.http.AgentServlet 94 | 1 95 | 96 | 97 | 98 | JolokiaAgent 99 | /monitor/* 100 | 101 | 102 | 103 | 104 | Root 105 | /* 106 | PUT 107 | POST 108 | DELETE 109 | OPTIONS 110 | TRACE 111 | PROPFIND 112 | 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /deployment/src/test/java/com/mapcode/services/cli/MainTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.cli; 18 | 19 | import org.junit.Ignore; 20 | import org.junit.Test; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | @SuppressWarnings("OverlyBroadThrowsClause") 25 | public class MainTest { 26 | private static final Logger LOG = LoggerFactory.getLogger(MainTest.class); 27 | 28 | @Ignore 29 | @SuppressWarnings("ProhibitedExceptionDeclared") 30 | @Test(expected = IllegalStateException.class) 31 | public void testMainFails() throws Exception { 32 | LOG.info("testMainFails"); 33 | 34 | // This will fail, as it needs to run from a WAR file and we can't do that here. 35 | // Arguments: [--port ] [--silent] [--debug] [--help] 36 | Main.main("--port", "8080", "--debug"); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /deployment/src/test/java/com/mapcode/services/deployment/DeploymentModuleTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.deployment; 18 | 19 | import com.google.inject.Binder; 20 | import com.google.inject.Key; 21 | import com.google.inject.binder.AnnotatedBindingBuilder; 22 | import com.google.inject.binder.LinkedBindingBuilder; 23 | import com.google.inject.name.Names; 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | import org.mockito.Mock; 27 | import org.mockito.MockitoAnnotations; 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | 31 | import static org.mockito.ArgumentMatchers.any; 32 | import static org.mockito.Mockito.doNothing; 33 | import static org.mockito.Mockito.when; 34 | 35 | @SuppressWarnings("rawtypes") 36 | public class DeploymentModuleTest { 37 | private static final Logger LOG = LoggerFactory.getLogger(DeploymentModuleTest.class); 38 | 39 | @Mock 40 | private Binder mockBinder; 41 | 42 | @Mock 43 | private AnnotatedBindingBuilder mockAnnotatedBindingBuilder; 44 | 45 | @Mock 46 | private LinkedBindingBuilder mockLinkedBindingBuilder; 47 | 48 | @SuppressWarnings("unchecked") 49 | @Test 50 | public void testDeploymentModule() { 51 | LOG.info("testDeploymentModule"); 52 | 53 | // Initialize Mockito. 54 | MockitoAnnotations.initMocks(this); 55 | doNothing().when(mockAnnotatedBindingBuilder).asEagerSingleton(); 56 | doNothing().when(mockLinkedBindingBuilder).asEagerSingleton(); 57 | doNothing().when(mockLinkedBindingBuilder).toInstance(String.class); 58 | when(mockBinder.skipSources(Names.class)).thenReturn(mockBinder); 59 | when(mockBinder.bind(any(Key.class))).thenReturn(mockLinkedBindingBuilder); 60 | when(mockBinder.bind(any(Class.class))).thenReturn(mockAnnotatedBindingBuilder); 61 | 62 | // Execute start-up check. 63 | final DeploymentModule deploymentModule = new DeploymentModule(); 64 | deploymentModule.configure(mockBinder); 65 | Assert.assertNotNull(deploymentModule); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /deployment/src/test/java/com/mapcode/services/deployment/StartupCheckTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.deployment; 18 | 19 | import com.google.inject.Injector; 20 | import com.mapcode.services.jmx.SystemMetricsAgent; 21 | import org.junit.Assert; 22 | import org.junit.Test; 23 | import org.mockito.Mock; 24 | import org.mockito.MockitoAnnotations; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | import static org.mockito.Mockito.doNothing; 29 | import static org.mockito.Mockito.when; 30 | 31 | public class StartupCheckTest { 32 | private static final Logger LOG = LoggerFactory.getLogger(StartupCheckTest.class); 33 | 34 | @Mock 35 | private Injector mockInjector; 36 | 37 | @Mock 38 | private SystemMetricsAgent mockJmxAgent; 39 | 40 | @SuppressWarnings("InstantiationOfUtilityClass") 41 | @Test(expected = IllegalStateException.class) 42 | public void testStartupCheckFails() { 43 | LOG.info("testStartupCheckFailure"); 44 | 45 | // Initialize Mockito. 46 | MockitoAnnotations.initMocks(this); 47 | when(mockInjector.getInstance(SystemMetricsAgent.class)).thenReturn(null); 48 | 49 | // Execute start-up check. 50 | //noinspection ResultOfObjectAllocationIgnored 51 | new StartupCheck(mockInjector); 52 | } 53 | 54 | @SuppressWarnings("InstantiationOfUtilityClass") 55 | @Test 56 | public void testStartupCheckSuccess() throws Exception { 57 | LOG.info("testStartupCheckSuccess"); 58 | 59 | // Initialize Mockito. 60 | MockitoAnnotations.initMocks(this); 61 | doNothing().when(mockJmxAgent).register(); 62 | when(mockInjector.getInstance(SystemMetricsAgent.class)).thenReturn(mockJmxAgent); 63 | 64 | // Execute start-up check. 65 | final StartupCheck startupCheck = new StartupCheck(mockInjector); 66 | Assert.assertNotNull(startupCheck); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /example/monitorclient/MapcodeMonitor.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | $(document).ready(function () { 18 | var fInterval = 1000; 19 | 20 | // To use on production system: 21 | var jolokiaConnector = new Jolokia({ url: "https://api.mapcode.com/monitor", fetchInterval: fInterval}); 22 | 23 | // For local testing: 24 | // jolokiaConnector = new Jolokia({url: "http://localhost:8080/monitor", fetchInterval: fInterval}); 25 | 26 | 27 | var colorsRed = ["#FDBE85", "#FEEDDE", "#FD8D3C", "#E6550D", "#A63603", "#FDBE85", "#FEEDDE", "#FD8D3C", "#E6550D", "#A63603"]; 28 | var colorsGreen = ["#FDBE85"]; 29 | var colorsBlue = ["#ECE7F2", "#A6BDDB", "#2B8CBE", "#ECE7F2", "#A6BDDB", "#2B8CBE"]; 30 | 31 | var context = cubism.context() 32 | .serverDelay(0) 33 | .clientDelay(0) 34 | .step(fInterval) 35 | .size(400); 36 | var jolokia = context.jolokia(jolokiaConnector); 37 | 38 | function metric(metricName, path, label) { 39 | return jolokia.metric({ 40 | type: "read", 41 | mbean: "mapcode:name=SystemMetrics", 42 | attribute: metricName, 43 | path: path 44 | }, label); 45 | } 46 | 47 | function graph(selector, title, metrics) { 48 | return d3.select(selector).call(function (div) { 49 | div.append("h2").text(title); 50 | div.selectAll(".horizon") 51 | .data(metrics) 52 | .enter() 53 | .append("div") 54 | .attr("class", "horizon") 55 | .call(context.horizon() 56 | .colors(colorsBlue) 57 | .format(d3.format("10d"))); 58 | div.append("div") 59 | .attr("class", "axis") 60 | .attr("style", "fill: white") 61 | .call(context.axis().orient("bottom")); 62 | 63 | div.append("div") 64 | .attr("class", "rule") 65 | .call(context.rule()); 66 | 67 | }); 68 | } 69 | 70 | function stdgraph(selector, title, metricName, pathPostfix) { 71 | return graph(selector, title, [ 72 | metric(metricName, "lastMinute/" + pathPostfix, "Last Minute"), 73 | metric(metricName, "lastHour/" + pathPostfix, "Last Hour"), 74 | metric(metricName, "lastDay/" + pathPostfix, "Last Day"), 75 | metric(metricName, "lastWeek/" + pathPostfix, "Last Week"), 76 | metric(metricName, "lastMonth/" + pathPostfix, "Last Month")]); 77 | } 78 | 79 | stdgraph("#allMapcodeToLatLonRequestsSum", "All", "AllMapcodeToLatLonRequests", "sum"); 80 | stdgraph("#validMapcodeToLatLonRequestsSum", "Valid", "ValidMapcodeToLatLonRequests", "sum"); 81 | stdgraph("#allClientNoneMapcodeToLatLonRequestsSum", "None/Unknown", "AllClientNoneMapcodeToLatLonRequests", "sum"); 82 | stdgraph("#allClientIOSMapcodeToLatLonRequestsSum", "iOS", "AllClientIOSMapcodeToLatLonRequests", "sum"); 83 | stdgraph("#allClientAndroidMapcodeToLatLonRequestsSum", "AndroidOS", "AllClientAndroidMapcodeToLatLonRequests", "sum"); 84 | stdgraph("#allClientWebMapcodeToLatLonRequestsSum", "Web (mapcode.com)", "AllClientWebMapcodeToLatLonRequests", "sum"); 85 | 86 | stdgraph("#allLatLonToMapcodeRequestsSum", "All", "AllLatLonToMapcodeRequests", "sum"); 87 | stdgraph("#validLatLonToMapcodeRequestsSum", "Valid", "ValidLatLonToMapcodeRequests", "sum"); 88 | stdgraph("#allClientNoneLatLonToMapcodeRequestsSum", "None/Unknown", "AllClientNoneLatLonToMapcodeRequests", "sum"); 89 | stdgraph("#allClientIOSLatLonToMapcodeRequestsSum", "iOS", "AllClientIOSLatLonToMapcodeRequests", "sum"); 90 | stdgraph("#allClientAndroidLatLonToMapcodeRequestsSum", "Android", "AllClientAndroidLatLonToMapcodeRequests", "sum"); 91 | stdgraph("#allClientWebLatLonToMapcodeRequestsSum", "Web (mapcode.com)", "AllClientWebLatLonToMapcodeRequests", "sum"); 92 | 93 | stdgraph("#allAlphabetRequestsSum", "Alphabet:", "AllAlphabetRequests", "sum"); 94 | stdgraph("#allTerritoryRequestsSum", "Territory:", "AllTerritoryRequests", "sum"); 95 | stdgraph("#warningsAndErrorsSum", "Warnings/Errors", "WarningsAndErrors", "sum"); 96 | 97 | var value = jolokiaConnector.getAttribute("java.lang:type=Memory", "HeapMemoryUsage", "used") / (1024 * 1024); 98 | $("#memoryUsage").text("Memory used: " + Math.round(value) + "Mb"); 99 | }); 100 | -------------------------------------------------------------------------------- /example/monitorclient/index.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | Mapcode Monitor 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 34 | 35 | 36 |

37 |
38 |
39 |
40 |

Mapcode System Monitor

41 |
42 |
43 | 44 |
45 |
46 |

System Health

47 | 48 |
49 |
50 |
51 |
52 |
53 |
54 | 55 | 56 |
57 |

Mapcode to LatLon

58 | 59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | 91 |
92 |

LatLon to Mapcode

93 | 94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 | 126 |
127 |

Others

128 | 129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 | 142 | 164 |
165 |
166 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /example/monitorclient/jolokia-cubism-min.js: -------------------------------------------------------------------------------- 1 | 2 | (function(){var builder=function(cubism,Jolokia){var VERSION="1.3.0";var ctx_jolokia=function(url,opts){var source={},context=this,j4p=createAgent(url,opts),step=5e3;try 3 | {context.on("start",function(){j4p.start();});context.on("stop",function(){j4p.stop();});} 4 | catch(err) 5 | {} 6 | source.metric=function(){var values=[];var name;var argsLen=arguments.length;var options={};var lastIdx=arguments.length-1;var lastArg=arguments[lastIdx];if(typeof lastArg=="string"){name=lastArg;argsLen=lastIdx;} 7 | if(typeof lastArg=="object"&&!lastArg.type){options=lastArg;name=options.name;argsLen=lastIdx;} 8 | if(!name&&typeof arguments[0]!="function"){name=arguments[0].mbean;} 9 | var metric=context.metric(mapValuesFunc(values,options.keepDelay,context.width),name);if(options.delta){var prevMetric=metric.shift(-options.delta);metric=metric.subtract(prevMetric);if(name){metric.toString=function(){return name};}} 10 | if(typeof arguments[0]=="function"){var func=arguments[0];var respFunc=function(resp){var isError=false;for(var i=0;i0?values[vLen-1].time:undefined;if(!vLen||cStopvalues[0].time+cStep){retVals.unshift(NaN);cTime-=cStep;} 18 | while(cTime>=cStart&&cTime>=vStart){while(values[vIdx].time>cTime){vIdx++;} 19 | retVals.unshift(values[vIdx].value);cTime-=cStep;} 20 | while(cTime>=cStart){retVals.unshift(NaN);cTime-=cStep;} 21 | if(vLen>width){if(!keepDelay){values.length=width;}else{var keepUntil=values[width].time-keepDelay,i=width;while(ikeepUntil){i++;} 22 | values.length=i;}} 23 | callback(null,retVals);}}};ctx_jolokia.VERSION=VERSION;cubism.context.prototype.jolokia=ctx_jolokia;return ctx_jolokia;};(function(root){if(typeof define==='function'&&define.amd){define(["cubism","jolokia"],function(cubism,Jolokia){return builder(cubism,Jolokia);});}else{if(root.Jolokia&&root.cubism){builder(root.cubism,root.Jolokia);}else{console.error("No "+(root.cubism?"Cubism":"Jolokia")+" definition found. "+"Please include jolokia.js and cubism.js before jolokia-cubism.js");}}})(this);})(); -------------------------------------------------------------------------------- /example/monitorclient/jolokia-min.js: -------------------------------------------------------------------------------- 1 | 2 | (function(){var _jolokiaConstructorFunc=function($){var DEFAULT_CLIENT_PARAMS={type:"POST",jsonp:false};var GET_AJAX_PARAMS={type:"GET"};var POST_AJAX_PARAMS={type:"POST",processData:false,dataType:"json",contentType:"text/json"};var PROCESSING_PARAMS=["maxDepth","maxCollectionSize","maxObjects","ignoreErrors","canonicalNaming","serializeException","includeStackTrace","ifModifiedSince"];function Jolokia(param){if(!(this instanceof arguments.callee)){return new Jolokia(param);} 3 | this.CLIENT_VERSION="1.3.0";var jobs=[];var agentOptions={};var pollerIsRunning=false;if(typeof param==="string"){param={url:param};} 4 | $.extend(agentOptions,DEFAULT_CLIENT_PARAMS,param);this.request=function(request,params){var opts=$.extend({},agentOptions,params);assertNotNull(opts.url,"No URL given");var ajaxParams={};$.each(["username","password","timeout"],function(i,key){if(opts[key]){ajaxParams[key]=opts[key];}});if(ajaxParams['username']&&ajaxParams['password']){if(window.btoa){ajaxParams.beforeSend=function(xhr){var tok=ajaxParams['username']+':'+ajaxParams['password'];xhr.setRequestHeader('Authorization',"Basic "+window.btoa(tok));};} 5 | ajaxParams.xhrFields={withCredentials:true};} 6 | if(extractMethod(request,opts)==="post"){$.extend(ajaxParams,POST_AJAX_PARAMS);ajaxParams.data=JSON.stringify(request);ajaxParams.url=ensureTrailingSlash(opts.url);}else{$.extend(ajaxParams,GET_AJAX_PARAMS);ajaxParams.dataType=opts.jsonp?"jsonp":"json";ajaxParams.url=opts.url+"/"+constructGetUrlPath(request);} 7 | ajaxParams.url=addProcessingParameters(ajaxParams.url,opts);if(opts.ajaxError){ajaxParams.error=opts.ajaxError;} 8 | if(opts.success){var success_callback=constructCallbackDispatcher(opts.success);var error_callback=constructCallbackDispatcher(opts.error);ajaxParams.success=function(data){var responses=$.isArray(data)?data:[data];for(var idx=0;idx0){job.lastModified=lastModified;callback.apply(jolokia,responses);}}};function addResponse(resp,j){if(resp.status!=304){if(lastModified==0||resp.timestamp0?"&":"?";$.each(PROCESSING_PARAMS,function(i,key){if(opts[key]!=null){url+=sep+key+"="+opts[key];sep="&";}});return url;} 39 | function constructGetUrlPath(request){var type=request.type;assertNotNull(type,"No request type given for building a GET request");type=type.toLowerCase();var extractor=GET_URL_EXTRACTORS[type];assertNotNull(extractor,"Unknown request type "+type);var result=extractor(request);var parts=result.parts||[];var url=type;$.each(parts,function(i,v){url+="/"+Jolokia.escape(v)});if(result.path){url+=(result.path[0]=='/'?"":"/")+result.path;} 40 | console.log(url);return url;} 41 | function ensureTrailingSlash(url){return url.replace(/\/*$/,"/");} 42 | var GET_URL_EXTRACTORS={"read":function(request){if(request.attribute==null){return{parts:[request.mbean,'*'],path:request.path};}else{return{parts:[request.mbean,request.attribute],path:request.path};}},"write":function(request){return{parts:[request.mbean,request.attribute,valueToString(request.value)],path:request.path};},"exec":function(request){var ret=[request.mbean,request.operation];if(request.arguments&&request.arguments.length>0){$.each(request.arguments,function(index,value){ret.push(valueToString(value));});} 43 | return{parts:ret};},"version":function(){return{};},"search":function(request){return{parts:[request.mbean]};},"list":function(request){return{path:request.path};}};function valueToString(value){if(value==null){return"[null]";} 44 | if($.isArray(value)){var ret="";for(var i=0;i=200&&xhr.status<300||xhr.status===304||xhr.status===1223;}catch(e){} 48 | return false;} 49 | function assertNotNull(object,message){if(object==null){throw new Error(message);}} 50 | Jolokia.prototype.escape=Jolokia.escape=function(part){return encodeURIComponent(part.replace(/!/g,"!!").replace(/\//g,"!/"));};Jolokia.prototype.isError=Jolokia.isError=function(resp){return resp.status==null||resp.status!=200;};return Jolokia;};(function(root,factory){if(typeof define==='function'&&define.amd){define(["jquery"],factory);}else{root.Jolokia=factory(root.jQuery);}}(this,function(jQuery){return _jolokiaConstructorFunc(jQuery);}));}()); -------------------------------------------------------------------------------- /example/monitorclient/jolokia-simple-min.js: -------------------------------------------------------------------------------- 1 | 2 | (function(){var builder=function($,Jolokia){function getAttribute(mbean,attribute,path,opts){if(arguments.length===3&&$.isPlainObject(path)){opts=path;path=null;}else if(arguments.length==2&&$.isPlainObject(attribute)){opts=attribute;attribute=null;path=null;} 3 | var req={type:"read",mbean:mbean,attribute:attribute};addPath(req,path);return extractValue(this.request(req,prepareSucessCallback(opts)),opts);} 4 | function setAttribute(mbean,attribute,value,path,opts){if(arguments.length===4&&$.isPlainObject(path)){opts=path;path=null;} 5 | var req={type:"write",mbean:mbean,attribute:attribute,value:value};addPath(req,path);return extractValue(this.request(req,prepareSucessCallback(opts)),opts);} 6 | function execute(mbean,operation){var req={type:"exec",mbean:mbean,operation:operation};var opts,end=arguments.length;if(arguments.length>2&&$.isPlainObject(arguments[arguments.length-1])){opts=arguments[arguments.length-1];end=arguments.length-1;} 7 | if(end>2){var args=[];for(var i=2;i 16 | 17 | 21 | 4.0.0 22 | 23 | 24 | com.mapcode.rest 25 | mapcode-rest-service 26 | 2.4.18.2 27 | 28 | 29 | resources 30 | jar 31 | 32 | Resources 33 | 34 | 35 | Shared resources for Mapcode REST API. 36 | 37 | 38 | 39 | 40 | 41 | src/main/resources 42 | true 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | test 52 | 53 | true 54 | 55 | 56 | 57 | 58 | src/main/external-resources-test 59 | true 60 | 61 | 62 | 63 | 64 | 65 | org.apache.maven.plugins 66 | maven-remote-resources-plugin 67 | 68 | 69 | 70 | bundle 71 | 72 | 73 | 74 | **/external-resources-test/*.properties 75 | **/external-resources-test/*.xml 76 | **/external-resources-test/*.conf 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | prod 89 | 90 | 91 | 92 | src/main/external-resources 93 | true 94 | 95 | 96 | 97 | 98 | 99 | org.apache.maven.plugins 100 | maven-remote-resources-plugin 101 | 102 | 103 | 104 | bundle 105 | 106 | 107 | 108 | **/external-resources/*.properties 109 | **/external-resources/*.xml 110 | **/external-resources/*.conf 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /resources/src/main/external-resources-test/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /resources/src/main/external-resources-test/mapcode-secret.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Example properties file which should be placed in the classpath. 18 | # Set mapcode-secret.properties to true to trace REST calls to the MongoDB database. 19 | 20 | MongoDBTrace.readEnabled = false 21 | MongoDBTrace.writeEnabled = false 22 | MongoDBTrace.servers = your-server:27017 23 | MongoDBTrace.database = your-database 24 | MongoDBTrace.userName = your-username 25 | MongoDBTrace.password = your-password 26 | -------------------------------------------------------------------------------- /resources/src/main/external-resources/README.md: -------------------------------------------------------------------------------- 1 | This file only keeps the folder `external-resources` from being removed. -------------------------------------------------------------------------------- /resources/src/main/resources/mapcode.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Override these default properties: 18 | 19 | Maven.pomVersion = ${pom.version} 20 | 21 | MongoDBTrace.readEnabled = false 22 | MongoDBTrace.writeEnabled = false 23 | MongoDBTrace.maxDatabaseSizeMB = 1000 24 | MongoDBTrace.connectionTimeoutMsecs = 20000 25 | 26 | # If you wish to use MongoDB tracing, override these in your own 27 | # mapcode-secret.properties file: 28 | 29 | # MongoDBTrace.writeEnabled = true 30 | MongoDBTrace.servers = localhost:27017 31 | MongoDBTrace.database = trace 32 | MongoDBTrace.userName = {empty} 33 | MongoDBTrace.password = {empty} 34 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/ApiConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | /** 20 | * This utility class contains constants used in the Web services API. 21 | */ 22 | public final class ApiConstants { 23 | 24 | /** 25 | * General HTTP timeout for @Suspend() annotations. 26 | */ 27 | public static final int SUSPEND_TIMEOUT = 30000; 28 | 29 | /** 30 | * General limits for count and offset. 31 | */ 32 | public static final int API_COUNT_MAX = Integer.MAX_VALUE; 33 | public static final int API_OFFSET_MAX = Integer.MAX_VALUE; 34 | 35 | /** 36 | * Ranges for binder values. 37 | */ 38 | public static final int API_NAME_LEN_MIN = 1; 39 | public static final int API_NAME_LEN_MAX = 250; 40 | 41 | public static final int API_MAPCODE_LEN_MIN = 1; 42 | public static final int API_MAPCODE_LEN_MAX = 19; 43 | 44 | public static final int API_TERRITORY_LEN_MIN = 2; 45 | public static final int API_TERRITORY_LEN_MAX = 7; 46 | 47 | public static final int API_VERSION_LEN_MIN = 1; 48 | public static final int API_VERSION_LEN_MAX = 250; 49 | 50 | public static final double API_LAT_MAX = 90.0; 51 | public static final double API_LAT_MIN = -90.0; 52 | 53 | public static final int API_PRECISION_MIN = 0; 54 | public static final int API_PRECISION_MAX = 8; 55 | 56 | public static final int WEB_ID_MAX_LENGTH = 200; 57 | public static final int WEB_ID_MIN_LENGTH = 0; 58 | 59 | public static final int WEB_APP_TOKEN_MAX_LENGTH = 255; 60 | public static final int WEB_APP_TOKEN_MIN_LENGTH = 1; 61 | 62 | public static final int WEB_PASSWORD_MAX_LENGTH = 32; 63 | public static final int WEB_PASSWORD_MIN_LENGTH = 6; 64 | 65 | public static final int WEB_USER_NAME_MAX_LENGTH = 64; 66 | public static final int WEB_USER_NAME_MIN_LENGTH = 1; 67 | 68 | // Prevent instantiation. 69 | private ApiConstants() { 70 | super(); 71 | assert false; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/OnlyJsonResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import com.tomtom.speedtools.apivalidation.exceptions.ApiException; 20 | 21 | import javax.annotation.Nonnull; 22 | import javax.annotation.Nullable; 23 | import javax.ws.rs.*; 24 | import javax.ws.rs.container.AsyncResponse; 25 | import javax.ws.rs.container.Suspended; 26 | import javax.ws.rs.core.MediaType; 27 | 28 | import static com.mapcode.services.MapcodeResource.*; 29 | 30 | /** 31 | * This class handle the Mapcode REST API, which includes conversions to and from mapcodes. 32 | */ 33 | @Path("/mapcode/json") 34 | public interface OnlyJsonResource { 35 | 36 | @Path("version") 37 | @GET 38 | @Produces(MediaType.APPLICATION_JSON) 39 | void getVersionJson(@Suspended @Nonnull AsyncResponse response); 40 | 41 | @Path("status") 42 | @Produces(MediaType.APPLICATION_JSON) 43 | @GET 44 | void getStatusJson(@Suspended @Nonnull AsyncResponse response); 45 | 46 | @GET 47 | @Produces(MediaType.APPLICATION_JSON) 48 | @Path("codes") 49 | void convertLatLonToMapcodeJson( 50 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 51 | 52 | @GET 53 | @Produces(MediaType.APPLICATION_JSON) 54 | @Path("codes/{" + PARAM_LAT_DEG + "},{" + PARAM_LON_DEG + '}') 55 | void convertLatLonToMapcodeJson( 56 | @PathParam(PARAM_LAT_DEG) @Nullable String paramLatDegAsString, 57 | @PathParam(PARAM_LON_DEG) @Nullable String paramLonDegAsString, 58 | @QueryParam(PARAM_PRECISION) @DefaultValue("0") @Nullable String paramPrecisionAsString, 59 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritory, 60 | @QueryParam(PARAM_COUNTRY) @Nullable String paramCountry, 61 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContextMustBeNull, 62 | @QueryParam(PARAM_ALPHABET) @Nullable String paramAlphabet, 63 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 64 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 65 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 66 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 67 | 68 | @GET 69 | @Produces(MediaType.APPLICATION_JSON) 70 | @Path("codes/{" + PARAM_LAT_DEG + "},{" + PARAM_LON_DEG + "}/{" + PARAM_TYPE + '}') 71 | void convertLatLonToMapcodeJson( 72 | @PathParam(PARAM_LAT_DEG) @Nullable String paramLatDegAsString, 73 | @PathParam(PARAM_LON_DEG) @Nullable String paramLonDegAsString, 74 | @PathParam(PARAM_TYPE) @Nullable String paramType, 75 | @QueryParam(PARAM_PRECISION) @DefaultValue("0") @Nullable String paramPrecisionAsString, 76 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritory, 77 | @QueryParam(PARAM_COUNTRY) @Nullable String paramCountry, 78 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContextMustBeNull, 79 | @QueryParam(PARAM_ALPHABET) @Nullable String paramAlphabet, 80 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 81 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 82 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramDebug, 83 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 84 | 85 | @GET 86 | @Produces(MediaType.APPLICATION_JSON) 87 | @Path("coords") 88 | void convertMapcodeToLatLonJson( 89 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 90 | 91 | @GET 92 | @Produces(MediaType.APPLICATION_JSON) 93 | @Path("coords/{" + PARAM_MAPCODE + '}') 94 | void convertMapcodeToLatLonJson( 95 | @PathParam(PARAM_MAPCODE) @Nonnull String paramCode, 96 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContext, 97 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritoryMustBeNull, 98 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 99 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 100 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramDebug, 101 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 102 | 103 | @GET 104 | @Produces(MediaType.APPLICATION_JSON) 105 | @Path("territories") 106 | void getTerritoriesJson( 107 | @QueryParam(PARAM_OFFSET) @DefaultValue(DEFAULT_OFFSET) int offset, 108 | @QueryParam(PARAM_COUNT) @DefaultValue(DEFAULT_COUNT) int count, 109 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 110 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 111 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 112 | 113 | @GET 114 | @Produces(MediaType.APPLICATION_JSON) 115 | @Path("territories/{" + PARAM_TERRITORY + '}') 116 | void getTerritoryJson( 117 | @PathParam(PARAM_TERRITORY) @Nonnull String paramTerritory, 118 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContext, 119 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 120 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 121 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 122 | 123 | @GET 124 | @Produces(MediaType.APPLICATION_JSON) 125 | @Path("alphabets") 126 | void getAlphabetsJson( 127 | @QueryParam(PARAM_OFFSET) @DefaultValue(DEFAULT_OFFSET) int offset, 128 | @QueryParam(PARAM_COUNT) @DefaultValue(DEFAULT_COUNT) int count, 129 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 130 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 131 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 132 | 133 | @GET 134 | @Produces(MediaType.APPLICATION_JSON) 135 | @Path("alphabets/{" + PARAM_ALPHABET + '}') 136 | void getAlphabetJson( 137 | @PathParam(PARAM_ALPHABET) @Nonnull String paramAlphabet, 138 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 139 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 140 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 141 | } 142 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/OnlyXmlResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import com.tomtom.speedtools.apivalidation.exceptions.ApiException; 20 | 21 | import javax.annotation.Nonnull; 22 | import javax.annotation.Nullable; 23 | import javax.ws.rs.*; 24 | import javax.ws.rs.container.AsyncResponse; 25 | import javax.ws.rs.container.Suspended; 26 | import javax.ws.rs.core.MediaType; 27 | 28 | import static com.mapcode.services.MapcodeResource.*; 29 | 30 | /** 31 | * This class handle the Mapcode REST API, which includes conversions to and from mapcodes. 32 | */ 33 | @Path("/mapcode/xml") 34 | public interface OnlyXmlResource { 35 | 36 | @Path("version") 37 | @GET 38 | @Produces(MediaType.APPLICATION_XML) 39 | void getVersionXml(@Suspended @Nonnull AsyncResponse response); 40 | 41 | @Path("status") 42 | @Produces(MediaType.APPLICATION_XML) 43 | @GET 44 | void getStatusXml(@Suspended @Nonnull AsyncResponse response); 45 | 46 | @GET 47 | @Produces(MediaType.APPLICATION_XML) 48 | @Path("codes") 49 | void convertLatLonToMapcodeXml( 50 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 51 | 52 | @GET 53 | @Produces(MediaType.APPLICATION_XML) 54 | @Path("codes/{" + PARAM_LAT_DEG + "},{" + PARAM_LON_DEG + '}') 55 | void convertLatLonToMapcodeXml( 56 | @PathParam(PARAM_LAT_DEG) @Nullable String paramLatDegAsString, 57 | @PathParam(PARAM_LON_DEG) @Nullable String paramLonDegAsString, 58 | @QueryParam(PARAM_PRECISION) @DefaultValue("0") @Nullable String paramPrecisionAsString, 59 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritory, 60 | @QueryParam(PARAM_COUNTRY) @Nullable String paramCountry, 61 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContextMustBeNull, 62 | @QueryParam(PARAM_ALPHABET) @Nullable String paramAlphabet, 63 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 64 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 65 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 66 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 67 | 68 | @GET 69 | @Produces(MediaType.APPLICATION_XML) 70 | @Path("codes/{" + PARAM_LAT_DEG + "},{" + PARAM_LON_DEG + "}/{" + PARAM_TYPE + '}') 71 | void convertLatLonToMapcodeXml( 72 | @PathParam(PARAM_LAT_DEG) @Nullable String paramLatDegAsString, 73 | @PathParam(PARAM_LON_DEG) @Nullable String paramLonDegAsString, 74 | @PathParam(PARAM_TYPE) @Nullable String paramType, 75 | @QueryParam(PARAM_PRECISION) @DefaultValue("0") @Nullable String paramPrecisionAsString, 76 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritory, 77 | @QueryParam(PARAM_COUNTRY) @Nullable String paramCountry, 78 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContextMustBeNull, 79 | @QueryParam(PARAM_ALPHABET) @Nullable String paramAlphabet, 80 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 81 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 82 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramDebug, 83 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 84 | 85 | @GET 86 | @Produces(MediaType.APPLICATION_XML) 87 | @Path("coords") 88 | void convertMapcodeToLatLonXml( 89 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 90 | 91 | @GET 92 | @Produces(MediaType.APPLICATION_XML) 93 | @Path("coords/{" + PARAM_MAPCODE + '}') 94 | void convertMapcodeToLatLonXml( 95 | @PathParam(PARAM_MAPCODE) @Nonnull String paramCode, 96 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContext, 97 | @QueryParam(PARAM_TERRITORY) @Nullable String paramTerritoryMustBeNull, 98 | @QueryParam(PARAM_INCLUDE) @DefaultValue("") @Nonnull String paramInclude, 99 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 100 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramDebug, 101 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 102 | 103 | @GET 104 | @Produces(MediaType.APPLICATION_XML) 105 | @Path("territories") 106 | void getTerritoriesXml( 107 | @QueryParam(PARAM_OFFSET) @DefaultValue(DEFAULT_OFFSET) int offset, 108 | @QueryParam(PARAM_COUNT) @DefaultValue(DEFAULT_COUNT) int count, 109 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 110 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 111 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 112 | 113 | @GET 114 | @Produces(MediaType.APPLICATION_XML) 115 | @Path("territories/{" + PARAM_TERRITORY + '}') 116 | void getTerritoryXml( 117 | @PathParam(PARAM_TERRITORY) @Nonnull String paramTerritory, 118 | @QueryParam(PARAM_CONTEXT) @Nullable String paramContext, 119 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 120 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 121 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 122 | 123 | @GET 124 | @Produces(MediaType.APPLICATION_XML) 125 | @Path("alphabets") 126 | void getAlphabetsXml( 127 | @QueryParam(PARAM_OFFSET) @DefaultValue(DEFAULT_OFFSET) int offset, 128 | @QueryParam(PARAM_COUNT) @DefaultValue(DEFAULT_COUNT) int count, 129 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 130 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 131 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 132 | 133 | @GET 134 | @Produces(MediaType.APPLICATION_XML) 135 | @Path("alphabets/{" + PARAM_ALPHABET + '}') 136 | void getAlphabetXml( 137 | @PathParam(PARAM_ALPHABET) @Nonnull String paramAlphabet, 138 | @QueryParam(PARAM_CLIENT) @DefaultValue("") @Nonnull String paramClient, 139 | @QueryParam(PARAM_ALLOW_LOG) @DefaultValue("true") @Nonnull String paramAllowLog, 140 | @Suspended @Nonnull AsyncResponse response) throws ApiException; 141 | } 142 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/ResourcesModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import com.google.inject.Binder; 20 | import com.google.inject.Module; 21 | import com.google.inject.Provides; 22 | import com.mapcode.services.implementation.*; 23 | import com.mapcode.services.jmx.SystemMetricsAgent; 24 | import com.mapcode.services.metrics.SystemMetrics; 25 | import com.mapcode.services.metrics.SystemMetricsCollector; 26 | 27 | import javax.annotation.Nonnull; 28 | import javax.inject.Singleton; 29 | 30 | 31 | /** 32 | * This class defines the deployment configuration for Google Guice. 33 | *

34 | * The deployment module "bootstraps" the whole Guice injection process. 35 | *

36 | * It bootstraps the Guice injection and specifies the property files to be read. It also needs to bind the tracer, so 37 | * they can be used early on in the app. Finally, it can bind a "startup check" (example provided) as an eager 38 | * singleton, so the system won't start unless a set of basic preconditions are fulfilled. 39 | *

40 | * The "speedtools.default.properties" is required, but its values may be overridden in other property files. 41 | */ 42 | public class ResourcesModule implements Module { 43 | 44 | @Override 45 | public void configure(@Nonnull final Binder binder) { 46 | assert binder != null; 47 | 48 | // Bind APIs to their implementation. 49 | binder.bind(RootResource.class).to(RootResourceImpl.class).in(Singleton.class); 50 | binder.bind(MapcodeResource.class).to(MapcodeResourceImpl.class).in(Singleton.class); 51 | binder.bind(OnlyJsonResource.class).to(OnlyJsonResourceImpl.class).in(Singleton.class); 52 | binder.bind(OnlyXmlResource.class).to(OnlyXmlResourceImpl.class).in(Singleton.class); 53 | 54 | // JMX interface. 55 | binder.bind(SystemMetricsImpl.class).in(Singleton.class); 56 | binder.bind(SystemMetricsAgent.class).in(Singleton.class); 57 | } 58 | 59 | @Provides 60 | @Singleton 61 | @Nonnull 62 | public SystemMetrics provideSystemMetrics( 63 | @Nonnull final SystemMetricsImpl impl) { 64 | assert impl != null; 65 | return impl; 66 | } 67 | 68 | @Provides 69 | @Singleton 70 | @Nonnull 71 | public SystemMetricsCollector provideSystemMetricsCollector( 72 | @Nonnull final SystemMetricsImpl impl) { 73 | assert impl != null; 74 | return impl; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/RootResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import io.swagger.annotations.Api; 20 | import io.swagger.annotations.ApiOperation; 21 | import io.swagger.annotations.ApiResponse; 22 | import io.swagger.annotations.ApiResponses; 23 | 24 | import javax.annotation.Nonnull; 25 | import javax.ws.rs.GET; 26 | import javax.ws.rs.Path; 27 | import javax.ws.rs.Produces; 28 | import javax.ws.rs.container.AsyncResponse; 29 | import javax.ws.rs.container.Suspended; 30 | import javax.ws.rs.core.MediaType; 31 | 32 | @SuppressWarnings("SimplifiableAnnotation") 33 | @Api(value = "monitoring", description = "These resources are provided for monitoring purposes.") 34 | @Path("/mapcode") 35 | public interface RootResource { 36 | 37 | /** 38 | * This method provides help info. 39 | * 40 | * @return Returns help text as HTML. 41 | */ 42 | @ApiOperation( 43 | value = "Provide a simple help page for the REST API.") 44 | @ApiResponses(@ApiResponse(code = 200, message = "HTML help page.")) 45 | @GET 46 | @Produces(MediaType.TEXT_HTML) 47 | @Nonnull 48 | String getHelpHTML(); 49 | 50 | /** 51 | * This method provides a version number for the service. Normally, this is the 52 | * version number of the pom.xml file. 53 | * 54 | * @param response Returns a version number as JSON. 55 | */ 56 | @ApiOperation( 57 | value = "Returns the version number of the REST API.") 58 | @ApiResponses({ 59 | @ApiResponse(code = 200, message = "Version number (no assumption can be made on its format).")}) 60 | @Path("version") 61 | @GET 62 | @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 63 | void getVersion(@Suspended @Nonnull AsyncResponse response); 64 | 65 | /** 66 | * This method returns whether the service is operational or not (status code 200 is OK). 67 | * 68 | * @param response Returns a version number as JSON. 69 | */ 70 | @ApiOperation( 71 | value = "Indicates whether the service is active or not.") 72 | @ApiResponses({ 73 | @ApiResponse(code = 200, message = "Service is working.")}) 74 | @Path("status") 75 | @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 76 | @GET 77 | void getStatus(@Suspended @Nonnull AsyncResponse response); 78 | 79 | /** 80 | * This method returns system metrics. 81 | * 82 | * @param response Returns a system metrics. 83 | */ 84 | @Path("metrics") 85 | @GET 86 | @Produces(MediaType.APPLICATION_JSON) 87 | void getMetrics(@Suspended @Nonnull AsyncResponse response); 88 | } 89 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/AlphabetDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.Alphabet; 22 | import com.tomtom.speedtools.apivalidation.ApiDTO; 23 | import io.swagger.annotations.ApiModel; 24 | import io.swagger.annotations.ApiModelProperty; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.xml.bind.annotation.XmlAccessType; 28 | import javax.xml.bind.annotation.XmlAccessorType; 29 | import javax.xml.bind.annotation.XmlElement; 30 | import javax.xml.bind.annotation.XmlRootElement; 31 | 32 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 33 | @ApiModel( 34 | value = "alphabet", 35 | description = "An alphabet definition object, such as returned by `GET /mapcode/alphabets/roman`.") 36 | @JsonInclude(Include.NON_EMPTY) 37 | @XmlRootElement(name = "alphabet") 38 | @XmlAccessorType(XmlAccessType.FIELD) 39 | public final class AlphabetDTO extends ApiDTO { 40 | 41 | @ApiModelProperty( 42 | name = "name", 43 | value = "The name of the alphabet. Currently, this is the only attribute for an alphabet.") 44 | @XmlElement(name = "name") 45 | @Nonnull 46 | private String name; 47 | 48 | @Override 49 | public void validate() { 50 | validator().start(); 51 | validator().checkNotNull(true, "name", name); 52 | validator().done(); 53 | } 54 | 55 | public AlphabetDTO(@Nonnull final String name) { 56 | this.name = name; 57 | } 58 | 59 | public AlphabetDTO(@Nonnull final Alphabet alphabet) { 60 | this(alphabet.name()); 61 | } 62 | 63 | @SuppressWarnings("UnusedDeclaration") 64 | @Deprecated 65 | private AlphabetDTO() { 66 | // Default constructor required by JAX-B. 67 | super(); 68 | } 69 | 70 | @Nonnull 71 | public String getName() { 72 | beforeGet(); 73 | return name; 74 | } 75 | 76 | public void setName(@Nonnull final String name) { 77 | beforeSet(); 78 | assert name != null; 79 | this.name = name; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/AlphabetListDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.Alphabet; 22 | import com.tomtom.speedtools.apivalidation.ApiListDTO; 23 | 24 | import javax.annotation.Nonnull; 25 | import javax.xml.bind.annotation.XmlAccessType; 26 | import javax.xml.bind.annotation.XmlAccessorType; 27 | import javax.xml.bind.annotation.XmlRootElement; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | import java.util.stream.Collectors; 31 | 32 | @JsonInclude(Include.NON_EMPTY) 33 | @XmlRootElement(name = "alphabets") 34 | @XmlAccessorType(XmlAccessType.FIELD) 35 | public final class AlphabetListDTO extends ApiListDTO { 36 | 37 | @Override 38 | public void validateOne(@Nonnull final AlphabetDTO elm) { 39 | validator().checkNotNullAndValidate(true, "alphabet", elm); 40 | } 41 | 42 | public AlphabetListDTO(@Nonnull final List alphabets) { 43 | super(alphabets); 44 | } 45 | 46 | public AlphabetListDTO(@Nonnull final Alphabet... alphabets) { 47 | this(Arrays.stream(alphabets).map(AlphabetDTO::new).collect(Collectors.toList())); 48 | } 49 | 50 | @SuppressWarnings("UnusedDeclaration") 51 | @Deprecated 52 | private AlphabetListDTO() { 53 | // Default constructor required by JAX-B. 54 | super(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/AlphabetsDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 23 | import com.mapcode.Alphabet; 24 | import com.tomtom.speedtools.apivalidation.ApiDTO; 25 | import io.swagger.annotations.ApiModel; 26 | import io.swagger.annotations.ApiModelProperty; 27 | 28 | import javax.annotation.Nonnull; 29 | import javax.xml.bind.annotation.XmlAccessType; 30 | import javax.xml.bind.annotation.XmlAccessorType; 31 | import javax.xml.bind.annotation.XmlElement; 32 | import javax.xml.bind.annotation.XmlRootElement; 33 | 34 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 35 | @ApiModel( 36 | value = "alphabets", 37 | description = "A list of alphabet objects, such as returned by `GET /mapcode/alphabets`.") 38 | @JsonInclude(Include.NON_EMPTY) 39 | @XmlRootElement(name = "alphabets") 40 | @XmlAccessorType(XmlAccessType.FIELD) 41 | public final class AlphabetsDTO extends ApiDTO { 42 | 43 | @ApiModelProperty( 44 | name = "total", 45 | value = "The total number of alphabet objects (not just the ones in this response).") 46 | @JsonProperty("total") 47 | @XmlElement(name = "total") 48 | @Nonnull 49 | private int total; 50 | 51 | @ApiModelProperty( 52 | name = "alphabets", 53 | value = "A list of alphabet objects.", 54 | dataType = "com.mapcode.services.dto.AlphabetDTO", 55 | reference = "com.mapcode.services.dto.AlphabetDTO") 56 | @JsonProperty("alphabets") 57 | @JsonUnwrapped 58 | @XmlElement(name = "alphabet") 59 | @Nonnull 60 | private AlphabetListDTO alphabets; 61 | 62 | @Override 63 | public void validate() { 64 | validator().start(); 65 | validator().checkInteger(true, "total", total, 0, Alphabet.values().length); 66 | validator().checkNotNullAndValidateAll(false, "alphabets", alphabets); 67 | validator().done(); 68 | } 69 | 70 | public AlphabetsDTO( 71 | final int total, 72 | @Nonnull final AlphabetListDTO alphabets) { 73 | this.total = total; 74 | this.alphabets = alphabets; 75 | } 76 | 77 | public AlphabetsDTO( 78 | final int total, 79 | @Nonnull final Alphabet... alphabets) { 80 | this(total, new AlphabetListDTO(alphabets)); 81 | } 82 | 83 | @SuppressWarnings("UnusedDeclaration") 84 | @Deprecated 85 | private AlphabetsDTO() { 86 | // Default constructor required by JAX-B. 87 | super(); 88 | } 89 | 90 | public int getTotal() { 91 | beforeGet(); 92 | return total; 93 | } 94 | 95 | public void setTotal(final int total) { 96 | beforeSet(); 97 | this.total = total; 98 | } 99 | 100 | @Nonnull 101 | public AlphabetListDTO getAlphabets() { 102 | beforeGet(); 103 | return alphabets; 104 | } 105 | 106 | public void setAlphabets(@Nonnull final AlphabetListDTO alphabets) { 107 | beforeSet(); 108 | this.alphabets = alphabets; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/MapcodeDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.services.ApiConstants; 22 | import com.tomtom.speedtools.apivalidation.ApiDTO; 23 | import io.swagger.annotations.ApiModel; 24 | import io.swagger.annotations.ApiModelProperty; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import javax.xml.bind.annotation.XmlAccessType; 29 | import javax.xml.bind.annotation.XmlAccessorType; 30 | import javax.xml.bind.annotation.XmlElement; 31 | import javax.xml.bind.annotation.XmlRootElement; 32 | 33 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 34 | @ApiModel( 35 | value = "mapcode", 36 | description = "A mapcode object, such as returned by `GET /mapcode/codes/52,5/local`.") 37 | @JsonInclude(Include.NON_EMPTY) 38 | @XmlRootElement(name = "mapcode") 39 | @XmlAccessorType(XmlAccessType.FIELD) 40 | public final class MapcodeDTO extends ApiDTO { 41 | 42 | @ApiModelProperty( 43 | name = "mapcode", 44 | value = "The mapcode without the territory code. Format: 5-10 characters, including the '.'.", 45 | example = "2TNM") 46 | @XmlElement(name = "mapcode") 47 | @Nonnull 48 | private String mapcode; 49 | 50 | @ApiModelProperty( 51 | name = "mapcodeInAlphabet", 52 | value = "(optional) The same mapcode in a specific alphabet. " + 53 | "To view which alphabets are available: `GET /mapcode/alphabets`") 54 | @XmlElement(name = "mapcodeInAlphabet") 55 | @Nullable 56 | private String mapcodeInAlphabet; 57 | 58 | @ApiModelProperty( 59 | name = "territory", 60 | value = "The territory code. Format: `XXX` or `XX-YY`. " + 61 | "To view which alphabets are available: `GET /mapcode/territories`", 62 | example = "NLD") 63 | @XmlElement(name = "territory") 64 | @Nullable 65 | private String territory; 66 | 67 | @ApiModelProperty( 68 | name = "territoryInAlphabet", 69 | value = "(optional) The same territory code in a specific alphabet.") 70 | @XmlElement(name = "territoryInAlphabet") 71 | @Nullable 72 | private String territoryInAlphabet; 73 | 74 | @ApiModelProperty( 75 | name = "offsetMeters", 76 | value = "(optional) The approximated offset from the specified coordinate " + 77 | "to the center of this mapcode area.") 78 | @XmlElement(name = "offsetMeters") 79 | @Nullable 80 | private Double offsetMeters; 81 | 82 | @ApiModelProperty( 83 | name = "rectangle", 84 | value = "(optional) The rectangular area covered by the mapcode.") 85 | @XmlElement(name = "rectangle") 86 | @Nullable 87 | private RectangleDTO rectangle; 88 | 89 | @Override 90 | public void validate() { 91 | validator().start(); 92 | validator().checkString(true, "mapcode", mapcode, ApiConstants.API_MAPCODE_LEN_MIN, ApiConstants.API_MAPCODE_LEN_MAX); 93 | validator().checkString(false, "mapcodeInAlphabet", mapcodeInAlphabet, ApiConstants.API_MAPCODE_LEN_MIN, ApiConstants.API_MAPCODE_LEN_MAX); 94 | validator().checkString(false, "territory", territory, ApiConstants.API_TERRITORY_LEN_MIN, ApiConstants.API_TERRITORY_LEN_MAX); 95 | validator().checkString(false, "territoryInAlphabet", territoryInAlphabet, ApiConstants.API_TERRITORY_LEN_MIN, ApiConstants.API_TERRITORY_LEN_MAX); 96 | validator().checkDouble(false, "offsetMeters", offsetMeters, -Double.MAX_VALUE, Double.MAX_VALUE, false); 97 | validator().checkNotNullAndValidate(false, "rectangle", rectangle); 98 | validator().done(); 99 | } 100 | 101 | public MapcodeDTO( 102 | @Nonnull final String mapcode, 103 | @Nullable final String mapcodeInAlphabet, 104 | @Nullable final String territory, 105 | @Nullable final String territoryInAlphabet, 106 | @Nullable final Double offsetMeters, 107 | @Nullable final RectangleDTO rectangle) { 108 | this.mapcode = mapcode; 109 | this.mapcodeInAlphabet = mapcodeInAlphabet; 110 | this.territory = territory; 111 | this.territoryInAlphabet = territoryInAlphabet; 112 | this.offsetMeters = offsetMeters; 113 | this.rectangle = rectangle; 114 | } 115 | 116 | public MapcodeDTO( 117 | @Nonnull final String mapcode, 118 | @Nullable final String mapcodeInAlphabet, 119 | @Nullable final String territory, 120 | @Nullable final String territoryInAlphabet, 121 | @Nullable final Double offsetMeters) { 122 | this(mapcode, mapcodeInAlphabet, territory, territoryInAlphabet, offsetMeters, null); 123 | } 124 | 125 | public MapcodeDTO( 126 | @Nonnull final String mapcode, 127 | @Nullable final String mapcodeInAlphabet, 128 | @Nullable final String territory, 129 | @Nullable final String territoryInAlphabet) { 130 | this(mapcode, mapcodeInAlphabet, territory, territoryInAlphabet, null, null); 131 | } 132 | 133 | public MapcodeDTO( 134 | @Nonnull final String mapcode, 135 | @Nullable final String mapcodeInAlphabet, 136 | @Nullable final String territory) { 137 | this(mapcode, mapcodeInAlphabet, territory, null, null, null); 138 | } 139 | 140 | public MapcodeDTO( 141 | @Nonnull final String mapcode, 142 | @Nullable final String mapcodeInAlphabet) { 143 | this(mapcode, mapcodeInAlphabet, null, null, null, null); 144 | } 145 | 146 | public MapcodeDTO(@Nonnull final String mapcode) { 147 | this(mapcode, null, null, null, null, null); 148 | } 149 | 150 | @SuppressWarnings("UnusedDeclaration") 151 | @Deprecated 152 | private MapcodeDTO() { 153 | // Default constructor required by JAX-B. 154 | super(); 155 | } 156 | 157 | @Nonnull 158 | public String getMapcode() { 159 | beforeGet(); 160 | return mapcode; 161 | } 162 | 163 | public void setMapcode(@Nonnull final String mapcode) { 164 | beforeSet(); 165 | assert mapcode != null; 166 | this.mapcode = mapcode; 167 | } 168 | 169 | @Nullable 170 | public String getMapcodeInAlphabet() { 171 | beforeGet(); 172 | return mapcodeInAlphabet; 173 | } 174 | 175 | public void setMapcodeInAlphabet(@Nullable final String mapcodeInAlphabet) { 176 | beforeSet(); 177 | this.mapcodeInAlphabet = mapcodeInAlphabet; 178 | } 179 | 180 | @Nullable 181 | public String getTerritory() { 182 | beforeGet(); 183 | return territory; 184 | } 185 | 186 | public void setTerritory(@Nullable final String territory) { 187 | beforeSet(); 188 | this.territory = territory; 189 | } 190 | 191 | @Nullable 192 | public String getTerritoryInAlphabet() { 193 | beforeGet(); 194 | return territoryInAlphabet; 195 | } 196 | 197 | public void setTerritoryInAlphabet(@Nullable final String territoryInAlphabet) { 198 | beforeSet(); 199 | this.territoryInAlphabet = territoryInAlphabet; 200 | } 201 | 202 | @Nullable 203 | public Double getOffsetMeters() { 204 | beforeGet(); 205 | return offsetMeters; 206 | } 207 | 208 | public void setOffsetMeters(@Nullable final Double offsetMeters) { 209 | beforeSet(); 210 | this.offsetMeters = offsetMeters; 211 | } 212 | 213 | @Nullable 214 | public RectangleDTO getRectangle() { 215 | beforeGet(); 216 | return rectangle; 217 | } 218 | 219 | public void setRectangle(@Nullable final RectangleDTO rectangle) { 220 | beforeSet(); 221 | this.rectangle = rectangle; 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/MapcodeListDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.tomtom.speedtools.apivalidation.ApiListDTO; 22 | 23 | import javax.annotation.Nonnull; 24 | import javax.xml.bind.annotation.XmlAccessType; 25 | import javax.xml.bind.annotation.XmlAccessorType; 26 | import javax.xml.bind.annotation.XmlRootElement; 27 | import java.util.List; 28 | 29 | @JsonInclude(Include.NON_EMPTY) 30 | @XmlRootElement(name = "mapcodes") 31 | @XmlAccessorType(XmlAccessType.FIELD) 32 | public final class MapcodeListDTO extends ApiListDTO { 33 | 34 | @Override 35 | public void validateOne(@Nonnull final MapcodeDTO elm) { 36 | validator().checkNotNullAndValidate(true, "mapcode", elm); 37 | } 38 | 39 | public MapcodeListDTO(@Nonnull final List mapcodes) { 40 | super(mapcodes); 41 | } 42 | 43 | @SuppressWarnings("UnusedDeclaration") 44 | @Deprecated 45 | private MapcodeListDTO() { 46 | // Default constructor required by JAX-B. 47 | super(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/MapcodesDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | import com.tomtom.speedtools.apivalidation.ApiDTO; 23 | import io.swagger.annotations.ApiModel; 24 | import io.swagger.annotations.ApiModelProperty; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import javax.xml.bind.annotation.*; 29 | import java.util.List; 30 | 31 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 32 | @ApiModel( 33 | value = "mapcodes", 34 | description = "A full coordinate to mapcode response object, such as returned by `GET /mapcode/codes/52,5`.") 35 | @JsonInclude(Include.NON_EMPTY) 36 | @XmlRootElement(name = "mapcodes") 37 | @XmlAccessorType(XmlAccessType.FIELD) 38 | public final class MapcodesDTO extends ApiDTO { 39 | 40 | @ApiModelProperty( 41 | name = "local", 42 | value = "A local mapcode. This is the shortest local mapcode which seems to best match input coordinate. " + 43 | "Note that coordinates near borders of adjacent territories may be covered by different local " + 44 | "mapcodes (with different territory codes). In such cases, the 'local' mapcode may not always " + 45 | "specify the territory you would expect. The `mapcodes` attribute will contain the 'correct' local " + 46 | "mapcode in those cases. This `local` mapcode is only offered as a convenience.") 47 | @XmlElement(name = "local") 48 | @Nullable 49 | private MapcodeDTO local; 50 | 51 | @ApiModelProperty( 52 | name = "international", 53 | value = "The international mapcode. This is globally unique mapcode, which does not require a territory " + 54 | "code. The downside of using international mapcodes is their length: they are always 10 characters.") 55 | @XmlElement(name = "international") 56 | @Nonnull 57 | private MapcodeDTO international; 58 | 59 | @ApiModelProperty( 60 | name = "mapcodes", 61 | value = "The list of all alternative mapcodes for the specified coordinate. Coordinates near borders of " + 62 | "territories may be covered by mapcodes from multiple territories and within a single territory, " + 63 | "mapcodes of different lengths may exist. Normally, the logical thing to do, is select the shortest " + 64 | "mapcode in the correct territory from this list. The attribute `local` tries to achieve this as well " + 65 | "but in some cases it may use a territory you don't wish to use.", 66 | dataType = "com.mapcode.services.dto.MapcodeDTO", 67 | reference = "com.mapcode.services.dto.MapcodeDTO") 68 | @JsonProperty("mapcodes") 69 | @XmlElementWrapper(name = "mapcodes") 70 | @XmlElement(name = "mapcode") 71 | @Nonnull 72 | private MapcodeListDTO mapcodes; 73 | 74 | @Override 75 | public void validate() { 76 | validator().start(); 77 | validator().checkNotNullAndValidate(false, "local", local); 78 | validator().checkNotNullAndValidate(true, "international", international); 79 | validator().checkNotNullAndValidateAll(true, "mapcodes", mapcodes); 80 | validator().done(); 81 | } 82 | 83 | public MapcodesDTO( 84 | @Nullable final MapcodeDTO local, 85 | @Nonnull final MapcodeDTO international, 86 | @Nonnull final MapcodeListDTO mapcodes) { 87 | this.local = local; 88 | this.international = international; 89 | this.mapcodes = mapcodes; 90 | } 91 | 92 | public MapcodesDTO( 93 | @Nullable final MapcodeDTO local, 94 | @Nonnull final MapcodeDTO international, 95 | @Nonnull final List mapcodes) { 96 | this(local, international, new MapcodeListDTO(mapcodes)); 97 | } 98 | 99 | @SuppressWarnings("UnusedDeclaration") 100 | @Deprecated 101 | private MapcodesDTO() { 102 | // Default constructor required by JAX-B. 103 | super(); 104 | } 105 | 106 | @Nullable 107 | public MapcodeDTO getLocal() { 108 | beforeGet(); 109 | return local; 110 | } 111 | 112 | public void setLocal(@Nullable final MapcodeDTO local) { 113 | beforeSet(); 114 | this.local = local; 115 | } 116 | 117 | @Nonnull 118 | public MapcodeDTO getInternational() { 119 | beforeGet(); 120 | return international; 121 | } 122 | 123 | public void setInternational(@Nonnull final MapcodeDTO international) { 124 | beforeSet(); 125 | assert international != null; 126 | this.international = international; 127 | } 128 | 129 | @Nonnull 130 | public List getMapcodes() { 131 | beforeGet(); 132 | return mapcodes; 133 | } 134 | 135 | public void setMapcodes(@Nonnull final MapcodeListDTO mapcodes) { 136 | beforeSet(); 137 | assert mapcodes != null; 138 | this.mapcodes = mapcodes; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/PointDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.Point; 22 | import com.mapcode.services.ApiConstants; 23 | import com.tomtom.speedtools.apivalidation.ApiDTO; 24 | import io.swagger.annotations.ApiModel; 25 | import io.swagger.annotations.ApiModelProperty; 26 | 27 | import javax.annotation.Nonnull; 28 | import javax.xml.bind.annotation.XmlAccessType; 29 | import javax.xml.bind.annotation.XmlAccessorType; 30 | import javax.xml.bind.annotation.XmlElement; 31 | import javax.xml.bind.annotation.XmlRootElement; 32 | 33 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 34 | @ApiModel( 35 | value = "point", 36 | description = "A WGS84 coordinate, specified as a latitude and logitude.") 37 | @JsonInclude(Include.NON_EMPTY) 38 | @XmlRootElement(name = "point") 39 | @XmlAccessorType(XmlAccessType.FIELD) 40 | public final class PointDTO extends ApiDTO { 41 | 42 | @ApiModelProperty( 43 | name = "latDeg", 44 | value = "The latitude (South-North) in degrees. Format: [-90, 90], 0 indicates the equator.", 45 | allowableValues = "range[-90,90]") 46 | @XmlElement(name = "latDeg") 47 | @Nonnull 48 | private Double latDeg; 49 | 50 | @ApiModelProperty( 51 | name = "lonDeg", 52 | value = "The longitude (West-East) in degrees. Format: [-180, 180), 0 indicates the Greenwich meridian.", 53 | allowableValues = "range[-180,180]") 54 | @XmlElement(name = "lonDeg") 55 | @Nonnull 56 | private Double lonDeg; 57 | 58 | @Override 59 | public void validate() { 60 | validator().start(); 61 | validator().checkDouble(true, "latDeg", latDeg, ApiConstants.API_LAT_MIN, ApiConstants.API_LAT_MAX, false); 62 | validator().checkDouble(true, "lonDeg", lonDeg, -Double.MAX_VALUE, Double.MAX_VALUE, false); 63 | validator().done(); 64 | } 65 | 66 | public PointDTO( 67 | @Nonnull final Double latDeg, 68 | @Nonnull final Double lonDeg) { 69 | this.latDeg = latDeg; 70 | this.lonDeg = lonDeg; 71 | } 72 | 73 | public PointDTO(@Nonnull final Point point) { 74 | this(point.getLatDeg(), point.getLonDeg()); 75 | } 76 | 77 | @SuppressWarnings("UnusedDeclaration") 78 | @Deprecated 79 | private PointDTO() { 80 | // Default constructor required by JAX-B. 81 | super(); 82 | } 83 | 84 | @Nonnull 85 | public Double getLatDeg() { 86 | beforeGet(); 87 | return latDeg; 88 | } 89 | 90 | public void setLatDeg(@Nonnull final Double latDeg) { 91 | beforeSet(); 92 | assert latDeg != null; 93 | this.latDeg = latDeg; 94 | } 95 | 96 | @Nonnull 97 | public Double getLonDeg() { 98 | beforeGet(); 99 | return lonDeg; 100 | } 101 | 102 | public void setLonDeg(@Nonnull final Double lonDeg) { 103 | beforeSet(); 104 | assert lonDeg != null; 105 | this.lonDeg = lonDeg; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/RectangleDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.Rectangle; 22 | import com.tomtom.speedtools.apivalidation.ApiDTO; 23 | import io.swagger.annotations.ApiModel; 24 | import io.swagger.annotations.ApiModelProperty; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import javax.xml.bind.annotation.XmlAccessType; 29 | import javax.xml.bind.annotation.XmlAccessorType; 30 | import javax.xml.bind.annotation.XmlElement; 31 | import javax.xml.bind.annotation.XmlRootElement; 32 | 33 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 34 | @ApiModel( 35 | value = "rectangle", 36 | description = "A rectangular geospatial area, defined by its South-West and North-East corners.") 37 | @JsonInclude(Include.NON_EMPTY) 38 | @XmlRootElement(name = "rectangle") 39 | @XmlAccessorType(XmlAccessType.FIELD) 40 | public final class RectangleDTO extends ApiDTO { 41 | 42 | @ApiModelProperty( 43 | name = "southWest", 44 | value = "The South-West corner of the rectangular area.") 45 | @XmlElement(name = "southWest") 46 | @Nonnull 47 | private PointDTO southWest; 48 | 49 | @ApiModelProperty( 50 | name = "northEast", 51 | value = "The North-East corner of the rectangular area.") 52 | @XmlElement(name = "northEast") 53 | @Nonnull 54 | private PointDTO northEast; 55 | 56 | @ApiModelProperty( 57 | name = "center", 58 | value = "The center coordinate of the rectangular area.") 59 | @XmlElement(name = "center") 60 | @Nullable 61 | private PointDTO center; 62 | 63 | @Override 64 | public void validate() { 65 | validator().start(); 66 | validator().checkNotNullAndValidate(true, "southWest", southWest); 67 | validator().checkNotNullAndValidate(true, "northEast", northEast); 68 | validator().checkNotNullAndValidate(false, "center", center); 69 | validator().done(); 70 | } 71 | 72 | public RectangleDTO( 73 | @Nonnull final PointDTO southWest, 74 | @Nonnull final PointDTO northEast, 75 | @Nullable final PointDTO center) { 76 | this.southWest = southWest; 77 | this.northEast = northEast; 78 | this.center = center; 79 | } 80 | 81 | public RectangleDTO( 82 | @Nonnull final PointDTO southWest, 83 | @Nonnull final PointDTO northEast) { 84 | this(southWest, northEast, 85 | new PointDTO((southWest.getLatDeg() + northEast.getLatDeg()) / 2.0, 86 | (southWest.getLonDeg() + northEast.getLonDeg()) / 2.0)); 87 | } 88 | 89 | public RectangleDTO(@Nonnull final Rectangle rectangle) { 90 | this(new PointDTO(rectangle.getSouthWest()), new PointDTO(rectangle.getNorthEast())); 91 | } 92 | 93 | @SuppressWarnings("UnusedDeclaration") 94 | @Deprecated 95 | private RectangleDTO() { 96 | // Default constructor required by JAX-B. 97 | super(); 98 | } 99 | 100 | @Nonnull 101 | public PointDTO getSouthWest() { 102 | beforeGet(); 103 | return southWest; 104 | } 105 | 106 | public void setSouthWest(@Nonnull final PointDTO southWest) { 107 | beforeSet(); 108 | assert southWest != null; 109 | this.southWest = southWest; 110 | } 111 | 112 | @Nonnull 113 | public PointDTO getNorthEast() { 114 | beforeGet(); 115 | return northEast; 116 | } 117 | 118 | public void setNorthEast(@Nonnull final PointDTO northEast) { 119 | beforeSet(); 120 | assert northEast != null; 121 | this.northEast = northEast; 122 | } 123 | 124 | @Nullable 125 | public PointDTO getCenter() { 126 | beforeGet(); 127 | return center; 128 | } 129 | 130 | public void setCenter(@Nullable final PointDTO center) { 131 | beforeSet(); 132 | this.center = center; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/TerritoriesDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 23 | import com.mapcode.Territory; 24 | import com.tomtom.speedtools.apivalidation.ApiDTO; 25 | import io.swagger.annotations.ApiModel; 26 | import io.swagger.annotations.ApiModelProperty; 27 | 28 | import javax.annotation.Nonnull; 29 | import javax.xml.bind.annotation.XmlAccessType; 30 | import javax.xml.bind.annotation.XmlAccessorType; 31 | import javax.xml.bind.annotation.XmlElement; 32 | import javax.xml.bind.annotation.XmlRootElement; 33 | 34 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 35 | @ApiModel( 36 | value = "territories", 37 | description = "A list of territory objects, such as returned by `GET /mapcode/territories`.") 38 | @JsonInclude(Include.NON_EMPTY) 39 | @XmlRootElement(name = "territories") 40 | @XmlAccessorType(XmlAccessType.FIELD) 41 | public final class TerritoriesDTO extends ApiDTO { 42 | 43 | @ApiModelProperty( 44 | name = "total", 45 | value = "The total number of territory objects (not just the ones in this response).") 46 | @JsonProperty("total") 47 | @XmlElement(name = "total") 48 | @Nonnull 49 | private int total; 50 | 51 | @ApiModelProperty( 52 | name = "territories", 53 | value = "A list of territory objects.", 54 | dataType = "com.mapcode.services.dto.TerritoriesDTO", 55 | reference = "com.mapcode.services.dto.TerritoriesDTO") 56 | @JsonProperty("territories") 57 | @JsonUnwrapped 58 | @XmlElement(name = "territory") 59 | @Nonnull 60 | private TerritoryListDTO territories; 61 | 62 | @Override 63 | public void validate() { 64 | validator().start(); 65 | validator().checkInteger(true, "total", total, 0, Territory.values().length); 66 | validator().checkNotNullAndValidateAll(false, "territories", territories); 67 | validator().done(); 68 | } 69 | 70 | public TerritoriesDTO( 71 | final int total, 72 | @Nonnull final TerritoryListDTO territories) { 73 | this.total = total; 74 | this.territories = territories; 75 | } 76 | 77 | @SuppressWarnings("UnusedDeclaration") 78 | @Deprecated 79 | private TerritoriesDTO() { 80 | // Default constructor required by JAX-B. 81 | super(); 82 | } 83 | 84 | public int getTotal() { 85 | beforeGet(); 86 | return total; 87 | } 88 | 89 | public void setTotal(final int total) { 90 | beforeSet(); 91 | this.total = total; 92 | } 93 | 94 | @Nonnull 95 | public TerritoryListDTO getTerritories() { 96 | beforeGet(); 97 | return territories; 98 | } 99 | 100 | public void setTerritories(@Nonnull final TerritoryListDTO territories) { 101 | beforeSet(); 102 | this.territories = territories; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/TerritoryListDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.Territory; 22 | import com.mapcode.Territory.AlphaCodeFormat; 23 | import com.tomtom.speedtools.apivalidation.ApiListDTO; 24 | 25 | import javax.annotation.Nonnull; 26 | import javax.xml.bind.annotation.XmlAccessType; 27 | import javax.xml.bind.annotation.XmlAccessorType; 28 | import javax.xml.bind.annotation.XmlRootElement; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.stream.Collectors; 32 | 33 | @SuppressWarnings("NullableProblems") 34 | @JsonInclude(Include.NON_EMPTY) 35 | @XmlRootElement(name = "territories") 36 | @XmlAccessorType(XmlAccessType.FIELD) 37 | public final class TerritoryListDTO extends ApiListDTO { 38 | 39 | @Override 40 | public void validateOne(@Nonnull final TerritoryDTO elm) { 41 | validator().checkNotNullAndValidate(true, "territory", elm); 42 | } 43 | 44 | public TerritoryListDTO(@Nonnull final List territories) { 45 | super(territories); 46 | } 47 | 48 | public TerritoryListDTO(@Nonnull final Territory... territories) { 49 | this(Arrays.stream(territories).map(x -> new TerritoryDTO( 50 | x.toString(), 51 | x.toAlphaCode(AlphaCodeFormat.MINIMAL_UNAMBIGUOUS), 52 | x.toAlphaCode(AlphaCodeFormat.MINIMAL), 53 | x.getFullName(), 54 | (x.getParentTerritory() == null) ? null : x.getParentTerritory().toString(), 55 | x.getAliases(), 56 | x.getFullNameAliases(), 57 | x.getAlphabets() 58 | )).collect(Collectors.toList())); 59 | } 60 | 61 | @SuppressWarnings("UnusedDeclaration") 62 | @Deprecated 63 | private TerritoryListDTO() { 64 | // Default constructor required by JAX-B. 65 | super(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/dto/VersionDTO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.dto; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; 20 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 21 | import com.mapcode.services.ApiConstants; 22 | import com.tomtom.speedtools.apivalidation.ApiDTO; 23 | import io.swagger.annotations.ApiModel; 24 | import io.swagger.annotations.ApiModelProperty; 25 | import org.apache.commons.lang3.builder.ToStringBuilder; 26 | 27 | import javax.annotation.Nonnull; 28 | import javax.xml.bind.annotation.XmlAccessType; 29 | import javax.xml.bind.annotation.XmlAccessorType; 30 | import javax.xml.bind.annotation.XmlElement; 31 | import javax.xml.bind.annotation.XmlRootElement; 32 | 33 | @SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"}) 34 | @ApiModel( 35 | value = "version", 36 | description = "The version of the Mapcode REST API.") 37 | @JsonInclude(Include.NON_EMPTY) 38 | @XmlRootElement(name = "version") 39 | @XmlAccessorType(XmlAccessType.FIELD) 40 | public final class VersionDTO extends ApiDTO { 41 | 42 | @ApiModelProperty( 43 | name = "version", 44 | value = "Version of the API.") 45 | @XmlElement(name = "version") 46 | @Nonnull 47 | private String version; 48 | 49 | @Override 50 | public void validate() { 51 | validator().start(); 52 | validator().checkString(true, "version", version, ApiConstants.API_VERSION_LEN_MIN, ApiConstants.API_VERSION_LEN_MAX); 53 | validator().done(); 54 | } 55 | 56 | public VersionDTO(@Nonnull final String version) { 57 | this.version = version; 58 | } 59 | 60 | @SuppressWarnings("UnusedDeclaration") 61 | @Deprecated 62 | private VersionDTO() { 63 | // Default constructor required by JAX-B. 64 | super(); 65 | } 66 | 67 | @Nonnull 68 | public String getVersion() { 69 | beforeGet(); 70 | return version; 71 | } 72 | 73 | public void setVersion(@Nonnull final String version) { 74 | beforeSet(); 75 | assert version != null; 76 | this.version = version; 77 | } 78 | 79 | @Override 80 | @Nonnull 81 | public String toString() { 82 | return ToStringBuilder.reflectionToString(this); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/implementation/OnlyJsonResourceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.implementation; 18 | 19 | import com.mapcode.services.MapcodeResource; 20 | import com.mapcode.services.OnlyJsonResource; 21 | import com.mapcode.services.RootResource; 22 | import com.tomtom.speedtools.apivalidation.exceptions.ApiIntegerOutOfRangeException; 23 | import com.tomtom.speedtools.apivalidation.exceptions.ApiInvalidFormatException; 24 | import com.tomtom.speedtools.apivalidation.exceptions.ApiNotFoundException; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import javax.inject.Inject; 29 | import javax.ws.rs.container.AsyncResponse; 30 | import javax.ws.rs.container.Suspended; 31 | 32 | public class OnlyJsonResourceImpl implements OnlyJsonResource { 33 | 34 | private final RootResource rootResource; 35 | private final MapcodeResource mapcodeResource; 36 | 37 | @Inject 38 | public OnlyJsonResourceImpl( 39 | @Nonnull final RootResource rootResource, 40 | @Nonnull final MapcodeResource mapcodeResource) { 41 | this.rootResource = rootResource; 42 | this.mapcodeResource = mapcodeResource; 43 | } 44 | 45 | @Override 46 | public void convertLatLonToMapcodeJson( 47 | @Suspended @Nonnull final AsyncResponse response) throws ApiInvalidFormatException { 48 | mapcodeResource.convertLatLonToMapcode(response); 49 | } 50 | 51 | @Override 52 | public void getVersionJson(@Suspended @Nonnull final AsyncResponse response) { 53 | rootResource.getVersion(response); 54 | } 55 | 56 | @Override 57 | public void getStatusJson(@Suspended @Nonnull final AsyncResponse response) { 58 | rootResource.getStatus(response); 59 | } 60 | 61 | @Override 62 | public void convertLatLonToMapcodeJson( 63 | @Nullable final String paramLatDegAsString, 64 | @Nullable final String paramLonDegAsString, 65 | @Nullable final String paramPrecisionAsString, 66 | @Nullable final String paramTerritory, 67 | @Nullable final String paramCountry, 68 | @Nullable final String paramContextMustBeNull, 69 | @Nullable final String paramAlphabet, 70 | @Nonnull final String paramInclude, 71 | @Nonnull final String paramClient, 72 | @Nonnull final String paramAllowLog, 73 | @Suspended @Nonnull final AsyncResponse response) 74 | throws ApiInvalidFormatException { 75 | mapcodeResource.convertLatLonToMapcode(paramLatDegAsString, paramLonDegAsString, paramPrecisionAsString, paramTerritory, paramCountry, 76 | paramContextMustBeNull, paramAlphabet, paramInclude, paramClient, paramAllowLog, response); 77 | } 78 | 79 | @Override 80 | public void convertLatLonToMapcodeJson( 81 | @Nullable final String paramLatDegAsString, 82 | @Nullable final String paramLonDegAsString, 83 | @Nullable final String paramType, 84 | @Nullable final String paramPrecisionAsString, 85 | @Nullable final String paramTerritory, 86 | @Nullable final String paramCountry, 87 | @Nullable final String paramContextMustBeNull, 88 | @Nullable final String paramAlphabet, 89 | @Nonnull final String paramInclude, 90 | @Nonnull final String paramClient, 91 | @Nonnull final String paramDebug, 92 | @Suspended @Nonnull final AsyncResponse response) 93 | throws ApiInvalidFormatException { 94 | mapcodeResource.convertLatLonToMapcode(paramLatDegAsString, paramLonDegAsString, paramType, paramPrecisionAsString, paramTerritory, paramCountry, 95 | paramContextMustBeNull, paramAlphabet, paramInclude, paramClient, paramDebug, response); 96 | } 97 | 98 | @Override 99 | public void convertMapcodeToLatLonJson( 100 | @Suspended @Nonnull final AsyncResponse response) 101 | throws ApiNotFoundException, ApiInvalidFormatException { 102 | mapcodeResource.convertMapcodeToLatLon(response); 103 | } 104 | 105 | @Override 106 | public void convertMapcodeToLatLonJson( 107 | @Nonnull final String paramCode, 108 | @Nullable final String paramContext, 109 | @Nullable final String paramTerritoryMustBeNull, 110 | @Nonnull final String paramInclude, 111 | @Nonnull final String paramClient, 112 | @Nonnull final String paramDebug, 113 | @Suspended @Nonnull final AsyncResponse response) 114 | throws ApiNotFoundException, ApiInvalidFormatException { 115 | mapcodeResource.convertMapcodeToLatLon(paramCode, paramContext, paramTerritoryMustBeNull, paramInclude, paramClient, paramDebug, response); 116 | } 117 | 118 | @Override 119 | public void getTerritoriesJson( 120 | final int offset, 121 | final int count, 122 | @Nonnull final String paramClient, 123 | @Nonnull final String paramAllowLog, 124 | @Suspended @Nonnull final AsyncResponse response) 125 | throws ApiIntegerOutOfRangeException { 126 | mapcodeResource.getTerritories(offset, count, paramClient, paramAllowLog, response); 127 | } 128 | 129 | @Override 130 | public void getTerritoryJson( 131 | @Nonnull final String paramTerritory, 132 | @Nullable final String paramContext, 133 | @Nonnull final String paramClient, 134 | @Nonnull final String paramAllowLog, 135 | @Suspended @Nonnull final AsyncResponse response) 136 | throws ApiInvalidFormatException { 137 | mapcodeResource.getTerritory(paramTerritory, paramContext, paramClient, paramAllowLog, response); 138 | } 139 | 140 | @Override 141 | public void getAlphabetsJson( 142 | final int offset, 143 | final int count, 144 | @Nonnull final String paramClient, 145 | @Nonnull final String paramAllowLog, 146 | @Suspended @Nonnull final AsyncResponse response) 147 | throws ApiIntegerOutOfRangeException { 148 | mapcodeResource.getAlphabets(offset, count, paramClient, paramAllowLog, response); 149 | } 150 | 151 | @Override 152 | public void getAlphabetJson( 153 | @Nonnull final String paramAlphabet, 154 | @Nonnull final String paramClient, 155 | @Nonnull final String paramAllowLog, 156 | @Suspended @Nonnull final AsyncResponse response) 157 | throws ApiInvalidFormatException { 158 | mapcodeResource.getAlphabet(paramAlphabet, paramClient, paramAllowLog, response); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/implementation/OnlyXmlResourceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.implementation; 18 | 19 | import com.mapcode.services.MapcodeResource; 20 | import com.mapcode.services.OnlyXmlResource; 21 | import com.mapcode.services.RootResource; 22 | import com.tomtom.speedtools.apivalidation.exceptions.ApiIntegerOutOfRangeException; 23 | import com.tomtom.speedtools.apivalidation.exceptions.ApiInvalidFormatException; 24 | import com.tomtom.speedtools.apivalidation.exceptions.ApiNotFoundException; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import javax.inject.Inject; 29 | import javax.ws.rs.container.AsyncResponse; 30 | import javax.ws.rs.container.Suspended; 31 | 32 | public class OnlyXmlResourceImpl implements OnlyXmlResource { 33 | 34 | private final RootResource rootResource; 35 | private final MapcodeResource mapcodeResource; 36 | 37 | @Inject 38 | public OnlyXmlResourceImpl( 39 | @Nonnull final RootResource rootResource, 40 | @Nonnull final MapcodeResource mapcodeResource) { 41 | this.rootResource = rootResource; 42 | this.mapcodeResource = mapcodeResource; 43 | } 44 | 45 | @Override 46 | public void getVersionXml(@Suspended @Nonnull final AsyncResponse response) { 47 | rootResource.getVersion(response); 48 | } 49 | 50 | @Override 51 | public void getStatusXml(@Suspended @Nonnull final AsyncResponse response) { 52 | rootResource.getStatus(response); 53 | } 54 | 55 | @Override 56 | public void convertLatLonToMapcodeXml( 57 | @Suspended @Nonnull final AsyncResponse response) throws ApiInvalidFormatException { 58 | mapcodeResource.convertLatLonToMapcode(response); 59 | } 60 | 61 | @Override 62 | public void convertLatLonToMapcodeXml( 63 | @Nullable final String paramLatDegAsString, 64 | @Nullable final String paramLonDegAsString, 65 | @Nullable final String paramPrecisionAsString, 66 | @Nullable final String paramTerritory, 67 | @Nullable final String paramCountry, 68 | @Nullable final String paramContextMustBeNull, 69 | @Nullable final String paramAlphabet, 70 | @Nonnull final String paramInclude, 71 | @Nonnull final String paramClient, 72 | @Nonnull final String paramAllowLog, 73 | @Suspended @Nonnull final AsyncResponse response) 74 | throws ApiInvalidFormatException { 75 | mapcodeResource.convertLatLonToMapcode(paramLatDegAsString, paramLonDegAsString, paramPrecisionAsString, paramTerritory, paramCountry, 76 | paramContextMustBeNull, paramAlphabet, paramInclude, paramClient, paramAllowLog, response); 77 | } 78 | 79 | @Override 80 | public void convertLatLonToMapcodeXml( 81 | @Nullable final String paramLatDegAsString, 82 | @Nullable final String paramLonDegAsString, 83 | @Nullable final String paramType, 84 | @Nullable final String paramPrecisionAsString, 85 | @Nullable final String paramTerritory, 86 | @Nullable final String paramCountry, 87 | @Nullable final String paramContextMustBeNull, 88 | @Nullable final String paramAlphabet, 89 | @Nonnull final String paramInclude, 90 | @Nonnull final String paramClient, 91 | @Nonnull final String paramDebug, 92 | @Suspended @Nonnull final AsyncResponse response) 93 | throws ApiInvalidFormatException { 94 | mapcodeResource.convertLatLonToMapcode(paramLatDegAsString, paramLonDegAsString, paramType, paramPrecisionAsString, paramTerritory, paramCountry, 95 | paramContextMustBeNull, paramAlphabet, paramInclude, paramClient, paramDebug, response); 96 | } 97 | 98 | @Override 99 | public void convertMapcodeToLatLonXml( 100 | @Suspended @Nonnull final AsyncResponse response) 101 | throws ApiNotFoundException, ApiInvalidFormatException { 102 | mapcodeResource.convertMapcodeToLatLon(response); 103 | } 104 | 105 | @Override 106 | public void convertMapcodeToLatLonXml( 107 | @Nonnull final String paramCode, 108 | @Nullable final String paramContext, 109 | @Nullable final String paramTerritoryMustBeNull, 110 | @Nonnull final String paramInclude, 111 | @Nonnull final String paramClient, 112 | @Nonnull final String paramDebug, 113 | @Suspended @Nonnull final AsyncResponse response) 114 | throws ApiNotFoundException, ApiInvalidFormatException { 115 | mapcodeResource.convertMapcodeToLatLon(paramCode, paramContext, paramTerritoryMustBeNull, paramInclude, paramClient, paramDebug, response); 116 | } 117 | 118 | @Override 119 | public void getTerritoriesXml( 120 | final int offset, 121 | final int count, 122 | @Nonnull final String paramClient, 123 | @Nonnull final String paramAllowLog, 124 | @Suspended @Nonnull final AsyncResponse response) 125 | throws ApiIntegerOutOfRangeException { 126 | mapcodeResource.getTerritories(offset, count, paramClient, paramAllowLog, response); 127 | } 128 | 129 | @Override 130 | public void getTerritoryXml( 131 | @Nonnull final String paramTerritory, 132 | @Nullable final String paramContext, 133 | @Nonnull final String paramClient, 134 | @Nonnull final String paramAllowLog, 135 | @Suspended @Nonnull final AsyncResponse response) 136 | throws ApiInvalidFormatException { 137 | mapcodeResource.getTerritory(paramTerritory, paramContext, paramClient, paramAllowLog, response); 138 | } 139 | 140 | @Override 141 | public void getAlphabetsXml( 142 | final int offset, 143 | final int count, 144 | @Nonnull final String paramClient, 145 | @Nonnull final String paramAllowLog, 146 | @Suspended @Nonnull final AsyncResponse response) 147 | throws ApiIntegerOutOfRangeException { 148 | mapcodeResource.getAlphabets(offset, count, paramClient, paramAllowLog, response); 149 | } 150 | 151 | @Override 152 | public void getAlphabetXml( 153 | @Nonnull final String paramAlphabet, 154 | @Nonnull final String paramClient, 155 | @Nonnull final String paramAllowLog, 156 | @Suspended @Nonnull final AsyncResponse response) 157 | throws ApiInvalidFormatException { 158 | mapcodeResource.getAlphabet(paramAlphabet, paramClient, paramAllowLog, response); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/implementation/TestAsyncResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.implementation; 18 | 19 | import javax.annotation.Nullable; 20 | import javax.ws.rs.container.AsyncResponse; 21 | import javax.ws.rs.container.TimeoutHandler; 22 | import java.util.Collection; 23 | import java.util.Date; 24 | import java.util.Map; 25 | import java.util.concurrent.TimeUnit; 26 | 27 | public class TestAsyncResponse implements AsyncResponse { 28 | 29 | private boolean ready = false; 30 | private Object response = null; 31 | 32 | public boolean isReady() { 33 | return ready; 34 | } 35 | 36 | @Nullable 37 | public Object getResponse() { 38 | return response; 39 | } 40 | 41 | @Override 42 | public boolean resume(final Object response) { 43 | this.ready = true; 44 | this.response = response; 45 | return true; 46 | } 47 | 48 | @Override 49 | public boolean resume(final Throwable response) { 50 | this.ready = true; 51 | this.response = response; 52 | return true; 53 | } 54 | 55 | @Override 56 | public boolean cancel() { 57 | this.ready = true; 58 | return true; 59 | } 60 | 61 | @Override 62 | public boolean cancel(final int retryAfter) { 63 | this.ready = true; 64 | return true; 65 | } 66 | 67 | @Override 68 | public boolean cancel(final Date retryAfter) { 69 | this.ready = true; 70 | return true; 71 | } 72 | 73 | @Override 74 | public boolean isSuspended() { 75 | return false; 76 | } 77 | 78 | @Override 79 | public boolean isCancelled() { 80 | return false; 81 | } 82 | 83 | @Override 84 | public boolean isDone() { 85 | return false; 86 | } 87 | 88 | @Override 89 | public boolean setTimeout(final long time, final TimeUnit unit) { 90 | return true; 91 | } 92 | 93 | @Override 94 | public void setTimeoutHandler(final TimeoutHandler handler) { 95 | // Empty. 96 | } 97 | 98 | @Override 99 | @Nullable 100 | public Collection> register(final Class callback) { 101 | return null; 102 | } 103 | 104 | @Override 105 | @Nullable 106 | public Map, Collection>> register(final Class callback, final Class... callbacks) { 107 | return null; 108 | } 109 | 110 | @Override 111 | @Nullable 112 | public Collection> register(final Object callback) { 113 | return null; 114 | } 115 | 116 | @Override 117 | @Nullable 118 | public Map, Collection>> register(final Object callback, final Object... callbacks) { 119 | return null; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/jmx/SystemMetricsAgent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.jmx; 18 | 19 | import com.mapcode.services.metrics.SystemMetrics; 20 | 21 | import javax.annotation.Nonnull; 22 | import javax.inject.Inject; 23 | import javax.management.InstanceAlreadyExistsException; 24 | import javax.management.InstanceNotFoundException; 25 | import javax.management.MBeanRegistrationException; 26 | import javax.management.MBeanServer; 27 | import javax.management.MalformedObjectNameException; 28 | import javax.management.NotCompliantMBeanException; 29 | import javax.management.ObjectName; 30 | import java.lang.management.ManagementFactory; 31 | 32 | /** 33 | * JMX agent that serves {@link SystemMetrics} through JMX. 34 | */ 35 | public class SystemMetricsAgent { 36 | 37 | @Nonnull 38 | private final SystemMetrics systemMetrics; 39 | 40 | @Inject 41 | public SystemMetricsAgent(@Nonnull final SystemMetrics systemMetrics) { 42 | assert systemMetrics != null; 43 | this.systemMetrics = systemMetrics; 44 | } 45 | 46 | public void register() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, 47 | MBeanRegistrationException { 48 | 49 | // Get the platform MBeanServer. 50 | final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 51 | 52 | // Uniquely identify the MBeans and register them with the platform MBeanServer. 53 | final ObjectName name = new ObjectName("mapcode:name=SystemMetrics"); 54 | 55 | // Unregister old bean. Needed for tests. 56 | try { 57 | mbs.unregisterMBean(name); 58 | } catch (final InstanceNotFoundException ignored) { 59 | // Ignored. 60 | } 61 | 62 | // Register metrics bean. 63 | mbs.registerMBean(systemMetrics, name); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/metrics/SystemMetrics.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.metrics; 18 | 19 | 20 | import com.tomtom.speedtools.metrics.MultiMetricsData; 21 | 22 | import javax.annotation.Nonnull; 23 | import javax.management.MXBean; 24 | 25 | 26 | /** 27 | * Mapcode metrics interface. Metrics are aggregated for multiple time intervals, being last minute, hour day, week and 28 | * month. For each time interval, the sum, average, standard deviation, minimum value and maximum value can be 29 | * retrieved. 30 | * 31 | * Note that the returned {@link MultiMetricsData} and embedded {@link com.tomtom.speedtools.metrics.MetricsData} 32 | * instances are 'live' objects. They will continue to change when values are requested. They are thread-safe. 33 | */ 34 | @MXBean 35 | public interface SystemMetrics { 36 | 37 | enum Metric { 38 | ALL_MAPCODE_TO_LATLON_REQUESTS, // All requests. 39 | ALL_CLIENT_NONE_MAPCODE_TO_LATLON_REQUESTS, // Request per client type. 40 | ALL_CLIENT_IOS_MAPCODE_TO_LATLON_REQUESTS, 41 | ALL_CLIENT_ANDROID_MAPCODE_TO_LATLON_REQUESTS, 42 | ALL_CLIENT_WEB_MAPCODE_TO_LATLON_REQUESTS, 43 | VALID_MAPCODE_TO_LATLON_REQUESTS, 44 | 45 | ALL_LATLON_TO_MAPCODE_REQUESTS, // Requests. 46 | ALL_CLIENT_NONE_LATLON_TO_MAPCODE_REQUESTS, // Requests per client type. 47 | ALL_CLIENT_IOS_LATLON_TO_MAPCODE_REQUESTS, 48 | ALL_CLIENT_ANDROID_LATLON_TO_MAPCODE_REQUESTS, 49 | ALL_CLIENT_WEB_LATLON_TO_MAPCODE_REQUESTS, 50 | VALID_LATLON_TO_MAPCODE_REQUESTS, 51 | 52 | ALL_ALPHABET_REQUESTS, 53 | ALL_TERRITORY_REQUESTS, 54 | WARNINGS_AND_ERRORS 55 | } 56 | 57 | enum Client { 58 | NONE, // No client specified. 59 | IOS, // iOS app. 60 | ANDROID, // Android app. 61 | WEB // Mapcode Foundation web page. 62 | } 63 | 64 | /** 65 | * Return metrics data. 66 | * 67 | * @param metric Metric to return data for. 68 | * @return Metric data for given metric. 69 | */ 70 | @Nonnull 71 | MultiMetricsData getMetricData(@Nonnull Metric metric); 72 | 73 | /** 74 | * @return The total number of requests for mapcode to lat/lon. 75 | */ 76 | @Nonnull 77 | MultiMetricsData getAllMapcodeToLatLonRequests(); 78 | 79 | @Nonnull 80 | MultiMetricsData getAllClientNoneMapcodeToLatLonRequests(); 81 | 82 | @Nonnull 83 | MultiMetricsData getAllClientIOSMapcodeToLatLonRequests(); 84 | 85 | @Nonnull 86 | MultiMetricsData getAllClientAndroidMapcodeToLatLonRequests(); 87 | 88 | @Nonnull 89 | MultiMetricsData getAllClientWebMapcodeToLatLonRequests(); 90 | 91 | /** 92 | * @return The number of valid requests for mapcode to lat/lon. 93 | */ 94 | @Nonnull 95 | MultiMetricsData getValidMapcodeToLatLonRequests(); 96 | 97 | /** 98 | * @return The total number of requests for lat/lon to mapcode. 99 | */ 100 | @Nonnull 101 | MultiMetricsData getAllLatLonToMapcodeRequests(); 102 | 103 | @Nonnull 104 | MultiMetricsData getAllClientNoneLatLonToMapcodeRequests(); 105 | 106 | @Nonnull 107 | MultiMetricsData getAllClientIOSLatLonToMapcodeRequests(); 108 | 109 | @Nonnull 110 | MultiMetricsData getAllClientAndroidLatLonToMapcodeRequests(); 111 | 112 | @Nonnull 113 | MultiMetricsData getAllClientWebLatLonToMapcodeRequests(); 114 | 115 | /** 116 | * @return The number of valid requests for lat/lon to mapcode. 117 | */ 118 | @Nonnull 119 | MultiMetricsData getValidLatLonToMapcodeRequests(); 120 | 121 | /** 122 | * @return The total number of requests for alphabets. 123 | */ 124 | @Nonnull 125 | MultiMetricsData getAllAlphabetRequests(); 126 | 127 | /** 128 | * @return The total number of requests for territories. 129 | */ 130 | @Nonnull 131 | MultiMetricsData getAllTerritoryRequests(); 132 | 133 | /** 134 | * @return The number of warnings and errors that were logged through log4j. 135 | */ 136 | @Nonnull 137 | MultiMetricsData getWarningsAndErrors(); 138 | } 139 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/metrics/SystemMetricsCollector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012. TomTom International BV. All rights reserved. 19 | */ 20 | 21 | package com.mapcode.services.metrics; 22 | 23 | import javax.annotation.Nullable; 24 | 25 | /** 26 | * Interface through which metrics data can be provided. This may or may not be an actor. 27 | */ 28 | public interface SystemMetricsCollector { 29 | 30 | /** 31 | * Called whenever ANY mapcode to lat/lon request is made. The request may fail because 32 | * the parameters may be invalid though. 33 | * 34 | * @param client Client that issued the call. Can be null 35 | */ 36 | public void addOneMapcodeToLatLonRequest(@Nullable String client); 37 | 38 | /** 39 | * Called whenever a successful mapcode to lat/lon request is made. 40 | * 41 | * @param client Client that issued the call. Can be null 42 | */ 43 | public void addOneValidMapcodeToLatLonRequest(@Nullable String client); 44 | 45 | /** 46 | * Called whenever ANY lat/lon to mapcode request is made. The request may fail because 47 | * the parameters may be invalid though. 48 | * 49 | * @param client Client that issued the call. Can be null 50 | */ 51 | public void addOneLatLonToMapcodeRequest(@Nullable String client); 52 | 53 | /** 54 | * Called whenever a successful lat/lon to mapcode request is made. 55 | * 56 | * @param client Client that issued the call. Can be null 57 | */ 58 | public void addOneValidLatLonToMapcodeRequest(@Nullable String client); 59 | 60 | /** 61 | * Called whenever a alphabet request is made. 62 | * 63 | * @param client Client that issued the call. Can be null 64 | */ 65 | public void addOneAlphabetRequest(@Nullable String client); 66 | 67 | /** 68 | * Called whenever a territory request is made. 69 | * 70 | * @param client Client that issued the call. Can be null 71 | */ 72 | public void addOneTerritoryRequest(@Nullable String client); 73 | } 74 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/standalone/MainCommandLine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.standalone; 18 | 19 | import com.google.inject.Guice; 20 | import com.google.inject.Injector; 21 | import com.mapcode.services.ResourcesModule; 22 | import com.tomtom.speedtools.guice.GuiceConfigurationModule; 23 | import com.tomtom.speedtools.rest.ServicesModule; 24 | import org.apache.log4j.ConsoleAppender; 25 | import org.apache.log4j.Level; 26 | import org.apache.log4j.Logger; 27 | import org.apache.log4j.SimpleLayout; 28 | 29 | @SuppressWarnings({"UseOfSystemOutOrSystemErr", "ConstantConditions"}) 30 | public final class MainCommandLine { 31 | private static final String CMD_HELP = "--help"; 32 | private static final String CMD_SILENT = "--silent"; 33 | private static final String CMD_DEBUG = "--debug"; 34 | private static final String CMD_PORT = "--port"; 35 | 36 | private static final int DEFAULT_PORT = 8080; 37 | 38 | private static final Server server; 39 | private static final Logger rootLogger; 40 | private static final ConsoleAppender consoleAppender; 41 | 42 | // Static init. 43 | static { 44 | final Injector guice = createGuice(); 45 | server = guice.getInstance(Server.class); 46 | 47 | // Configure log4j. 48 | rootLogger = Logger.getRootLogger(); 49 | rootLogger.setLevel(Level.INFO); 50 | 51 | consoleAppender = new ConsoleAppender(new SimpleLayout()); 52 | consoleAppender.setThreshold(Level.INFO); 53 | rootLogger.addAppender(consoleAppender); 54 | } 55 | 56 | private MainCommandLine() { 57 | // Prevent instantiation. 58 | } 59 | 60 | public static void execute(final String... args) { 61 | int port = DEFAULT_PORT; 62 | String command = null; 63 | boolean debug = false; 64 | 65 | // Parse command-line arguments. 66 | int index = 0; 67 | while (index < args.length) { 68 | 69 | switch (args[index]) { 70 | case CMD_SILENT: 71 | rootLogger.setLevel(Level.WARN); 72 | consoleAppender.setThreshold(Level.WARN); 73 | break; 74 | 75 | case CMD_DEBUG: 76 | debug = true; 77 | break; 78 | 79 | case CMD_PORT: 80 | if (index >= (args.length - 1)) { 81 | System.out.println("Missing port number"); 82 | printUsage(); 83 | return; 84 | } 85 | port = Integer.parseInt(args[index + 1]); 86 | ++index; 87 | break; 88 | 89 | default: 90 | if (args[index].startsWith("-")) { 91 | System.out.println("Unknown option: " + args[index]); 92 | printUsage(); 93 | return; 94 | } 95 | if (command != null) { 96 | System.out.println("Unknown argument: " + args[index]); 97 | printUsage(); 98 | return; 99 | } 100 | command = args[index]; 101 | break; 102 | } 103 | ++index; 104 | } 105 | 106 | if (debug) { 107 | consoleAppender.setThreshold(Level.DEBUG); 108 | } 109 | 110 | if ((command != null) && command.equals(CMD_HELP)) { 111 | printUsage(); 112 | } else { 113 | server.startServer(port); 114 | } 115 | } 116 | 117 | public static void stop() { 118 | server.stopServer(); 119 | } 120 | 121 | /** 122 | * Create the guice injector. 123 | * 124 | * @return Guice injector. 125 | */ 126 | private static Injector createGuice() { 127 | return Guice.createInjector( 128 | new GuiceConfigurationModule( 129 | "classpath:speedtools.default.properties", // Default set required by SpeedTools. 130 | "classpath:mapcode.properties", // Mapcode properties. 131 | "classpath:mapcode-secret.properties"), // Mapcode secret properties. 132 | new ServicesModule(), 133 | new ResourcesModule(), 134 | new StandaloneModule()); 135 | } 136 | 137 | private static void printUsage() { 138 | System.out.println("Usage: java -jar " + " [" + CMD_PORT + " ] [" + CMD_SILENT + "] [" + CMD_DEBUG + ']'); 139 | System.out.println(" java -jar " + CMD_HELP); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/standalone/Server.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.standalone; 18 | 19 | import com.google.inject.Inject; 20 | import com.mapcode.services.implementation.*; 21 | import com.tomtom.speedtools.maven.MavenProperties; 22 | import com.tomtom.speedtools.rest.Reactor; 23 | import com.tomtom.speedtools.rest.ResourceProcessor; 24 | import com.tomtom.speedtools.testutils.SimpleExecutionContext; 25 | import org.jboss.resteasy.core.Dispatcher; 26 | import org.jboss.resteasy.plugins.interceptors.CacheControlFeature; 27 | import org.jboss.resteasy.plugins.providers.*; 28 | import org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider; 29 | import org.jboss.resteasy.plugins.providers.jaxb.*; 30 | import org.jboss.resteasy.plugins.providers.multipart.*; 31 | import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; 32 | import org.jboss.resteasy.spi.ResteasyDeployment; 33 | import org.jboss.resteasy.spi.ResteasyProviderFactory; 34 | import org.joda.time.DateTime; 35 | import org.slf4j.Logger; 36 | import org.slf4j.LoggerFactory; 37 | import scala.concurrent.ExecutionContext; 38 | 39 | import javax.annotation.Nonnull; 40 | import java.util.List; 41 | 42 | public class Server { 43 | private static final Logger LOG = LoggerFactory.getLogger(Server.class); 44 | 45 | private final MavenProperties mavenProperties; 46 | private boolean started = false; 47 | private final TJWSEmbeddedJaxrsServer server; 48 | 49 | @Inject 50 | public Server(@Nonnull final MavenProperties mavenProperties) { 51 | this.mavenProperties = mavenProperties; 52 | server = new TJWSEmbeddedJaxrsServer(); 53 | } 54 | 55 | public synchronized void startServer(final int port) { 56 | stopServer(); 57 | server.setPort(port); 58 | 59 | /** 60 | * Create a simple ResourceProcessor, required for implementation of REST service using the 61 | * SpeedTools framework. 62 | */ 63 | LOG.debug("Server: create execution context..."); 64 | final Reactor reactor = new Reactor() { 65 | @Nonnull 66 | @Override 67 | public ExecutionContext getExecutionContext() { 68 | return SimpleExecutionContext.getInstance(); 69 | } 70 | 71 | // This method is stubbed and never used. 72 | @Nonnull 73 | @Override 74 | public DateTime getSystemStartupTime() { 75 | return new DateTime(); 76 | } 77 | }; 78 | final ResourceProcessor resourceProcessor = new ResourceProcessor(reactor); 79 | final SystemMetricsImpl metrics = new SystemMetricsImpl(); 80 | 81 | LOG.debug("Server: add resources..."); 82 | final ResteasyDeployment deployment = server.getDeployment(); 83 | final List resources = deployment.getResources(); 84 | 85 | // Add mapcode resource. 86 | final MapcodeResourceImpl mapcodeResource = new MapcodeResourceImpl( 87 | resourceProcessor, 88 | metrics 89 | ); 90 | resources.add(mapcodeResource); 91 | 92 | // Add root resource. 93 | final RootResourceImpl rootResource = new RootResourceImpl( 94 | mapcodeResource, 95 | mavenProperties, 96 | metrics 97 | ); 98 | resources.add(rootResource); 99 | 100 | // Add JSON and XML mapcode resources. 101 | resources.add(new OnlyJsonResourceImpl(rootResource, mapcodeResource)); 102 | resources.add(new OnlyXmlResourceImpl(rootResource, mapcodeResource)); 103 | 104 | LOG.debug("Server: start server..."); 105 | server.start(); 106 | 107 | LOG.debug("Server: register providers..."); 108 | final Dispatcher dispatcher = deployment.getDispatcher(); 109 | final ResteasyProviderFactory providerFactory = dispatcher.getProviderFactory(); 110 | 111 | /** 112 | * Register providers for JSON and XML. This list was obtained by looking at which providers 113 | * were registered when the application would be running its unit tests, which works as well. 114 | */ 115 | providerFactory.registerProvider(JAXBXmlSeeAlsoProvider.class, true); 116 | providerFactory.registerProvider(JAXBXmlRootElementProvider.class, true); 117 | providerFactory.registerProvider(JAXBElementProvider.class, true); 118 | providerFactory.registerProvider(JAXBXmlTypeProvider.class, true); 119 | providerFactory.registerProvider(CollectionProvider.class, true); 120 | providerFactory.registerProvider(MapProvider.class, true); 121 | providerFactory.registerProvider(XmlJAXBContextFinder.class, true); 122 | providerFactory.registerProvider(DataSourceProvider.class, true); 123 | providerFactory.registerProvider(DocumentProvider.class, true); 124 | providerFactory.registerProvider(DefaultTextPlain.class, true); 125 | providerFactory.registerProvider(StringTextStar.class, true); 126 | providerFactory.registerProvider(SourceProvider.class, true); 127 | providerFactory.registerProvider(InputStreamProvider.class, true); 128 | providerFactory.registerProvider(ReaderProvider.class, true); 129 | providerFactory.registerProvider(ByteArrayProvider.class, true); 130 | providerFactory.registerProvider(FormUrlEncodedProvider.class, true); 131 | providerFactory.registerProvider(JaxrsFormProvider.class, true); 132 | providerFactory.registerProvider(FileProvider.class, true); 133 | providerFactory.registerProvider(FileRangeWriter.class, true); 134 | providerFactory.registerProvider(StreamingOutputProvider.class, true); 135 | providerFactory.registerProvider(IIOImageProvider.class, true); 136 | providerFactory.registerProvider(CacheControlFeature.class, true); 137 | providerFactory.registerProvider(ResteasyJackson2Provider.class, true); 138 | providerFactory.registerProvider(MultipartReader.class, true); 139 | providerFactory.registerProvider(ListMultipartReader.class, true); 140 | providerFactory.registerProvider(MultipartFormDataReader.class, true); 141 | providerFactory.registerProvider(MultipartRelatedReader.class, true); 142 | providerFactory.registerProvider(MapMultipartFormDataReader.class, true); 143 | providerFactory.registerProvider(MultipartWriter.class, true); 144 | providerFactory.registerProvider(MultipartFormDataWriter.class, true); 145 | providerFactory.registerProvider(MultipartRelatedWriter.class, true); 146 | providerFactory.registerProvider(ListMultipartWriter.class, true); 147 | providerFactory.registerProvider(MapMultipartFormDataWriter.class, true); 148 | providerFactory.registerProvider(MultipartFormAnnotationReader.class, true); 149 | providerFactory.registerProvider(MultipartFormAnnotationWriter.class, true); 150 | providerFactory.registerProvider(MimeMultipartProvider.class, true); 151 | providerFactory.registerProvider(XopWithMultipartRelatedReader.class, true); 152 | providerFactory.registerProvider(XopWithMultipartRelatedWriter.class, true); 153 | 154 | LOG.debug("Server: server is ready"); 155 | started = true; 156 | } 157 | 158 | public synchronized void stopServer() { 159 | LOG.debug("Server: stop server, started={}", started); 160 | if (started) { 161 | server.stop(); 162 | started = false; 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /service/src/main/java/com/mapcode/services/standalone/StandaloneModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.standalone; 18 | 19 | import com.google.inject.Binder; 20 | import com.google.inject.Module; 21 | 22 | import javax.annotation.Nonnull; 23 | 24 | /** 25 | * This module is used only in stand-alone (CLI) mode. It inserts a default properties 26 | * file into the server. 27 | */ 28 | public class StandaloneModule implements Module { 29 | 30 | @Override 31 | public void configure(@Nonnull final Binder binder) { 32 | assert binder != null; 33 | binder.bind(Server.class).asEagerSingleton(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /service/src/test/java/com/mapcode/services/ApiCoordsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; 20 | import org.junit.After; 21 | import org.junit.Assert; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import javax.ws.rs.core.MediaType; 28 | import javax.ws.rs.core.Response; 29 | 30 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 31 | public class ApiCoordsTest { 32 | private static final Logger LOG = LoggerFactory.getLogger(ApiCoordsTest.class); 33 | 34 | private static final String TEST_CODE1 = "VJ0L6.9PNQ"; 35 | private static final String TEST_CODE2 = "JL0.KP"; 36 | private static final String TEST_CONTEXT2 = "LUX"; 37 | 38 | private LocalTestServer server; 39 | 40 | @Before 41 | public void startServer() { 42 | server = new LocalTestServer("1.0", 8081); 43 | server.start(); 44 | } 45 | 46 | @After 47 | public void stopServer() { 48 | server.stop(); 49 | } 50 | 51 | @Test 52 | public void checkCoords1Json() { 53 | LOG.info("checkCoords1Json"); 54 | final Response response = new ResteasyClientBuilder().build(). 55 | target(server.url("/mapcode/coords/" + TEST_CODE1)). 56 | request(). 57 | accept(MediaType.APPLICATION_JSON_TYPE).get(); 58 | Assert.assertNotNull(response); 59 | Assert.assertEquals(200, response.getStatus()); 60 | Assert.assertEquals("{\"latDeg\":50.141726,\"lonDeg\":6.1358875}", 61 | response.readEntity(String.class)); 62 | } 63 | 64 | @Test 65 | public void checkCoords1Xml() { 66 | LOG.info("checkCoords1Xml"); 67 | final Response response = new ResteasyClientBuilder().build(). 68 | target(server.url("/mapcode/coords/" + TEST_CODE1)). 69 | request(). 70 | accept(MediaType.APPLICATION_XML_TYPE).get(); 71 | Assert.assertNotNull(response); 72 | Assert.assertEquals(200, response.getStatus()); 73 | Assert.assertEquals("50.1417266.1358875", 74 | response.readEntity(String.class)); 75 | } 76 | 77 | @Test 78 | public void checkCoords2Json() { 79 | LOG.info("checkCoords2Json"); 80 | final Response response = new ResteasyClientBuilder().build(). 81 | target(server.url("/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2)). 82 | request(). 83 | accept(MediaType.APPLICATION_JSON_TYPE).get(); 84 | Assert.assertNotNull(response); 85 | Assert.assertEquals(200, response.getStatus()); 86 | Assert.assertEquals("{\"latDeg\":50.141735,\"lonDeg\":6.135845}", 87 | response.readEntity(String.class)); 88 | } 89 | 90 | @Test 91 | public void checkCoords2Xml() { 92 | LOG.info("checkCoords2Xml"); 93 | final Response response = new ResteasyClientBuilder().build(). 94 | target(server.url("/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2)). 95 | request(). 96 | accept(MediaType.APPLICATION_XML_TYPE).get(); 97 | Assert.assertNotNull(response); 98 | Assert.assertEquals(200, response.getStatus()); 99 | Assert.assertEquals("50.1417356.135845", 100 | response.readEntity(String.class)); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /service/src/test/java/com/mapcode/services/ApiOthersTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import com.google.gson.Gson; 20 | import com.mapcode.services.dto.VersionDTO; 21 | import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; 22 | import org.junit.After; 23 | import org.junit.Assert; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | 29 | import javax.ws.rs.core.MediaType; 30 | import javax.ws.rs.core.Response; 31 | 32 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 33 | public class ApiOthersTest { 34 | private static final Logger LOG = LoggerFactory.getLogger(ApiOthersTest.class); 35 | 36 | private LocalTestServer server; 37 | 38 | @Before 39 | public void startServer() { 40 | server = new LocalTestServer("1.0", 8081); 41 | server.start(); 42 | } 43 | 44 | @After 45 | public void stopServer() { 46 | server.stop(); 47 | } 48 | 49 | @Test 50 | public void checkStatusXmlJson() { 51 | LOG.info("checkStatusXmlJson"); 52 | Response request = new ResteasyClientBuilder().build(). 53 | target(server.url("/mapcode/status")). 54 | request(). 55 | get(); 56 | Assert.assertNotNull(request); 57 | int status = request.getStatus(); 58 | LOG.info("status = {}", status); 59 | Assert.assertEquals(200, status); 60 | 61 | request = new ResteasyClientBuilder().build(). 62 | target(server.url("/mapcode/xml/status")). 63 | request(). 64 | get(); 65 | Assert.assertNotNull(request); 66 | status = request.getStatus(); 67 | LOG.info("status = {}", status); 68 | Assert.assertEquals(200, status); 69 | 70 | request = new ResteasyClientBuilder().build(). 71 | target(server.url("/mapcode/json/status")). 72 | request(). 73 | get(); 74 | Assert.assertNotNull(request); 75 | status = request.getStatus(); 76 | LOG.info("status = {}", status); 77 | Assert.assertEquals(200, status); 78 | } 79 | 80 | @Test 81 | public void getHelp() { 82 | LOG.info("getHelp"); 83 | final Response r = new ResteasyClientBuilder().build(). 84 | target(server.url("/mapcode")). 85 | request(). 86 | get(); 87 | Assert.assertNotNull(r); 88 | final int status = r.getStatus(); 89 | LOG.info("status = {}", status); 90 | Assert.assertEquals(200, status); 91 | Assert.assertEquals("", r.readEntity(String.class).substring(0, 6)); 92 | } 93 | 94 | @Test 95 | public void checkVersionJson() { 96 | LOG.info("checkVersionJson"); 97 | final Response response = new ResteasyClientBuilder().build(). 98 | target(server.url("/mapcode/version")). 99 | request(). 100 | accept(MediaType.APPLICATION_JSON).get(); 101 | Assert.assertNotNull(response); 102 | Assert.assertEquals(200, response.getStatus()); 103 | final String s = response.readEntity(String.class); 104 | Assert.assertEquals("{\"version\":\"1.0\"}", 105 | s); 106 | final VersionDTO x = new Gson().fromJson(s, VersionDTO.class); 107 | Assert.assertNotNull(x); 108 | Assert.assertEquals("1.0", x.getVersion()); 109 | } 110 | 111 | @Test 112 | public void checkVersionXmlJson() { 113 | LOG.info("checkVersionXmlJson"); 114 | final String expectedXml = "1.0"; 115 | final String expectedJson = "{\"version\":\"1.0\"}"; 116 | Response response = new ResteasyClientBuilder().build(). 117 | target(server.url("/mapcode/version")). 118 | request(). 119 | accept(MediaType.APPLICATION_XML_TYPE).get(); 120 | Assert.assertNotNull(response); 121 | Assert.assertEquals(200, response.getStatus()); 122 | Assert.assertEquals(expectedXml, response.readEntity(String.class)); 123 | 124 | response = new ResteasyClientBuilder().build(). 125 | target(server.url("/mapcode/xml/version")). 126 | request(). 127 | get(); 128 | Assert.assertNotNull(response); 129 | Assert.assertEquals(200, response.getStatus()); 130 | Assert.assertEquals(expectedXml, response.readEntity(String.class)); 131 | 132 | response = new ResteasyClientBuilder().build(). 133 | target(server.url("/mapcode/json/version")). 134 | request(). 135 | get(); 136 | Assert.assertNotNull(response); 137 | Assert.assertEquals(200, response.getStatus()); 138 | Assert.assertEquals(expectedJson, response.readEntity(String.class)); 139 | } 140 | 141 | @Test 142 | public void checkMetrics() { 143 | LOG.info("checkMetrics"); 144 | final Response response = new ResteasyClientBuilder().build(). 145 | target(server.url("/mapcode/metrics")). 146 | request(). 147 | accept(MediaType.APPLICATION_JSON).get(); 148 | Assert.assertNotNull(response); 149 | Assert.assertEquals(200, response.getStatus()); 150 | final String s = response.readEntity(String.class); 151 | Assert.assertEquals("{\"allMapcodeToLatLonRequests\":{\"calculators\":[{\"totalMetricDuration\":2592000000,\"timeSlotDuration\":86400000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":604800000,\"timeSlotDuration\":3600000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":86400000,\"timeSlotDuration\":1800000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":3600000,\"timeSlotDuration\":60000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDura", 152 | s.substring(0, 500)); 153 | Assert.assertEquals("Duration\":86400000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":604800000,\"timeSlotDuration\":3600000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":86400000,\"timeSlotDuration\":1800000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":3600000,\"timeSlotDuration\":60000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0},{\"totalMetricDuration\":60000,\"timeSlotDuration\":2000,\"values\":[],\"sum\":0.0,\"count\":0,\"sumSquares\":0.0}]}}}", 154 | s.substring(s.length() - 500, s.length())); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /service/src/test/java/com/mapcode/services/LocalTestServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services; 18 | 19 | import com.mapcode.services.implementation.*; 20 | import com.tomtom.speedtools.maven.MavenProperties; 21 | import com.tomtom.speedtools.rest.Reactor; 22 | import com.tomtom.speedtools.rest.ResourceProcessor; 23 | import com.tomtom.speedtools.testutils.SimpleExecutionContext; 24 | import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; 25 | import org.joda.time.DateTime; 26 | import org.junit.After; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | import scala.concurrent.ExecutionContext; 30 | 31 | import javax.annotation.Nonnull; 32 | 33 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 34 | public class LocalTestServer { 35 | private static final Logger LOG = LoggerFactory.getLogger(LocalTestServer.class); 36 | 37 | private static final String HOST = "http://localhost:"; 38 | private static final int PORT = 8081; 39 | 40 | private final TJWSEmbeddedJaxrsServer server; 41 | private final String version; 42 | private final int port; 43 | 44 | public LocalTestServer( 45 | @Nonnull final String version, 46 | final int port) { 47 | this.version = version; 48 | this.port = port; 49 | server = new TJWSEmbeddedJaxrsServer(); 50 | server.setPort(port); 51 | } 52 | 53 | public void start() { 54 | 55 | // Create a simple ResourceProcessor, required for implementation of REST service using the SpeedTools framework. 56 | final Reactor reactor = new Reactor() { 57 | @Nonnull 58 | @Override 59 | public ExecutionContext getExecutionContext() { 60 | return SimpleExecutionContext.getInstance(); 61 | } 62 | 63 | // This method is stubbed and never used. 64 | @Nonnull 65 | @Override 66 | public DateTime getSystemStartupTime() { 67 | return new DateTime(); 68 | } 69 | }; 70 | final ResourceProcessor resourceProcessor = new ResourceProcessor(reactor); 71 | 72 | final MavenProperties mavenProperties = new MavenProperties(version); 73 | final SystemMetricsImpl metrics = new SystemMetricsImpl(); 74 | 75 | // Add mapcode resource. 76 | final MapcodeResourceImpl mapcodeResource = new MapcodeResourceImpl( 77 | resourceProcessor, 78 | metrics 79 | ); 80 | server.getDeployment().getResources().add(mapcodeResource); 81 | 82 | // Add root resource. 83 | final RootResourceImpl rootResource = new RootResourceImpl( 84 | mapcodeResource, 85 | mavenProperties, 86 | metrics 87 | ); 88 | server.getDeployment().getResources().add(rootResource); 89 | 90 | // Add JSON and XML mapcode resource. 91 | server.getDeployment().getResources().add(new OnlyJsonResourceImpl(rootResource, mapcodeResource)); 92 | server.getDeployment().getResources().add(new OnlyXmlResourceImpl(rootResource, mapcodeResource)); 93 | server.start(); 94 | LOG.debug("start: Start local server, baseUrl={}", getBaseUrl()); 95 | } 96 | 97 | @After 98 | public void stop() { 99 | LOG.debug("stop: Stop local server, baseUrl={}", getBaseUrl()); 100 | server.stop(); 101 | } 102 | 103 | public int getPort() { 104 | return port; 105 | } 106 | 107 | @Nonnull 108 | public String getBaseUrl() { 109 | return HOST + PORT; 110 | } 111 | 112 | @Nonnull 113 | public String url(@Nonnull final String relativeUrl) { 114 | return getBaseUrl() + relativeUrl; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /service/src/test/java/com/mapcode/services/standalone/MainCommandLineTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.standalone; 18 | 19 | import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; 20 | import org.junit.Assert; 21 | import org.junit.Test; 22 | import org.mockito.MockitoAnnotations; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | import javax.annotation.Nonnull; 27 | import javax.ws.rs.core.MediaType; 28 | import javax.ws.rs.core.Response; 29 | 30 | @SuppressWarnings({"rawtypes", "ProhibitedExceptionDeclared", "unchecked"}) 31 | public class MainCommandLineTest { 32 | private static final Logger LOG = LoggerFactory.getLogger(MainCommandLineTest.class); 33 | 34 | private static final int SERVER_PORT = 8081; 35 | 36 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 37 | @Test 38 | public void testHelp() { 39 | LOG.info("testHelp"); 40 | 41 | // Initialize Mockito. 42 | MockitoAnnotations.initMocks(this); 43 | MainCommandLine.execute("--help"); 44 | } 45 | 46 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 47 | @Test 48 | public void testUnknownArgument() { 49 | LOG.info("testUnknownArgument"); 50 | 51 | // Initialize Mockito. 52 | MockitoAnnotations.initMocks(this); 53 | MainCommandLine.execute("--help", "unknown"); 54 | MainCommandLine.execute("--unknown"); 55 | MainCommandLine.execute("--port"); 56 | } 57 | 58 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 59 | @Test 60 | public void testServer() { 61 | LOG.info("testServer"); 62 | 63 | // Initialize Mockito. 64 | MockitoAnnotations.initMocks(this); 65 | MainCommandLine.execute("--silent", "--debug", "--port", "8081"); 66 | 67 | // Execute a REST API call. 68 | checkVersionXmlJson(); 69 | 70 | MainCommandLine.stop(); 71 | } 72 | 73 | public void checkVersionXmlJson() { 74 | LOG.info("checkVersionXmlJson"); 75 | final String expectedXml = ""; 76 | final String expectedJson = "{\"version\":\""; 77 | 78 | Response response = new ResteasyClientBuilder().build(). 79 | target(localUrl("/mapcode/version")). 80 | request(). 81 | accept(MediaType.APPLICATION_XML_TYPE).get(); 82 | Assert.assertNotNull(response); 83 | Assert.assertEquals(200, response.getStatus()); 84 | Assert.assertTrue(response.readEntity(String.class).contains(expectedXml)); 85 | 86 | response = new ResteasyClientBuilder().build(). 87 | target(localUrl("/mapcode/xml/version")). 88 | request(). 89 | get(); 90 | Assert.assertNotNull(response); 91 | Assert.assertEquals(200, response.getStatus()); 92 | Assert.assertTrue(response.readEntity(String.class).contains(expectedXml)); 93 | 94 | response = new ResteasyClientBuilder().build(). 95 | target(localUrl("/mapcode/json/version")). 96 | request(). 97 | get(); 98 | Assert.assertNotNull(response); 99 | Assert.assertEquals(200, response.getStatus()); 100 | Assert.assertTrue(response.readEntity(String.class).contains(expectedJson)); 101 | } 102 | 103 | @Nonnull 104 | private static String localUrl(@Nonnull final String url) { 105 | return "http://localhost:" + SERVER_PORT + url; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /service/src/test/java/com/mapcode/services/standalone/StandaloneModuleTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.mapcode.services.standalone; 18 | 19 | import com.google.inject.Binder; 20 | import com.google.inject.Key; 21 | import com.google.inject.binder.AnnotatedBindingBuilder; 22 | import com.google.inject.binder.LinkedBindingBuilder; 23 | import com.google.inject.name.Names; 24 | import org.junit.Test; 25 | import org.mockito.Mock; 26 | import org.mockito.MockitoAnnotations; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | import static org.mockito.ArgumentMatchers.any; 31 | import static org.mockito.Mockito.when; 32 | 33 | @SuppressWarnings({"rawtypes", "ProhibitedExceptionDeclared", "unchecked"}) 34 | public class StandaloneModuleTest { 35 | private static final Logger LOG = LoggerFactory.getLogger(StandaloneModuleTest.class); 36 | 37 | @Mock 38 | private Binder mockBinder; 39 | 40 | @Mock 41 | private AnnotatedBindingBuilder mockAnnotatedBindingBuilder; 42 | 43 | @Mock 44 | private LinkedBindingBuilder mockLinkedBindingBuilder; 45 | 46 | @SuppressWarnings("JUnitTestMethodWithNoAssertions") 47 | @Test 48 | public void testStandaloneModule() { 49 | LOG.info("testStandaloneModule"); 50 | 51 | // Initialize Mockito. 52 | MockitoAnnotations.initMocks(this); 53 | when(mockBinder.skipSources(Names.class)).thenReturn(mockBinder); 54 | when(mockBinder.bind(any(Key.class))).thenReturn(mockLinkedBindingBuilder); 55 | when(mockBinder.bind(any(Class.class))).thenReturn(mockAnnotatedBindingBuilder); 56 | 57 | // Execute start-up check. 58 | final StandaloneModule standaloneModule = new StandaloneModule(); 59 | standaloneModule.configure(mockBinder); 60 | } 61 | } 62 | --------------------------------------------------------------------------------