Compare commits
35 Commits
Author | SHA1 | Date | |
---|---|---|---|
70144573d0 | |||
e0e2547288 | |||
c61e637df9 | |||
dea83e81be | |||
fd45bc3db0 | |||
3a2f35047b | |||
39e1f41c0e | |||
8f8c335e81 | |||
0ecceca35a | |||
7b212abdc3 | |||
e9e80a4a08 | |||
a2c8f416ba | |||
d571675a31 | |||
f0205d1cc7 | |||
9ff4555ce8 | |||
bd94a98a30 | |||
90b7c5cb35 | |||
e957553e80 | |||
1698622fc9 | |||
b9656b386a | |||
ee91f05898 | |||
83e6e446ba | |||
e8ca106037 | |||
5808365777 | |||
9e7a2a92ee | |||
4de8f3f073 | |||
8631a43ed8 | |||
c9444bbc97 | |||
0d0859bd3a | |||
d5e09392ef | |||
d12c585083 | |||
ffa8af2d5d | |||
eb400b52ca | |||
0e21c0d64c | |||
7e3af36e22 |
18
.drone.yml
Normal file
18
.drone.yml
Normal file
@ -0,0 +1,18 @@
|
||||
kind: pipeline
|
||||
name: java8
|
||||
|
||||
steps:
|
||||
- name: test
|
||||
image: maven:3-jdk-8-alpine
|
||||
commands:
|
||||
- mvn clean test
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
name: java11
|
||||
|
||||
steps:
|
||||
- name: test
|
||||
image: maven:3-jdk-11-slim
|
||||
commands:
|
||||
- mvn clean test
|
@ -1,6 +1,7 @@
|
||||
language: java
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
- openjdk8
|
||||
- openjdk11
|
||||
install: true
|
||||
addons:
|
||||
sonarcloud:
|
||||
@ -12,4 +13,4 @@ cache:
|
||||
- '$HOME/.m2/repository'
|
||||
- '$HOME/.sonar/cache'
|
||||
script:
|
||||
- mvn -P jacoco clean package sonar:sonar
|
||||
- if [ "$TRAVIS_JDK_VERSION" == "openjdk11" ]; then mvn -P jacoco clean package sonar:sonar; else mvn clean test; fi
|
||||
|
57
CHANGELOG.md
57
CHANGELOG.md
@ -1,12 +1,49 @@
|
||||
## 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
|
||||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 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.2.0 - 2019-06-20
|
||||
### Security
|
||||
* Updated dependencies
|
||||
|
||||
## 1.0.0 [2017-01-02]
|
||||
* Initial release
|
||||
### Features
|
||||
* Added support for stream API with asynchronous reader, using `getTripsStream()` method (#1)
|
||||
|
||||
## 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.3 - 2018-11-13
|
||||
### Security
|
||||
* Updates Jackson dependency 2.9.4 to 2.9.7 (CVE-2018-7489)
|
||||
|
||||
### Improvements
|
||||
* Client and model classes implement `Serializable`
|
||||
* Dependency updates
|
||||
|
||||
|
||||
## 1.1.2 - 2018-03-24
|
||||
### Improvements
|
||||
* Added automatic module name for JPMS compatibility
|
||||
|
||||
|
||||
## 1.1.1 - 2018-02-20
|
||||
### Improvements
|
||||
* 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
|
||||
### Features
|
||||
* 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
118
CONTRIBUTING.md
Normal 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.
|
@ -1,8 +1,9 @@
|
||||
# jURAclient
|
||||
[](https://travis-ci.org/stklcode/juraclient)
|
||||
[](https://sonarcloud.io/dashboard?id=de.stklcode.pubtrans%3Ajuraclient)
|
||||
[](https://github.com/stklcode/juraclient/blob/master/LICENSE.txt)
|
||||
[](https://sonarcloud.io/dashboard?id=de.stklcode.pubtrans%3Ajuraclient)
|
||||
[](https://www.javadoc.io/doc/de.stklcode.pubtrans/juraclient)
|
||||
[](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22de.stklcode.pubtrans%22%20AND%20a%3A%22juraclient%22)
|
||||
[](https://github.com/stklcode/juraclient/blob/master/LICENSE.txt)
|
||||
|
||||
Java client for URA based public transport APIs.
|
||||
|
||||
@ -54,7 +55,7 @@ List<Trip> trips = ura.forStopByName("Piccadilly Circus")
|
||||
<dependency>
|
||||
<groupId>de.stklcode.pubtrans</groupId>
|
||||
<artifactId>juraclient</artifactId>
|
||||
<version>1.1.1</version>
|
||||
<version>1.1.4</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
|
154
pom.xml
154
pom.xml
@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>de.stklcode.pubtrans</groupId>
|
||||
<artifactId>juraclient</artifactId>
|
||||
<version>1.1.1</version>
|
||||
<version>1.2.0</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.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.9.4</version>
|
||||
<version>2.9.9</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.4.2</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.13</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.13</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -88,14 +88,32 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.7.0</version>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifestEntries>
|
||||
<Automatic-Module-Name>de.stklcode.pubtrans.juraclient</Automatic-Module-Name>
|
||||
</manifestEntries>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>jacoco</id>
|
||||
@ -103,7 +121,7 @@
|
||||
<dependency>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>org.jacoco.agent</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.4</version>
|
||||
<classifier>runtime</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -112,7 +130,7 @@
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-instrument</id>
|
||||
@ -141,7 +159,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<version>2.22.2</version>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<jacoco-agent.destfile>${project.build.directory}/jacoco.exec</jacoco-agent.destfile>
|
||||
@ -151,5 +169,109 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>sources</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<goals>
|
||||
<goal>jar-no-fork</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>javadoc</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<configuration>
|
||||
<overview>${basedir}/src/main/javadoc/overview.html</overview>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-javadocs</id>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>sign</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-gpg-plugin</artifactId>
|
||||
<version>1.6</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>sign-artifacts</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>sign</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<keyname>${gpg.keyname}</keyname>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>local</id>
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
<id>local</id>
|
||||
<url>${dist.repo.local}</url>
|
||||
</repository>
|
||||
<snapshotRepository>
|
||||
<id>local</id>
|
||||
<url>${dist.repo.local.snapshot}</url>
|
||||
</snapshotRepository>
|
||||
</distributionManagement>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>sonatype</id>
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
<id>ossrh</id>
|
||||
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
|
||||
</repository>
|
||||
<snapshotRepository>
|
||||
<id>ossrh</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
</snapshotRepository>
|
||||
</distributionManagement>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
@ -19,21 +19,26 @@ package de.stklcode.pubtrans.ura;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import de.stklcode.pubtrans.ura.model.Stop;
|
||||
import de.stklcode.pubtrans.ura.model.Trip;
|
||||
import de.stklcode.pubtrans.ura.reader.AsyncUraTripReader;
|
||||
|
||||
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.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
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";
|
||||
|
||||
@ -238,6 +243,38 @@ public class UraClient {
|
||||
return trips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trips for given stopIDs and lineIDs using stream API and pass each result to given consumer.
|
||||
*
|
||||
* @param query The query.
|
||||
* @param consumer Consumer(s) for single trips.
|
||||
* @see #getTripsStream(Query, List)
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public AsyncUraTripReader getTripsStream(final Query query, final Consumer<Trip> consumer) throws IOException {
|
||||
return getTripsStream(query, Collections.singletonList(consumer));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trips for given stopIDs and lineIDs using stream API and pass each result to given consumers.
|
||||
*
|
||||
* @param query The query.
|
||||
* @param consumers Consumer(s) for single trips.
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public AsyncUraTripReader getTripsStream(final Query query, final List<Consumer<Trip>> consumers) throws IOException {
|
||||
// Create the reader.
|
||||
AsyncUraTripReader reader = new AsyncUraTripReader(
|
||||
new URL(requestURL(baseURL + streamURL, REQUEST_TRIP, query)),
|
||||
consumers
|
||||
);
|
||||
|
||||
// Open the reader, i.e. start reading from API.
|
||||
reader.open();
|
||||
|
||||
return reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of stops without filters.
|
||||
*
|
||||
@ -281,36 +318,59 @@ public class UraClient {
|
||||
* @throws IOException on errors
|
||||
*/
|
||||
private InputStream requestInstant(final String[] returnList, final Query query) throws IOException {
|
||||
String urlStr = baseURL + instantURL + "?ReturnList=" + String.join(",", returnList);
|
||||
return request(requestURL(baseURL + instantURL, returnList, query));
|
||||
}
|
||||
|
||||
/**
|
||||
* Build request URL from given parameters.
|
||||
*
|
||||
* @param endpointURL Endpoint URL.
|
||||
* @param returnList Fields to fetch.
|
||||
* @param query The query.
|
||||
* @return The URL
|
||||
* @throws IOException on errors
|
||||
* @since 1.2.0
|
||||
*/
|
||||
private String requestURL(final String endpointURL, final String[] returnList, final Query query) throws IOException {
|
||||
String urlStr = endpointURL + "?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 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();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -436,5 +496,26 @@ public class UraClient {
|
||||
public List<Trip> getTrips() {
|
||||
return UraClient.this.getTrips(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trips for set filters.
|
||||
*
|
||||
* @param consumer Consumer for single trips.
|
||||
* @see #getTripsStream(List)
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public AsyncUraTripReader getTripsStream(Consumer<Trip> consumer) throws IOException {
|
||||
return UraClient.this.getTripsStream(this, consumer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trips for set filters.
|
||||
*
|
||||
* @param consumers Consumers for single trips.
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public AsyncUraTripReader getTripsStream(List<Consumer<Trip>> consumers) throws IOException {
|
||||
return UraClient.this.getTripsStream(this, consumers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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.
|
||||
*
|
||||
|
@ -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;
|
||||
|
@ -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;
|
20
src/main/java/de/stklcode/pubtrans/ura/package-info.java
Normal file
20
src/main/java/de/stklcode/pubtrans/ura/package-info.java
Normal 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;
|
@ -0,0 +1,150 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package de.stklcode.pubtrans.ura.reader;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Asynchronous stream reader foR URA stream API.
|
||||
* <p>
|
||||
* This reader provides a handler for asynchronous stream events.
|
||||
*
|
||||
* @author Stefan Kalscheuer
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public class AsyncUraTripReader implements AutoCloseable {
|
||||
private static final Integer RES_TYPE_PREDICTION = 1;
|
||||
private static final Integer RES_TYPE_URA_VERSION = 4;
|
||||
|
||||
private final List<Consumer<Trip>> consumers;
|
||||
private final URL url;
|
||||
private CompletableFuture<Void> future;
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Initialize trip reader.
|
||||
*
|
||||
* @param url URL to read trips from.
|
||||
* @param consumer Initial consumer.
|
||||
*/
|
||||
public AsyncUraTripReader(URL url, Consumer<Trip> consumer) {
|
||||
this.url = url;
|
||||
this.consumers = new ArrayList<>();
|
||||
this.consumers.add(consumer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize trip reader.
|
||||
*
|
||||
* @param url URL to read trips from.
|
||||
* @param consumers Initial list of consumers.
|
||||
*/
|
||||
public AsyncUraTripReader(URL url, List<Consumer<Trip>> consumers) {
|
||||
this.url = url;
|
||||
this.consumers = new ArrayList<>(consumers);
|
||||
}
|
||||
|
||||
public void open() {
|
||||
// Throw exeption, if future is already present.
|
||||
if (future != null) {
|
||||
throw new IllegalStateException("Reader already opened");
|
||||
}
|
||||
|
||||
this.future = CompletableFuture.runAsync(() -> {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
try (InputStream is = getInputStream(url);
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
|
||||
String version = null;
|
||||
String line = br.readLine();
|
||||
while (line != null && !this.cancelled) {
|
||||
List l = mapper.readValue(line, List.class);
|
||||
// Check if result exists and has correct response type.
|
||||
if (l != null && !l.isEmpty()) {
|
||||
if (l.get(0).equals(RES_TYPE_URA_VERSION)) {
|
||||
version = l.get(1).toString();
|
||||
} else if (l.get(0).equals(RES_TYPE_PREDICTION)) {
|
||||
// Parse Trip and pass to each consumer.
|
||||
Trip trip = new Trip(l, version);
|
||||
this.consumers.forEach(c -> c.accept(trip));
|
||||
}
|
||||
}
|
||||
line = br.readLine();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to read from API", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an additional consumer.
|
||||
*
|
||||
* @param consumer New consumer.
|
||||
*/
|
||||
public void addConsumer(Consumer<Trip> consumer) {
|
||||
consumers.add(consumer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the reader.
|
||||
* This is done by signaliung cancel to the asyncronous task. If the task is not completed
|
||||
* within 1 second however it is cancelled hard.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
// Nothing to do if future is not yet started.
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Signal cancelling to gracefully stop future.
|
||||
cancelled = true;
|
||||
try {
|
||||
future.get(1, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException e) {
|
||||
throw new IllegalStateException("Failed to read from API", e);
|
||||
} catch (TimeoutException e) {
|
||||
// Task failed to finish within 1 second.
|
||||
future.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get input stream from given URL.
|
||||
*
|
||||
* @param url URL to read from.
|
||||
* @return Input Stream.
|
||||
* @throws IOException On errors.
|
||||
*/
|
||||
private static InputStream getInputStream(URL url) throws IOException {
|
||||
return url.openStream();
|
||||
}
|
||||
}
|
14
src/main/javadoc/overview.html
Normal file
14
src/main/javadoc/overview.html
Normal 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>
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
@ -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.
|
||||
|
@ -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");
|
||||
|
@ -0,0 +1,280 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package de.stklcode.pubtrans.ura.reader;
|
||||
|
||||
import de.stklcode.pubtrans.ura.UraClientTest;
|
||||
import de.stklcode.pubtrans.ura.model.Trip;
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.agent.ByteBuddyAgent;
|
||||
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static net.bytebuddy.implementation.MethodDelegation.to;
|
||||
import static net.bytebuddy.matcher.ElementMatchers.named;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.junit.Assume.assumeThat;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
/**
|
||||
* Unit test for the asynchronous URA Trip reader.
|
||||
*
|
||||
* @author Stefan Kalscheuer
|
||||
*/
|
||||
public class AsyncUraTripReaderTest {
|
||||
private static final Queue<String> MOCK_LINES = new ArrayDeque<>();
|
||||
private static PipedOutputStream mockOutputStream = new PipedOutputStream();
|
||||
|
||||
@BeforeAll
|
||||
public static void initByteBuddy() {
|
||||
// Install ByteBuddy Agent.
|
||||
ByteBuddyAgent.install();
|
||||
|
||||
// Mock the URL.openStream() call.
|
||||
new ByteBuddy().redefine(AsyncUraTripReader.class)
|
||||
.method(named("getInputStream"))
|
||||
.intercept(to(AsyncUraTripReaderTest.class))
|
||||
.make()
|
||||
.load(AsyncUraTripReader.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the reader.
|
||||
* This test contains some timing values, which is not very nice for debugging, but should do the job here
|
||||
* as 1s is most likely more than enough time on any reasonable build system to parse some simple JSON lines.
|
||||
*
|
||||
* @throws InterruptedException Thread interrupted.
|
||||
* @throws IOException Error reading or writing mocked data.
|
||||
*/
|
||||
@Test
|
||||
public void readerTest() throws InterruptedException, IOException {
|
||||
// Callback counter for some unhandy async mockery.
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
// The list which will be populated by the callback.
|
||||
Deque<Trip> trips = new ConcurrentLinkedDeque<>();
|
||||
|
||||
// Start with V1 data and read file to mock list.
|
||||
readLinesToMock(UraClientTest.class.getResource("stream_V1_stops_all.txt"));
|
||||
|
||||
AsyncUraTripReader tr = new AsyncUraTripReader(
|
||||
UraClientTest.class.getResource("stream_V1_stops_all.txt"),
|
||||
Collections.singletonList(
|
||||
trip -> {
|
||||
trips.add(trip);
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Open the rewader.
|
||||
tr.open();
|
||||
// Read for 1 second.
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
assumeThat("Trips should empty after 1s without reading", trips, is(empty()));
|
||||
|
||||
// Now write a single line to the stream pipe.
|
||||
assumeTrue("First line (version info) should be written", writeNextLine());
|
||||
assumeTrue("Second line (first record) should be written", writeNextLine());
|
||||
|
||||
// Wait up to 1s for the callback to be triggered.
|
||||
int i = 10;
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
assertThat("Unexpected number of trips after first entry", trips.size(), is(1));
|
||||
|
||||
// Flush all remaining lines.
|
||||
while (writeNextLine()) {
|
||||
TimeUnit.MILLISECONDS.sleep(10);
|
||||
}
|
||||
|
||||
i = 10;
|
||||
counter.set(0);
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
tr.close();
|
||||
|
||||
assertThat("Unexpected number of trips after all lines have been flushed", trips.size(), is(7));
|
||||
|
||||
// Clear trip list and repeat with V2 data.
|
||||
trips.clear();
|
||||
readLinesToMock(UraClientTest.class.getResource("stream_V2_stops_all.txt"));
|
||||
tr = new AsyncUraTripReader(
|
||||
UraClientTest.class.getResource("stream_V2_stops_all.txt"),
|
||||
Collections.singletonList(trips::add)
|
||||
);
|
||||
|
||||
// Open the reader.
|
||||
tr.open();
|
||||
// Read for 1 second.
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
assumeThat("Trips should empty after 1s without reading", trips, is(empty()));
|
||||
|
||||
assumeTrue("First line of v2 (version info) should be written", writeNextLine());
|
||||
assumeTrue("Second line of v2 (first record) should be written", writeNextLine());
|
||||
|
||||
i = 10;
|
||||
counter.set(0);
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
assertThat("Unexpected number of v2 trips after first entry", trips.size(), is(1));
|
||||
|
||||
// Add a second consumer that pushes to another list.
|
||||
Deque<Trip> trips2 = new ConcurrentLinkedDeque<>();
|
||||
tr.addConsumer(trips2::add);
|
||||
|
||||
// Flush all remaining lines.
|
||||
while (writeNextLine()) {
|
||||
TimeUnit.MILLISECONDS.sleep(10);
|
||||
}
|
||||
|
||||
i = 10;
|
||||
counter.set(0);
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
tr.close();
|
||||
|
||||
assertThat("Unexpected number of v2 trips after all lines have been flushed", trips.size(), is(7));
|
||||
assertThat("Unexpected number of v2 trips in list 2 after all lines have been flushed", trips2.size(), is(6));
|
||||
assertThat("Same object should have been pushed to both lists", trips.containsAll(trips2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test behavior if the stream is closed.
|
||||
*
|
||||
* @throws InterruptedException Thread interrupted.
|
||||
* @throws IOException Error reading or writing mocked data.
|
||||
*/
|
||||
@Test
|
||||
public void streamClosedTest() throws InterruptedException, IOException {
|
||||
// Callback counter for some unhandy async mockery.
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
// The list which will be populated by the callback.
|
||||
Deque<Trip> trips = new ConcurrentLinkedDeque<>();
|
||||
|
||||
// Start with V1 data and read file to mock list.
|
||||
readLinesToMock(UraClientTest.class.getResource("stream_V1_stops_all.txt"));
|
||||
|
||||
AsyncUraTripReader tr = new AsyncUraTripReader(
|
||||
UraClientTest.class.getResource("stream_V1_stops_all.txt"),
|
||||
Collections.singletonList(
|
||||
trip -> {
|
||||
trips.add(trip);
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Open the reader.
|
||||
tr.open();
|
||||
|
||||
// Read for 100ms.
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
assumeThat("Trips should empty after 100ms without reading", trips, is(empty()));
|
||||
|
||||
// Now write a single line to the stream pipe.
|
||||
assumeTrue("First line (version info) should be written", writeNextLine());
|
||||
assumeTrue("Second line (first record) should be written", writeNextLine());
|
||||
|
||||
// Wait up to 1s for the callback to be triggered.
|
||||
int i = 10;
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
assumeThat("Unexpected number of trips after first entry", trips.size(), is(1));
|
||||
|
||||
// Close the stream.
|
||||
mockOutputStream.close();
|
||||
|
||||
i = 10;
|
||||
counter.set(0);
|
||||
while (counter.get() < 1 && i-- > 0) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
tr.close();
|
||||
|
||||
assertThat("Unexpected number of trips after all lines have been flushed", trips.size(), is(1));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an input file to the line buffer.
|
||||
*
|
||||
* @param url Input URL.
|
||||
* @throws IOException Error reading the data.
|
||||
*/
|
||||
private static void readLinesToMock(URL url) throws IOException {
|
||||
try (InputStream is = url.openStream();
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
|
||||
String line = br.readLine();
|
||||
while (line != null) {
|
||||
MOCK_LINES.add(line);
|
||||
line = br.readLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write next line from the buffer to the mocked stream pipe.
|
||||
*
|
||||
* @return {@code true} if a line has been written.
|
||||
* @throws IOException Errir writing the data.
|
||||
*/
|
||||
private static boolean writeNextLine() throws IOException {
|
||||
String line = MOCK_LINES.poll();
|
||||
if (line != null) {
|
||||
line += "\n";
|
||||
mockOutputStream.write(line.getBytes(StandardCharsets.UTF_8));
|
||||
mockOutputStream.flush();
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to mock the static {@code AsyncUraTripReader#getInputStream(URL)} method.
|
||||
*
|
||||
* @param url URL to read from.
|
||||
* @return Input Stream.
|
||||
* @throws IOException On errors.
|
||||
*/
|
||||
public static InputStream getInputStream(URL url) throws IOException {
|
||||
mockOutputStream = new PipedOutputStream();
|
||||
return new PipedInputStream(mockOutputStream);
|
||||
}
|
||||
}
|
@ -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]
|
||||
|
@ -0,0 +1,8 @@
|
||||
[4,"1.0",1542370828725]
|
||||
[1,"Campus Melaten","100629","",0,50.78247,6.05053,4,"764","3B","2","Ponttor-Hbf.-Schanz","Ponttor-Hbf.-Schanz","327001",16000304013001,1542375720000]
|
||||
[1,"Eckenerstraße","100308","",0,50.7539658,6.1541161,15,"65","65","2","Elisenbrunnen","Elisenbrunnen","301001",16000428004001,1542372660000]
|
||||
[1,"Talbot","100111","",0,50.7845802,6.1093236,51,"1","1","2","Süsterau-Uniklinik","Süsterau-Uniklinik","305001",16000351007001,1542372900000]
|
||||
[1,"Herz. Schulzentrum","210541","",0,50.8642111,6.1053944,1,"831","HZ1","1","Hofstadt","Hofstadt","737001",16000212021001,1542375000000]
|
||||
[1,"Weisweiler Ziegelei","213237","",0,50.8254738,6.325058,14,"96","96","1","Langerwehe Schulzentr.","Langerwehe Schulzentr.",null,16000417012001,1542373320000]
|
||||
[1,"Pongs","100233","",0,50.7725688,6.1285466,24,"7","7","2","Eilendorf Am Tunnel","Eilendorf Am Tunnel","540001",16000444014001,1542377460000]
|
||||
[1,"Velau","215624","",0,50.7893811,6.2223038,17,"8","8","2","Stolberg Mühlener Bf.","Stolberg Mühlener Bf.","568001",16000319014001,1542374400000]
|
@ -0,0 +1,8 @@
|
||||
[4,"2.0",1542370788379]
|
||||
[1,"Campus Melaten","100629","",0,50.78247,6.05053,4,"764","3B","2","Ponttor-Hbf.-Schanz","Ponttor-Hbf.-Schanz","327001","16000304013001",1542375720000]
|
||||
[1,"Eckenerstraße","100308","",0,50.7539658,6.1541161,15,"65","65","2","Elisenbrunnen","Elisenbrunnen","301001","16000428004001",1542372660000]
|
||||
[1,"Talbot","100111","",0,50.7845802,6.1093236,51,"1","1","2","Süsterau-Uniklinik","Süsterau-Uniklinik","305001","16000351007001",1542372900000]
|
||||
[1,"Herz. Schulzentrum","210541","",0,50.8642111,6.1053944,1,"831","HZ1","1","Hofstadt","Hofstadt","737001","16000212021001",1542375000000]
|
||||
[1,"Weisweiler Ziegelei","213237","",0,50.8254738,6.325058,14,"96","96","1","Langerwehe Schulzentr.","Langerwehe Schulzentr.",null,"16000417012001",1542373320000]
|
||||
[1,"Pongs","100233","",0,50.7725688,6.1285466,24,"7","7","2","Eilendorf Am Tunnel","Eilendorf Am Tunnel","540001","16000444014001",1542377460000]
|
||||
[1,"Velau","215624","",0,50.7893811,6.2223038,17,"8","8","2","Stolberg Mühlener Bf.","Stolberg Mühlener Bf.","568001","16000319014001",1542374400000]
|
Reference in New Issue
Block a user