Example usage for javax.json JsonReader readObject

List of usage examples for javax.json JsonReader readObject

Introduction

In this page you can find the example usage for javax.json JsonReader readObject.

Prototype

JsonObject readObject();

Source Link

Document

Returns a JSON object that is represented in the input source.

Usage

From source file:ke.co.tawi.babblesms.server.servlet.accountmngmt.Login.java

public static boolean validateCaptcha(String gRecaptchaResponse) throws IOException {
    if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
        return false;
    }//from w  w  w .j  av  a2  s  . c o  m

    try {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());

        //parse JSON response and return 'success' value
        JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();

        return jsonObject.getBoolean("success");
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:de.pksoftware.springstrap.cms.util.CmsUtils.java

public static String getModelProperty(CmsModel model, String path, String defaultValue)
        throws InvalidPathException {
    if (null == model) {
        return defaultValue;
    }/* ww  w. java 2s. c  o  m*/

    Pattern pattern = Pattern.compile("^(\\/\\w+)+$");
    Matcher matcher = pattern.matcher(path);

    if (!matcher.matches()) {
        throw new RuntimeException(
                "Path must start with /, must not end with / and must only contain letters and numbers.");
    }

    String value = defaultValue;

    logger.info("Trying to get " + model.getModelName() + ">" + path);

    String data = model.getData();

    String[] pathParts = path.split("\\/");
    int partsLength = pathParts.length;

    JsonReader jsonReader = Json.createReader(new StringReader(data));
    JsonObject jsonObject = jsonReader.readObject();

    boolean pointerIsArray = false;
    Object pointer = jsonObject;

    for (int i = 1; i < partsLength; i++) {
        String pathPart = pathParts[i];
        logger.info("Testing property: " + pathPart);
        JsonValue jsonValue = null;
        Assert.notNull(pointer);
        if (pointerIsArray) {
            if (!NumberUtils.isNumber(pathPart)) {
                throw new InvalidPathException("Path element '" + pathPart + "' should be numeric.");
            }
            jsonValue = ((JsonArray) pointer).get(Integer.parseInt(pathPart));
        } else {
            jsonValue = ((JsonObject) pointer).get(pathPart);
        }

        if (null == jsonValue) {
            logger.info(model.getModelName() + " has no property: " + path);

            break;
        }

        JsonValue.ValueType valueType = jsonValue.getValueType();
        if (i < partsLength - 1) {
            //Must be Object or Array
            if (valueType == JsonValue.ValueType.ARRAY) {
                logger.info(pathPart + " is an array.");
                pointer = (JsonArray) jsonValue;
                pointerIsArray = true;
            } else if (valueType == JsonValue.ValueType.OBJECT) {
                logger.info(pathPart + " is an object.");
                pointer = (JsonObject) jsonValue;
                pointerIsArray = false;
            } else {
                throw new InvalidPathException("Path element '" + pathPart
                        + "' should be a be an object or array, but " + valueType.toString() + " found.");
            }
        } else {
            if (valueType == JsonValue.ValueType.STRING) {
                logger.info(pathPart + " is an string.");
                value = ((JsonString) jsonValue).getString();
                break;
            } else {
                throw new InvalidPathException("Path element '" + pathPart + "' should be a string, but "
                        + valueType.toString() + " found.");
            }
        }
    }

    jsonReader.close();

    return value;
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static JsonObject getJsonObject(final String jsonString) throws IOException {

    final JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(jsonString, APIStatics.UTF_8));
    final JsonObject jsonObject = jsonReader.readObject();

    jsonReader.close();/*from  w w w  . jav  a 2s . c om*/

    return jsonObject;
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static JsonObject doInit(final String resourceWatchFolder, final String initResourceFileName,
        final String serviceName, final Integer engineThreads, final Properties config, final int cnt)
        throws Exception {

    final String initResourceFile = resourceWatchFolder + File.separatorChar + initResourceFileName;

    final String initResultJSONString = TPUUtil.executeInit(initResourceFile, serviceName, engineThreads,
            config, cnt);/*from   w w  w  .ja  va 2  s. co  m*/

    if (initResultJSONString == null) {

        final String message = "couldn't create data model";

        LOG.error(message);

        throw new Exception(message);
    }

    final JsonReader initResultJsonReader = Json
            .createReader(IOUtils.toInputStream(initResultJSONString, UTF_8));
    final JsonObject initResultJSON = initResultJsonReader.readObject();

    if (initResultJSON == null) {

        final String message = "couldn't create data model";

        LOG.error(message);

        throw new Exception(message);
    }

    return initResultJSON;
}

From source file:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
    JsonReader jsonReader = Json.createReader(inputStream);
    return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavenlicense.MavenLicenseDeleteAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json.createReader(new StringReader(request.param(MavenLicenseConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();// w w  w  . j  av  a2 s  .  c  om

    if (StringUtils.isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX))) {
        mavenLicenseSettingsService
                .deleteMavenLicense(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX));
        LOGGER.info(MavenLicenseConfiguration.INFO_DELETE_SUCCESS + jsonObject.toString());
        mavenLicenseSettingsService.sortMavenLicenses();
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
    } else {
        LOGGER.error(MavenLicenseConfiguration.ERROR_DELETE_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:com.natixis.appdynamics.traitements.GetInfoLicense.java

public Map<String, Object> RetrieveInfoLicense() throws ClientProtocolException, IOException {
    Map<String, Object> myMapInfoLicense = new HashMap<String, Object>();

    HttpClient client = new DefaultHttpClient();

    String[] chaineUrl = GetParamApplication.urlApm.split("/" + "/");
    String hostApm = chaineUrl[1];

    URI uri = null;/*from   w  w w . j  a  v a  2  s.  co m*/
    try {
        uri = new URIBuilder().setScheme("http").setHost(hostApm).setPath(GetParamApplication.uriInfoLicense)
                .setParameter("startdate", GetDateInfoLicence()).setParameter("enddate", GetDateInfoLicence())
                .build();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(hostApm, 80),
            new UsernamePasswordCredentials(GetParamApplication.userApm, GetParamApplication.passwordApm));
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    String jsonContent = EntityUtils.toString(entity);
    Reader stringReader = new StringReader(jsonContent);
    JsonReader rdr = Json.createReader(stringReader);
    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("usages");

    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        BeanInfoLicense myBeanInfoLicense = new BeanInfoLicense(result.getString("agentType"),
                result.getInt("avgUnitsAllowed"), result.getInt("avgUnitsUsed"));
        myMapInfoLicense.put(result.getString("agentType"), myBeanInfoLicense);
        //System.out.println(result.getString("agentType")+","+result.getInt("avgUnitsAllowed")+","+result.getInt("avgUnitsUsed"));
    }

    return myMapInfoLicense;
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavendependency.MavenDependencyDeleteAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json
            .createReader(new StringReader(request.param(MavenDependencyConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from  w  w  w .j  a v a  2  s  .  co  m*/

    if (StringUtils.isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY))) {
        mavenDependencySettingsService
                .deleteMavenDependency(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY));
        LOGGER.info(MavenDependencyConfiguration.INFO_DELETE_SUCCESS + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
    } else {
        LOGGER.error(MavenDependencyConfiguration.ERROR_DELETE_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:org.acruxsource.sandbox.spring.jmstows.websocket.ChatHandler.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    logger.info("New incoming message: " + message.getPayload());

    StringReader stringReader = new StringReader(message.getPayload());
    JsonReader jsonReader = Json.createReader(stringReader);
    JsonObject chatMessageObject = jsonReader.readObject();

    if (chatMessageObject.getJsonString("name") != null && chatMessageObject.getJsonString("message") != null) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setName(chatMessageObject.getJsonString("name").getString());
        chatMessage.setMessage(chatMessageObject.getJsonString("message").getString());
        jmsMessageSender.sendMessage("websocket.out", chatMessage);
    } else {// w  w  w.jav  a 2  s.com
        session.sendMessage(new TextMessage("Empty name or message"));
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavenlicense.MavenLicenseAddAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json.createReader(new StringReader(request.param(MavenLicenseConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from w  w w .  j a v a  2s.c  o m*/

    boolean keyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_KEY));
    boolean regexIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX));

    if (keyIsNotBlank && regexIsNotBlank) {
        boolean success = mavenLicenseSettingsService.addMavenLicense(
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX),
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_KEY));

        if (success) {
            LOGGER.info(MavenLicenseConfiguration.INFO_ADD_SUCCESS + jsonObject.toString());
            mavenLicenseSettingsService.sortMavenLicenses();
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
        } else {
            LOGGER.error(MavenLicenseConfiguration.ERROR_ADD_ALREADY_EXISTS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
        }
    } else {
        LOGGER.error(MavenLicenseConfiguration.ERROR_ADD_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}