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:com.cognifide.aet.job.common.comparators.w3chtml5.parser.W3cHtml5ValidationResultParser.java

License:Apache License

public W3cHtml5ComparatorResult parse(String json) {

    Gson gson = new GsonBuilder().registerTypeAdapter(W3cHtml5Issue.class, new W3cHtml5IssueDeserializer())
            .create();//  w  w w  .  j a  v  a2s  .  co m

    JsonArray messages = new JsonParser().parse(json).getAsJsonObject().getAsJsonArray("messages");
    Type list = new TypeToken<List<W3cHtml5Issue>>() {
    }.getType();
    List<W3cHtml5Issue> issues = gson.fromJson(messages, list);

    IssuesUtils utils = new IssuesUtils(issues).invoke();
    int errorCount = utils.getErrorCount();
    int warningCount = utils.getWarningCount();

    return new W3cHtml5ComparatorResult(errorCount, warningCount, issues, new ArrayList<W3cHtml5Issue>());
}

From source file:com.cognifide.qa.bb.aem.content.CrxRequestSender.java

License:Apache License

/**
 * This method sends request to author instance
 *
 * @param request request to send//from  www  . ja v a  2 s. c  om
 * @return JsonObject representation of response
 * @throws IOException if response doesn't contain desired message
 */
public JsonObject sendCrxRequest(HttpUriRequest request) throws IOException {
    String resultJson;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        resultJson = EntityUtils.toString(response.getEntity());
    }
    JsonObject result;
    try {
        result = new JsonParser().parse(resultJson).getAsJsonObject();
    } catch (JsonSyntaxException e) {
        throw new JsonSyntaxException("Unable to parse as Json: " + resultJson, e);
    }
    if (result.get("success").getAsBoolean()) {
        return result;
    }
    throw new IOException(result.get("msg").getAsString());
}

From source file:com.collaborne.build.txgh.GitHubServlet.java

License:Apache License

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String event = request.getHeader("X-GitHub-Event");
    // Filter out irrelevant events quickly, without costly validation.
    if (!"ping".equals(event) && !"push".equals(event)) {
        LOGGER.debug("'{}' event ignored", event);
        response.setStatus(HttpServletResponse.SC_OK);
        return;/*w w  w.j a v a  2  s  . co m*/
    }

    String payload;
    if ("application/json".equals(request.getContentType())) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            sb.append(reader.readLine());
        }
        payload = sb.toString();
    } else if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
        payload = request.getParameter("payload");
    } else {
        LOGGER.error("'{}' event with unexpected content type {}", event, request.getContentType());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (payload == null) {
        LOGGER.error("'{}' event without payload", event);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    Map<String, Object> parameterMap = request.getParameterMap();
    for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
        if (entry.getValue() instanceof String[]) {
            LOGGER.debug(entry.getKey() + "::" + Arrays.toString((String[]) entry.getValue()));
        }
    }

    JsonObject payloadObject = new JsonParser().parse(payload).getAsJsonObject();
    JsonObject repository = payloadObject.get("repository").getAsJsonObject();
    String gitHubProjectName = repository.get("full_name").getAsString();

    TXGHProject project = Settings.getProject(gitHubProjectName);
    if (project == null) {
        // Nothing to do, we don't know this repository
        LOGGER.info("Ignoring hook for unknown repository '{}'", gitHubProjectName);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    GitHubProject gitHubProject = project.getGitHubProject();

    // Validate the secret, if we have one: either the project has it configured, then it must
    // also be in the request, or the request has it, and then it must also be configured in the project.
    String signature = request.getHeader("X-Hub-Signature");
    if (signature != null) {
        String secret = gitHubProject.getConfig().getGitHubSecret();
        if (secret == null) {
            LOGGER.error("Secret is not configured for repository '{}', but required. Ignoring request",
                    gitHubProjectName);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // Parse the signature into a byte array
        if (!signature.startsWith(SIGNATURE_SHA1_PREFIX)) {
            LOGGER.error("Unexpected signature type for repository '{}': {}", gitHubProjectName, signature);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (!validateSignature(payload, secret, signature.substring(SIGNATURE_SHA1_PREFIX.length()))) {
            LOGGER.error("Invalid signature for repository '{}'", gitHubProjectName);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    }

    // Handle the event
    if ("ping".equals(event)) {
        LOGGER.info("'ping' event: {}", payloadObject.get("zen").getAsString());
    } else if ("push".equals(event)) {
        processPushEvent(project, payloadObject);
    }
}

From source file:com.collaborne.build.txgh.TransifexApi.java

License:Apache License

public String download(TransifexResource resource, String language) throws IOException {

    StringBuilder url = new StringBuilder();
    url.append(API_ROOT);//from   w w  w .  j  a v  a 2 s .co  m
    url.append("/project/");
    url.append(resource.getProjectSlug());
    url.append("/resource/");
    url.append(resource.getResourceSlug());
    url.append("/translation/");
    url.append(language);

    WebTarget webTarget = client.target(TARGET_URL + url);
    Response response = webTarget.request(MediaType.TEXT_PLAIN).get();

    String jsonData = response.readEntity(String.class);

    if (response.getStatus() / 100 != 2) {
        LOGGER.debug(jsonData);
        throw new IOException("Transifex API call has failed. Status code: " + response.getStatus());
    }

    JsonObject jsonObject = new JsonParser().parse(jsonData).getAsJsonObject();

    return jsonObject.get("content").getAsString();
}

From source file:com.collaide.fileuploader.requests.Collaide.java

protected JsonElement getResponseToJsonElement(ClientResponse response) {
    return new JsonParser().parse(response.getEntity(String.class));
}

From source file:com.collaide.fileuploader.requests.GroupsRequest.java

@SuppressWarnings("empty-statement")
public static Group[] index() {
    ClientResponse response = Collaide//from ww  w. j  av a  2s.c  o m
            .request("user/" + CurrentUser.getUser().getId() + "/groups?" + CurrentUser.getAuthParams())
            .type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    if (response.getStatus() != 200) {
        return null;
    }
    String json = response.getEntity(String.class);
    Gson gson = new Gson();
    return gson.fromJson(new JsonParser().parse(json).getAsJsonObject().get("groups"), Group[].class);
}

From source file:com.commonslibrary.commons.utils.JsonUtils.java

License:Open Source License

/**
 * ?JsonObject//from ww w . jav a2  s .  co  m
 *
 * @param json
 * @return
 */
public static JsonObject parseJson(String json) {
    try {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(json).getAsJsonObject();
        return jsonObj;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.commonslibrary.commons.utils.LogUtils.java

License:Open Source License

public static String prettyJson(String body) {
    if (TextUtils.isEmpty(body)) {
        return body;
    }/*  w ww  .j av  a2 s .  c  o m*/
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        jsonWriter.setIndent("\u00A0\u00A0");
        JsonElement jsonElement = new JsonParser().parse(body);
        gson.toJson(jsonElement, jsonWriter);
        return stringWriter.toString();
    } catch (JsonParseException e) {
        return body;
    }
}

From source file:com.compose.nifi.processors.ComposeBatchPutMongo.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*from w ww. j a  v a2 s .  c  om*/
    }

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String collectionName = context.getProperty(COLLECTION_NAME).getValue();
    final WriteConcern writeConcern = mongoWrapper.getWriteConcern(context);

    final MongoCollection<Document> collection = mongoWrapper.getDatabase(context).getCollection(collectionName)
            .withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, content, true);
            }
        });

        //Hack away :)
        ArrayList<Document> docs = new ArrayList<>();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(new String(content, charset)).getAsJsonArray();
        for (JsonElement element : array) {
            //Terrible. surely a better way. learn more.
            Document doc = Document.parse(element.toString());
            docs.add(doc);
        }

        collection.insertMany(docs);

        session.getProvenanceReporter().send(flowFile, mongoWrapper.getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        getLogger().error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:com.continusec.client.ContinusecClient.java

License:Apache License

/**
 * Fetch the list of logs held by this account.
 * @return list of logs/*from   www.  j  a  v  a 2 s  . c o  m*/
 * @throws ContinusecException upon error
 */
public List<LogInfo> listLogs() throws ContinusecException {
    ResponseData rd = this.makeRequest("GET", "/logs", null, null);
    try {
        JsonObject o = new JsonParser().parse(new String(rd.data, "UTF-8")).getAsJsonObject();
        ArrayList<LogInfo> rv = new ArrayList<LogInfo>();
        for (JsonElement e : o.getAsJsonArray("results")) {
            rv.add(new LogInfo(e.getAsJsonObject().getAsJsonPrimitive("name").getAsString()));
        }
        return rv;
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}