Example usage for com.google.gson JsonElement getAsInt

List of usage examples for com.google.gson JsonElement getAsInt

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsInt.

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:org.waveprotocol.wave.concurrencycontrol.proto.ResponseStatusProtoImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set; however these (obviously) will need to be set by other means
    // before accessing this object.
    invalidateAll();//from w w w  .  ja  v  a2s. c o  m

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("1")) {
        JsonElement elem = jsonObject.get("1");
        setStatus(ProtoEnums.valOf(elem.getAsInt(), ResponseCode.values()));
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("2")) {
        JsonElement elem = jsonObject.get("2");
        if (!elem.isJsonNull()) {
            setFailureReason(elem.getAsString());
        }
    }
}

From source file:org.waveprotocol.wave.concurrencycontrol.proto.SubmitDeltaResponseProtoImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set; however these (obviously) will need to be set by other means
    // before accessing this object.
    invalidateAll();/*from   ww  w .j av a2s.  com*/

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("1")) {
        JsonElement elem = jsonObject.get("1");
        {
            ResponseStatusProtoImpl payload = new ResponseStatusProtoImpl();
            GsonUtil.extractJsonObject(payload, elem, gson, raw);
            setStatus(payload);
        }
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("2")) {
        JsonElement elem = jsonObject.get("2");
        setOperationsApplied(elem.getAsInt());
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("3")) {
        JsonElement elem = jsonObject.get("3");
        if (!elem.isJsonNull()) {
            {
                ProtocolHashedVersionProtoImpl payload = new ProtocolHashedVersionProtoImpl();
                GsonUtil.extractJsonObject(payload, elem, gson, raw);
                setHashedVersionAfterApplication(payload);
            }
        }
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("4")) {
        JsonElement elem = jsonObject.get("4");
        if (!elem.isJsonNull()) {
            setTimestampAfterApplication(GsonUtil.fromJson(elem));
        }
    }
}

From source file:org.waveprotocol.wave.federation.proto.ProtocolAppliedWaveletDeltaProtoImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set; however these (obviously) will need to be set by other means
    // before accessing this object.
    invalidateAll();// w  ww .j  av  a  2  s.  com

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("1")) {
        JsonElement elem = jsonObject.get("1");
        {
            ProtocolSignedDeltaProtoImpl payload = new ProtocolSignedDeltaProtoImpl();
            GsonUtil.extractJsonObject(payload, elem, gson, raw);
            setSignedOriginalDelta(payload);
        }
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("2")) {
        JsonElement elem = jsonObject.get("2");
        if (!elem.isJsonNull()) {
            {
                ProtocolHashedVersionProtoImpl payload = new ProtocolHashedVersionProtoImpl();
                GsonUtil.extractJsonObject(payload, elem, gson, raw);
                setHashedVersionAppliedAt(payload);
            }
        }
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("3")) {
        JsonElement elem = jsonObject.get("3");
        setOperationsApplied(elem.getAsInt());
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("4")) {
        JsonElement elem = jsonObject.get("4");
        setApplicationTimestamp(elem.getAsDouble());
    }
}

From source file:org.waveprotocol.wave.federation.proto.ProtocolSignatureProtoImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set; however these (obviously) will need to be set by other means
    // before accessing this object.
    invalidateAll();/*from w w  w  .j  ava 2 s.c  o  m*/

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("1")) {
        JsonElement elem = jsonObject.get("1");
        setSignatureBytes(new Blob(elem.getAsString()));
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("2")) {
        JsonElement elem = jsonObject.get("2");
        setSignerId(new Blob(elem.getAsString()));
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("3")) {
        JsonElement elem = jsonObject.get("3");
        setSignatureAlgorithm(ProtoEnums.valOf(elem.getAsInt(), SignatureAlgorithm.values()));
    }
}

From source file:org.waveprotocol.wave.federation.proto.ProtocolSignerInfoProtoImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set; however these (obviously) will need to be set by other means
    // before accessing this object.
    invalidateAll();//from   w ww . ja v a2 s  .c  o  m

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("1")) {
        JsonElement elem = jsonObject.get("1");
        setHashAlgorithm(ProtoEnums.valOf(elem.getAsInt(), HashAlgorithm.values()));
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("2")) {
        JsonElement elem = jsonObject.get("2");
        setDomain(elem.getAsString());
    }

    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements. See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership. The ASF licenses this file
     * to you 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.
     */
    if (jsonObject.has("3")) {
        JsonElement elem = jsonObject.get("3");
        {
            JsonArray array = elem.getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                addCertificate(new Blob(array.get(i).getAsString()));
            }
        }
    }
}

From source file:org.wso2.iot.integration.jmeter.DeviceTypeManagementJMeterTestCase.java

License:Open Source License

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = {
        "DeviceTypeManagementTest" })
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\","
            + "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId
            + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic,
            accessToken);/*w ww .j  ava2 s  .c om*/
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);

    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not recieve mqtt messages ", 1, mqttMessages.size());

    String topicPub = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId
            + "/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient
            .get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK, response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(), count > 0);

}

From source file:org.zoxweb.server.util.GSONUtil.java

License:Apache License

public static QueryRequest fromQueryRequest(String json) {
    JsonElement je = new JsonParser().parse(json);
    QueryRequest ret = null;/*from  ww  w .ja  v a2  s  .  com*/

    if (je instanceof JsonObject) {
        ret = new QueryRequest();
        JsonObject jo = (JsonObject) je;
        ret.setCanonicalID(jo.get(MetaToken.CANONICAL_ID.getName()).getAsString());
        JsonElement batchSize = jo.get("batch_size");

        if (batchSize != null) {
            ret.setBatchSize(batchSize.getAsInt());
        }

        JsonArray jaFNs = (JsonArray) jo.get("field_names");

        if (jaFNs != null) {
            List<String> fieldNames = new ArrayList<String>();

            for (int i = 0; i < jaFNs.size(); i++) {
                fieldNames.add(jaFNs.get(i).getAsString());
            }

            ret.setFieldNames(fieldNames);
        }

        JsonArray jaQuery = (JsonArray) jo.get("query");
        if (jaQuery != null) {
            List<QueryMarker> qms = new ArrayList<QueryMarker>();
            for (int i = 0; i < jaQuery.size(); i++) {
                // get the query marker
                JsonObject joQM = (JsonObject) jaQuery.get(i);
                QueryMarker qm = null;

                JsonPrimitive lo = (JsonPrimitive) joQM.get(MetaToken.LOGICAL_OPERATOR.getName());

                if (lo != null) {
                    qm = Const.LogicalOperator.valueOf(lo.getAsString());
                } else {
                    Const.RelationalOperator ro = null;

                    JsonPrimitive jpRO = (JsonPrimitive) joQM.get(MetaToken.RELATIONAL_OPERATOR.getName());

                    if (jpRO != null) {
                        ro = Const.RelationalOperator.valueOf(jpRO.getAsString());
                    }

                    String name = null;
                    JsonElement value = null;

                    Set<Map.Entry<String, JsonElement>> allParams = joQM.entrySet();

                    for (Map.Entry<String, JsonElement> e : allParams) {
                        if (!e.getKey().equals(MetaToken.RELATIONAL_OPERATOR.getName())) {
                            name = e.getKey();
                            value = e.getValue();
                            break;
                        }
                    }

                    // try to guess the type
                    if (value.isJsonPrimitive()) {
                        JsonPrimitive jp = (JsonPrimitive) value;

                        if (jp.isString()) {
                            qm = new QueryMatchString(ro, jp.getAsString(), name);
                        } else if (jp.isNumber()) {
                            qm = new QueryMatchLong(ro, jp.getAsLong(), name);
                        }
                    }
                }

                if (qm != null) {
                    qms.add(qm);
                }
            }

            ret.setQuery(qms);
        }
    }

    return ret;
}

From source file:textrpg.builtin.actions.Edit.java

License:Apache License

@Override
public void run(JsonObject parameters) {
    System.out.println("Edit: " + parameters.toString());
    if (parameters.get("key") == null)
        return;/*from w w w  . ja v  a2 s. c o  m*/
    JsonArray root;
    if (!parameters.has("root"))
        root = new JsonArray();
    else
        root = parameters.get("root").getAsJsonArray();
    JsonElement out = Game.playerdata.get("variables");

    for (JsonElement j : root) {
        if (out.isJsonArray())
            out = out.getAsJsonArray().get(j.getAsInt());
        else if (out.isJsonObject())
            out = out.getAsJsonObject().get(j.getAsString());
    }

    if (out.isJsonArray())
        out.getAsJsonArray().set(parameters.get("key").getAsInt(), parameters.get("value"));
    else if (out.isJsonObject())
        out.getAsJsonObject().add(parameters.get("key").getAsString(), parameters.get("value"));
}

From source file:textrpg.builtin.actions.Get.java

License:Apache License

@Override
public JsonElement run(JsonObject params) {
    if (params.get("key") == null)
        return null;
    JsonArray root;//from w ww  .  jav  a 2 s  .  c om
    if (!params.has("root"))
        root = new JsonArray();
    else
        root = params.get("root").getAsJsonArray();
    JsonElement out = Game.playerdata.get("variables");

    for (JsonElement j : root) {
        if (out.isJsonArray())
            out = out.getAsJsonArray().get(j.getAsInt());
        else if (out.isJsonObject())
            out = out.getAsJsonObject().get(j.getAsString());
    }

    if (out.isJsonArray())
        return out.getAsJsonArray().get(params.get("key").getAsInt());
    else if (out.isJsonObject())
        return out.getAsJsonObject().get(params.get("key").getAsString());
    return null;
}

From source file:uk.co.thinkofdeath.mapviewer.assets.TextureBuilder.java

License:Apache License

public static void main(String[] args) throws IOException {
    long startTime = System.currentTimeMillis();
    final Gson gson = new Gson();
    final JsonParser parser = new JsonParser();
    File assetDir = new File("assets/block_images");
    File[] files = assetDir.listFiles(new FilenameFilter() {
        @Override//from  w w  w. j av  a2 s .  c  om
        public boolean accept(File dir, String name) {
            return name.endsWith(".png");
        }
    });
    BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
    HashMap<String, int[]> textures = new HashMap<String, int[]>();
    int pos = 0;

    for (File file : files) {
        BufferedImage sprite = ImageIO.read(file);

        if (sprite.getWidth() != 16 || sprite.getHeight() != 16) {
            JsonObject meta = parser.parse(new FileReader("assets/block_images/" + file.getName() + ".mcmeta"))
                    .getAsJsonObject();
            ArrayList<Integer> frames = new ArrayList<Integer>();
            JsonObject animation = meta.get("animation").getAsJsonObject();
            JsonElement frsEle = animation.get("frames");
            if (frsEle != null) {
                JsonArray frs = frsEle.getAsJsonArray();
                for (JsonElement ele : frs) {
                    frames.add(ele.getAsInt());
                }
            } else {
                for (int i = 0; i < sprite.getHeight() / sprite.getWidth(); i++) {
                    frames.add(i);
                }
            }
            int frameTime = animation.has("frametime") ? animation.get("frametime").getAsInt() : 1;
            int start = pos;
            for (int frame : frames) {
                for (int i = 0; i < frameTime; i++) {
                    int[] data = sprite.getRGB(0, 16 * frame, 16, 16, null, 0, 16);
                    image.setRGB((pos % 32) * 16, (pos / 32) * 16, 16, 16, data, 0, 16);
                    pos++;
                }
            }
            textures.put(file.getName().substring(0, file.getName().length() - 4),
                    new int[] { start, pos - 1 });
            continue;
        }

        int[] data = sprite.getRGB(0, 0, 16, 16, null, 0, 16);
        image.setRGB((pos % 32) * 16, (pos / 32) * 16, 16, 16, data, 0, 16);
        textures.put(file.getName().substring(0, file.getName().length() - 4), new int[] { pos, pos });
        pos++;
    }
    Files.write(Paths.get("build", "block_images", "blocks.json"), gson.toJson(textures).getBytes("UTF-8"));
    ImageIO.write(image, "PNG", new File("build/block_images/blocks.png"));

    System.out.printf("Done in %dms\n", System.currentTimeMillis() - startTime);
}