Example usage for com.liferay.portal.kernel.json JSONObject getJSONObject

List of usage examples for com.liferay.portal.kernel.json JSONObject getJSONObject

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.json JSONObject getJSONObject.

Prototype

public JSONObject getJSONObject(String key);

Source Link

Usage

From source file:com.beorn.paymentpluginapi.config.ConfigDescription.java

License:Open Source License

/**
 * Verifies if a configuration is valid for the description
 * //from w ww. ja v a 2 s . c o m
 * @param configObject
 *            the configuration to check against the description
 * @return a boolean indicating if the configuration is valid or not for the
 *         description
 */
public boolean isValid(JSONObject configObject) {
    for (ConfigGroup configGroup : _configGroups) {
        if (!configObject.has(configGroup.getKey()))
            return false;

        JSONObject configObjectGroup = configObject.getJSONObject(configGroup.getKey());

        for (ConfigParameter configParameter : configGroup.getConfigParameters()) {
            if (!configObjectGroup.has(configParameter.getKey()))
                return false;

            // Extra validation can be added here (required parameters,
            // etc...)
        }
    }
    return true;
}

From source file:com.beorn.paymentpluginapi.test.ConfigValidatorTestBase.java

License:Open Source License

@Test
public void testNullConfig() throws Exception {
    String configString = "configString";

    mockStatic(JSONFactoryUtil.class);

    JSONObject config = mock(JSONObject.class);

    when(JSONFactoryUtil.createJSONObject(configString)).thenReturn(config);
    when(config.has(Mockito.anyString())).thenReturn(true);
    when(config.getJSONObject(Mockito.anyString())).thenReturn(config);

    ConfigValidator validator = getValidator();

    Assert.assertTrue(validator.isValid(configString));
}

From source file:com.beorn.paypalpaymentplugin.method.PaypalMethodHandlerTest.java

License:Open Source License

@Test
public void testGetPaymentUrl() throws Exception {

    // Data//from  www  .j  av a  2 s  .c  o  m

    String domain = "http://testdomain";
    String token = "t1";
    Map<String, String> serviceConfigMap = new HashMap<String, String>();
    serviceConfigMap.put("acct1.UserName", "testUserName");
    serviceConfigMap.put("acct1.Password", "testPassword");
    serviceConfigMap.put("acct1.Signature", "testSignature");
    serviceConfigMap.put("acct1.AppId", "testAppId");
    serviceConfigMap.put("mode", "sandbox");

    long transactionId = 123;
    long sellerId = 456;
    double amount = 789;
    String currencyCode = "EUR";
    long status = 1;
    ApiTransaction transaction = new ApiTransaction(transactionId, sellerId, amount, currencyCode, status);
    String languageId = "B";
    String backUrl = "C";
    String successUrl = "D";
    String errorUrl = "E";

    // Mocks

    mockStatic(PaymentPluginUtil.class);
    mockStatic(PayPalConfigUtil.class);
    mockStatic(TokenLocalServiceUtil.class);

    ServletContext servletContext = mock(ServletContext.class);
    JSONObject miscSellerConfig = mock(JSONObject.class);
    JSONObject sellerConfig = mock(JSONObject.class);
    JSONObject serviceSandboxConfig = mock(JSONObject.class);
    JSONObject pluginConfig = mock(JSONObject.class);
    JSONObject config = mock(JSONObject.class);
    PaymentPluginSender paymentPluginSender = mock(PaymentPluginSender.class);
    SetExpressCheckoutResponseType setExpressCheckoutResponseType = mock(SetExpressCheckoutResponseType.class);
    PayPalAPIInterfaceServiceService payPalAPIInterfaceServiceService = mock(
            PayPalAPIInterfaceServiceService.class);

    when(PaymentPluginUtil.getPaymentPluginSender()).thenReturn(paymentPluginSender);
    when(paymentPluginSender.getPaymentPluginConfig(sellerId)).thenReturn(config);
    when(PayPalConfigUtil.toPaypalServiceConfig(config)).thenReturn(serviceConfigMap);
    whenNew(PayPalAPIInterfaceServiceService.class).withArguments(serviceConfigMap)
            .thenReturn(payPalAPIInterfaceServiceService);
    when(payPalAPIInterfaceServiceService.setExpressCheckout(Mockito.any(SetExpressCheckoutReq.class)))
            .thenReturn(setExpressCheckoutResponseType);
    when(setExpressCheckoutResponseType.getAck()).thenReturn(AckCodeType.SUCCESS);
    when(setExpressCheckoutResponseType.getToken()).thenReturn(token);
    when(config.getJSONObject("sellerConfig")).thenReturn(sellerConfig);
    when(config.getJSONObject("pluginConfig")).thenReturn(pluginConfig);
    when(sellerConfig.getJSONObject("misc")).thenReturn(miscSellerConfig);
    when(miscSellerConfig.getBoolean("useSandbox")).thenReturn(true);
    when(pluginConfig.getJSONObject("serviceSandbox")).thenReturn(serviceSandboxConfig);
    when(serviceSandboxConfig.getString("paymentDomain")).thenReturn(domain);

    // Test

    PaypalMethodHandler methodHandler = new PaypalMethodHandler();
    methodHandler.initialize(servletContext);

    String paymentUrl = methodHandler.getPaymentUrl(transaction, languageId, backUrl, successUrl, errorUrl);

    verifyStatic();
    TokenLocalServiceUtil.addToken(token, transactionId, TokenStatus.AWAITING_PAYMENT);

    Assert.assertEquals(domain + "/cgi-bin/webscr?cmd=_express-checkout&useraction=commit&token=" + token,
            paymentUrl);
}

From source file:com.beorn.paypalpaymentplugin.util.PayPalConfigUtil.java

License:Open Source License

public static Map<String, String> toPaypalServiceConfig(JSONObject config) throws InvalidConfigException {
    Map<String, String> configurationMap = new HashMap<String, String>();

    JSONObject sellerConfig = config.getJSONObject("sellerConfig");
    if (sellerConfig == null)
        throw new InvalidConfigException("No sellerConfig");

    JSONObject pluginConfig = config.getJSONObject("pluginConfig");
    if (pluginConfig == null)
        throw new InvalidConfigException("No pluginConfig");

    boolean useSandbox = sellerConfig.getJSONObject("misc").getBoolean("useSandbox");

    putSellerConfig(configurationMap, sellerConfig);
    putPluginConfig(configurationMap, pluginConfig, useSandbox);

    return configurationMap;
}

From source file:com.beorn.paypalpaymentplugin.util.PayPalConfigUtil.java

License:Open Source License

private static void putPropertiesFromGroup(Map<String, String> configurationMap, JSONObject config,
        String groupName, String[] propertiesName) throws InvalidConfigException {

    if (!config.has(groupName))
        throw new InvalidConfigException("Missing group \"" + groupName + "\"");

    JSONObject groupConfig = config.getJSONObject(groupName);

    for (String propertyName : propertiesName)
        putProperty(configurationMap, groupConfig, propertyName);
}

From source file:com.beorn.paypalpaymentplugin.util.PayPalUtil.java

License:Open Source License

public static String getPaymentUrl(ServletContext servletContext, ApiTransaction transaction, String languageId,
        String backUrl, String successUrl, String errorUrl) throws SystemException, PortalException {

    PaymentPluginSender paymentPluginSender = PaymentPluginUtil.getPaymentPluginSender();
    JSONObject config = paymentPluginSender.getPaymentPluginConfig(transaction.getSellerId());

    PayPalAPIInterfaceServiceService paypalService = getPaypalService(config);

    List<PaymentDetailsType> paymentDetails = getPaymentDetailsTypes(transaction);

    String localeCode = LocaleUtil.fromLanguageId(languageId).getCountry();

    SetExpressCheckoutRequestDetailsType requestDetails = new SetExpressCheckoutRequestDetailsType();
    requestDetails.setReturnURL(getReturnUrl(servletContext, successUrl, errorUrl));
    requestDetails.setCancelURL(backUrl);
    requestDetails.setPaymentDetails(paymentDetails);
    requestDetails.setLocaleCode(localeCode);
    requestDetails.setAllowNote("0"); // No buyer note
    requestDetails.setNoShipping("1"); // No shipping address fields

    SetExpressCheckoutRequestType requestType = new SetExpressCheckoutRequestType();
    requestType.setSetExpressCheckoutRequestDetails(requestDetails);

    SetExpressCheckoutReq request = new SetExpressCheckoutReq();
    request.setSetExpressCheckoutRequest(requestType);

    SetExpressCheckoutResponseType response;
    try {//from w w  w  .j a  v a2 s .  c om
        response = paypalService.setExpressCheckout(request);

    } catch (Exception e) {
        throw new SystemException(e);
    }

    boolean success = response.getAck().equals(AckCodeType.SUCCESS);

    if (success) {
        String tokenId = response.getToken();

        JSONObject sellerConfig = config.getJSONObject("sellerConfig");
        JSONObject pluginConfig = config.getJSONObject("pluginConfig");
        boolean useSandbox = sellerConfig.getJSONObject("misc").getBoolean("useSandbox");
        String paymentDomain = pluginConfig.getJSONObject(useSandbox ? "serviceSandbox" : "service")
                .getString("paymentDomain");

        TokenLocalServiceUtil.addToken(tokenId, transaction.getTransactionId(), TokenStatus.AWAITING_PAYMENT);

        return paymentDomain + "/cgi-bin/webscr?cmd=_express-checkout&useraction=commit&token=" + tokenId;

    } else {
        List<ErrorType> errorTypes = response.getErrors();
        throw new SystemException(PayPalUtil.toString(response.getAck(), errorTypes));
    }
}

From source file:com.evozon.evoportal.my_account.wrapper.UserExpandoWrapper.java

public int getRemainingFreeDaysFromYear(int year) {
    int remainingFromYear = 0;

    try {/*w w  w  .ja  v  a  2  s  .c  o  m*/
        String remDaysFromLastStr = user.getExpandoBridge()
                .getAttribute(MyAccountConstants.REMAINING_FREE_DAYS_LAST, false).toString();
        if (!remDaysFromLastStr.isEmpty()) {
            JSONObject yearsSituation = JSONFactoryUtil.createJSONObject(remDaysFromLastStr);

            String pastYearStr = String.valueOf(year);
            if (yearsSituation.has(pastYearStr)) {
                JSONObject yearJSON = yearsSituation.getJSONObject(pastYearStr);
                remainingFromYear = yearJSON.getInt(MyAccountConstants.DAYS_LEFT);
            }
        }

    } catch (JSONException e) {
        log.error("Couldn't retrieve remaining free days from last year for user: " + user.getFullName());
    }

    return remainingFromYear;
}

From source file:com.fb.action.FacebookConnectAction.java

License:Open Source License

protected void setFacebookCredentials(HttpSession session, long companyId, String token) throws Exception {

    JSONObject jsonObject = FacebookConnectUtil.getGraphResources(companyId, "/me", token,
            "id,email,first_name,last_name,gender");

    if ((jsonObject == null) || (jsonObject.getJSONObject("error") != null)) {

        return;//  ww  w. j a va 2 s. co  m
    }

    if (FacebookConnectUtil.isVerifiedAccountRequired(companyId) && !jsonObject.getBoolean("verified")) {

        return;
    }

    User user = null;

    long facebookId = jsonObject.getLong("id");

    if (facebookId > 0) {
        session.setAttribute(FACEBOOK_USER_ID, String.valueOf(facebookId));

        try {
            user = UserLocalServiceUtil.getUserByFacebookId(companyId, facebookId);
        } catch (NoSuchUserException nsue) {
        }
    }

    String emailAddress = jsonObject.getString("email");

    if ((user == null) && Validator.isNotNull(emailAddress)) {
        session.setAttribute(FACEBOOK_USER_EMAIL_ADDRESS, emailAddress);

        try {
            user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
        } catch (NoSuchUserException nsue) {
        }
    }

    if (user != null) {
        user = updateUser(user, jsonObject);
    } else {
        user = addUser(session, companyId, jsonObject);
    }

    saveTokenExpando(user, token);
}

From source file:com.liferay.adaptive.media.image.internal.util.AdaptiveMediaImageSerializerImpl.java

License:Open Source License

@Override
public AdaptiveMedia<AdaptiveMediaImageProcessor> deserialize(String s,
        Supplier<InputStream> inputStreamSupplier) {

    try {/*  ww  w. j  av  a2  s.  c o  m*/
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject(s);

        Map<String, String> properties = new HashMap<>();

        JSONObject attributesJSONObject = jsonObject.getJSONObject("attributes");

        Map<String, AdaptiveMediaAttribute<?, ?>> allowedAttributes = AdaptiveMediaImageAttribute
                .allowedAttributes();

        allowedAttributes.forEach((name, attribute) -> {
            if (attributesJSONObject.has(name)) {
                properties.put(name, attributesJSONObject.getString(name));
            }
        });

        String uri = jsonObject.getString("uri");

        return new AdaptiveMediaImage(inputStreamSupplier,
                AdaptiveMediaImageAttributeMapping.fromProperties(properties), URI.create(uri));
    } catch (JSONException jsone) {
        throw new AdaptiveMediaRuntimeException(jsone);
    }
}

From source file:com.liferay.adaptive.media.image.internal.util.AMImageSerializerImpl.java

License:Open Source License

@Override
public AdaptiveMedia<AMImageProcessor> deserialize(String s, Supplier<InputStream> inputStreamSupplier) {

    try {//from   w  w w .j  av a 2s.  co m
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject(s);

        Map<String, String> properties = new HashMap<>();

        JSONObject attributesJSONObject = jsonObject.getJSONObject("attributes");

        Map<String, AMAttribute<?, ?>> allowedAMAttributes = AMImageAttribute.getAllowedAMAttributes();

        allowedAMAttributes.forEach((name, amAttribute) -> {
            if (attributesJSONObject.has(name)) {
                properties.put(name, attributesJSONObject.getString(name));
            }
        });

        String uri = jsonObject.getString("uri");

        return new AMImage(inputStreamSupplier, AMImageAttributeMapping.fromProperties(properties),
                URI.create(uri));
    } catch (JSONException jsone) {
        throw new AMRuntimeException(jsone);
    }
}