Example usage for java.math BigDecimal intValue

List of usage examples for java.math BigDecimal intValue

Introduction

In this page you can find the example usage for java.math BigDecimal intValue.

Prototype

@Override
public int intValue() 

Source Link

Document

Converts this BigDecimal to an int .

Usage

From source file:com.nextep.designer.sqlgen.mysql.impl.MySqlCapturer.java

/**
 * Builds the columns map of the given table. This table will be filled with
 * the new fetched columns./*w ww .j a va 2 s.co  m*/
 * 
 * @param conn
 *            Connection to fetch columns
 * @param md
 *            pre-computed {@link DatabaseMetaData}
 * @param context
 *            the current {@link ICaptureContext}
 * @param monitor
 *            the {@link IProgressMonitor} to report progress to
 * @param table
 *            the table to fetch columns for
 * @return a map of {@link IBasicColumn} hashed by their qualified column
 *         name
 * @throws SQLException
 */
private Map<String, IBasicColumn> buildColumnsMap(Connection conn, DatabaseMetaData md, ICaptureContext context,
        IProgressMonitor monitor, Map<String, IBasicTable> tablesMap) throws SQLException {
    final IMySqlModelService mysqlModelService = CorePlugin.getService(IMySqlModelService.class);
    final IDatatypeProvider datatypeProvider = DBGMHelper.getDatatypeProvider(DBVendor.MYSQL);
    final Map<String, IBasicColumn> columnsMap = new HashMap<String, IBasicColumn>();
    PreparedStatement stmt = null;
    ResultSet rset = null;
    try {
        stmt = conn.prepareStatement(
                "select TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE, EXTRA, COLUMN_DEFAULT, CHARACTER_SET_NAME, COLLATION_NAME, COLUMN_TYPE, COLUMN_COMMENT "
                        + " from information_schema.columns where table_schema=?");
        stmt.setString(1, context.getSchema());

        rset = stmt.executeQuery();
        while (rset.next()) {
            monitor.worked(1);
            final String tableName = rset.getString("TABLE_NAME"); //$NON-NLS-1$
            final IMySQLTable table = (IMySQLTable) tablesMap.get(tableName);
            if (table == null) {
                continue;
            }
            final String columnName = rset.getString("COLUMN_NAME"); //$NON-NLS-1$
            final int rank = rset.getInt("ORDINAL_POSITION"); //$NON-NLS-1$
            String datatype = rset.getString("DATA_TYPE").toUpperCase(); //$NON-NLS-1$
            int numericLength = rset.getInt("NUMERIC_PRECISION"); //$NON-NLS-1$
            int dataPrecision = rset.getInt("NUMERIC_SCALE"); //$NON-NLS-1$
            BigDecimal dataCharLength = rset.getBigDecimal("CHARACTER_MAXIMUM_LENGTH"); //$NON-NLS-1$
            final boolean nullable = "YES".equals(rset.getString("IS_NULLABLE")); //$NON-NLS-1$ //$NON-NLS-2$
            final boolean autoInc = "auto_increment".equals(rset.getString("EXTRA")); //$NON-NLS-1$ //$NON-NLS-2$
            String dataDefault = rset.getString("COLUMN_DEFAULT"); //$NON-NLS-1$

            final String charset = rset.getString("CHARACTER_SET_NAME"); //$NON-NLS-1$
            final String collation = rset.getString("COLLATION_NAME"); //$NON-NLS-1$
            final String columnType = rset.getString("COLUMN_TYPE"); //$NON-NLS-1$
            final String colComments = rset.getString("COLUMN_COMMENT"); //$NON-NLS-1$
            boolean unsigned = columnType.toLowerCase().indexOf("unsigned") >= 0; //$NON-NLS-1$

            int dataLength = (dataCharLength != null && dataCharLength.intValue() > 0)
                    ? dataCharLength.intValue()
                    : numericLength > 0 ? numericLength : 0;
            dataPrecision = Math.max(dataPrecision, 0);
            // Workaround the bloody management of MySQL default values !!
            // TODO: Check for JDBC updates of the mysql driver...
            if ("CURRENT_TIMESTAMP".equalsIgnoreCase(dataDefault)) { //$NON-NLS-1$
                dataDefault = null;
            }
            if (dataDefault != null && !"".equals(dataDefault)) { //$NON-NLS-1$
                // Adding quotes and escaping quotes in default values for
                // string datatypes
                if (datatypeProvider.listStringDatatypes().contains(datatype)) {
                    dataDefault = "'" + dataDefault.replace("'", "''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                }
            }

            /*
             * Since 1.0.6, for every type, we base our capture on the
             * COLUMN_TYPE information which provides much more accurate
             * information (mostly on length/precision) and is the field
             * used by the MySQL "show create table" command.
             */
            if (datatype.startsWith("ENUM") || datatype.startsWith("SET")) { //$NON-NLS-1$ //$NON-NLS-2$
                // Taking the whole column type
                dataLength = 0;
                dataPrecision = 0;
                datatype = columnType;
            } else {
                if (columnType != null) {
                    final String mysqlType = columnType.toUpperCase();
                    // Parsing the type as "datatype(length,precision)"
                    int ind = mysqlType.indexOf('(');
                    // Have we got a size ?
                    if (ind > 0) {
                        try {
                            // Data type is the text before bracket
                            datatype = mysqlType.substring(0, ind).toUpperCase();
                            int comma = mysqlType.indexOf(',', ind);
                            int rightpar = mysqlType.indexOf(')', ind);
                            // Have we got a comma ?
                            if (comma > 0) {
                                // The comma separates length and precision
                                dataLength = Integer.parseInt(mysqlType.substring(ind + 1, comma));
                                dataPrecision = Integer.parseInt(mysqlType.substring(comma + 1, rightpar));
                            } else {
                                // Otherwise we got a 0 precision
                                dataLength = Integer.parseInt(mysqlType.substring(ind + 1, rightpar));
                                dataPrecision = 0;
                            }
                        } catch (NumberFormatException nfe) {
                            // Unknown type definition, resetting everything
                            // to 0
                            LOGGER.warn("Could not parse the data type [" + columnType + "] of column ["
                                    + tableName + "." + columnName + "]: " //$NON-NLS-1$ //$NON-NLS-2$
                                    + "data type could be incorrect");
                            datatype = columnType;
                            dataLength = 0;
                            dataPrecision = 0;
                        }
                    } else {
                        // No size definition, resetting everything to 0
                        datatype = mysqlType;
                        dataLength = 0;
                        dataPrecision = 0;
                    }
                }
            }

            // Specific behavior when data type name contains the "UNSIGNED"
            // keyword
            if (datatype.indexOf("UNSIGNED") > -1) { //$NON-NLS-1$
                unsigned = true;
                datatype = datatype.replaceAll("UNSIGNED", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
            }

            IDatatype d = new Datatype(datatype, dataLength, dataPrecision);
            IMySQLColumn c = new MySQLColumn(columnName, colComments, d, rank - 1);
            // (IBasicColumn)ControllerFactory.getController(IElementType.COLUMN).emptyInstance(t);
            c.setName(columnName);
            c.setDescription(colComments);
            d.setUnsigned(unsigned);
            c.setDatatype(d);
            c.setRank(rank - 1);
            c.setAutoIncremented(autoInc);
            c.setNotNull(!nullable);
            c.setDefaultExpr(dataDefault == null ? "" : dataDefault.trim()); //$NON-NLS-1$

            // Character set management
            final String tabCharset = table.getCharacterSet();
            final String tabCollation = table.getCollation();

            if (charset != null && !charset.equals(tabCharset)) {
                c.setCharacterSet(charset);
            }
            if (collation != null && !collation.equals(tabCollation)
                    && !collation.equals(mysqlModelService.getDefaultCollation(charset))) {
                c.setCollation(collation);
            }
            // TODO Warning: might cause save problems / column list
            // duplicates because
            // adding unsaved columns
            c.setParent(table);
            table.addColumn(c);
            // Storing columns for later use
            final String colName = CaptureHelper.getUniqueColumnName(c);
            columnsMap.put(colName, c);

        }
    } finally {
        CaptureHelper.safeClose(rset, null);
    }

    return columnsMap;
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchasingActionBase.java

/**
 * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#deleteSourceLine(org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */// w w  w  .j a v a2s .co m
@Override
public ActionForward deleteSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    PurchasingFormBase purchasingForm = (PurchasingFormBase) form;

    String[] indexes = getSelectedLineForAccounts(request);
    int itemIndex = Integer.parseInt(indexes[0]);
    int accountIndex = Integer.parseInt(indexes[1]);
    if (itemIndex == -2) {
        purchasingForm.getAccountDistributionsourceAccountingLines().remove(accountIndex);
    } else {
        PurApItem item = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument())
                .getItem((itemIndex));
        item.getSourceAccountingLines().remove(accountIndex);
        List<PurApAccountingLine> purApAccountingLineList = item.getSourceAccountingLines();
        BigDecimal initialPercent = new BigDecimal(0);
        for (PurApAccountingLine purApAccountingLine : purApAccountingLineList) {
            initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
        }
        initialPercent = new BigDecimal(100).subtract(initialPercent);
        if (initialPercent.intValue() > 0) {
            item.resetAccount(initialPercent);
        } else {
            item.resetAccount(new BigDecimal(0));
        }
    }
    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:org.kuali.ole.module.purap.document.web.struts.OlePurchaseOrderAction.java

/**
 * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*  ww  w.  ja  v  a 2s . c  o  m*/
@Override
public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
    PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;

    // index of item selected
    int itemIndex = getSelectedLine(request);
    PurApItem item = null;

    // if custom processing of an accounting line is not done then insert a line generically.
    if (processCustomInsertAccountingLine(purapForm, request) == false) {
        String errorPrefix = null;
        PurApAccountingLine line = null;

        boolean rulePassed = false;
        if (itemIndex >= 0) {
            item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
            //Calculating the dollar amount for the accounting Line.
            PurApAccountingLine lineItem = item.getNewSourceLine();
            if (lineItem.getAccountLinePercent() != null) {
                BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
            } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
                KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                BigDecimal dollarToPercent = dollar.bigDecimalValue()
                        .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                lineItem.setAccountLinePercent(dollarToPercent);
            }
            line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
            //end
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "["
                    + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        } else if (itemIndex == -2) {
            //corrected: itemIndex == -2 is the only case for distribute account
            //This is the case when we're inserting an accounting line for distribute account.
            line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        }
        AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
        if (accountingLineBase != null) {
            String accountNumber = accountingLineBase.getAccountNumber();
            String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
            Map<String, String> criteria = new HashMap<String, String>();
            criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
            criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
            Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
                    criteria);
            rulePassed = checkForValidAccount(account);
        }
        if (rulePassed) {
            // add accountingLine
            SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);

            PurApAccountingLine newSourceLine = item.getNewSourceLine();
            List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();

            BigDecimal initialValue = new BigDecimal(0);

            for (PurApAccountingLine accountLine : existingSourceLine) {
                initialValue = initialValue.add(accountLine.getAccountLinePercent());
            }
            if (itemIndex >= 0) {

                if ((newSourceLine.getAccountLinePercent()
                        .intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED
                        && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT
                                .subtract(initialValue).intValue())
                        && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
                    if (OleSelectConstant.MAX_PERCENT.subtract(initialValue)
                            .intValue() != OleSelectConstant.ZERO) {
                        insertAccountingLine(purapForm, item, line);
                    }
                } else {
                    checkAccountingLinePercent(newSourceLine);

                }
                for (PurApAccountingLine oldSourceAccountingLine : item.getSourceAccountingLines()) {
                    if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
                        ((OlePurchaseOrderAccount) oldSourceAccountingLine)
                                .setExistingAmount(oldSourceAccountingLine.getAmount());
                    }
                }
                List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
                BigDecimal totalPercent = new BigDecimal(100);
                BigDecimal initialPercent = new BigDecimal(0);
                for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
                    initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());

                }
                initialPercent = totalPercent.subtract(initialPercent);
                BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
                if (maxPercent.intValue() == OleSelectConstant.ZERO) {
                    item.resetAccount(OleSelectConstant.ZERO_PERCENT);

                } else {
                    item.resetAccount(initialPercent);

                }
            } else if (itemIndex == -2) {
                //this is the case for distribute account
                ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
            }
        }
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:tajo.master.GlobalPlanner.java

/**
 *  ? SubQuery QueryUnit localize//from   www. j  a va  2s. c  om
 * 
 * @param unit localize SubQuery
 * @param maxTaskNum localize? QueryUnit?  
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public QueryUnit[] localize(SubQuery unit, int maxTaskNum) throws IOException, URISyntaxException {
    FileStatus[] files;
    Fragment[] frags;
    List<Fragment> fragList;
    List<URI> uriList;
    // fragments and fetches are maintained for each scan of the SubQuery
    Map<ScanNode, List<Fragment>> fragMap = new HashMap<ScanNode, List<Fragment>>();
    Map<ScanNode, List<URI>> fetchMap = new HashMap<ScanNode, List<URI>>();

    // set partition numbers for two phase algorithms
    // TODO: the following line might occur a bug. see the line 623
    unit = setPartitionNumberForTwoPhase(unit, maxTaskNum);

    Schema sortSchema = null;

    // make fetches and fragments for each scan
    Path tablepath = null;
    ScanNode[] scans = unit.getScanNodes();
    for (ScanNode scan : scans) {
        if (scan.getTableId().startsWith(QueryId.PREFIX)) {
            tablepath = sm.getTablePath(scan.getTableId());
        } else {
            tablepath = catalog.getTableDesc(scan.getTableId()).getPath();
        }
        if (scan.isLocal()) {
            SubQuery prev = unit.getChildIterator().next();
            TableStat stat = prev.getStats();
            if (stat.getNumRows() == 0) {
                return new QueryUnit[0];
            }
            // make fetches from the previous query units
            uriList = new ArrayList<URI>();
            fragList = new ArrayList<Fragment>();

            if (prev.getOutputType() == PARTITION_TYPE.RANGE) {
                StoreTableNode store = (StoreTableNode) prev.getLogicalPlan();
                SortNode sort = (SortNode) store.getSubNode();
                sortSchema = PlannerUtil.sortSpecsToSchema(sort.getSortKeys());

                // calculate the number of tasks based on the data size
                int mb = (int) Math.ceil((double) stat.getNumBytes() / 1048576);
                LOG.info("Total size of intermediate data is approximately " + mb + " MB");

                maxTaskNum = (int) Math.ceil((double) mb / 64); // determine the number of task by considering 1 task per 64MB
                LOG.info("The desired number of tasks is set to " + maxTaskNum);

                // calculate the number of maximum query ranges
                TupleRange mergedRange = TupleUtil.columnStatToRange(sort.getOutSchema(), sortSchema,
                        stat.getColumnStats());
                RangePartitionAlgorithm partitioner = new UniformRangePartition(sortSchema, mergedRange);
                BigDecimal card = partitioner.getTotalCardinality();

                // if the number of the range cardinality is less than the desired number of tasks,
                // we set the the number of tasks to the number of range cardinality.
                if (card.compareTo(new BigDecimal(maxTaskNum)) < 0) {
                    LOG.info("The range cardinality (" + card + ") is less then the desired number of tasks ("
                            + maxTaskNum + ")");
                    maxTaskNum = card.intValue();
                }

                LOG.info("Try to divide " + mergedRange + " into " + maxTaskNum + " sub ranges (total units: "
                        + maxTaskNum + ")");
                TupleRange[] ranges = partitioner.partition(maxTaskNum);
                String[] queries = TupleUtil.rangesToQueries(sortSchema, ranges);
                for (QueryUnit qu : unit.getChildQuery(scan).getQueryUnits()) {
                    for (Partition p : qu.getPartitions()) {
                        for (String query : queries) {
                            uriList.add(new URI(p.getFileName() + "&" + query));
                        }
                    }
                }
            } else {
                SubQuery child = unit.getChildQuery(scan);
                QueryUnit[] units = null;
                if (child.getStoreTableNode().getSubNode().getType() == ExprType.UNION) {
                    List<QueryUnit> list = Lists.newArrayList();
                    for (ScanNode s : child.getScanNodes()) {
                        for (QueryUnit qu : child.getChildQuery(s).getQueryUnits()) {
                            list.add(qu);
                        }
                    }
                    units = new QueryUnit[list.size()];
                    units = list.toArray(units);
                } else {
                    units = child.getQueryUnits();
                }
                for (QueryUnit qu : units) {
                    for (Partition p : qu.getPartitions()) {
                        uriList.add(new URI(p.getFileName()));
                        //              System.out.println("Partition: " + uriList.get(uriList.size() - 1));
                    }
                }
            }

            fetchMap.put(scan, uriList);
            // one fragment is shared by query units
            Fragment frag = new Fragment(scan.getTableId(), tablepath,
                    TCatUtil.newTableMeta(scan.getInSchema(), StoreType.CSV), 0, 0);
            fragList.add(frag);
            fragMap.put(scan, fragList);
        } else {
            fragList = new ArrayList<Fragment>();
            // set fragments for each scan
            if (unit.hasChildQuery() && (unit.getChildQuery(scan).getOutputType() == PARTITION_TYPE.HASH
                    || unit.getChildQuery(scan).getOutputType() == PARTITION_TYPE.RANGE)) {
                files = sm.getFileSystem().listStatus(tablepath);
            } else {
                files = new FileStatus[1];
                files[0] = sm.getFileSystem().getFileStatus(tablepath);
            }
            for (FileStatus file : files) {
                // make fragments
                if (scan.isBroadcast()) {
                    frags = sm.splitBroadcastTable(file.getPath());
                } else {
                    frags = sm.split(file.getPath());
                }
                for (Fragment f : frags) {
                    // TODO: the fragment ID should be set before
                    f.setId(scan.getTableId());
                    fragList.add(f);
                }
            }
            fragMap.put(scan, fragList);
        }
    }

    List<QueryUnit> unitList = null;
    if (scans.length == 1) {
        unitList = makeUnaryQueryUnit(unit, maxTaskNum, fragMap, fetchMap, sortSchema);
    } else if (scans.length == 2) {
        unitList = makeBinaryQueryUnit(unit, maxTaskNum, fragMap, fetchMap);
    }
    // TODO: The partition number should be set here,
    // because the number of query units is decided above.

    QueryUnit[] units = new QueryUnit[unitList.size()];
    units = unitList.toArray(units);
    unit.setQueryUnits(units);

    return units;
}

From source file:org.openbravo.service.json.AdvancedQueryBuilder.java

private Object getTypeSafeValue(String operator, Property property, Object value) throws JSONException {
    if (value == null) {
        return value;
    }//from   w w w.j  a  v  a 2  s .  c  om

    if (isLike(operator)) {
        if (operator.equals(OPERATOR_INOTCONTAINS) || operator.equals(OPERATOR_ICONTAINS)
                || operator.equals(OPERATOR_CONTAINSFIELD)) {
            return "%" + escapeLike(value.toString()).replaceAll(" ", "%") + "%";
        } else if (operator.equals(OPERATOR_NOTCONTAINS) || operator.equals(OPERATOR_CONTAINS)) {
            return "%" + escapeLike(value.toString()).replaceAll(" ", "%") + "%";
        } else if (operator.equals(OPERATOR_INOTSTARTSWITH) || operator.equals(OPERATOR_ISTARTSWITH)
                || operator.equals(OPERATOR_STARTSWITHFIELD)) {
            return escapeLike(value.toString()).replaceAll(" ", "%") + "%";
        } else if (operator.equals(OPERATOR_NOTSTARTSWITH) || operator.equals(OPERATOR_STARTSWITH)) {
            return escapeLike(value.toString()).replaceAll(" ", "%") + "%";
        } else {
            return "%" + escapeLike(value.toString());
        }
    }

    if (operator.equals(OPERATOR_INSET) || operator.equals(OPERATOR_NOTINSET)) {
        final List<Object> typedValues = new ArrayList<Object>();
        final JSONArray values = (JSONArray) value;
        for (int i = 0; i < values.length(); i++) {
            typedValues.add(getTypeSafeValue(OPERATOR_EQUALS, property, values.get(i)));
        }
        return typedValues;
    }

    if (property.getDomainType() instanceof SearchDomainType) {
        return value;
    }

    // a FK. Old selectors is an special key, though they are not primitive they should be treated
    // as text
    if (!property.isPrimitive() && !(property.getDomainType() instanceof SearchDomainType)) {
        return value;
    }

    if (Boolean.class == property.getPrimitiveObjectType()) {
        return new Boolean(value.toString());
    } else if (property.isNumericType()) {
        try {
            final BigDecimal bdValue = new BigDecimal(value.toString());
            if (Long.class == property.getPrimitiveObjectType()) {
                return bdValue.longValue();
            } else if (Integer.class == property.getPrimitiveObjectType()) {
                return bdValue.intValue();
            } else {
                return bdValue;
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (Date.class.isAssignableFrom(property.getPrimitiveObjectType())) {
        try {
            Date date = null;
            boolean hasComeADateTime = true;
            if (property.isDatetime() || property.isAbsoluteDateTime()) {
                try {
                    date = simpleDateTimeFormat.parse(value.toString());
                } catch (ParseException e) {
                    // When a DateTime column is filtered, plan Date values are used
                    // See issue https://issues.openbravo.com/view.php?id=23203
                    hasComeADateTime = false;
                    date = simpleDateFormat.parse(value.toString());
                }
            }
            if (property.isDate()) {
                date = simpleDateFormat.parse(value.toString());
            }
            final Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // move the date to the beginning of the day
            if (isGreaterOperator(operator)) {
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
            } else if (isLesserOperator(operator)) {
                // move the data to the end of the day
                calendar.set(Calendar.HOUR, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
            }

            if (hasComeADateTime || property.isDatetime() || property.isDate()) {

                // Applies the time zone offset difference of the client
                // Just in case the date needs to be changed
                calendar.add(Calendar.MINUTE, -clientUTCMinutesTimeZoneDiff);

                // Applies the time zone offset difference of the server
                calendar.add(Calendar.MINUTE, UTCServerMinutesTimeZoneDiff);
            }

            return calendar.getTime();
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
    return value;
}

From source file:module.siadap.domain.wrappers.UnitSiadapWrapper.java

/**
 * @param totalPeople/*from  w  ww  . j ava  2 s .  co  m*/
 *            the number of people to calculate the quota on
 * @param quota
 *            the percentage points of quota
 * @return how many people it represents, it is never 0 due to SIADAPs rules
 */
private int calculateQuota(int totalPeople, Integer quota) {
    BigDecimal result = new BigDecimal(totalPeople).multiply(new BigDecimal(quota)).divide(new BigDecimal(100));

    int value = result.intValue();
    return value > 0 ? value : 1;// if the quota is 0 the the quota shifts
    // to 1

}

From source file:org.egov.collection.web.actions.receipts.ReceiptAction.java

/**
 * This method is invoked when user creates a receipt.
 *
 * @return//from  ww w.  ja va  2 s  .  c o m
 */
@ValidationErrorPage(value = "new")
@Action(value = "/receipts/receipt-save")
public String save() {
    String returnValue;
    if (instrumentTypeCashOrCard != null
            && instrumentTypeCashOrCard.equals(CollectionConstants.INSTRUMENTTYPE_ONLINE)) {
        if (callbackForApportioning && !overrideAccountHeads)
            apportionBillAmount();
        ServiceDetails paymentService;
        paymentService = (ServiceDetails) getPersistenceService().findByNamedQuery(
                CollectionConstants.QUERY_SERVICE_BY_CODE, CollectionConstants.SERVICECODE_SBIMOPS);
        if (null != paymentService)
            setPaymentRequest(collectionService.populateAndPersistReceipts(paymentService, receiptHeader,
                    receiptDetailList, instrHeaderOnline.getInstrumentAmount(),
                    CollectionConstants.COLLECTION_TYPE_COUNTER));
        return REDIRECT;
    } else {
        List<InstrumentHeader> receiptInstrList = new ArrayList<>(0);
        LOGGER.info("Receipt creation process is started !!!!!!");
        ReceiptHeader rhForValidation = null;
        final long startTimeMillis = System.currentTimeMillis();
        if (manualReceiptNumber != null && manualReceiptDate != null) {
            final CFinancialYear financialYear = collectionsUtil.getFinancialYearforDate(manualReceiptDate);
            rhForValidation = receiptHeaderService.findByNamedQuery(
                    CollectionConstants.QUERY_RECEIPT_BY_SERVICE_MANUALRECEIPTNO_AND_DATE, manualReceiptNumber,
                    receiptHeader.getService().getCode(), financialYear.getStartingDate(),
                    financialYear.getEndingDate(), CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED);
        }

        if (rhForValidation == null) {
            // For interday cancellation
            if (oldReceiptId != null) {
                final ReceiptHeader receiptHeaderToBeCancelled = receiptHeaderService.findById(oldReceiptId,
                        false);

                receiptHeaderToBeCancelled.setStatus(
                        statusDAO.getStatusByModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER,
                                CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED));
                receiptHeaderToBeCancelled.setReasonForCancellation(reasonForCancellation);
                // set isReconciled to false before calling update to
                // billing system for
                // cancel receipt
                receiptHeaderToBeCancelled.setIsReconciled(false);
                receiptHeader.setLocation(receiptHeaderToBeCancelled.getLocation());
                receiptHeaderService.persist(receiptHeaderToBeCancelled);
                if (receiptHeaderToBeCancelled.getReceipttype() == CollectionConstants.RECEIPT_TYPE_BILL) {
                    populateReceiptModelWithExistingReceiptInfo(receiptHeaderToBeCancelled);
                    LOGGER.info("Receipt Cancelled with Receipt Number(recreateNewReceiptOnCancellation): "
                            + receiptHeaderToBeCancelled.getReceiptnumber() + "; Consumer Code: "
                            + receiptHeaderToBeCancelled.getConsumerCode());
                }
            }

            if ("misc".equalsIgnoreCase(billSource)) {
                createMisc();
                if (!setMiscReceiptDetails())
                    returnValue = NEW;
            } else {
                if (callbackForApportioning && !overrideAccountHeads)
                    apportionBillAmount();
                if (receiptDetailList == null || receiptDetailList.isEmpty())
                    throw new ApplicationRuntimeException(
                            "Receipt could not be created as the apportioned receipt detail list is empty");
                else {
                    BigDecimal totalCreditAmount = BigDecimal.ZERO;
                    for (final ReceiptDetail receiptDetail : receiptDetailList)
                        totalCreditAmount = totalCreditAmount.add(receiptDetail.getCramount());
                    if (totalCreditAmount.intValue() == 0)
                        throw new ApplicationRuntimeException("Apportioning Failed at the Billing System: "
                                + receiptHeader.getService().getCode() + ", for bill number: "
                                + receiptHeader.getReferencenumber());
                    else
                        receiptHeader.setReceiptDetails(new HashSet(receiptDetailList));
                }
            }
            int noOfNewlyCreatedReceipts = 0;
            boolean setInstrument = true;

            // only newly created receipts need to be initialised with the
            // data.
            // The cancelled receipt can be excluded from this processing.
            if (receiptHeader.getStatus() == null) {
                noOfNewlyCreatedReceipts++;
                // Set created by Date as this required to generate receipt
                // number before persist
                if (manualReceiptDate == null)
                    receiptHeader.setReceiptdate(new Date());
                else {
                    // If the receipt has been manually created, the receipt
                    // date is same as the date of manual creation.
                    // set Createdby, in MySavelistner if createdBy is null
                    // it set both createdBy and createdDate with
                    // currentDate.
                    // Thus overridding the manualReceiptDate set above
                    // receiptHeader.setCreatedBy(collectionsUtil.getLoggedInUser());
                    receiptHeader.setManualreceiptdate(manualReceiptDate);
                    receiptHeader.setReceiptdate(manualReceiptDate);
                    receiptHeader.setVoucherDate(manualReceiptDate);
                }
                if (StringUtils.isNotBlank(manualReceiptNumber))
                    receiptHeader.setManualreceiptnumber(manualReceiptNumber);
                if (isBillSourcemisc()) {
                    receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_ADHOC);
                    receiptHeader.setVoucherDate(voucherDate);
                    receiptHeader.setReceiptdate(voucherDate);
                    receiptHeader.setVoucherNum(voucherNum);
                    receiptHeader.setIsReconciled(Boolean.TRUE);
                    receiptHeader.setManualreceiptdate(manualReceiptDate);
                    receiptHeader.setPayeeName(StringEscapeUtils.unescapeHtml(paidBy));

                } else {
                    receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_BILL);
                    receiptHeader.setIsModifiable(Boolean.TRUE);
                    receiptHeader.setIsReconciled(Boolean.FALSE);
                }
                // serviceType =
                // receiptHeader.getService().getServiceType();
                receiptHeader.setCollectiontype(CollectionConstants.COLLECTION_TYPE_COUNTER);
                // Bank Collection Operator location is not captured.
                if (!collectionsUtil.isBankCollectionOperator(receiptCreatedByCounterOperator)
                        && receiptHeader.getLocation() == null)
                    receiptHeader.setLocation(collectionsUtil.getLocationOfUser(getSession()));
                receiptHeader.setStatus(
                        collectionsUtil.getStatusForModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER,
                                CollectionConstants.RECEIPT_STATUS_CODE_TO_BE_SUBMITTED));
                receiptHeader.setPaidBy(StringEscapeUtils.unescapeHtml(paidBy));
                receiptHeader.setSource(Source.SYSTEM.toString());

                // If this is a new receipt in lieu of cancelling old
                // receipt, update
                // old receipt id to the reference collection header id
                // field of this new receipt.
                if (getOldReceiptId() != null)
                    receiptHeader.setReceiptHeader(receiptHeaderService.findById(getOldReceiptId(), false));
                if (setInstrument) {
                    receiptInstrList = populateInstrumentDetails();
                    setInstrument = false;
                }

                receiptHeader.setReceiptInstrument(new HashSet(receiptInstrList));

                BigDecimal debitAmount = BigDecimal.ZERO;

                for (final ReceiptDetail creditChangeReceiptDetail : receiptDetailList)
                    for (final ReceiptDetail receiptDetail : receiptHeader.getReceiptDetails())
                        if (creditChangeReceiptDetail.getReceiptHeader().getReferencenumber()
                                .equals(receiptDetail.getReceiptHeader().getReferencenumber())
                                && receiptDetail.getOrdernumber()
                                        .equals(creditChangeReceiptDetail.getOrdernumber())) {

                            receiptDetail.setCramount(creditChangeReceiptDetail.getCramount());
                            receiptDetail.setDramount(creditChangeReceiptDetail.getDramount());
                            // calculate sum of creditamounts as a debit
                            // value to create a
                            // debit account head and add to receipt details
                            debitAmount = debitAmount.add(creditChangeReceiptDetail.getCramount());
                            debitAmount = debitAmount.subtract(creditChangeReceiptDetail.getDramount());
                        }

                if (chequeInstrumenttotal != null && chequeInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                    receiptHeader.setTotalAmount(chequeInstrumenttotal);

                if (cashOrCardInstrumenttotal != null
                        && cashOrCardInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                    receiptHeader.setTotalAmount(cashOrCardInstrumenttotal);
                DebitAccountHeadDetailsService debitAccountHeadService = (DebitAccountHeadDetailsService) beanProvider
                        .getBean(collectionsUtil.getBeanNameForDebitAccountHead());
                if (isBillSourcemisc())
                    receiptHeader.addReceiptDetail(debitAccountHeadService.addDebitAccountHeadDetails(
                            totalDebitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal,
                            instrumentTypeCashOrCard));
                else
                    receiptHeader.addReceiptDetail(debitAccountHeadService.addDebitAccountHeadDetails(
                            debitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal,
                            instrumentTypeCashOrCard));

            }
            // }// end of looping through receipt headers
            // }// end of looping through model receipt payee list

            LOGGER.info("Call back for apportioning is completed");
            // billing system
            receiptHeaderService.populateAndPersistReceipts(receiptHeader, receiptInstrList);

            // populate all receipt header ids except the cancelled receipt
            // (in effect the newly created receipts)
            selectedReceipts = new Long[noOfNewlyCreatedReceipts];
            int i = 0;
            if (!receiptHeader.getId().equals(oldReceiptId)) {
                selectedReceipts[i] = receiptHeader.getId();
                i++;
            }

            final long elapsedTimeMillis = System.currentTimeMillis() - startTimeMillis;
            LOGGER.info("$$$$$$ Receipt Persisted with Receipt Number: " + receiptHeader.getReceiptnumber()
                    + (receiptHeader.getConsumerCode() != null
                            ? " and consumer code: " + receiptHeader.getConsumerCode()
                            : "")
                    + "; Time taken(ms) = " + elapsedTimeMillis);
            // Do not invoke print receipt in case of bulk upload.
            if (!receiptBulkUpload)
                returnValue = printReceipts();
            else
                returnValue = SUCCESS;
        } else {
            if (rhForValidation.getService().getCode().equals(CollectionConstants.SERVICECODE_PROPERTYTAX))
                addActionError("Entered Manual receipt number already exists for the index number"
                        + rhForValidation.getConsumerCode()
                        + ".Please enter a valid manual receipt number and create the receipt.");
            else
                addActionError("Receipt already exists for the service ");
            returnValue = NEW;
        }
    }
    return returnValue;
}

From source file:service.AdService.java

public void create(Boolean isAutherized, Long catId, String email, String phone, String price,
        MultipartFile previews[], String name, String desc, Long booleanIds[], String booleanVals[],
        Long stringIds[], String stringVals[], Long numIds[], String snumVals[], Long dateIds[],
        Date dateVals[], Long selIds[], Long selVals[], Long multyIds[], String multyVals[], Date dateFrom,
        Date dateTo, Long localIds[]) throws IOException {
    Boolean newUser = false;// w  w  w  .  j a va  2  s .  c o  m
    if (catId != null) {
        Category cat = catDao.find(catId);
        if (cat != null) {
            if (isAutherized || (!isAutherized && email != null && !email.equals(""))) {

                PhoneEditor phe = new PhoneEditor();
                phone = phe.getPhone(phone);
                addError(phe.error);

                if ((phone == null || phone.equals("")) && (email == null || email.equals(""))) {
                    addError(
                            "  email    ? ");
                }

                User user = userService.getUserByMail(email);
                if (!isAutherized && user == null) {
                    user = userService.registerStandardUser(email);
                    newUser = true;
                    List<String> userErrors = userService.getErrors();
                    if (!userErrors.isEmpty()) {
                        for (String er : userErrors) {
                            addError("user_service: " + er + "; ");
                        }
                    }
                }
                Ad ad = new Ad();
                ad.setInsertDate(new Date());
                ad.setShowCount((long) 0);
                ad.setStatus(Ad.NEW);
                ad.setDateFrom(dateFrom);
                ad.setDateTo(dateTo);
                ad.setEmail(email);
                ad.setPhone(phone);

                ad.setAuthor(user);

                ad.setCat(cat);

                Set<Locality> locals = new HashSet();
                /*if (region != null) {
                 if (region.isAllRussia()) {
                 locals.addAll(locDao.getAll());
                 } else {
                 locals.addAll(region.getLocalities());
                 }
                 }*/
                if (localIds != null && localIds.length > 0) {
                    locals.addAll(locDao.getLocs(localIds));
                } else {
                    addError("  ?   ");
                }
                ad.setLocalities(locals);
                ad.setName(name);
                ad.setDescription(desc);
                ad.setPrice(getNumFromString(price, true));
                ad.setValues(new HashSet());
                if (validate(ad) && getErrors().isEmpty()) {
                    adDao.save(ad);

                    List<Long> reqParamIds = catDao.getRequiredParamsIds(catId);
                    List<Parametr> catParams = paramDao.getParamsFromCat(catId);
                    int i = 0;
                    ArrayList<String> paramValsErrs = new ArrayList();
                    // ? ??  ? ?  ? ??,  ?, ? ?  
                    //? ad

                    ArrayList<ParametrValue> list4Save = new ArrayList();

                    //      
                    if (booleanIds != null) {
                        if (booleanVals == null) {
                            booleanVals = new String[booleanIds.length];
                        }
                        while (i < booleanIds.length) {
                            Parametr p = paramDao.find(booleanIds[i]);
                            if (catParams.contains(p) && Parametr.BOOL == p.getParamType()) {
                                Long val = ParametrValue.NO;
                                String sval = "";
                                if (booleanVals[i] != null) {
                                    val = ParametrValue.YES;
                                    sval = "";
                                }
                                ParametrValue pv = new ParametrValue();
                                pv.setAd(ad);
                                pv.setParametr(p);
                                pv.setSelectVal(val);
                                pv.setStringVal(sval);
                                if (validate(pv)) {
                                    list4Save.add(pv);
                                }

                            }
                            i++;
                        }
                    }

                    if (stringVals != null && stringVals.length > 0) {
                        i = 0;
                        while (i < stringIds.length) {
                            Long paramId = stringIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.TEXT == p.getParamType()) {
                                String val = stringVals[i];
                                if (val != null && !val.equals("")) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }

                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setStringVal(val);
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (snumVals != null && snumVals.length > 0) {
                        i = 0;
                        while (i < numIds.length) {
                            Long paramId = numIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.NUM == p.getParamType()) {
                                String sval = snumVals[i];
                                if (sval != null && !sval.equals("")) {
                                    Double val = getNumFromString(sval, true);
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setNumVal(val);
                                    pv.setStringVal(StringAdapter.getString(val));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                        if (!getErrors().isEmpty()) {
                            for (String e : getErrors()) {
                                paramValsErrs.add(e);
                            }
                        }
                    }

                    if (dateVals != null && dateVals.length > 0) {
                        i = 0;
                        while (i < dateIds.length) {
                            Long paramId = dateIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.DATE == p.getParamType()) {
                                Date val = dateVals[i];
                                if (val != null) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setDateVal(val);
                                    pv.setStringVal(DateAdapter.formatByDate(val, DateAdapter.SMALL_FORMAT));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (selVals != null && selVals.length > 0) {
                        i = 0;

                        while (i < selIds.length) {
                            Long paramId = selIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.SELECTING == p.getParamType()) {
                                Long val = selVals[i];
                                if (val != null && !val.equals(0L)) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    //?  ?
                    //TO DO       (??)
                    if (multyVals != null && multyVals.length > 0) {
                        for (String rawVal : multyVals) {
                            String idValArr[] = rawVal.split("_");
                            if (idValArr.length == 2) {
                                String strId = idValArr[0];
                                String strVal = idValArr[1];
                                Long paramId = Long.valueOf(strId);
                                Long val = Long.valueOf(strVal);
                                Parametr p = paramDao.find(paramId);
                                if (catParams.contains(p) && Parametr.MULTISELECTING == p.getParamType()) {
                                    if (reqParamIds.contains(paramId) && val != null) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }
                                }
                            }
                        }
                    }

                    //?  ?    ?    ?
                    if (!reqParamIds.isEmpty() || !paramValsErrs.isEmpty()) {
                        for (Long id : reqParamIds) {
                            addError("    "
                                    + paramDao.find(id).getName() + "; ");
                        }
                        //?
                        adDao.delete(ad);
                    } else {

                        for (ParametrValue pv : list4Save) {
                            paramValueDao.save(pv);
                        }

                        File file = new File("/usr/local/seller/preview/" + ad.getId() + "/");
                        if (file.exists()) {
                            for (File f : file.listFiles()) {
                                f.delete();
                            }
                            file.delete();
                        }
                        file.mkdirs();
                        if (previews != null && previews.length > 0) {
                            i = 0;
                            while (i < 10 && i < previews.length) {
                                MultipartFile prev = previews[i];
                                if (prev != null && 0L < prev.getSize()) {
                                    if (prev.getSize() <= (long) 3 * 1024 * 1024) {
                                        File f = new File(
                                                "/usr/local/seller/preview/" + ad.getId() + "/supPreview");
                                        if (f.exists()) {
                                            f.delete();
                                        }
                                        prev.transferTo(f);
                                        //to do  ? - ??
                                        try {
                                            BufferedImage bi = ImageIO.read(f);
                                            BigDecimal x = BigDecimal.valueOf(0);
                                            BigDecimal y = BigDecimal.valueOf(0);
                                            BigDecimal h = BigDecimal.valueOf(bi.getHeight());
                                            BigDecimal w = BigDecimal.valueOf(bi.getWidth());
                                            if (h.compareTo(w) > 0) {
                                                y = (h.subtract(w)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                h = w;
                                            } else if (h.compareTo(w) < 0) {
                                                x = (w.subtract(h)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                w = h;
                                            }
                                            bi = bi.getSubimage(x.intValue(), y.intValue(), w.intValue(),
                                                    h.intValue());
                                            f.delete();
                                            f = new File("/usr/local/seller/preview/" + ad.getId() + "/" + i);
                                            ImageIO.write(bi, "png", f);
                                        } catch (Exception e) {
                                            addError(
                                                    "? ?   "
                                                            + prev.getName()
                                                            + /*"; s="+prev.getSize()+"; t="+prev.getContentType()+"; l="+previews.length+*/ "; "
                                                            + StringAdapter.getStackTraceException(e));
                                        }
                                    } else {
                                        addError(" " + prev.getName()
                                                + "   ,      ?  3 .");
                                    }
                                }
                                i++;
                            }
                        }

                        if (newUser) {
                            userService.notifyAboutRegistration(email);
                        }
                    }

                } /* else {
                  addError("user:" + user.getId() + " " + user.getName());
                  }*/

            } else {
                addError(
                        "?  ??     email");
            }
        } else {
            addError("? ?  " + catId + "   .");
        }
    } else {
        addError("?  ");
    }
}

From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java

/**
 * Adds positive or negative influence to the start value, depending on the
 * quality of the master data objects.//from ww  w.j a v  a 2  s . c  o  m
 *
 * @param influencingMasterDataQuality list of influencing master data quality
 * @param higherIsBetter true if positiv influence shall be added, negative
 *                       influence otherwise
 * @param influence influence value to be added to the start value
 * @param startValue the start value
 * @return aggregated start value
 */
protected Float getValue(List<Float> influencingMasterDataQuality, boolean higherIsBetter, Float influence,
        Float startValue) {
    Float value = startValue;

    BigDecimal influenceCount = BigDecimal.ZERO;

    for (float quality : influencingMasterDataQuality) {
        // check quality value of the masterdata and adjust the result value
        influenceCount = influenceCount.add(BigDecimal.valueOf(quality));
    }

    if (influenceCount.compareTo(BigDecimal.ZERO) > 0) {
        influenceCount = influenceCount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // normalize the quality value
        influenceCount = influenceCount.divide(BigDecimal.valueOf(influencingMasterDataQuality.size()), 8,
                RoundingMode.HALF_UP);
        // subtract the avg normal, for standard config it is 0.5
        influenceCount = influenceCount.subtract(getAvgNormal());

        // if the normalized value is greater than the avg
        if (influenceCount.compareTo(BigDecimal.ZERO) == 1) {
            // calculate how much times the value is greater than the difference
            // between the avg normal value and the lowest good value
            influenceCount = influenceCount.divide(
                    BigDecimal.valueOf(getQualityGood()).subtract(getAvgNormal()).abs(), 0,
                    BigDecimal.ROUND_HALF_UP);
            // if the normalized value is LOWER than the avg
        } else if (influenceCount.compareTo(BigDecimal.ZERO) == -1) {
            // calculate how much times the value is smaller than the difference
            // between the avg normal value and the lowest normal value
            influenceCount = influenceCount.divide(
                    BigDecimal.valueOf(getQualityNormal()).subtract(getAvgNormal()).abs(), 0,
                    BigDecimal.ROUND_HALF_UP);
        }
    }
    influence *= influenceCount.intValue();

    if (higherIsBetter) {
        value += influence;
    } else {
        value -= influence;
    }
    return value;
}

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromDecimal(Type targetType, BigDecimal value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Decimal:
        return value;
    case Double:
        return new Double(value.doubleValue());
    case Float:
        return new Float(value.floatValue());
    case Int:/*  w ww . j ava  2s . co  m*/
        return new Integer(value.intValue());
    case Long:
        return new Long(value.longValue());
    case Integer:
        return value.toBigInteger();
    case String:
        // as per spec: ('+'|'-')? [0-9]* ('.'[0-9]*)? (('E'|'e') ('+'|'-')? [0-9]+)?
        /*
         *  [123,0]      "123"
         *   [-123,0]     "-123"
         *   [123,-1]     "1.23E+3"
         *   [123,-3]     "1.23E+5"
         *   [123,1]      "12.3"
         *   [123,5]      "0.00123"
         *   [123,10]     "1.23E-8"
         *   [-123,12]    "-1.23E-10"
         */
        return value.toString();
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Decimal, value);
    }
}