Example usage for javax.json JsonObject getString

List of usage examples for javax.json JsonObject getString

Introduction

In this page you can find the example usage for javax.json JsonObject getString.

Prototype

String getString(String name, String defaultValue);

Source Link

Document

Returns the string value of the associated JsonString mapping for the specified name.

Usage

From source file:org.jboss.set.aphrodite.stream.services.json.StreamsJsonParser.java

public static Map<String, Stream> parse(final URL url) throws NotFoundException {
    try (InputStream is = url.openStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        JsonReader jr = Json.createReader(rd);

        final JsonArray jsonArray = jr.readObject().getJsonArray(JSON_STREAMS);
        Objects.requireNonNull(jsonArray, "streams array must be specified in json file");
        final Map<String, Stream> streamMap = new LinkedHashMap<String, Stream>();
        for (JsonValue value : jsonArray) {
            JsonObject json = (JsonObject) value;

            String upstreamName = json.getString(JSON_UPSTREAM, null);
            Stream upstream = streamMap.get(upstreamName);

            JsonArray codebases = json.getJsonArray(JSON_CODEBASES);
            Map<String, StreamComponent> codebaseMap = parseStreamCodebases(codebases);

            Stream currentStream = new Stream(url, json.getString(JSON_NAME), upstream, codebaseMap);
            streamMap.put(currentStream.getName(), currentStream);
        }//from   ww  w .ja v  a2 s.c o m
        return streamMap;
    } catch (Exception e) {
        Utils.logException(LOG, "Unable to load url: " + url.toString(), e);
        throw new NotFoundException(e);
    }
}

From source file:com.amazon.alexa.avs.config.DeviceConfigUtils.java

/**
 * Reads the {@link DeviceConfig} from disk. Pass in the name of the config file
 *
 * @return The configuration.//from   ww w  .j a  v  a2 s . co m
 */
public static DeviceConfig readConfigFile(String filename) {
    FileInputStream file = null;
    try {
        deviceConfigName = filename.trim();
        file = new FileInputStream(deviceConfigName);
        JsonReader json = Json.createReader(file);
        JsonObject configObject = json.readObject();

        JsonObject companionServiceObject = configObject.getJsonObject(DeviceConfig.COMPANION_SERVICE);
        CompanionServiceInformation companionServiceInfo = null;
        if (companionServiceObject != null) {
            String serviceUrl = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SERVICE_URL, null);
            String sessionId = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SESSION_ID, null);
            String sslClientKeyStore = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CLIENT_KEYSTORE, null);
            String sslClientKeyStorePassphrase = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CLIENT_KEYSTORE_PASSPHRASE, null);
            String sslCaCert = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CA_CERT, null);

            companionServiceInfo = new CompanionServiceInformation(serviceUrl, sslClientKeyStore,
                    sslClientKeyStorePassphrase, sslCaCert);
            companionServiceInfo.setSessionId(sessionId);
        }

        JsonObject companionAppObject = configObject.getJsonObject(DeviceConfig.COMPANION_APP);
        CompanionAppInformation companionAppInfo = null;
        if (companionAppObject != null) {
            int localPort = companionAppObject.getInt(DeviceConfig.CompanionAppInformation.LOCAL_PORT, -1);
            String lwaUrl = companionAppObject.getString(DeviceConfig.CompanionAppInformation.LWA_URL, null);
            String clientId = companionAppObject.getString(DeviceConfig.CompanionAppInformation.CLIENT_ID,
                    null);
            String refreshToken = companionAppObject
                    .getString(DeviceConfig.CompanionAppInformation.REFRESH_TOKEN, null);
            String sslKeyStore = companionAppObject.getString(DeviceConfig.CompanionAppInformation.SSL_KEYSTORE,
                    null);
            String sslKeyStorePassphrase = companionAppObject
                    .getString(DeviceConfig.CompanionAppInformation.SSL_KEYSTORE_PASSPHRASE, null);

            companionAppInfo = new CompanionAppInformation(localPort, lwaUrl, sslKeyStore,
                    sslKeyStorePassphrase);
            companionAppInfo.setClientId(clientId);
            companionAppInfo.setRefreshToken(refreshToken);
        }

        String productId = configObject.getString(DeviceConfig.PRODUCT_ID, null);
        String dsn = configObject.getString(DeviceConfig.DSN, null);
        String provisioningMethod = configObject.getString(DeviceConfig.PROVISIONING_METHOD, null);
        String avsHost = configObject.getString(DeviceConfig.AVS_HOST, null);
        boolean wakeWordAgentEnabled = configObject.getBoolean(DeviceConfig.WAKE_WORD_AGENT_ENABLED, false);
        String locale = configObject.getString(DeviceConfig.LOCALE, null);

        DeviceConfig deviceConfig = new DeviceConfig(productId, dsn, provisioningMethod, wakeWordAgentEnabled,
                locale, companionAppInfo, companionServiceInfo, avsHost);

        return deviceConfig;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("The required file " + deviceConfigName + " could not be opened.", e);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:com.buffalokiwi.aerodrome.jet.products.ProductVariationGroupRec.java

/**
 * Create a new JetProductVariationGroup instance based on Jet JSON.
 * @param sku The parent sku that was queried 
 * @param json JSON response from jet product variation query.
 * @return object/*w ww  .  j  a v a  2s  . co  m*/
 * @throws IllegalArgumentException if sku or json are null/empty
 * @throws ClassCastException if Any array items are of an incorrect type
 */
public static ProductVariationGroupRec fromJSON(final String sku, final JsonObject json)
        throws IllegalArgumentException, ClassCastException {
    Utils.checkNullEmpty(sku, "sku");
    Utils.checkNull(json, "json");

    final List<String> childSkus = new ArrayList<>();
    final JsonArray skus = json.getJsonArray("children_skus");
    if (skus != null) {
        for (int i = 0; i < skus.size(); i++) {
            final JsonObject entry = skus.getJsonObject(i);
            if (entry != null) {
                final String child = entry.getString("merchant_sku", "");
                if (!child.isEmpty())
                    childSkus.add(child);
            }
        }
    }

    return new ProductVariationGroupRec(sku, Relationship.byText(json.getString("relationship", "")),
            Utils.jsonArrayToLongList(json.getJsonArray("variation_refinements")), childSkus,
            json.getString("group_title", ""));
}

From source file:com.buffalokiwi.aerodrome.jet.products.ShippingExceptionRec.java

public static ShippingExceptionRec fromJSON(final JsonObject o) {
    Utils.checkNull(o, "o");

    ShipExceptionType ex = ShipExceptionType.EXCLUSIVE;

    try {/*from   w  w  w .  ja v a2s. c  o  m*/
        ex = ShipExceptionType.fromText(o.getString("shipping_exception_type", ""));
    } catch (IllegalArgumentException e) {
        APILog.info(LOG, e, "Product found with incorrect shipping exception type");
        //..do nothing, it's set to exclusive.
        //..The old include method can sometimes be returned from old products.
    }

    return new ShippingExceptionRec(ShippingServiceLevel.fromText(o.getString("service_level", "")),
            ShippingMethod.fromText(o.getString("shipping_method", "")),
            ShipOverrideType.fromText(o.getString("override_type", "")),
            Utils.jsonNumberToMoney(o, "shipping_charge_amount"), ex);
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderItemRec.java

/**
 * Create an OrderItemRec from jet json 
 * @param json jet json/*  w  ww.  j  a v a2 s.c  om*/
 * @return instance
 */
public static OrderItemRec fromJson(final JsonObject json) throws JetException {

    final Builder b = (new Builder()).setOrderItemId(json.getString("order_item_id", ""))
            .setAltOrderItemId(json.getString("alt_order_item_id", ""))
            .setMerchantSku(json.getString("merchant_sku", "")).setTitle(json.getString("product_title", ""))
            .setRequestOrderQty(json.getInt("request_order_quantity", 0))

            //..This appears to have been removed.  I don't know if jet still returns this value or not.
            .setRequestOrderCancelQty(json.getInt("request_order_cancel_qty", 0))

            .setAdjReason(json.getString("adjustment_reason", ""))
            .setTaxCode(json.getString("item_tax_code", "")).setUrl(json.getString("url", ""))
            .setPriceAdj(Utils.jsonNumberToMoney(json, "price_adjustment"))
            .setFees(Utils.jsonNumberToMoney(json, "item_fees")).setTaxInfo(json.getString("tax_info", "")) //..This might not work...
            .setRegFees(Utils.jsonNumberToMoney(json, "regulatory_fees"))
            .setAdjustments(jsonToFeeAdj(json.getJsonArray("fee_adjustments")))
            .setItemAckStatus(ItemAckStatus.fromText(json.getString("order_item_acknowledgement_status", "")));

    final JsonObject price = json.getJsonObject("item_price");
    if (price != null)
        b.setItemPrice(ItemPriceRec.fromJson(price));

    return b.build();
}

From source file:org.jboss.set.aphrodite.JsonStreamService.java

private void parseJson(JsonObject jsonObject) throws NotFoundException {
    JsonArray jsonArray = jsonObject.getJsonArray("streams");
    Objects.requireNonNull(jsonArray, "streams array must be specified in json file");

    for (JsonValue value : jsonArray) {
        JsonObject json = (JsonObject) value;

        String upstreamName = json.getString("upstream", null);
        Stream upstream = streamMap.get(upstreamName);

        JsonArray codebases = json.getJsonArray("codebases");
        Map<String, StreamComponent> codebaseMap = parseStreamCodebases(codebases);

        Stream currentStream = new Stream(json.getString("name"), upstream, codebaseMap);
        streamMap.put(currentStream.getName(), currentStream);
    }// w w  w  .j a  va 2 s .c o  m
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Request the companion service's information once the user has registered. Once the user has
 * registered and we've received the {@link CompanionAppProvisioningInfo} we can then exchange
 * that information for tokens./*ww w.  j  av a  2  s. c om*/
 *
 * @param sessionId
 * @return accessToken
 * @throws IOException
 *             If an I/O exception occurs.
 */
public OAuth2AccessToken getAccessToken(String sessionId) throws IOException {
    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put(AuthConstants.SESSION_ID, sessionId);

    JsonObject response = callService("/provision/accessToken", queryParameters);

    String accessToken = response.getString(AuthConstants.OAuth2.ACCESS_TOKEN, null);
    int expiresIn = response.getInt(AuthConstants.OAuth2.EXPIRES_IN, -1);

    return new OAuth2AccessToken(accessToken, expiresIn);
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

JsonObject callService(String path, Map<String, String> parameters) throws IOException {
    HttpURLConnection con = null;
    InputStream response = null;/*from ww w.  j  av a2 s.  c  o m*/
    try {
        String queryString = mapToQueryString(parameters);
        URL obj = new URL(deviceConfig.getCompanionServiceInfo().getServiceUrl(), path + queryString);
        con = (HttpURLConnection) obj.openConnection();

        if (con instanceof HttpsURLConnection) {
            ((HttpsURLConnection) con).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestMethod("GET");

        if ((con.getResponseCode() >= 200) || (con.getResponseCode() < 300)) {
            response = con.getInputStream();
        }

        if (response != null) {
            String responsestring = IOUtils.toString(response);
            JsonReader reader = Json
                    .createReader(new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
            IOUtils.closeQuietly(response);
            return reader.readObject();
        }
        return Json.createObjectBuilder().build();
    } catch (IOException e) {
        if (con != null) {
            response = con.getErrorStream();

            if (response != null) {
                String responsestring = IOUtils.toString(response);
                JsonReader reader = Json.createReader(
                        new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
                JsonObject error = reader.readObject();

                String errorName = error.getString("error", null);
                String errorMessage = error.getString("message", null);

                if (!StringUtils.isBlank(errorName) && !StringUtils.isBlank(errorMessage)) {
                    throw new RemoteServiceException(errorName + ": " + errorMessage);
                }
            }
        }
        throw e;
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response);
        }
    }
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Send the device's provisioning information to the companion service, and receive back
 * {@link CompanionServiceRegCodeResponse} which has a regCode to display to the user.
 *
 * @return Information from the companion service to begin the provisioning process.
 * @throws IOException/*from w w w.  j a  v a2  s  .  c  om*/
 *             If an I/O exception occurs.
 */
public CompanionServiceRegCodeResponse getRegistrationCode() throws IOException {
    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put(AuthConstants.PRODUCT_ID, deviceConfig.getProductId());
    queryParameters.put(AuthConstants.DSN, deviceConfig.getDsn());

    JsonObject response = callService("/provision/regCode", queryParameters);

    // The sessionId created from the 3pService
    String sessionId = response.getString(AuthConstants.SESSION_ID, null);
    String regCode = response.getString(AuthConstants.REG_CODE, null);

    return new CompanionServiceRegCodeResponse(sessionId, regCode);
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn Jet Json into an OrderRec/*from www .  j  a  v a 2  s. co m*/
 * @param json Jet json
 * @return object 
 */
public static OrderRec fromJson(final JsonObject json) {
    Utils.checkNull(json, "json");
    final Builder b = new Builder().setMerchantOrderId(json.getString("merchant_order_id", ""))
            .setReferenceOrderId(json.getString("reference_order_id", ""))
            .setCustomerReferenceOrderId(json.getString("customer_reference_order_id", ""))
            .setFulfillmentNode(json.getString("fulfillment_node", ""))
            .setAltOrderId(json.getString("alt_order_id", "")).setHashEmail(json.getString("hash_email", ""))
            .setStatus(OrderStatus.fromText(json.getString("status", "")))
            .setExceptionState(OrderExceptionState.fromText(json.getString("exception_state", "")))
            .setOrderPlacedDate(JetDate.fromJetValueOrNull(json.getString("order_placed_date", "")))
            .setOrderTransmissionDate(JetDate.fromJetValueOrNull(json.getString("order_transmission_date", "")))
            .setJetRequestDirectedCancel(json.getBoolean("jet_requested_directed_cancel", false))
            .setOrderReadyDate(JetDate.fromJetValueOrNull(json.getString("order_ready_date", "")))
            .setHasShipments(json.getBoolean("has_shipments", false))
            .setOrderAckDate(JetDate.fromJetValueOrNull(json.getString("order_acknowledge_date", "")))
            .setAckStatus(AckStatus.fromText(json.getString("acknowledgement_status", "")));

    buildOrderDetail(b, json.getJsonObject("order_detail"));
    buildBuyer(b, json.getJsonObject("buyer"));
    buildShipTo(b, json.getJsonObject("shipping_to"));
    buildOrderTotals(b, json.getJsonObject("order_totals"));

    try {
        buildOrderItems(b, json.getJsonArray("order_items"));
    } catch (JetException e) {
        APILog.error(LOG, e, "Failed to generate order items");
    }

    //..Build the shipments
    final JsonArray shipments = json.getJsonArray("shipments");
    if (shipments != null) {
        for (int i = 0; i < shipments.size(); i++) {
            final JsonObject shipment = shipments.getJsonObject(i);
            if (shipment == null)
                continue;

            b.getShipments().add(ShipmentRec.fromJson(shipment));
        }
    }

    return new OrderRec(b);
}