Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Jackson library #295

Merged
merged 4 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .pubnub.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ sdks:
license-url: https://github.com/google/gson/blob/gson-parent-2.9.0/LICENSE
is-required: Required
-
name: jackson-databind
min-version: 2.14.2
location: https://repo.maven.apache.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.14.2/jackson-databind-2.14.2.jar
license: Apache License, Version 2.0
license-url: hhttps://github.com/FasterXML/jackson-databind/blob/jackson-databind-2.14.2/README.md
name: cbor
min-version: "0.9"
location: https://repo.maven.apache.org/maven2/co/nstant/in/cbor/0.9
license: The Apache Software License, Version 2.0
license-url: https://www.apache.org/licenses/LICENSE-2.0.txt
is-required: Required
-
name: json
Expand Down
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ dependencies {
implementation group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.6.2'

// cbor
implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:2.14.2'
implementation 'co.nstant.in:cbor:0.9'


implementation 'org.jetbrains:annotations:23.0.0'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ protected void validateParams() throws PubNubException {

@Override
protected Call<List<Object>> doWork(Map<String, String> baseParams) throws PubNubException {
String stringifiedMessage = mapper.toJsonUsinJackson(new FileUploadNotification(this.message, pnFile));
String stringifiedMessage = mapper.toJson(new FileUploadNotification(this.message, pnFile));
String messageAsString;
CryptoModule cryptoModule = getPubnub().getCryptoModule();
if (cryptoModule != null) {
Expand All @@ -99,7 +99,7 @@ protected Call<List<Object>> doWork(Map<String, String> baseParams) throws PubNu
final HashMap<String, String> params = new HashMap<>(baseParams);

if (meta != null) {
String stringifiedMeta = mapper.toJsonUsinJackson(meta);
String stringifiedMeta = mapper.toJson(meta);
stringifiedMeta = PubNubUtil.urlEncode(stringifiedMeta);
params.put("meta", stringifiedMeta);
}
Expand Down
16 changes: 0 additions & 16 deletions src/main/java/com/pubnub/api/managers/MapperManager.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.pubnub.api.managers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
Expand Down Expand Up @@ -38,8 +36,6 @@ public class MapperManager {
@Getter
private final Converter.Factory converterFactory;

private final ObjectMapper jacksonObjectMapper = new ObjectMapper();

public MapperManager() {
TypeAdapter<Boolean> booleanAsIntAdapter = getBooleanTypeAdapter();

Expand Down Expand Up @@ -160,18 +156,6 @@ public String toJson(Object input) throws PubNubException {
}
}

public String toJsonUsinJackson(Object input) throws PubNubException {
try {
return this.jacksonObjectMapper.writeValueAsString(input);
} catch (JsonProcessingException e) {
throw PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_JSON_ERROR)
.errormsg(e.getMessage())
.cause(e)
.build();
}
}

@NotNull
private TypeAdapter<Boolean> getBooleanTypeAdapter() {
return new TypeAdapter<Boolean>() {
Expand Down

This file was deleted.

110 changes: 110 additions & 0 deletions src/main/java/com/pubnub/api/managers/token_manager/TokenParser.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.pubnub.api.managers.token_manager

import co.nstant.`in`.cbor.CborDecoder
import co.nstant.`in`.cbor.model.ByteString
import co.nstant.`in`.cbor.model.NegativeInteger
import co.nstant.`in`.cbor.model.UnsignedInteger
import com.pubnub.api.PubNubException
import com.pubnub.api.builder.PubNubErrorBuilder
import com.pubnub.api.models.consumer.access_manager.v3.PNToken
import com.pubnub.api.vendor.Base64
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import kotlin.collections.Map
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
import co.nstant.`in`.cbor.model.Map as CborMap

internal class TokenParser {

private fun getException(message: String) = PubNubException(
message, PubNubErrorBuilder.PNERROBJ_INVALID_ACCESS_TOKEN, null, null, 0, null, null
)

@Throws(PubNubException::class)
fun unwrapToken(token: String): PNToken {
val byteArray = Base64.decode(token.toByteArray(StandardCharsets.UTF_8), Base64.URL_SAFE)
val firstElement = CborDecoder(byteArray.inputStream()).decode().firstOrNull() ?: throw getException("Empty token")

val firstLevelMap = (firstElement as? CborMap)?.toJvmMap() ?: throw getException("First element is not a map")
val version = firstLevelMap[VERSION_KEY]?.toString()?.toInt() ?: throw getException("Couldn't parse version")
val timestamp = firstLevelMap[TIMESTAMP_KEY]?.toString()?.toLong() ?: throw getException("Couldn't parse timestamp")
val ttl = firstLevelMap[TTL_KEY]?.toString()?.toLong() ?: throw getException("Couldn't parse ttl")
val resourcesValue = firstLevelMap[RESOURCES_KEY] as? Map<*, *> ?: throw getException("Resources are not present or are not map")
val patternsValue = firstLevelMap[PATTERNS_KEY] as? Map<*, *> ?: throw getException("Patterns are not present or are not map")

return try {
PNToken.of(
version,
timestamp,
ttl,
resourcesValue.toPNTokenResources(),
patternsValue.toPNTokenResources(),
firstLevelMap[AUTHORIZED_UUID_KEY]?.toString(),
firstLevelMap[META_KEY],
)
} catch (e: Exception) {
if (e is PubNubException) throw e
throw getException("Couldn't parse token: ${e.message}")
}
}

private fun CborMap.toJvmMap(depth: Int = 0): MutableMap<String, Any> {
if (depth > 3) {
throw getException("Token is too deep")
}
val result = mutableMapOf<String, Any>()
for (key in this.keys) {
val value = this.get(key)
val keyString = when (key) {
is ByteString -> key.bytes.toString(StandardCharsets.UTF_8)
else -> key.toString()
}

when (value) {
is CborMap -> result[keyString] = value.toJvmMap(depth + 1)
is ByteString -> result[keyString] = value.bytes
is List<*> -> result[keyString] = value.map { it.toString() }
is UnsignedInteger -> result[keyString] = value.value
is NegativeInteger -> result[keyString] = value.value
else -> result[keyString] = value.toString()
}
}
return result
}

private fun Map<*, *>.toMapOfStringToInt(): Map<String, Int> {
return mapNotNull { (k, v) ->
when (v) {
is BigInteger -> k.toString() to v.toInt()
else -> v.toString().toIntOrNull()?.let { k.toString() to it }
}
}.toMap()
}

private fun Map<*, *>.toPNTokenResources(): PNToken.PNTokenResources {
val channels = (this[CHANNELS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()
val groups = (this[GROUPS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()
val uuids = (this[UUIDS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()

return PNToken.PNTokenResources.of(
channels.mapValues { (_, v) -> PNToken.PNResourcePermissions.of(v) },
groups.mapValues { (_, v) -> PNToken.PNResourcePermissions.of(v) },
uuids.mapValues { (_, v) -> PNToken.PNResourcePermissions.of(v) }
)
}

companion object {
private const val VERSION_KEY = "v"
private const val TIMESTAMP_KEY = "t"
private const val TTL_KEY = "ttl"
private const val AUTHORIZED_UUID_KEY = "uuid"
private const val RESOURCES_KEY = "res"
private const val PATTERNS_KEY = "pat"
private const val META_KEY = "meta"
private const val CHANNELS_KEY = "chan"
private const val GROUPS_KEY = "grp"
private const val UUIDS_KEY = "uuid"
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
package com.pubnub.api.models.consumer.access_manager.v3;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.pubnub.api.models.TokenBitmask;
import lombok.Data;
import lombok.NonNull;

import java.util.Map;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class PNToken {
private final int version;
private final long timestamp;
Expand All @@ -22,20 +18,18 @@ public class PNToken {
@NonNull
private final PNTokenResources patterns;

@JsonCreator
public static PNToken of(
@JsonProperty("v") final int v,
@JsonProperty("t") final long t,
@JsonProperty("ttl") final long ttl,
@JsonProperty("res") final PNTokenResources res,
@JsonProperty("pat") final PNTokenResources pat,
@JsonProperty("uuid") final String uuid,
@JsonProperty("meta") final Object meta) {
final int v,
final long t,
final long ttl,
final PNTokenResources res,
final PNTokenResources pat,
final String uuid,
final Object meta) {
return new PNToken(v, t, ttl, uuid, meta, res, pat);
}

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class PNTokenResources {
@NonNull
private final Map<String, PNResourcePermissions> channels;
Expand All @@ -44,10 +38,9 @@ public static class PNTokenResources {
@NonNull
private final Map<String, PNResourcePermissions> uuids;

@JsonCreator
public static PNTokenResources of(@JsonProperty("chan") final Map<String, PNResourcePermissions> chan,
@JsonProperty("grp") final Map<String, PNResourcePermissions> grp,
@JsonProperty("uuid") final Map<String, PNResourcePermissions> uuid) {
public static PNTokenResources of(final Map<String, PNResourcePermissions> chan,
final Map<String, PNResourcePermissions> grp,
final Map<String, PNResourcePermissions> uuid) {
return new PNTokenResources(chan, grp, uuid);
}

Expand All @@ -63,7 +56,6 @@ public static class PNResourcePermissions {
private final boolean update;
private final boolean join;

@JsonCreator
public static PNResourcePermissions of(int grant) {
return new PNResourcePermissions(
(grant & TokenBitmask.READ) != 0,
Expand Down
Loading