17 Commits

Author SHA1 Message Date
d571675a31 Preparations for release 1.1.4 2018-11-19 11:40:57 +01:00
f0205d1cc7 Extend unit tests for accepted Non-Integer values (#2) 2018-11-17 12:32:14 +01:00
9ff4555ce8 Add URLEncoder to query paraemters to fix issue with special chars (#4) 2018-11-17 12:19:34 +01:00
bd94a98a30 Add CONTRIBUTING.md [skip ci] 2018-11-16 15:25:16 +01:00
1698622fc9 Accept NULL for vehicle ID field (fix #3) 2018-11-16 11:19:45 +01:00
b9656b386a Accept direction ID as String instead if Integer (fix #2) 2018-11-16 11:04:27 +01:00
ee91f05898 Preparations for release 1.1.3 2018-11-13 13:52:15 +01:00
83e6e446ba Updated dependencies 2018-11-13 13:49:06 +01:00
e8ca106037 Migrated Drone Matrix build to Multi-Machine pipeline 2018-11-13 13:49:02 +01:00
5808365777 Fixed Sonarcloud quality gate badge [skip ci] 2018-10-02 22:17:01 +02:00
9e7a2a92ee Add JDK11 to CI configuration 2018-10-02 22:14:51 +02:00
4de8f3f073 Add Drone CI configuration 2018-08-03 19:23:39 +02:00
8631a43ed8 Add JDK10 to CI configuration 2018-08-03 17:57:42 +02:00
c9444bbc97 Migrated tests to JUnit 5 and removed PowerMock dependency
As a replacement for the static mock of the URL class, the tests have
been rewritten using ByteBuddy to redefine the calling method.
2018-08-03 17:52:44 +02:00
0d0859bd3a Updated dependencies and Maven plugins for Java 10 build system compat 2018-08-03 16:14:22 +02:00
d5e09392ef Client and model classes implement Serializable 2018-03-25 17:37:24 +02:00
d12c585083 Add package-info and overview.html for enhanced Javadoc output 2018-03-25 14:40:37 +02:00
16 changed files with 464 additions and 191 deletions

35
.drone.yml Normal file
View File

@ -0,0 +1,35 @@
kind: pipeline
name: java8
clone:
disable: true
steps:
- name: clone
image: plugins/git
settings:
depth: 10
skip_verify: true
- name: test
image: maven:3.5-jdk-8-alpine
commands:
- mvn clean test
---
kind: pipeline
name: java11
clone:
disable: true
steps:
- name: clone
image: plugins/git
settings:
depth: 10
skip_verify: true
- name: test
image: maven:3.5-jdk-11-slim
commands:
- mvn clean test

View File

@ -1,6 +1,7 @@
language: java
jdk:
- oraclejdk8
- oraclejdk11
install: true
addons:
sonarcloud:

View File

@ -1,15 +1,42 @@
## 1.1.2 [2018-03-24]
* [improvement] Added automatic module name for JPMS compatibility
# Changelog
All notable changes to this project will be documented in this file.
## 1.1.1 [2018-02-20]
* [improvement] On connection or parsing errors, the `IOException` is no longer ignored, but encapsulated in `RuntimeException` (no StackTraces printed)
* [internal] Code cleanup and minor improvements
* [dependeny] Minor dependency updates
## 1.1.4 - 2018-11-19
### Fixed
* Fixed issue with direction ID as `String` instead if `Integer` (#2)
* Fixed issue with vehicle ID being `null` (#3)
* Fixed issue with spaces in search parametes (#4)
## 1.1.0 [2017-01-07]
* [feature] Filter stops by coordinates and radius
* [feature] Filter trips by destination and and towards fields
* [test] Test coverage 100% (line); tested against ASEAG and TFL APIs
## 1.0.0 [2017-01-02]
* Initial release
## 1.1.3 - 2018-11-13
### Security
* Updates Jackson dependency 2.9.4 to 2.9.7 (CVE-2018-7489)
### Changed
* Client and model classes implement `Serializable`
* Dependency updates
## 1.1.2 - 2018-03-24
### Changed
* Added automatic module name for JPMS compatibility
## 1.1.1 - 2018-02-20
### Changed
* On connection or parsing errors, the `IOException` is no longer ignored, but encapsulated in `RuntimeException` (no StackTraces printed)
* Code cleanup and minor improvements
* Minor dependency updates
## 1.1.0 - 2017-01-07
### Added
* Filter stops by coordinates and radius
* Filter trips by destination and and towards fields
### Misc
* Test coverage 100% (line); tested against ASEAG and TFL APIs
## 1.0.0 - 2017-01-02
* Initial release

118
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,118 @@
# How to contribute
As for all great Open Source projects, contributions in form of bug reports and code are welcome and important to keep the project alive.
In general, this project follows the [GitHub Flow](https://guides.github.com/introduction/flow/).
Fork the project, commit your changes to your branch, open a pull request and it will probably be merged.
However, to ensure maintainability and quality of the code, there are some guidelines you might be more or less familiar with.
For that purpose, this document describes the important points.
## Opening an Issue
If you experience any issues with the plugin or the code, don't hesitate to file an issue.
### Bug Reports
Think you found a bug?
Please clearly state what happens and describe your environment to help tracking down the issue.
* Which version of the project are you running?
* Which version of Java?
* Which API do you try to query?
### Feature Requests
Missing a feature or like to have certain functionality enhanced?
No problem, please open an issue and describe what and why you think this change is required.
## Pull Requests
If you want to contribute your code to solve an issue or implement a desired feature yourself, you might open a pull request.
If the changes introduce new functionality or affect major parts of existing code, please consider opening an issue for discussion first.
For adding new functionality a new test case the corresponding JUnit test would be nice (no hard criterion though).
### Branches
The `master` branch represents the current state of development.
Please ensure your initial code is up to date with it at the time you start development.
The `master` should also be target for most pull requests.
In addition, this project features a `develop` branch, which holds bleeding edge developments, not necessarily considered stable or even compatible.
Do not expect this code to run smoothly, but you might have a look into the history to see if some work on an issue has already been started there.
For fixes and features, there might be additional branches, likely prefixed by `feature/` `fix/` followed by an issue number (if applicable) and/or a title.
Feel free to adapt these naming scheme to your forks.
### Merge Requirements
To be merged into the master branch, your code has to pass the automated continuous integration tests, to ensure compatibility.
In Addition your code has to be approved by a project member.
#### What if my code fails the tests?
Don't worry, you can submit your PR anyway.
The reviewing process might help you to solve remaining issues.
### Commit messages
Please use speaking titles and messages for your commits, to ensure a transparent history.
If your patch fixes an issue, reference the ID in the first line.
If you feel like you have to _briefly_ explain your changes, do it (for long explanations and discussion, consider opening an issue or describe in the PR).
**Example commit:**
```text
Fix nasty bug from #1337
This example commit fixes the issue that some people write non-speaking commit messages like 'done magic'.
A short description is helpful sometimes.
```
You might sign your work, although that's no must.
### When will it be merged?
Short answer: When it makes sense.
Bugfixes should be merged in time - assuming they pass the above criteria.
New features might be assigned to a certain milestone and as a result of this be scheduled according to the planned release cycle.
## Versioning
This projects tries to adapt the [Semantic Versioning](https://semver.org).
In short, bug fixes without do not affect any compatibility will raise the third number only, new features will be reflected in the second number and any change breaking compatibility with the public API require raising the first number.
If you have to make a decision for which version to go please keep this in mind.
However for most non-member commits this is mostly informative, as the decision will be made by the project team later.
## Build Environment
All you need to start off - besides your favorite IDE of course - is Java and Maven.
The project requires Java 8 or higher, both OpenJDK and Oracle JDK are supported.
All build steps are executed by calling e.g. `mvn clean package` in the project's root directory,
## Unit Tests
The Java code is tested by a set of JUnit tests.
All test files are located in the `src/test` directory.
Files ending with `Test.java` will be automatically included into the test suite.
## Continuous Integration
Automated tests are run using [Travis CI](https://travis-ci.org/stklcode/juraclient) for every commit including pull requests.
There is also a code quality analysis pushing results to [SonarCloud](https://sonarcloud.io/dashboard?id=de.stklcode.pubtrans%3Ajuraclient).
Keep in mind that the ruleset is not yet perfect, so not every minor issue has to be fixed immediately.
## Still Open Questions?
If anything is still left unanswered and you're unsure if you got it right, don't hesitate to contact a team member.
In any case you might submit your request/issue anyway, we won't refuse good code only for formal reasons.

View File

@ -1,6 +1,6 @@
# jURAclient
[![Build status](https://travis-ci.org/stklcode/juraclient.svg?branch=master)](https://travis-ci.org/stklcode/juraclient)
[![Quality Gate](https://sonarcloud.io/api/badges/gate?key=de.stklcode.pubtrans%3Ajuraclient)](https://sonarcloud.io/dashboard?id=de.stklcode.pubtrans%3Ajuraclient)
[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=de.stklcode.pubtrans%3Ajuraclient&metric=alert_status)](https://sonarcloud.io/dashboard?id=de.stklcode.pubtrans%3Ajuraclient)
[![Javadocs](https://www.javadoc.io/badge/de.stklcode.pubtrans/juraclient.svg)](https://www.javadoc.io/doc/de.stklcode.pubtrans/juraclient)
[![Maven Central](https://img.shields.io/maven-central/v/de.stklcode.pubtrans/juraclient.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22de.stklcode.pubtrans%22%20AND%20a%3A%22juraclient%22)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/stklcode/juraclient/blob/master/LICENSE.txt)
@ -55,7 +55,7 @@ List<Trip> trips = ura.forStopByName("Piccadilly Circus")
<dependency>
<groupId>de.stklcode.pubtrans</groupId>
<artifactId>juraclient</artifactId>
<version>1.1.2</version>
<version>1.1.4</version>
</dependency>
```

44
pom.xml
View File

@ -6,7 +6,7 @@
<groupId>de.stklcode.pubtrans</groupId>
<artifactId>juraclient</artifactId>
<version>1.1.2</version>
<version>1.1.4</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -50,17 +50,17 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
@ -70,15 +70,15 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0-beta.5</version>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0-beta.5</version>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.9.4</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -88,7 +88,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -97,7 +97,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<version>3.1.0</version>
<configuration>
<archive>
<manifestEntries>
@ -106,6 +106,11 @@
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>
<profiles>
@ -115,7 +120,7 @@
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.agent</artifactId>
<version>0.8.0</version>
<version>0.8.2</version>
<classifier>runtime</classifier>
</dependency>
</dependencies>
@ -124,7 +129,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.0</version>
<version>0.8.2</version>
<executions>
<execution>
<id>default-instrument</id>
@ -153,7 +158,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<version>2.22.1</version>
<configuration>
<systemPropertyVariables>
<jacoco-agent.destfile>${project.build.directory}/jacoco.exec</jacoco-agent.destfile>
@ -198,7 +203,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<version>3.0.1</version>
<configuration>
<overview>${basedir}/src/main/javadoc/overview.html</overview>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>

View File

@ -20,20 +20,22 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.pubtrans.ura.model.Stop;
import de.stklcode.pubtrans.ura.model.Trip;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Client for URA based public transport API.
* <p>
* This client features builder pattern style query functionality to obtain {@link Trip} and {@link Stop} information.
*
* @author Stefan Kalscheuer
*/
public class UraClient {
public class UraClient implements Serializable {
private static final String DEFAULT_INSTANT_URL = "/interfaces/ura/instant_V1";
private static final String DEFAULT_STREAM_URL = "/interfaces/ura/stream_V1";
@ -284,33 +286,42 @@ public class UraClient {
String urlStr = baseURL + instantURL + "?ReturnList=" + String.join(",", returnList);
if (query.stopIDs != null && query.stopIDs.length > 0) {
urlStr += "&" + PAR_STOP_ID + "=" + String.join(",", query.stopIDs);
urlStr += "&" + PAR_STOP_ID + "=" + URLEncoder.encode(String.join(",", query.stopIDs), UTF_8.name());
}
if (query.stopNames != null && query.stopNames.length > 0) {
urlStr += "&" + PAR_STOP_NAME + "=" + String.join(",", query.stopNames);
urlStr += "&" + PAR_STOP_NAME + "=" + URLEncoder.encode(String.join(",", query.stopNames), UTF_8.name());
}
if (query.lineIDs != null && query.lineIDs.length > 0) {
urlStr += "&" + PAR_LINE_ID + "=" + String.join(",", query.lineIDs);
urlStr += "&" + PAR_LINE_ID + "=" + URLEncoder.encode(String.join(",", query.lineIDs), UTF_8.name());
}
if (query.lineNames != null && query.lineNames.length > 0) {
urlStr += "&" + PAR_LINE_NAME + "=" + String.join(",", query.lineNames);
urlStr += "&" + PAR_LINE_NAME + "=" + URLEncoder.encode(String.join(",", query.lineNames), UTF_8.name());
}
if (query.direction != null) {
urlStr += "&" + PAR_DIR_ID + "=" + query.direction;
}
if (query.destinationNames != null) {
urlStr += "&" + PAR_DEST_NAME + "=" + String.join(",", query.destinationNames);
urlStr += "&" + PAR_DEST_NAME + "=" + URLEncoder.encode(String.join(",", query.destinationNames), UTF_8.name());
}
if (query.towards != null) {
urlStr += "&" + PAR_TOWARDS + "=" + String.join(",", query.towards);
urlStr += "&" + PAR_TOWARDS + "=" + URLEncoder.encode(String.join(",", query.towards), UTF_8.name());
}
if (query.circle != null) {
urlStr += "&" + PAR_CIRCLE + "=" + String.join(",", query.circle);
urlStr += "&" + PAR_CIRCLE + "=" + URLEncoder.encode(query.circle, UTF_8.name());
}
URL url = new URL(urlStr);
return request(urlStr);
}
return url.openStream();
/**
* Open given URL as InputStream.
*
* @param url The URL.
* @return Input Stream of results.
* @throws IOException Error opening conneciton or reading data.
*/
private InputStream request(String url) throws IOException {
return new URL(url).openStream();
}
/**

View File

@ -17,12 +17,15 @@
package de.stklcode.pubtrans.ura.model;
import java.io.IOException;
import java.io.Serializable;
/**
* Interface for model classes to bundle common methods.
*
* @author Stefan Kalscheuer
* @since 1.1.1
*/
interface Model {
interface Model extends Serializable {
/**
* Generate exception for unmatched type when String is expected.
*

View File

@ -176,13 +176,15 @@ public final class Trip implements Model {
throw Model.typeErrorString(LINE_NAME, raw.get(LINE_NAME).getClass());
}
if (raw.get(DIRECTION_ID) instanceof Integer) {
directionID = (Integer) raw.get(DIRECTION_ID);
if (raw.get(DIRECTION_ID) instanceof String // Also accept Strings (#2)
|| raw.get(DIRECTION_ID) instanceof Integer
|| raw.get(DIRECTION_ID) instanceof Long) {
directionID = Integer.valueOf(raw.get(DIRECTION_ID).toString());
if (directionID < 0 || directionID > 2) {
throw new IOException("Direction out of range. Expected 1 or 2, found " + directionID);
}
} else {
throw Model.typeError(DIRECTION_ID, raw.get(DIRECTION_ID).getClass(), "Integer");
throw Model.typeError(DIRECTION_ID, raw.get(DIRECTION_ID).getClass(), "String/Long/Integer");
}
if (raw.get(DESTINATION_NAME) instanceof String) {
@ -202,6 +204,8 @@ public final class Trip implements Model {
|| raw.get(VEHICLE_ID) instanceof Integer
|| raw.get(VEHICLE_ID) instanceof Long) {
vehicleID = raw.get(VEHICLE_ID).toString();
} else if (raw.get(VEHICLE_ID) == null) { // Only fail of field is not NULL (#3).
vehicleID = null;
} else {
throw Model.typeError(VEHICLE_ID, raw.get(VEHICLE_ID).getClass(), "String/Integer/Long");
}
@ -285,7 +289,7 @@ public final class Trip implements Model {
}
/**
* @return The vehicle ID.
* @return The vehicle ID or {@code null} if not present.
*/
public String getVehicleID() {
return vehicleID;

View File

@ -0,0 +1,20 @@
/*
* Copyright 2016-2018 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* jURAclient model classes that represent responses returned by the URA interface.
*/
package de.stklcode.pubtrans.ura.model;

View File

@ -0,0 +1,20 @@
/*
* Copyright 2016-2018 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* jURAclient base package - see {@link de.stklcode.pubtrans.ura.UraClient} for usage.
*/
package de.stklcode.pubtrans.ura;

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API Overview</title>
</head>
<body>
<p>Java client for URA based public transport APIs.</p>
<p>
This client allows to simply connect any Java application to the public transport API to implement a monitor for the
local bus station or any other custom queries. API versions 1.x and 2.x are supported.
</p>
</body>
</html>

View File

@ -18,108 +18,121 @@ package de.stklcode.pubtrans.ura;
import de.stklcode.pubtrans.ura.model.Stop;
import de.stklcode.pubtrans.ura.model.Trip;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeAll;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
/**
* Unit test for the URA Client.
* Tests run against mocked data collected from ASEAG API (http://ivu.aseag.de) and
* TFL API (http://http://countdown.api.tfl.gov.uk)
* TFL API (http://http://countdown.api.tfl.gov.uk)
*
* @author Stefan Kalscheuer
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ UraClient.class, URL.class })
public class UraClientTest {
@Test
public void getStopsTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V2_stops.txt"));
// Mocked resource URL and exception message.
private static String mockResource = null;
private static String mockException = null;
/* List stops and verify some values */
@BeforeAll
public static void initByteBuddy() {
// Install ByteBuddy Agent.
ByteBuddyAgent.install();
new ByteBuddy().redefine(UraClient.class)
.method(named("request"))
.intercept(to(UraClientTest.class))
.make()
.load(UraClient.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
}
@Test
public void getStopsTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V2_stops.txt");
// List stops and verify some values.
List<Stop> stops = new UraClient("mocked").getStops();
assertThat(stops, hasSize(10));
assertThat(stops.get(0).getId(), is("100210"));
assertThat(stops.get(1).getName(), is("Brockenberg"));
assertThat(stops.get(2).getState(), is(0));;
assertThat(stops.get(2).getState(), is(0));
assertThat(stops.get(3).getLatitude(), is(50.7578775));
assertThat(stops.get(4).getLongitude(), is(6.0708663));
/* Test exception handling */
PowerMockito.when(mockURL.openStream()).thenReturn(new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Provoked exception 1.");
}
});
// Test Exception handling.
mockHttpToException("Provoked Exception 1");
try {
new UraClient("mocked").getStops();
} catch (RuntimeException e) {
assertThat(e, is(instanceOf(IllegalStateException.class)));
assertThat(e.getCause(), is(instanceOf(IOException.class)));
assertThat(e.getCause().getMessage(), is("Provoked exception 1."));
assertThat(e.getCause().getMessage(), is("Provoked Exception 1"));
}
}
@Test
public void getStopsForLineTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V2_stops_line.txt"));
public static InputStream request(String originalURL) throws IOException {
if (mockResource == null && mockException != null) {
IOException e = new IOException(mockException);
mockException = null;
throw e;
}
/* List stops and verify some values */
InputStream res = UraClientTest.class.getResourceAsStream(mockResource);
mockResource = null;
return res;
}
@Test
public void getStopsForLineTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V2_stops_line.txt");
// List stops and verify some values.
List<Stop> stops = new UraClient("mocked").forLines("33").getStops();
assertThat(stops, hasSize(47));
assertThat(stops.get(0).getId(), is("100000"));
assertThat(stops.get(1).getName(), is("Kuckelkorn"));
assertThat(stops.get(2).getState(), is(0));;
assertThat(stops.get(2).getState(), is(0));
assertThat(stops.get(3).getLatitude(), is(50.7690688));
assertThat(stops.get(4).getIndicator(), is("H.1"));
assertThat(stops.get(5).getLongitude(), is(6.2314072));
}
@Test
public void getStopsForPositionTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_stops_circle.txt"));
public void getStopsForPositionTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_stops_circle.txt");
/* List stops and verify some values */
// List stops and verify some values.
List<Stop> stops = new UraClient("mocked")
.forPosition(51.51009, -0.1345734, 200)
.getStops();
assertThat(stops, hasSize(13));
assertThat(stops.get(0).getId(), is("156"));
assertThat(stops.get(1).getName(), is("Piccadilly Circus"));
assertThat(stops.get(2).getState(), is(0));;
assertThat(stops.get(2).getState(), is(0));
assertThat(stops.get(3).getLatitude(), is(51.509154));
assertThat(stops.get(4).getLongitude(), is(-0.134172));
assertThat(stops.get(5).getIndicator(), is(nullValue()));
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_stops_circle_name.txt"));
mockHttpToFile("instant_V1_stops_circle_name.txt");
stops = new UraClient("mocked")
.forStopsByName("Piccadilly Circus")
.forPosition(51.51009, -0.1345734, 200)
@ -129,21 +142,17 @@ public class UraClientTest {
}
@Test
public void getTripsForDestinationNamesTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_destination.txt"));
public void getTripsForDestinationNamesTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_destination.txt");
/* List stops and verify some values */
// List stops and verify some values.
List<Trip> trips = new UraClient("mocked").forDestinationNames("Piccadilly Circus").getTrips();
assertThat(trips, hasSize(9));
assertThat(trips.stream().filter(t -> !t.getDestinationName().equals("Piccadilly Cir")).findAny(),
is(Optional.empty()));
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop_destination.txt"));
mockHttpToFile("instant_V1_trips_stop_destination.txt");
trips = new UraClient("mocked")
.forStops("156")
.forDestinationNames("Marble Arch")
@ -156,38 +165,31 @@ public class UraClientTest {
}
@Test
public void getTripsTowardsTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_towards.txt"));
public void getTripsTowardsTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_towards.txt");
/* List stops and verify some values */
List<Trip> trips = new UraClient("mocked").towards("Marble Arch").getTrips();
assertThat(trips, hasSize(10));
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop_towards.txt"));
mockHttpToFile("instant_V1_trips_stop_towards.txt");
trips = new UraClient("mocked").forStops("156").towards("Marble Arch").getTrips();
assertThat(trips, hasSize(17));
assertThat(trips.stream().filter(t -> !t.getStop().getId().equals("156")).findAny(), is(Optional.empty()));
}
@Test
public void getTripsTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_all.txt"));
public void getTripsTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_all.txt");
/* Get trips without filters and verify some values */
// Get trips without filters and verify some values.
List<Trip> trips = new UraClient("mocked").getTrips();
assertThat(trips, hasSize(10));
assertThat(trips.get(0).getId(), is("27000165015001"));
assertThat(trips.get(1).getLineID(), is("55"));
assertThat(trips.get(2).getLineName(), is("28"));;
assertThat(trips.get(2).getLineName(), is("28"));
assertThat(trips.get(3).getDirectionID(), is(1));
assertThat(trips.get(4).getDestinationName(), is("Verlautenheide Endstr."));
assertThat(trips.get(5).getDestinationText(), is("Aachen Bushof"));
@ -196,15 +198,15 @@ public class UraClientTest {
assertThat(trips.get(8).getVisitID(), is(30));
assertThat(trips.get(9).getStop().getId(), is("100002"));
/* Repeat test for API V2 */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V2_trips_all.txt"));
/* Get trips without filters and verify some values */
// Repeat test for API V2.
mockHttpToFile("instant_V2_trips_all.txt");
// Get trips without filters and verify some values.
trips = new UraClient("mocked").getTrips();
assertThat(trips, hasSize(10));
assertThat(trips.get(0).getId(), is("27000165015001"));
assertThat(trips.get(1).getLineID(), is("55"));
assertThat(trips.get(2).getLineName(), is("28"));;
assertThat(trips.get(2).getLineName(), is("28"));
assertThat(trips.get(3).getDirectionID(), is(1));
assertThat(trips.get(4).getDestinationName(), is("Verlautenheide Endstr."));
assertThat(trips.get(5).getDestinationText(), is("Aachen Bushof"));
@ -213,37 +215,28 @@ public class UraClientTest {
assertThat(trips.get(8).getVisitID(), is(30));
assertThat(trips.get(9).getStop().getId(), is("100002"));
/* Get limited number of trips */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_all.txt"));
// Get limited number of trips.
mockHttpToFile("instant_V1_trips_all.txt");
trips = new UraClient("mocked").getTrips(5);
assertThat(trips, hasSize(5));
/* Test exception handling */
PowerMockito.when(mockURL.openStream()).thenReturn(new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Provoked exception 1.");
}
});
// Test mockException handling.
mockHttpToException("Provoked mockException 2");
try {
new UraClient("mocked").getTrips();
} catch (RuntimeException e) {
assertThat(e, is(instanceOf(IllegalStateException.class)));
assertThat(e.getCause(), is(instanceOf(IOException.class)));
assertThat(e.getCause().getMessage(), is("Provoked exception 1."));
assertThat(e.getCause().getMessage(), is("Provoked mockException 2"));
}
}
@Test
public void getTripsForStopTest() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop.txt"));
public void getTripsForStopTest() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_stop.txt");
/* Get trips for stop ID 100000 (Aachen Bushof) and verify some values */
// Get trips for stop ID 100000 (Aachen Bushof) and verify some values.
List<Trip> trips = new UraClient("mocked")
.forStops("100000")
.getTrips();
@ -251,12 +244,11 @@ public class UraClientTest {
assertThat(trips.stream().filter(t -> !t.getStop().getId().equals("100000")).findAny(), is(Optional.empty()));
assertThat(trips.get(0).getId(), is("27000158010001"));
assertThat(trips.get(1).getLineID(), is("7"));
assertThat(trips.get(2).getLineName(), is("25"));;
assertThat(trips.get(2).getLineName(), is("25"));
assertThat(trips.get(3).getStop().getIndicator(), is("H.15"));
/* Get trips for stop name "Uniklinik" and verify some values */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop_name.txt"));
// Get trips for stop name "Uniklinik" and verify some values.
mockHttpToFile("instant_V1_trips_stop_name.txt");
trips = new UraClient("mocked")
.forStopsByName("Uniklinik")
.getTrips();
@ -265,19 +257,16 @@ public class UraClientTest {
is(Optional.empty()));
assertThat(trips.get(0).getId(), is("92000043013001"));
assertThat(trips.get(1).getLineID(), is("5"));
assertThat(trips.get(2).getVehicleID(), is("317"));;
assertThat(trips.get(2).getVehicleID(), is("317"));
assertThat(trips.get(3).getDirectionID(), is(1));
}
@Test
public void getTripsForLine() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_line.txt"));
public void getTripsForLine() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_line.txt");
/* Get trips for line ID 3 and verify some values */
// Get trips for line ID 3 and verify some values.
List<Trip> trips = new UraClient("mocked")
.forLines("3")
.getTrips();
@ -285,12 +274,11 @@ public class UraClientTest {
assertThat(trips.stream().filter(t -> !t.getLineID().equals("3")).findAny(), is(Optional.empty()));
assertThat(trips.get(0).getId(), is("27000154004001"));
assertThat(trips.get(1).getLineID(), is("3"));
assertThat(trips.get(2).getLineName(), is("3.A"));;
assertThat(trips.get(2).getLineName(), is("3.A"));
assertThat(trips.get(3).getStop().getIndicator(), is("H.4 (Pontwall)"));
/* Get trips for line name "3.A" and verify some values */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_line_name.txt"));
// Get trips for line name "3.A" and verify some values.
mockHttpToFile("instant_V1_trips_line_name.txt");
trips = new UraClient("mocked")
.forLinesByName("3.A")
.getTrips();
@ -298,12 +286,11 @@ public class UraClientTest {
assertThat(trips.stream().filter(t -> !t.getLineName().equals("3.A")).findAny(), is(Optional.empty()));
assertThat(trips.get(0).getId(), is("92000288014001"));
assertThat(trips.get(1).getLineID(), is("3"));
assertThat(trips.get(2).getLineName(), is("3.A"));;
assertThat(trips.get(2).getLineName(), is("3.A"));
assertThat(trips.get(3).getStop().getName(), is("Aachen Gartenstraße"));
/* Get trips for line 3 with direction 1 and verify some values */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_line_direction.txt"));
// Get trips for line 3 with direction 1 and verify some values.
mockHttpToFile("instant_V1_trips_line_direction.txt");
trips = new UraClient("mocked")
.forLines("412")
.forDirection(2)
@ -312,9 +299,8 @@ public class UraClientTest {
assertThat(trips.stream().filter(t -> !t.getLineID().equals("412")).findAny(), is(Optional.empty()));
assertThat(trips.stream().filter(t -> !t.getDirectionID().equals(2)).findAny(), is(Optional.empty()));
/* Test lineID and direction in different order */
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_line_direction.txt"));
// Test lineID and direction in different order.
mockHttpToFile("instant_V1_trips_line_direction.txt");
trips = new UraClient("mocked")
.forDirection(2)
.forLines("412")
@ -325,14 +311,11 @@ public class UraClientTest {
}
@Test
public void getTripsForStopAndLine() throws Exception {
/* Mock the HTTP call */
URL mockURL = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
PowerMockito.when(mockURL.openStream())
.thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop_line.txt"));
public void getTripsForStopAndLine() {
// Mock the HTTP call.
mockHttpToFile("instant_V1_trips_stop_line.txt");
/* Get trips for line ID 25 and 25 at stop 100000 and verify some values */
// Get trips for line ID 25 and 25 at stop 100000 and verify some values.
List<Trip> trips = new UraClient("mocked")
.forLines("25", "35")
.forStops("100000")
@ -343,7 +326,16 @@ public class UraClientTest {
assertThat(trips.stream().filter(t -> !t.getStop().getId().equals("100000")).findAny(), is(Optional.empty()));
assertThat(trips.get(0).getId(), is("27000078014001"));
assertThat(trips.get(1).getLineID(), is("25"));
assertThat(trips.get(3).getLineName(), is("35"));;
assertThat(trips.get(3).getLineName(), is("35"));
assertThat(trips.get(5).getStop().getIndicator(), is("H.12"));
}
private static void mockHttpToFile(String newResourceFile) {
mockResource = newResourceFile;
}
private static void mockHttpToException(String newException) {
mockException = newException;
}
}

View File

@ -16,7 +16,7 @@
package de.stklcode.pubtrans.ura.model;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@ -26,7 +26,7 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit test for the Stop metamodel.

View File

@ -16,7 +16,7 @@
package de.stklcode.pubtrans.ura.model;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@ -26,7 +26,7 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit test for the Trip metamodel.
@ -130,6 +130,26 @@ public class TripTest {
fail("Creation of Trip from valid list failed: " + e.getMessage());
}
raw.remove(10);
raw.add(10, 0L); // Long values are OK.
try {
Trip trip = new Trip(raw);
assertThat(trip, is(notNullValue()));
assertThat(trip.getDirectionID(), is(0));
} catch (IOException e) {
fail("Creation of Trip from valid list failed: " + e.getMessage());
}
raw.remove(10);
raw.add(10, "0"); // String values are OK.
try {
Trip trip = new Trip(raw);
assertThat(trip, is(notNullValue()));
assertThat(trip.getDirectionID(), is(0));
} catch (IOException e) {
fail("Creation of Trip from valid list failed: " + e.getMessage());
}
/* Test exceptions on invalid data */
List<Object> invalid = new ArrayList<>(raw);
invalid.remove(7);
@ -163,7 +183,7 @@ public class TripTest {
invalid = new ArrayList<>(raw);
invalid.remove(10);
invalid.add(10, "1");
invalid.add(10, "7"); // Strings are generally OK, but 7 is out of range (#2).
try {
new Trip(invalid);
fail("Creation of Trip with invalid directionID field successfull");

View File

@ -1,11 +1,11 @@
[4,"2.0",1483362959788]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,11,"33","33",1,"Aachen Fuchserde","Aachen Fuchserde","318",92000043013001,1483362935000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,1,"5","5",1,"Driescher Hof-Brand","Driescher Hof-Brand","312",92000282009001,1483362936000]
[1,"Uniklinik","100600","H.4",0,50.7756388,6.04425,33,"45","45",1,"Uniklinik","Uniklinik","317",92000285009001,1483363294000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,28,"10","3.B",1,"Uniklinik-Ponttor-Hbf.","Uniklinik-Ponttor-Hbf.","347",92000053015001,1483363039000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,29,"33","33",1,"Uniklinik","Uniklinik","529",92000209014001,1483363288000]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,1,"73","73",1,"Aachen Bf.Rothe Erde","Aachen Bf.Rothe Erde","315",92000291016001,1483363080000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,29,"10","3.B",1,"Uniklinik-Ponttor-Hbf.","Uniklinik-Ponttor-Hbf.","347",92000053015001,1483363099000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,28,"3","3.A",1,"Uniklinik-Schanz-Hbf.","Uniklinik-Schanz-Hbf.","325",92000288012001,1483363080000]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,6,"70","70",1,"Aachen Adenauerallee","Aachen Adenauerallee","588",92000225009001,1483363346000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,1,"3","3.A",1,"Schanz-Hbf.-Ponttor","Schanz-Hbf.-Ponttor","325",92000288013001,1483363380000]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,11,"33","33","1","Aachen Fuchserde","Aachen Fuchserde","318",92000043013001,1483362935000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,1,"5","5","1","Driescher Hof-Brand","Driescher Hof-Brand","312",92000282009001,1483362936000]
[1,"Uniklinik","100600","H.4",0,50.7756388,6.04425,33,"45","45","1","Uniklinik","Uniklinik","317",92000285009001,1483363294000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,28,"10","3.B","1","Uniklinik-Ponttor-Hbf.","Uniklinik-Ponttor-Hbf.","347",92000053015001,1483363039000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,29,"33","33","1","Uniklinik","Uniklinik","529",92000209014001,1483363288000]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,1,"73","73","1","Aachen Bf.Rothe Erde","Aachen Bf.Rothe Erde","315",92000291016001,1483363080000]
[1,"Uniklinik","100600","H.3",0,50.7756388,6.04425,29,"10","3.B","1","Uniklinik-Ponttor-Hbf.","Uniklinik-Ponttor-Hbf.","347",92000053015001,1483363099000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,28,"3","3.A","1","Uniklinik-Schanz-Hbf.","Uniklinik-Schanz-Hbf.","325",92000288012001,1483363080000]
[1,"Uniklinik","100600","H.2",0,50.7756388,6.04425,6,"70","70","1","Aachen Adenauerallee","Aachen Adenauerallee","588",92000225009001,1483363346000]
[1,"Uniklinik","100600","H.1",0,50.7756388,6.04425,1,"3","3.A","1","Schanz-Hbf.-Ponttor","Schanz-Hbf.-Ponttor",null,92000288013001,1483363380000]