Search in sources :

Example 96 with TypeToken

use of com.google.gson.reflect.TypeToken in project Nukkit by Nukkit.

the class Config method parseContent.

private void parseContent(String content) {
    switch(this.type) {
        case Config.PROPERTIES:
            this.parseProperties(content);
            break;
        case Config.JSON:
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
            break;
        case Config.YAML:
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
            break;
        // case Config.SERIALIZED
        case Config.ENUM:
            this.parseList(content);
            break;
        default:
            this.correct = false;
    }
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) TypeToken(com.google.gson.reflect.TypeToken) Gson(com.google.gson.Gson) DumperOptions(org.yaml.snakeyaml.DumperOptions) Yaml(org.yaml.snakeyaml.Yaml)

Example 97 with TypeToken

use of com.google.gson.reflect.TypeToken in project DragonProxy by DragonetMC.

the class LoginChainDecoder method decode.

/**
 * decode the chain data in Login packet for MCPE Note: the credit of this
 * function goes to Nukkit development team
 */
public void decode() {
    Map<String, List<String>> map = gson.fromJson(new String(this.chainJWT, StandardCharsets.UTF_8), new TypeToken<Map<String, List<String>>>() {
    }.getType());
    if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty())
        return;
    List<DecodedJWT> chainJWTs = new ArrayList<>();
    // Add the JWT tokens to a chain
    for (String token : map.get("chain")) chainJWTs.add(JWT.decode(token));
    DecodedJWT clientJWT = null;
    if (this.clientDataJWT != null) {
        clientJWT = JWT.decode(new String(this.clientDataJWT, StandardCharsets.UTF_8));
        chainJWTs.add(clientJWT);
    }
    // first step, check if the public provided key can decode the received chain
    try {
        ECPublicKey prevPublicKey = null;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            String encodedPublicKey = null;
            ECPublicKey publicKey = null;
            if (payload.has("identityPublicKey")) {
                encodedPublicKey = payload.get("identityPublicKey").getAsString();
                publicKey = (ECPublicKey) EC_KEY_FACTORY.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedPublicKey)));
            }
            // Trust the root ca public key and use it to verify the chain
            if (ENCODED_ROOT_CA_KEY.equals(encodedPublicKey) && payload.has("certificateAuthority") && payload.get("certificateAuthority").getAsBoolean()) {
                prevPublicKey = publicKey;
                continue;
            }
            // This will happen if the root ca key we have does not match the one presented by the client chain
            if (prevPublicKey == null)
                throw new NullPointerException("No trusted public key found in chain, is the client logged in or cracked");
            // Throws a SignatureVerificationException if the verification failed
            Algorithm.ECDSA384(prevPublicKey, null).verify(jwt);
            // Verification was successful since no exception was thrown
            // Set the previous public key to this one so that it can be used
            // to verify the next JWT token in the chain
            prevPublicKey = publicKey;
        }
        // The for loop successfully verified all JWT tokens with no exceptions thrown
        this.loginVerified = true;
        Logger.getLogger(this.getClass().getSimpleName()).info("The LoginPacket has been successfully verified for integrity");
    } catch (Exception e) {
        this.loginVerified = false;
        Logger.getLogger(this.getClass().getSimpleName()).info("Failed to verify the integrity of the LoginPacket");
        e.printStackTrace();
    }
    // This is in its own for loop due to the possibility that the chain verification failed
    for (DecodedJWT jwt : chainJWTs) {
        JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
        // Get the information we care about - The UUID and display name
        if (payload.has("extraData") && !payload.has("certificateAuthority")) {
            extraData = payload.get("extraData").getAsJsonObject();
            if (extraData.has("displayName"))
                this.username = extraData.get("displayName").getAsString();
            if (extraData.has("identity"))
                this.clientUniqueId = UUID.fromString(extraData.get("identity").getAsString());
            break;
        }
    }
    // debug purpose
    if (log_profiles_files) {
        try {
            BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".rawChainJTW"));
            writer1.write(getChainJWT());
            writer1.close();
            BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + ".rawClientDataJTW"));
            writer.write(getClientDataJWT());
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // debug purpose
        int index = 0;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + "_" + index + ".decodedChain"));
                writer.write(payload.toString());
                writer.close();
                index++;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    // client data & skin
    if (clientJWT != null) {
        this.clientData = gson.fromJson(new String(Base64.getDecoder().decode(clientJWT.getPayload()), StandardCharsets.UTF_8), JsonObject.class);
        // debug purpose
        if (log_profiles_files) {
            try {
                BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".decodedData"));
                writer1.write(this.clientData.toString());
                writer1.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if (this.clientData.has("ClientRandomId"))
            this.clientId = this.clientData.get("ClientRandomId").getAsLong();
        if (this.clientData.has("SkinData") && this.clientData.has("SkinId")) {
            this.skin = new Skin(this.clientData.get("SkinData").getAsString(), this.clientData.get("SkinId").getAsString());
            if (this.clientData.has("CapeData"))
                this.skin.setCape(this.skin.new Cape(Base64.getDecoder().decode(this.clientData.get("CapeData").getAsString())));
        } else
            this.skin = Skin.DEFAULT_SKIN_STEVE;
        if (this.clientData.has("SkinGeometryName"))
            this.skinGeometryName = this.clientData.get("SkinGeometryName").getAsString();
        if (this.clientData.has("SkinGeometry"))
            this.skinGeometry = Base64.getDecoder().decode(this.clientData.get("SkinGeometry").getAsString());
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) BufferedWriter(java.io.BufferedWriter) ECPublicKey(java.security.interfaces.ECPublicKey) TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) List(java.util.List) Skin(org.dragonet.common.data.entity.Skin) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 98 with TypeToken

use of com.google.gson.reflect.TypeToken in project isItMayYet by CMPUT301W18T03.

the class JsonHandler method loadUserTasks.

/**
 * Loads a user task from gson to an ArrayList type.
 * @return object of type ArrayList
 */
public ArrayList<Task> loadUserTasks() {
    FileReader file = null;
    try {
        file = new FileReader(userTask);
    } catch (java.io.FileNotFoundException e) {
        Log.e("IOError", e.getMessage());
    }
    BufferedReader reader = new BufferedReader(file);
    ArrayList<Task> t = gson.fromJson(reader, new TypeToken<ArrayList<Task>>() {
    }.getType());
    return t;
}
Also used : TypeToken(com.google.gson.reflect.TypeToken) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 99 with TypeToken

use of com.google.gson.reflect.TypeToken in project isItMayYet by CMPUT301W18T03.

the class JsonHandler method loadTaskQueue.

/**
 * Load task from Queue
 * @return ArrayList of tasks.
 */
public ArrayList<Task> loadTaskQueue() {
    FileReader file = null;
    try {
        file = new FileReader(taskQueue);
    } catch (java.io.FileNotFoundException e) {
        Log.e("IOError", e.getMessage());
    }
    BufferedReader reader = new BufferedReader(file);
    ArrayList<Task> t = gson.fromJson(reader, new TypeToken<ArrayList<Task>>() {
    }.getType());
    return t;
}
Also used : TypeToken(com.google.gson.reflect.TypeToken) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 100 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class TestAppWithCube method query.

private Collection<TimeSeries> query(URL serviceUrl, CubeQuery query) throws IOException {
    URL url = new URL(serviceUrl, "query");
    HttpRequest request = HttpRequest.post(url).withBody(GSON.toJson(query)).build();
    HttpResponse response = HttpRequests.execute(request);
    Assert.assertEquals(200, response.getResponseCode());
    return GSON.fromJson(response.getResponseBodyAsString(), new TypeToken<Collection<TimeSeries>>() {
    }.getType());
}
Also used : HttpRequest(co.cask.common.http.HttpRequest) TimeSeries(co.cask.cdap.api.dataset.lib.cube.TimeSeries) TypeToken(com.google.gson.reflect.TypeToken) HttpResponse(co.cask.common.http.HttpResponse) URL(java.net.URL)

Aggregations

TypeToken (com.google.gson.reflect.TypeToken)418 Gson (com.google.gson.Gson)178 Test (org.junit.Test)99 IOException (java.io.IOException)83 Map (java.util.Map)71 List (java.util.List)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 ArrayList (java.util.ArrayList)53 HashMap (java.util.HashMap)52 GsonBuilder (com.google.gson.GsonBuilder)45 File (java.io.File)34 Notebook (org.apache.zeppelin.notebook.Notebook)32 Type (java.lang.reflect.Type)31 FileNotFoundException (java.io.FileNotFoundException)29 Paragraph (org.apache.zeppelin.notebook.Paragraph)27 RestResponse (com.google.gerrit.acceptance.RestResponse)24 JsonElement (com.google.gson.JsonElement)24 JsonObject (com.google.gson.JsonObject)24 OutputStreamWriter (java.io.OutputStreamWriter)22 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)21