Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:cn.savor.small.netty.NettyClientHandler.java

License:Open Source License

private void handleGreetingThenSpecialty(String json, MessageBean response) {
    try {// w w  w.jav a 2  s. co m
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(json);
        String deviceId = jsonObject.get("deviceId").getAsString();
        String deviceName = jsonObject.get("deviceName").getAsString();
        String words = jsonObject.get("word").getAsString();
        int template = jsonObject.get("templateId").getAsInt();

        ResponseT1<SpecialtyResponseBean> resp = new ResponseT1<>();
        if (TextUtils.isEmpty(GlobalValues.CURRENT_PROJECT_DEVICE_ID)
                || deviceId.equals(GlobalValues.CURRENT_PROJECT_DEVICE_ID) || GlobalValues.IS_RSTR_PROJECTION) {
            boolean isNewDevice = TextUtils.isEmpty(GlobalValues.CURRENT_PROJECT_DEVICE_ID);

            GlobalValues.CURRENT_PROJECT_DEVICE_ID = deviceId;
            GlobalValues.CURRENT_PROJECT_DEVICE_NAME = deviceName;
            GlobalValues.IS_RSTR_PROJECTION = true;
            GlobalValues.CURRENT_PROJECT_DEVICE_IP = NettyClient.host;
            AppApi.resetPhoneInterface(GlobalValues.CURRENT_PROJECT_DEVICE_IP);

            ArrayList<String> paths = new ArrayList<>();
            int interval;
            List<RstrSpecialty> specialties = DBHelper.get(mContext).findSpecialtyByWhere(null, null);

            if (specialties != null && specialties.size() > 0) {
                for (RstrSpecialty specialty : specialties) {
                    paths.add(specialty.getMedia_path());
                }
            }
            if (paths.size() > 1) {
                interval = 10;
            } else {
                interval = 20;
            }

            resp.setResult(ConstantValues.SERVER_RESPONSE_CODE_SUCCESS);
            SpecialtyResponseBean specialtyResponseBean = new SpecialtyResponseBean();
            specialtyResponseBean.setFailed_ids("");
            specialtyResponseBean.setFounded_count(paths.size());
            resp.setContent(specialtyResponseBean);
            resp.setInfo("??");

            ProjectOperationListener.getInstance(mContext).showGreetingThenSpecialty(words, template,
                    1000 * 60 * 5, paths, interval, isNewDevice);

        } else {
            resp.setResult(ConstantValues.SERVER_RESPONSE_CODE_FAILED);
            if (GlobalValues.IS_LOTTERY) {
                resp.setInfo("?" + GlobalValues.CURRENT_PROJECT_DEVICE_NAME + " ");
            } else {
                resp.setInfo("?" + GlobalValues.CURRENT_PROJECT_DEVICE_NAME + " ?");
            }
        }

        response.getContent().add(new Gson().toJson(resp));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cn.savor.small.netty.NettyClientHandler.java

License:Open Source License

private void handleStopProjection(String json, MessageBean response) {
    try {/* w w w .  j a  v  a2 s . c  om*/
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(json);
        String deviceId = jsonObject.get("deviceId").getAsString();

        ResponseT1 resp = new ResponseT1();
        if (!TextUtils.isEmpty(deviceId) && deviceId.equals(GlobalValues.CURRENT_PROJECT_DEVICE_ID)
                && GlobalValues.IS_RSTR_PROJECTION) {
            ProjectOperationListener.getInstance(mContext).rstrStop();
            resp.setResult(ConstantValues.SERVER_RESPONSE_CODE_SUCCESS);
            resp.setInfo("??");

            GlobalValues.IS_RSTR_PROJECTION = false;
            GlobalValues.CURRENT_PROJECT_IMAGE_ID = null;
        } else {
            resp.setResult(ConstantValues.SERVER_RESPONSE_CODE_FAILED);
            resp.setInfo("???");
        }

        response.getContent().add(new Gson().toJson(resp));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:co.aurasphere.botmill.rasa.service.RasaService.java

License:Open Source License

/**
 * Send train file request.// w  ww  .  j  ava 2  s.  co  m
 *
 * @param jsonFile the json file
 * @return the training response
 */
public static TrainingResponse sendTrainFileRequest(File jsonFile) {

    JsonParser parser = new JsonParser();
    Object obj;
    try {
        obj = parser.parse(new FileReader(jsonFile));
        JsonObject jsonObject = (JsonObject) obj;
        TrainingResponse resp = RasaService.sendTrainRequest(jsonObject.toString());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

From source file:co.cask.cdap.client.rest.RestClient.java

License:Apache License

/**
 * Utility method for converting {@link org.apache.http.HttpEntity} HTTP entity content to JsonObject.
 *
 * @param httpEntity {@link org.apache.http.HttpEntity}
 * @return {@link JsonObject} generated from input content stream
 * @throws IOException if entity content is not available
 *//*from   w w  w  .j a  v a2  s  .  c  o  m*/
public static JsonObject toJsonObject(HttpEntity httpEntity) throws IOException {
    String content = toString(httpEntity);
    if (StringUtils.isEmpty(content)) {
        throw new IOException("Failed to write entity content.");
    }
    return new JsonParser().parse(content).getAsJsonObject();
}

From source file:co.cask.cdap.examples.datacleansing.SimpleSchemaMatcher.java

License:Apache License

/**
 * Determines whether or not this matcher's schema fits a piece of data.
 * A failure to match could arise from any of:
 *  - a non-nullable field of the schema is missing from the data
 *  - a numerical field of the schema has non-numerical characters in it
 *  - the schema has non-simple types//from  w ww  .j a v  a 2s . co  m
 *
 * @param data a JSON string to check if the schema matches it
 * @return true if the schema matches the given data
 */
public boolean matches(String data) {
    // rely on validations in the StructuredRecord's builder
    try {
        JsonObject jsonObject = new JsonParser().parse(data).getAsJsonObject();
        StructuredRecord.Builder builder = StructuredRecord.builder(schema);
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            builder.convertAndSet(entry.getKey(), entry.getValue().getAsString());
        }
        builder.build();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:co.cask.cdap.passport.http.client.PassportClient.java

License:Apache License

/**
 * Get List of VPC for the apiKey./* w  w  w  . ja  v a  2 s.  c om*/
 * @return List of VPC Names
 */
public List<String> getVPCList(String apiKey) {
    Preconditions.checkNotNull(apiKey, "ApiKey cannot be null");
    List<String> vpcList = Lists.newArrayList();

    try {
        String data = responseCache.getIfPresent(apiKey);

        if (data == null) {
            data = httpGet(API_BASE + "vpc/list", apiKey);
            if (data != null) {
                responseCache.put(apiKey, data);
            }
        }

        if (data != null) {
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(data);
            JsonArray jsonArray = element.getAsJsonArray();

            for (JsonElement elements : jsonArray) {
                JsonObject vpc = elements.getAsJsonObject();
                if (vpc.get("vpc_name") != null) {
                    vpcList.add(vpc.get("vpc_name").getAsString());
                }
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    return vpcList;
}

From source file:co.cask.cdap.security.tools.AccessTokenClient.java

License:Apache License

private String getAuthenticationServerAddress() throws IOException {
    HttpClient client = new DefaultHttpClient();
    String baseUrl = "http";
    // ssl settings
    if (useSsl) {
        baseUrl = "https";
        if (disableCertCheck) {
            try {
                client = getHTTPClient();
            } catch (Exception e) {
                errorDebugExit("Could not create HTTP Client with SSL enabled", e);
                System.exit(1);//from   w w w .j ava  2  s.c o  m
            }
        }
    }
    HttpGet get = new HttpGet(String.format("%s://%s:%d", baseUrl, host, port));
    HttpResponse response = client.execute(get);

    if (response.getStatusLine().getStatusCode() == 200) {
        System.out.println("Security is not enabled. No Access Token may be acquired");
        System.exit(0);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteStreams.copy(response.getEntity().getContent(), bos);
    String responseBody = bos.toString("UTF-8");
    bos.close();
    JsonParser parser = new JsonParser();
    JsonObject responseJson = (JsonObject) parser.parse(responseBody);
    JsonArray addresses = responseJson.get("auth_uri").getAsJsonArray();
    ArrayList<String> list = new ArrayList<String>();
    for (JsonElement e : addresses) {
        list.add(e.getAsString());
    }
    return list.get(new Random().nextInt(list.size()));
}

From source file:co.cask.cdap.security.tools.AccessTokenClient.java

License:Apache License

public String execute0(String[] args) {
    buildOptions();/*from   ww w.  j a v  a 2s .  com*/
    parseArguments(args);
    if (help) {
        return "";
    }

    String baseUrl;
    try {
        baseUrl = getAuthenticationServerAddress();
    } catch (IOException e) {
        errorDebugExit("Could not find Authentication service to connect to.", e);
        return null;
    }

    System.out.println(String.format("Authentication server address is: %s", baseUrl));
    System.out.println(String.format("Authenticating as: %s", username));

    HttpClient client = new DefaultHttpClient();
    if (useSsl && disableCertCheck) {
        try {
            client = getHTTPClient();
        } catch (Exception e) {
            errorDebugExit("Could not create HTTP Client with SSL enabled", e);
            return null;
        }
    }

    // construct the full URL and verify its well-formedness
    try {
        URI.create(baseUrl);
    } catch (IllegalArgumentException e) {
        System.err.println(
                "Invalid base URL '" + baseUrl + "'. Check the validity of --host or --port arguments.");
        return null;
    }

    HttpGet get = new HttpGet(baseUrl);
    String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes());
    auth = auth.replaceAll("(\r|\n)", "");
    get.addHeader("Authorization", String.format("Basic %s", auth));
    HttpResponse response;
    try {
        response = client.execute(get);
    } catch (IOException e) {
        errorDebugExit("Error sending HTTP request: " + e.getMessage(), e);
        return null;
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        System.out.println(
                "Authentication failed. Please ensure that the username and password provided are correct.");
        return null;
    } else {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ByteStreams.copy(response.getEntity().getContent(), bos);
            String responseBody = bos.toString("UTF-8");
            bos.close();
            JsonParser parser = new JsonParser();
            JsonObject responseJson = (JsonObject) parser.parse(responseBody);
            String token = responseJson.get(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN)
                    .getAsString();

            PrintWriter writer = new PrintWriter(filePath, "UTF-8");
            writer.write(token);
            writer.close();
            System.out.println("Your Access Token is:" + token);
            System.out.println("Access Token saved to file " + filePath);
        } catch (Exception e) {
            System.err.println("Could not parse response contents.");
            e.printStackTrace(System.err);
            return null;
        }
    }
    client.getConnectionManager().shutdown();
    return "OK.";
}

From source file:co.com.codesoftware.facturacion.ajax.controlador.AjaxControllerFacturacion.java

public ArrayList<ProductosFactEntitiy> generaListaProductos() {
    JsonElement json = new JsonParser().parse(this.productosArray);
    JsonArray array = json.getAsJsonArray();
    Iterator iterator = array.iterator();
    ArrayList<ProductosFactEntitiy> productosList = null;
    while (iterator.hasNext()) {
        if (productosList == null) {
            productosList = new ArrayList<>();
        }/*from   www .  j  a v  a  2 s .c  o  m*/
        JsonElement json2 = (JsonElement) iterator.next();
        Gson gson = new Gson();
        ProductosFactEntitiy prod = gson.fromJson(json2, ProductosFactEntitiy.class);
        productosList.add(prod);
    }
    return productosList;
}

From source file:co.edu.poli.util.jqgrid.JqGridData.java

public void getJsonObject(String j) {

    /*String j = "{groupOp:OR,rules:[{field:id_encabezado,op:cn,data:prueba},"
     + "{field:modulo,op:cn,data:prueba},"
     + "{field:norma,op:cn,data:prueba},"
     + "{field:resultado,op:cn,data:prueba},"
     + "{field:evidencia,op:cn,data:prueba},"
     + "{field:elemento,op:cn,data:prueba},"
     + "{field:descripcion_encab,op:cn,data:prueba98}]}";*/
    filtersArr = new HashMap();
    Gson gson = new Gson();
    JsonElement jelement = new JsonParser().parse(j);
    JsonObject jobject = jelement.getAsJsonObject();
    filtersArr.put("groupOp", jobject.get("groupOp"));
    JsonArray array = jobject.getAsJsonArray("rules");
    ArrayList<filter> f = new ArrayList<>();

    for (int i = 0; i < array.size(); i++) {
        {//from   w w w.  ja va2 s  .c o m
            JsonObject cont = array.get(i).getAsJsonObject();
            f.add(new filter(cont.get("field").getAsString(), cont.get("op").getAsString(),
                    cont.get("data").getAsString()));
        }
    }
    filtersArr.put("rules", f);
    //        System.out.println(System.out.printf(searchOperation.get("cn").toString(),"oscar","mesa").toString());
}