Skip to content

Commit

Permalink
Merge pull request #18 from maxmielchen/master
Browse files Browse the repository at this point in the history
Update for 1.3.2
  • Loading branch information
maxmielchen authored Mar 10, 2023
2 parents 4e74692 + 2ee5e67 commit c28bcb4
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 145 deletions.
67 changes: 33 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# untis4j - a java API for webuntis

<p align="center">
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/untisapi/untis4j/maven_build.yml?label=Maven%20Build">
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/untisapi/untis4j/maven_publish.yml?label=Maven%20Publish">
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/untisapi/untis4j/maven_build.yml?label=Github%20Build">
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/untisapi/untis4j/maven_publish.yml?label=Github%20Publish">
<img alt="Jitpack Deploy Status" src="https://img.shields.io/github/actions/workflow/status/untisapi/untis4j/maven_publish.yml?label=Jitpack%20Deploy">
<img alt="GitHub all releases" src="https://img.shields.io/github/downloads/untisapi/untis4j/total?label=Downloads">
</p>

Expand All @@ -23,46 +24,44 @@ you can easily implement the method yourself with the `Session.getCustomData(...

### Maven

Add the GitHub repository to your build file
POM
```XML
<repository>
<id>github</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/untisapi/untis4j</url>
</repository>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

<dependencies>
<dependency>
<groupId>com.github.untisapi</groupId>
<artifactId>untis4j</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
```

Add the dependency
```XML
<dependency>
<groupId>org.bytedream</groupId>
<artifactId>untis4j</artifactId>
<version>${version}</version>
</dependency>
```
### Gradle

### Groovy

Add the GitHub repository to your build file
Groovy DSL
```groovy
maven { url 'https://maven.pkg.github.com/untisapi/untis4j' }
```

Add the dependency
```groovy
implementation 'org.bytedream:untis4j:${version}'
```

### Kotlin

Add the GitHub repository to your build file
```kotlin
maven { url='https://maven.pkg.github.com/untisapi/untis4j' }
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.untisapi:RELEASE'
}
```

Add the dependency
Kotlin DSL
```kotlin
implementation ("org.bytedream:untis4j:${version}")
repositories {
maven { url='https://jitpack.io' }
}
dependencies {
implementation ("com.github.untisapi:RELEASE")
}
```

# Examples
Expand Down
9 changes: 7 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
<version>1.3.1</version>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
</properties>

<dependencies>
Expand All @@ -19,6 +19,11 @@
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.5</version>
</dependency>
</dependencies>

<distributionManagement>
Expand Down
9 changes: 0 additions & 9 deletions src/main/java/org/bytedream/untis4j/CacheManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,6 @@ public <T extends BaseResponse> T getOrRequest(UntisUtils.Method method, Request
public <T extends BaseResponse> T getOrRequest(UntisUtils.Method method, RequestManager requestManager, Map<String, ?> params, ResponseConsumer<T> action) {
int keyHashCode = mapCode(method, params);

Function<Integer, BaseResponse> function = (objects) -> {
try {
return action.getResponse(requestManager.POST(method.getMethod(), params));
} catch (IOException e) {
return null;
}
};

BaseResponse response;
if ((response = cachedInformation.get(keyHashCode)) == null) {
try {
Expand Down Expand Up @@ -103,5 +95,4 @@ public void update(UntisUtils.Method method, RequestManager requestManager, Map<
private int mapCode(UntisUtils.Method method, Map<String, ?> params) {
return Arrays.toString(new Object[]{method, params}).hashCode();
}

}
125 changes: 70 additions & 55 deletions src/main/java/org/bytedream/untis4j/RequestManager.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.bytedream.untis4j;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.json.JSONException;
import org.json.JSONObject;

Expand All @@ -10,6 +12,7 @@
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -25,6 +28,7 @@ public class RequestManager {
private final Infos infos;
private final String url;
private boolean loggedIn = true;
private final LoadingCache<String, Response> requests = Caffeine.newBuilder().maximumSize(1_000).expireAfterWrite(Duration.ofMinutes(10)).refreshAfterWrite(Duration.ofMinutes(1)).build(this::POST);

/**
* Initialize the {@link RequestManager} class
Expand Down Expand Up @@ -105,82 +109,93 @@ public static Infos generateUserInfosAndLogin(String username, String password,
/**
* Sends a POST request to the server
*
* @param method params you want to send with the request
* @param method the POST method
* @param params params you want to send with the request
* @return {@link Response} with all information about the response
* @throws IOException if an IO Exception occurs
* @see RequestManager#POST(String, Map)
* @since 1.0
*/
public Response POST(String method) throws IOException {
return this.POST(method, new HashMap<>());
public Response POST(String method, Map<String, ?> params) throws IOException {

if (loggedIn || method.equals(UntisUtils.Method.LOGIN.getMethod())) {
Response response = POST(UntisUtils.processParams(method, params));
if (method.equals(UntisUtils.Method.LOGOUT.getMethod()) && loggedIn && response != null) {
loggedIn = false;
}
return response;
} else {
throw new LoginException("Not logged in");
}
}

/**
* Sends a POST request to the server
* Sends a POST request to the server, but only if it is not in the cache
*
* @param method the POST method
* @param params params you want to send with the request
* @return {@link Response} with all information about the response
* @throws IOException if an IO Exception occurs
* @since 1.0
*/
public Response POST(String method, Map<String, ?> params) throws IOException {

if (loggedIn || method.equals(UntisUtils.Method.LOGIN.getMethod())) {
boolean error;
URL url = new URL(this.url);
String requestBody = UntisUtils.processParams(method, params);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", infos.getUserAgent());
connection.setRequestProperty("Content-Type", "application/json");

connection.setRequestProperty("Cookie", "JSESSIONID=" + infos.getSessionId() + "; schoolname=" + infos.getSchoolName());

DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestBody);

BufferedReader input;

try {
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
error = false;
} catch (NullPointerException e) {
error = true;
input = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}

StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
stringBuilder.append(line);
}

JSONObject jsonObject;

try {
jsonObject = new JSONObject(stringBuilder.toString());

if (jsonObject.has("error")) {
JSONObject errorObject = jsonObject.getJSONObject("error");
throw new ConnectException("The response contains an error (" + errorObject.getInt("errorObject") + "): " + errorObject.getString("message"));
}
} catch (JSONException e) {
throw new ConnectException("An unexpected exception occurred: " + stringBuilder);
}
public Response CachedPOST(String method, Map<String, ?> params) throws IOException {

if (method.equals(UntisUtils.Method.LOGOUT.getMethod()) && loggedIn && !error) {
if (loggedIn) {
Response response = requests.get(UntisUtils.processParams(method, params));
if (method.equals(UntisUtils.Method.LOGOUT.getMethod()) && loggedIn && response != null) {
loggedIn = false;
}

return new Response(connection.getResponseCode(), jsonObject);
return response;
} else {
throw new LoginException("Not logged in");
}
}

/**
* Sends a POST request to the server
*
* @return {@link Response} with all information about the response
* @throws IOException if an IO Exception occurs
* @since 1.0
*/
private Response POST(String request) throws IOException
{
boolean error;
URL url = new URL(this.url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", infos.getUserAgent());
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Cookie", "JSESSIONID=" + infos.getSessionId() + "; schoolname=" + infos.getSchoolName());
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(request);
BufferedReader input;
try {
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
error = false;
} catch (NullPointerException e) {
error = true;
input = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
stringBuilder.append(line);
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(stringBuilder.toString());

if (jsonObject.has("error")) {
JSONObject errorObject = jsonObject.getJSONObject("error");
throw new ConnectException("The response contains an error (" + errorObject.getInt("errorObject") + "): " + errorObject.getString("message"));
}
} catch (JSONException e) {
throw new ConnectException("An unexpected exception occurred: " + stringBuilder);
}
if (error) return null;
return new Response(connection.getResponseCode(), jsonObject);
}

/**
Expand Down
Loading

0 comments on commit c28bcb4

Please sign in to comment.