Example usage for java.lang Short valueOf

List of usage examples for java.lang Short valueOf

Introduction

In this page you can find the example usage for java.lang Short valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Short valueOf(short s) 

Source Link

Document

Returns a Short instance representing the specified short value.

Usage

From source file:org.mifos.accounts.savings.struts.action.SavingsDepositWithdrawalAction.java

@TransactionDemarcate(joinToken = true)
public ActionForward reLoad(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, @SuppressWarnings("unused") final HttpServletResponse response)
        throws Exception {

    UserContext uc = (UserContext) SessionUtils.getAttribute(Constants.USER_CONTEXT_KEY, request.getSession());
    SavingsDepositWithdrawalActionForm actionForm = (SavingsDepositWithdrawalActionForm) form;
    SavingsBO savingsInSession = (SavingsBO) SessionUtils.getAttribute(Constants.BUSINESS_KEY, request);

    if (actionForm.getTrxnTypeId() != null && actionForm.getTrxnTypeId() != Constants.EMPTY_STRING) {

        Long savingsId = savingsInSession.getAccountId().longValue();
        SavingsBO savings = this.savingsDao.findById(savingsId);

        Integer customerId = savings.getCustomer().getCustomerId();
        if (StringUtils.isNotBlank(actionForm.getCustomerId())) {
            customerId = Integer.valueOf(actionForm.getCustomerId());
        }//from   w  ww  .j a  v  a2 s. c  om
        DepositWithdrawalReferenceDto depositWithdrawalReferenceDto = this.savingsServiceFacade
                .retrieveDepositWithdrawalReferenceData(savingsId, customerId);

        Short trxnTypeId = Short.valueOf(actionForm.getTrxnTypeId());
        // added for defect 1587 [start]
        LegacyAcceptedPaymentTypeDao persistence = legacyAcceptedPaymentTypeDao;
        if (trxnTypeId.equals(AccountActionTypes.SAVINGS_DEPOSIT.getValue())) {
            if (StringUtils.isNotBlank(actionForm.getCustomerId())) {
                actionForm.setAmount(depositWithdrawalReferenceDto.getDepositDue());
            }
            List<PaymentTypeEntity> depositPaymentTypes = persistence.getAcceptedPaymentTypesForATransaction(
                    uc.getLocaleId(), TrxnTypes.savings_deposit.getValue());
            SessionUtils.setCollectionAttribute(MasterConstants.PAYMENT_TYPE, depositPaymentTypes, request);
        } else {
            actionForm.setAmount(depositWithdrawalReferenceDto.getWithdrawalDue());
            List<PaymentTypeEntity> withdrawalPaymentTypes = persistence.getAcceptedPaymentTypesForATransaction(
                    uc.getLocaleId(), TrxnTypes.savings_withdrawal.getValue());
            SessionUtils.setCollectionAttribute(MasterConstants.PAYMENT_TYPE, withdrawalPaymentTypes, request);
        }
    }
    return mapping.findForward(ActionForwards.load_success.toString());
}

From source file:com.eventsourcing.postgresql.PostgreSQLJournalTest.java

@Test
@SneakyThrows//w  ww  . ja va 2s .  c o  m
public void serializationNull() {
    HybridTimestamp timestamp = new HybridTimestamp(timeProvider);
    timestamp.update();

    Journal.Transaction tx = journal.beginTransaction();
    SerializationEvent event = SerializationEvent.builder().test(TestClass.builder().build()).build();
    event = (SerializationEvent) journal.journal(tx, event);
    tx.rollback();

    TestClass test = event.getTest();

    assertEquals(test.pByte, 0);
    assertEquals(test.oByte, Byte.valueOf((byte) 0));

    assertEquals(test.pByteArr.length, 0);
    assertEquals(test.oByteArr.length, 0);

    assertEquals(test.pShort, 0);
    assertEquals(test.oShort, Short.valueOf((short) 0));

    assertEquals(test.pInt, 0);
    assertEquals(test.oInt, Integer.valueOf(0));

    assertEquals(test.pLong, 0);
    assertEquals(test.oLong, Long.valueOf(0));

    assertTrue(test.pFloat == 0.0);
    assertEquals(test.oFloat, Float.valueOf((float) 0.0));

    assertEquals(test.pDouble, 0.0);
    assertEquals(test.oDouble, Double.valueOf(0.0));

    assertEquals(test.pBoolean, false);
    assertEquals(test.oBoolean, Boolean.FALSE);

    assertEquals(test.str, "");

    assertEquals(test.uuid, new UUID(0, 0));

    assertEquals(test.e, TestClass.E.A);

    assertNotNull(test.value);
    assertEquals(test.value.value, "");

    assertNotNull(test.value1);
    assertTrue(test.value1.value().isEmpty());

    assertNotNull(test.list);
    assertEquals(test.list.size(), 0);

    assertNotNull(test.map);
    assertEquals(test.map.size(), 0);

    assertNotNull(test.optional);
    assertFalse(test.optional.isPresent());

    assertNotNull(test.bigDecimal);
    assertEquals(test.bigDecimal, BigDecimal.ZERO);

    assertNotNull(test.bigInteger);
    assertEquals(test.bigInteger, BigInteger.ZERO);

    assertNotNull(test.date);
    assertEquals(test.date, new Date(0));

}

From source file:mil.jpeojtrs.sca.util.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * //from  ww  w . j  av a  2s.c  om
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
private static Object primitiveConvertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if ("string".equals(type)) {
        return stringValue;
    } else if ("wstring".equals(type)) {
        return stringValue;
    } else if ("boolean".equals(type)) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if ("char".equals(type)) {
        switch (stringValue.length()) {
        case 1:
            return stringValue.charAt(0);
        case 0:
            return null;
        default:
            throw new IllegalArgumentException(stringValue + " is not a valid char value");
        }
    } else if ("wchar".equals(type)) {
        return stringValue.charAt(0);
    } else if ("double".equals(type)) {
        return Double.parseDouble(stringValue);
    } else if ("float".equals(type)) {
        return Float.parseFloat(stringValue);
    } else if ("short".equals(type)) {
        return Short.decode(stringValue);
    } else if ("long".equals(type)) {
        return Integer.decode(stringValue);
    } else if ("longlong".equals(type)) {
        return Long.decode(stringValue);
    } else if ("ulong".equals(type)) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if ("ushort".equals(type)) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if ("ulonglong".equals(type)) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = AnyUtils.bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if ("objref".equals(type)) {
        if ("".equals(stringValue)) {
            return null;
        }
        final List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (final String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if ("octet".equals(type)) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        final short val = Short.decode(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:com.isencia.passerelle.message.TokenHelper.java

/**
 * Tries to get a Integer Short the token, by:
 * <ul>//www . j  av  a2  s .c om
 * <li>checking if the token is not an ObjectToken, containing a Short
 * <li>checking if the token is not an ObjectToken, and converting the object.toString() into a Short
 * <li>checking if the token is not a StringToken, and converting the string into a Short
 * <li>checking if the token is not a ScalarToken, and reading its integer value and converting it to a short value
 * <li>checking if the token is not a ScalarToken, and reading its double value and rounding to an short value
 * </ul>
 * Remark that converting a integer to a short may lead to loss of precision and/or of most-significant bytes. The
 * result can be that a big integer value gets converted into some negative short value.
 * 
 * @param token
 * @return
 */
public static Short getShortFromToken(Token token) throws PasserelleException {
    if (logger.isTraceEnabled()) {
        logger.trace(token.toString()); // TODO Check if correct converted
    }
    Short res = null;

    if (token != null) {
        try {
            if (token instanceof ObjectToken) {
                Object obj = ((ObjectToken) token).getValue();
                if (obj instanceof Short) {
                    res = (Short) obj;
                } else if (obj != null) {
                    try {
                        res = Short.valueOf(obj.toString());
                    } catch (NumberFormatException e) {
                        throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                "Invalid Short format in " + token, e);
                    }
                }
            } else {
                if (token instanceof StringToken) {
                    String tokenMessage = ((StringToken) token).stringValue();
                    if (tokenMessage != null) {
                        try {
                            res = Short.valueOf(tokenMessage);
                        } catch (NumberFormatException e) {
                            throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                    "Invalid Short format in " + token, e);
                        }
                    }
                } else if (token instanceof ScalarToken) {
                    try {
                        res = new Short((short) ((ScalarToken) token).intValue());
                    } catch (IllegalActionException e) {
                        // try rounding it from a double
                        try {
                            res = new Short((short) Math.round(((ScalarToken) token).doubleValue()));
                        } catch (IllegalActionException e1) {
                            // not even doubleValue is supported...
                            throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                    "Invalid token for obtaining Short value in " + token, e1);
                        }
                    }
                } else {
                    throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                            "Invalid token for obtaining Short value in " + token, null);
                }
            }
        } catch (Exception e) {
            throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                    "Error building Short from token in " + token, e);
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("exit :" + res);
    }
    return res;
}

From source file:org.mifos.accounts.loan.struts.action.LoanDisbursementAction.java

@TransactionDemarcate(validateAndResetToken = true)
@CloseSession/*from  ww  w.  ja  va  2 s.  com*/
public ActionForward update(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, @SuppressWarnings("unused") final HttpServletResponse response)
        throws Exception {

    LoanDisbursementActionForm actionForm = (LoanDisbursementActionForm) form;

    UserContext uc = getUserContext(request);
    Date trxnDate = getDateFromString(actionForm.getTransactionDate(), uc.getPreferredLocale());
    trxnDate = DateUtils.getDateWithoutTimeStamp(trxnDate.getTime());
    Date receiptDate = getDateFromString(actionForm.getReceiptDate(), uc.getPreferredLocale());

    Integer loanAccountId = Integer.valueOf(actionForm.getAccountId());
    AccountBO accountBO = new AccountBusinessService().getAccount(loanAccountId);

    createGroupQuestionnaire.saveResponses(request, actionForm, loanAccountId);

    try {
        String paymentTypeIdStringForDisbursement = actionForm.getPaymentTypeId();
        Short paymentTypeIdForDisbursement = StringUtils.isEmpty(paymentTypeIdStringForDisbursement)
                ? PaymentTypes.CASH.getValue()
                : Short.valueOf(paymentTypeIdStringForDisbursement);

        Short paymentTypeId = Short.valueOf(paymentTypeIdForDisbursement);
        final String comment = "";
        final BigDecimal disbursalAmount = new BigDecimal(actionForm.getLoanAmount());
        CustomerDto customerDto = null;

        PaymentTypeDto paymentType = null;
        AccountPaymentParametersDto loanDisbursement = new AccountPaymentParametersDto(
                new UserReferenceDto(uc.getId()), new AccountReferenceDto(loanAccountId), disbursalAmount,
                new LocalDate(trxnDate), paymentType, comment, new LocalDate(receiptDate),
                actionForm.getReceiptId(), customerDto);

        monthClosingServiceFacade.validateTransactionDate(trxnDate);

        // GLIM
        List<LoanBO> individualLoans = this.loanDao.findIndividualLoans(loanAccountId);
        for (LoanBO individual : individualLoans) {
            if (!loanAccountServiceFacade.isTrxnDateValid(Integer.valueOf(individual.getAccountId()),
                    trxnDate)) {
                throw new BusinessRuleException("errors.invalidTxndateOfDisbursal");
            }
        }

        this.loanAccountServiceFacade.disburseLoan(loanDisbursement, paymentTypeId);

        for (LoanBO individual : individualLoans) {
            loanDisbursement = new AccountPaymentParametersDto(new UserReferenceDto(uc.getId()),
                    new AccountReferenceDto(individual.getAccountId()), individual.getLoanAmount().getAmount(),
                    new LocalDate(trxnDate), paymentType, comment, new LocalDate(receiptDate),
                    actionForm.getReceiptId(), customerDto);

            this.loanAccountServiceFacade.disburseLoan(loanDisbursement, paymentTypeId);
        }
    } catch (BusinessRuleException e) {
        throw new AccountException(e.getMessage());
    } catch (MifosRuntimeException e) {
        if (e.getCause() != null && e.getCause() instanceof AccountException) {
            throw new AccountException(e.getCause().getMessage());
        }
        String msg = "errors.cannotDisburseLoan.because.disburseFailed";
        logger.error(msg, e);
        throw new AccountException(msg);
    } catch (Exception e) {
        String msg = "errors.cannotDisburseLoan.because.disburseFailed";
        logger.error(msg, e);
        throw new AccountException(msg);
    }

    return mapping.findForward(Constants.UPDATE_SUCCESS);
}

From source file:candr.yoclip.option.OptionField.java

protected void setShortOption(final T bean, final String value) {

    final Short shortValue = StringUtils.isEmpty(value) ? 0 : Short.valueOf(value);
    set(bean, new Value<T>() {

        public void set(final T bean, final Field field) throws IllegalAccessException {

            field.set(bean, shortValue);
        }/*from ww w.  j a  v  a  2  s .  c  o  m*/
    });
}

From source file:org.droidparts.reflect.util.TypeHelper.java

public static Object parseValue(Class<?> valCls, String valStr) throws IllegalArgumentException {
    if (isByte(valCls)) {
        return Byte.valueOf(valStr);
    } else if (isShort(valCls)) {
        return Short.valueOf(valStr);
    } else if (isInteger(valCls)) {
        return Integer.valueOf(valStr);
    } else if (isLong(valCls)) {
        return Long.valueOf(valStr);
    } else if (isFloat(valCls)) {
        if (valStr.equals("-")) {
            return Float.valueOf("0");
        } else {/*from  w w w. ja  va 2  s . com*/
            return Float.valueOf(valStr);
        }

    } else if (isDouble(valCls)) {
        return Double.valueOf(valStr);
    } else if (isBoolean(valCls)) {
        return Boolean.valueOf(valStr);
    } else if (isCharacter(valCls)) {
        return Character.valueOf((valStr.length() == 0) ? ' ' : valStr.charAt(0));
    } else if (isString(valCls)) {
        return valStr;
    } else if (isEnum(valCls)) {
        return instantiateEnum(valCls, valStr);
    } else if (isUUID(valCls)) {
        return UUID.fromString(valStr);
    } else if (isDate(valCls)) {
        // fIX: date fixed wort app

        Date dateObj = null;
        try {
            dateObj = SimpleDateFormatFactory.getInstance().getFormatter().parse(String.valueOf(valStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateObj;

    } else if (isJsonObject(valCls) || isJsonArray(valCls)) {
        try {
            return isJsonObject(valCls) ? new JSONObject(valStr) : new JSONArray(valStr);
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    } else {
        throw new IllegalArgumentException(
                "Unable to convert '" + valStr + "' to " + valCls.getSimpleName() + ".");
    }
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a Short value to the object.//from www.j a va 2  s. co  m
 * 
 * @param o
 *            the object
 * @param field
 *            the field
 * @param values
 *            the array with the content at one line
 * @param idx
 *            the index of the field
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void shortReader(final Object o, final Field field, final String[] values, final int idx)
        throws ConverterException {
    String iValue = values[idx];
    if (StringUtils.isNotBlank(iValue)) {
        try {
            field.set(o, Short.valueOf(iValue));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new ConverterException(ExceptionMessage.CONVERTER_SHORT.getMessage(), e);
        }
    }
}

From source file:candr.yoclip.option.OptionSetter.java

protected void setShortOption(final T bean, final String value) {

    final Short shortValue = StringUtils.isEmpty(value) ? 0 : Short.valueOf(value);
    set(bean, new Value<T>() {

        public void set(final T bean, final Method setter)
                throws InvocationTargetException, IllegalAccessException {

            setter.invoke(bean, shortValue);
        }//from  w  w  w  . j a  v  a  2  s  . c  om
    });
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.CswFilterDelegate.java

@Override
public FilterType propertyIsEqualTo(String propertyName, short literal) {
    isComparisonOperationSupported(ComparisonOperatorType.EQUAL_TO);
    propertyName = mapPropertyName(propertyName);
    if (isPropertyQueryable(propertyName)) {
        return cswFilterFactory.buildPropertyIsEqualToFilter(propertyName, Short.valueOf(literal), false);
    } else {/*www .j ava2s.c  om*/
        return new FilterType();
    }
}