Example usage for java.lang Double equals

List of usage examples for java.lang Double equals

Introduction

In this page you can find the example usage for java.lang Double equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object against the specified object.

Usage

From source file:data.services.ParseBaseService.java

private void updateCars() throws SQLException, ClassNotFoundException, Exception {
    List<Car> carsForSaveList = new ArrayList();
    List<Car> carsForUpdateList = new ArrayList();
    List<Car> carList = carDao.getAllAsc();
    List<Long> actualQutoIdList = new ArrayList();
    HashMap<Long, Car> ourOldIdCarMap = new HashMap();
    for (Car car : carList) {
        ourOldIdCarMap.put(car.getCmqId(), car);
    }//from w w w  .  j  a  v a 2  s  . c om
    ResultSet resSet = getFromQutoBase(
            "SELECT c.*,cmc.title,cmsg.car_model_sub_id cms_id,cmsg.car_model_generation_id cmg_id,cmc.title completion_title,cmg.car_model_id model_id FROM car_modification c LEFT JOIN car_modification_completion cmc ON c.car_modification_completion_id=cmc.id LEFT JOIN car_model_sub_generation cmsg ON c.car_model_sub_generation_id=cmsg.id LEFT JOIN car_model_generation cmg ON cmsg.car_model_generation_id=cmg.id WHERE c.usage='ad_archive_catalog'");
    while (resSet.next()) {
        Long cmqId = resSet.getLong("id");
        actualQutoIdList.add(cmqId);

        Long modelQutoId = resSet.getLong("model_id");
        String completionTitle = StringAdapter.getString(resSet.getString("completion_title")).trim();
        Long cmsId = resSet.getLong("cms_id");
        Long cmgId = resSet.getLong("cmg_id");

        String title = StringAdapter.getString(resSet.getString("title")).trim();
        Long cmsgId = resSet.getLong("car_model_sub_generation_id");
        Long mediaId = resSet.getLong("media_id");
        String url = StringAdapter.getString(resSet.getString("url")).trim();
        Double price = resSet.getDouble("dt_price_min");

        Model model = new Model();
        model.setQutoId(modelQutoId);
        List<Model> supModelList = modelDao.find(model);
        if (!supModelList.isEmpty() && modelQutoId != 0) {
            model = supModelList.get(0);

            if (!ourOldIdCarMap.keySet().contains(cmqId)) {
                Car car = new Car();
                car.setCmqId(cmqId);
                car.setModel(model);
                ;
                car.setTitle(title);
                car.setMediaId(mediaId);
                car.setUrl(url);
                car.setCmPrice(price);
                car.setCmgqId(cmgId);
                car.setCmsgqId(cmsgId);
                car.setCmsqId(cmsId);
                car.setCompletionTitle(completionTitle);
                if (validate(car, " , TroubleQutoId=" + car.getCmqId() + "; ")) {
                    carsForSaveList.add(car);
                }
            } else {
                Car car = ourOldIdCarMap.get(cmqId);
                if (!cmgId.equals(car.getCmgqId()) || !title.equals(car.getTitle())
                        || !price.equals(car.getCmPrice()) || !url.equals(car.getUrl())
                        || !mediaId.equals(car.getMediaId())
                        || !completionTitle.equals(car.getCompletionTitle()) || !cmsgId.equals(car.getCmsgqId())
                        || !cmsId.equals(car.getCmsqId())) {
                    car.setCmqId(cmqId);
                    car.setModel(model);
                    ;
                    car.setTitle(title);
                    car.setMediaId(mediaId);
                    car.setUrl(url);
                    car.setCmPrice(price);
                    car.setCmgqId(cmgId);
                    car.setCmsgqId(cmsgId);
                    car.setCmsqId(cmsId);
                    car.setCompletionTitle(completionTitle);
                    ;
                    if (validate(car, " , TroubleQutoId=" + car.getCmqId() + "; ")) {
                        carsForUpdateList.add(car);
                    }
                }
            }
        }
    }
    int s = 0;
    int u = 0;
    int d = 0;
    for (Car car : carsForSaveList) {
        carService.create(car);
        s++;
    }
    for (Car car : carsForUpdateList) {
        carDao.update(car);
        u++;
    }
    for (Long qutoId : ourOldIdCarMap.keySet()) {
        if (!actualQutoIdList.contains(qutoId)) {
            d++;
            carService.delete(ourOldIdCarMap.get(qutoId));
        }
    }
    addError(" : " + s + " ? ?, " + u
            + " , " + d + " .");
}

From source file:org.apache.cocoon.acting.AbstractValidatorAction.java

/**
 * Validates nullability and default value for given parameter. If given
 * constraints are not null they are validated as well.
 *//*from www . j a  v  a 2  s .  c om*/
private ValidatorActionHelper validateDouble(String name, Configuration constraints, Configuration conf,
        Map params, boolean is_string, Object param) {

    boolean nullable = getNullable(conf, constraints);
    Double value = null;
    Double dflt = getDoubleValue(getDefault(conf, constraints), true);

    if (getLogger().isDebugEnabled())
        getLogger().debug("Validating double parameter " + name + " (encoded in a string: " + is_string + ")");
    try {
        value = getDoubleValue(param, is_string);
    } catch (Exception e) {
        // Unable to parse double
        return new ValidatorActionHelper(value, ValidatorActionResult.ERROR);
    }
    if (value == null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("double parameter " + name + " is null");
        if (!nullable) {
            return new ValidatorActionHelper(value, ValidatorActionResult.ISNULL);
        } else {
            return new ValidatorActionHelper(dflt);
        }
    }
    if (constraints != null) {
        Double eq = getAttributeAsDouble(constraints, "equals-to", null);
        String eqp = constraints.getAttribute("equals-to-param", "");

        Double min = getAttributeAsDouble(conf, "min", null);
        min = getAttributeAsDouble(constraints, "min", min);

        Double max = getAttributeAsDouble(conf, "max", null);
        max = getAttributeAsDouble(constraints, "max", max);

        // Validate whether param is equal to constant
        if (eq != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Double parameter " + name + " should be equal to " + eq);

            if (!value.equals(eq)) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
            }
        }

        // Validate whether param is equal to another param
        // FIXME: take default value of param being compared with into
        // account?
        if (!"".equals(eqp)) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Double parameter " + name + " should be equal to " + params.get(eqp));
            // Request parameter is stored as string.
            // Need to convert it beforehand.
            try {
                Double _eqp = new Double(Double.parseDouble((String) params.get(eqp)));
                if (!value.equals(_eqp)) {
                    if (getLogger().isDebugEnabled())
                        getLogger().debug("and it is not");
                    return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
                }
            } catch (NumberFormatException nfe) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Double parameter " + name + ": " + eqp + " is no double", nfe);
                return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
            }
        }

        // Validate wheter param is at least min
        if (min != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Double parameter " + name + " should be at least " + min);
            if (0 > value.compareTo(min)) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.TOOSMALL);
            }
        }

        // Validate wheter param is at most max
        if (max != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Double parameter " + name + " should be at most " + max);
            if (0 < value.compareTo(max)) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.TOOLARGE);
            }
        }
    }
    return new ValidatorActionHelper(value);
}

From source file:com.viettel.logistic.wms.service.StockGoodsTotalServiceImpl.java

/**
 * Ham dieu chinh trang thai/serial/so luong hang hoa theo yu cau
 *
 * @param changeOrder/*www .  j  a v a  2s . c o m*/
 * @param lstChangeGoods
 * @return
 */
@Override
public ResultKTTS changeStockGoods(ChangeOrder changeOrder, List<ChangeGoods> lstChangeGoods) {
    //day thong tin ra LOG
    System.out.println("START OUTPUT DATA CHANGE GOODS: " + changeOrder.getOrderCode());
    System.out.println(changeOrder.toString());
    for (ChangeGoods changeGods : lstChangeGoods) {
        System.out.println(changeGods.toString());
    }
    System.out.println("END OUTPUT DATA CHANGE GOODS: " + changeOrder.getOrderCode());
    //
    ResultKTTS resultKTTS = new ResultKTTS();
    if (DataUtil.isNullObject(changeOrder)) {
        resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
        resultKTTS.setReason(BundelUtils.getkey("infor.changeOrder.zero"));
        return resultKTTS;
    }
    resultKTTS.setOrderCode(changeOrder.getOrderCode());
    List<ConditionBean> lstConditionBeanSearch = new ArrayList<>();
    //danh sach trang thai hang hoa hop le
    List<String> lstGoodsState = new ArrayList();
    lstGoodsState.add("1");
    lstGoodsState.add("2");
    //danh sach lich su can luu lai
    List<HistoryChangeGoodsDTO> lstHistoryChangeGoodsDTOs = new ArrayList();
    List<ChangeGoods> lstChangeGoodsFilter = new ArrayList();
    List<String> lstGoodsCode = new ArrayList();
    Map<String, GoodsDTO> mapGoodsDTO = new HashMap<>();
    Map<String, GoodsDTO> mapGoodsDTOById = new HashMap<>();
    StockDTO stockDTOInfor = new StockDTO();
    List<GoodsDTO> lstGoodsDTO = new ArrayList();
    List<ConditionBean> lstConditionBean = new ArrayList<>();
    List<ChangeGoods> lstErrList = new ArrayList();
    String custId = "";
    String custName = "";
    SynLogDTO synLogDTO = new SynLogDTO();
    synLogDTO.setAppCode("WMS_CHANGE_STOCK_GOODS");
    try {
        //kiem tra thong tin yeu cau dau vao
        StringBuilder sbError = new StringBuilder();
        StringBuilder contentError = new StringBuilder();
        if (DataUtil.isStringNullOrEmpty(changeOrder.getOrderCode())) {//thieu thong tin ma yeu cau
            sbError.append(", ");
            sbError.append(BundelUtils.getkey("infor.orders.orderCode.zero"));
            System.out.println("Thieu thong tin ma yeu cau");
        } else {
            synLogDTO.setKey(changeOrder.getOrderCode());
        }
        if (DataUtil.isStringNullOrEmpty(changeOrder.getStockCode())) {//thieu thong tin kho
            sbError.append(", ");
            sbError.append(BundelUtils.getkey("infor.orders.stockCode.zero"));
            System.out.println("Thieu thong tin ma kho");
        }
        if (DataUtil.isStringNullOrEmpty(changeOrder.getExpectedDate())) {//thieu thong tin ngay gui yc
            sbError.append(", ");
            sbError.append(BundelUtils.getkey("infor.orders.expectedDate.zero"));
            System.out.println("Thieu thong tin ngay gui yeu cau");
        }
        if (DataUtil.isStringNullOrEmpty(changeOrder.getOrderUserName())) {//thieu thong tin nguoi gui yc
            sbError.append(", ");
            sbError.append(BundelUtils.getkey("infor.orders.orderUserName.zero"));
            System.out.println("Thieu thong tin nguoi gui yeu cau");
        }
        if (!DataUtil.isStringNullOrEmpty(sbError.toString())) {
            contentError.append(BundelUtils.getkey("infor.orders.zero"));
            contentError.append(":");
            contentError.append(sbError.toString().replaceFirst(",", ""));
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(contentError.toString());
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, BundelUtils.getkey("infor.orders.zero"));
            return resultKTTS;
        }
        // kiem tra la duy nhat tren he thong
        boolean iCheckOrder = checkOrderCodeInTrans(changeOrder.getOrderCode());
        if (!iCheckOrder) {
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(BundelUtils.getkey("notifi.orderCode.exists"));
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, BundelUtils.getkey("notifi.orderCode.exists"));
            return resultKTTS;
        }
        //map 2 kho ben KTTS vs Logistics
        MapStockDTO mapStockDTO = new MapStockDTO();
        mapStockDTO.setStockCode(changeOrder.getStockCode());
        mapStockDTO.setType("1");
        List<MapStockDTO> lstMapStockDTOs = WSMapStock.getListMapStockDTO(mapStockDTO, 0, Integer.MAX_VALUE, "",
                "");
        if (!DataUtil.isListNullOrEmpty(lstMapStockDTOs)) {
            changeOrder.setStockCode(lstMapStockDTOs.get(0).getLogStockCode());
        } else {
            contentError.append(BundelUtils.getkey("notifi.stock.notsearch"));
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(contentError.toString());
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, BundelUtils.getkey("notifi.stock.notsearch"));
            return resultKTTS;
        }
        //tim kiem thong tin khach hang
        if (!DataUtil.isStringNullOrEmpty(changeOrder.getCustCode())) {
            lstConditionBeanSearch.clear();
            lstConditionBeanSearch
                    .add(new ConditionBean("status", ParamUtils.NAME_EQUAL, "0", ParamUtils.TYPE_STRING));
            lstConditionBeanSearch.add(new ConditionBean("code", ParamUtils.NAME_EQUAL,
                    changeOrder.getCustCode(), ParamUtils.TYPE_STRING));
            List<CustomerDTO> lstTempCus = WSCustomer.getListCustomerByCondition(lstConditionBeanSearch, 0,
                    Integer.MAX_VALUE, "", "");
            if (!DataUtil.isListNullOrEmpty(lstTempCus)) {
                custId = lstTempCus.get(0).getCustId();
                custName = lstTempCus.get(0).getName();
                changeOrder.setCustId(custId);
                changeOrder.setCustName(custName);
            }
        }
        //kiem tra danh sach hang hoa dau vao
        if (DataUtil.isListNullOrEmpty(lstChangeGoods)) {
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(BundelUtils.getkey("infor.listGoods.zero"));
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, BundelUtils.getkey("infor.listGoods.zero"));
            return resultKTTS;
        }
        for (ChangeGoods change : lstChangeGoods) {
            if (DataUtil.isStringNullOrEmpty(change.getOldGoodsCode())) {//kiem tra ma hang hoa
                System.out.println("Thieu thong tin ma hang hoa");
                addInforErrorForList(lstErrList, change, "infor.goodscode.zero");
                continue;
            }
            if (DataUtil.isStringNullOrEmpty(change.getOldState())) {//kiem tra trang thai
                System.out.println("Thieu thong tin trang thai");
                addInforErrorForList(lstErrList, change, "infor.goodsstate.zero");
                continue;
            } else {
                if (!lstGoodsState.contains(change.getOldState())) {
                    System.out.println("Sai thong tin tran thai");
                    addInforErrorForList(lstErrList, change, "infor.goodsstate.error");
                    continue;
                }
            }
            if (DataUtil.isStringNullOrEmpty(change.getAmount())) {//kiem tra so luong
                System.out.println("Thieu thong tin so luong");
                addInforErrorForList(lstErrList, change, "infor.amount.zero");
                continue;
            } else {
                change.setAmount(DataUtil.getQuantity(change.getAmount()));
                if ("0".equals(change.getAmount())) {//neu amount = 0 thi bo qua hang hoa(do hang hoa khong thay doi)
                    if (!lstGoodsCode.contains(change.getOldGoodsCode())) {
                        lstGoodsCode.add(change.getOldGoodsCode());
                    }
                    if (!DataUtil.isStringNullOrEmpty(change.getNewGoodsCode())) {
                        if (!lstGoodsCode.contains(change.getNewGoodsCode())) {
                            lstGoodsCode.add(change.getNewGoodsCode());
                        }
                    }
                    continue;
                }
            }
            if (!DataUtil.isStringNullOrEmpty(change.getChangeType())) {
                if (change.getChangeType().equals("1")) {//dieu chinh trang thai
                    if (DataUtil.isStringNullOrEmpty(change.getNewState())) {//kiem tra trang thai hang hoa
                        addInforErrorForList(lstErrList, change, "infor.goodsstate.zero");
                        System.out.println("Thieu thong tin trang thai moi");
                        continue;
                    }
                    Double amount = Double.parseDouble(change.getAmount());
                    if (amount < 0) {//neu amount nho hon 0 thi hang hoa chuyen trang thai tu hong => tot
                        amount = amount * (-1);
                        change.setAmount(DataUtil.getQuantity(amount.toString()));
                        String oldState = change.getOldState();
                        String newState = change.getNewState();
                        change.setOldState(newState);
                        change.setNewState(oldState);
                    }
                } else if (change.getChangeType().equals("2")) {//dieu chinh serial_1 =>serial_2
                    if (!DataUtil.isStringNullOrEmpty(change.getOldFromSerial())
                            && !DataUtil.isStringNullOrEmpty(change.getOldToSerial())
                            && !DataUtil.isStringNullOrEmpty(change.getNewFromSerial())
                            && !DataUtil.isStringNullOrEmpty(change.getNewToSerial())) {
                        //Kiem tra do dai serial neu >19 thi cat do kieu Long chi co do dai toi da 19
                        Long oldAmount = amountInSerial(change.getOldFromSerial(), change.getOldToSerial());
                        Long newAmount = amountInSerial(change.getNewFromSerial(), change.getNewToSerial());
                        Long amount = Long.parseLong(DataUtil.getQuantity(change.getAmount()));
                        if (!amount.equals(oldAmount) || !amount.equals(newAmount)) {
                            addInforErrorForList(lstErrList, change, "infor.amountEqualSerial.zero");
                            System.out.println("Sai thong tin amount != oldAmount != newAmuont");
                            continue;
                        }
                    } else {
                        addInforErrorForList(lstErrList, change, "infor.serial.zero");
                        System.out.println("Thieu thong tin serial");
                        continue;
                    }
                } else if (change.getChangeType().equals("3")) {//dieu chinh ma hang hoa
                    if (DataUtil.isStringNullOrEmpty(change.getNewGoodsCode())) {
                        addInforErrorForList(lstErrList, change, "infor.goodscode.zero");
                        System.out.println("Thieu thong tin ma hang hoa moi");
                        continue;
                    }
                    if (!lstGoodsCode.contains(change.getNewGoodsCode())) {
                        lstGoodsCode.add(change.getNewGoodsCode());
                    }
                } else if (change.getChangeType().equals("4")) {//dieu chinh ca ma hang hoa va trang thai
                    if (DataUtil.isStringNullOrEmpty(change.getNewState())) {
                        addInforErrorForList(lstErrList, change, "infor.goodsstate.zero");
                        System.out.println("Thieu thong tin trang thai moi");
                        continue;
                    }
                    if (DataUtil.isStringNullOrEmpty(change.getNewGoodsCode())) {
                        addInforErrorForList(lstErrList, change, "infor.goodscode.zero");
                        System.out.println("Thieu thong tin ma hang hoa moi");
                        continue;
                    }
                    if (!lstGoodsCode.contains(change.getNewGoodsCode())) {
                        lstGoodsCode.add(change.getNewGoodsCode());
                    }
                } else {//ma dieu chuyen khong dung
                    System.out.println("Ma dieu chuyen khong dung");
                    addInforErrorForList(lstErrList, change, "infor.changeType.error");
                    continue;
                }
            } else {//thieu thong tin dieu chuyen
                addInforErrorForList(lstErrList, change, "infor.changeType.zero");
                System.out.println("Thieu thong tin loai dieu chuyen");
                continue;
            }
            if (!lstGoodsCode.contains(change.getOldGoodsCode())) {
                lstGoodsCode.add(change.getOldGoodsCode());
            }
            lstChangeGoodsFilter.add(change);
        }
        if (!DataUtil.isListNullOrEmpty(lstErrList)) {
            StringBuilder messReason = new StringBuilder();
            for (ChangeGoods goodsError : lstErrList) {
                if (!DataUtil.isStringNullOrEmpty(goodsError.getOldGoodsName())) {
                    messReason.append(BundelUtils.getkey("change.goodsCode"));
                    messReason.append(" ");
                    messReason.append(goodsError.getOldGoodsCode());
                    messReason.append(": ");
                    messReason.append(goodsError.getInforError());
                    messReason.append("; ");
                }
            }
            if (DataUtil.isStringNullOrEmpty(messReason)) {
                messReason.append(BundelUtils.getkey("infor.goodscode.zero"));
            }
            //resultKTTS.setLstChangeGoods(lstErrList);
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(BundelUtils.getkey("infor.inforError") + ". " + messReason.toString());
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL,
                    BundelUtils.getkey("infor.inforError") + messReason.toString());
            return resultKTTS;
        }
        //lay danh sach hang hoa va dua vao map
        lstGoodsDTO = getListGoods(lstGoodsCode, custId);
        mapGoodsDTO = putGoodsToMap(lstGoodsDTO);
        mapGoodsDTOById = putGoodsToMapById(lstGoodsDTO);
        //map danh sach kho
        if (!DataUtil.isStringNullOrEmpty(changeOrder.getStockCode())) {
            lstConditionBean.clear();
            lstConditionBean.add(new ConditionBean("code", ParamUtils.OP_IN, changeOrder.getStockCode(),
                    ParamUtils.TYPE_STRING));
            List<StockDTO> lstTemp = stockBusiness.searchByConditionBean(lstConditionBean, 0, Integer.MAX_VALUE,
                    "", "code");
            if (!DataUtil.isListNullOrEmpty(lstTemp)) {
                stockDTOInfor = (StockDTO) DataUtil.cloneObject(lstTemp.get(0));
                changeOrder.setStockId(stockDTOInfor.getStockId());
                changeOrder.setStockName(stockDTOInfor.getName());
                //
                StaffStockDTO staffStockDTO = new StaffStockDTO();
                staffStockDTO.setStatus("1");
                staffStockDTO.setStockId(stockDTOInfor.getStockId());
                List<StaffStockDTO> lstStaffStockDTO = WSStaffStock.getListStaffStockDTO(staffStockDTO, 0,
                        Integer.MAX_VALUE, "", "id");
                //loc lay danh sach hang hoa theo kho
                fillterMapStaffGoodsByStock(lstStaffStockDTO);
            }
        }
        //tao giao dich, chi tiet giao dich, chi tiet serial giao dich
        boolean isError = initGoodsTransferTrans(lstChangeGoodsFilter, mapGoodsDTO, changeOrder);
        if (!isError) {
            StringBuilder messReason = new StringBuilder();
            for (ChangeGoods goodsError : lstChangeGoodsError) {
                messReason.append(BundelUtils.getkey("change.goodsCode"));
                messReason.append(" ");
                messReason.append(goodsError.getOldGoodsCode());
                messReason.append(": ");
                messReason.append(goodsError.getInforError());
                messReason.append("; ");
            }
            resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
            resultKTTS.setReason(BundelUtils.getkey("infor.inforError") + ". " + messReason);
            insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL,
                    BundelUtils.getkey("infor.inforError") + ". " + messReason);
            return resultKTTS;
        }
        //
        ResultDTO result = new ResultDTO();
        /*
         Map giua hang da xuat -> danh sach stock_goods cua hang do
         */
        if (!DataUtil.isListNullOrEmpty(lstTransExportDetail)) {
            result = stockExportService.goodsTransferSynsKTTS(transExport, transImport, lstTransExportDetail,
                    lstTransImportDetail, lstTransExportSerial, lstTransImportSerial, changeOrder,
                    lstChangeGoods, mapGoodsDTO, lstMapStaffGoodsDTOs);
            if (!result.getMessage().equals(ParamUtils.SUCCESS)) {
                StringBuilder sb1 = new StringBuilder();
                String sb = "";
                String addInfor = "";
                if ("NotEnoughAmount".equals(result.getKey())) {
                    BundelUtils.getkey("NotEnoughAmount");
                    try {
                        if (!DataUtil.isStringNullOrEmpty(result.getFromSerial())
                                && !DataUtil.isStringNullOrEmpty(result.getToSerial())) {
                            sb1.append(BundelUtils.getkey("notitfi.trans.NotEnoughAmount"));
                            sb = sb1.toString();
                            sb = sb.replace("@fromSerial", result.getFromSerial());
                            sb = sb.replace("@toSerial", result.getToSerial());
                        } else {
                            String message = result.getMessage();
                            if (!DataUtil.isStringNullOrEmpty(message)) {
                                message = message.substring(0, message.indexOf(","));
                            }
                            GoodsDTO gdto = mapGoodsDTOById.get(message);
                            sb = BundelUtils.getkey("notitfi.trans.NotEnoughAmount2");
                            sb = sb.replace("@goodCode", gdto.getCode());
                        }
                    } catch (Exception e) {
                        sb = BundelUtils.getkey("notitfi.trans.NotEnoughAmount3");
                    }
                } else if ("INSERT_ERROR_HISTORY".equals(result.getKey())) {
                    sb = BundelUtils.getkey("notifi.insert.history");
                    addInfor = BundelUtils.getkey("notifi.addInfor.errorHistory");
                } else if ("INSERT_ERROR_MESSAGES".equals(result.getKey())) {
                    sb = BundelUtils.getkey("notifi.insert.history");
                    addInfor = BundelUtils.getkey("notifi.addInfor.errorMessage");
                }
                resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
                String mess = BundelUtils.getkey("changeGoods.error.trans") + sb;
                resultKTTS.setReason(BundelUtils.getkey("changeGoods.error.trans") + ". " + sb);
                insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, mess + ". " + addInfor);
                return resultKTTS;
            }
        } else {
            lstHistoryChangeGoodsDTOs = convertFromHistoryChangeGoods(changeOrder, lstChangeGoods, mapGoodsDTO);
            String messInsert = historyChangeGoodsBusiness.insertList(lstHistoryChangeGoodsDTOs);
            if (!ParamUtils.SUCCESS.equals(messInsert)) {
                insertSynLog(synLogDTO, ParamUtils.SYNC.SUCCESS, BundelUtils.getkey("notifi.insert.history"));
                resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
                return resultKTTS;
            }
            result.setKey(BundelUtils.getkey("notifi.trans.empty"));
        }
        StringBuilder mesSucc = new StringBuilder();
        mesSucc.append(BundelUtils.getkey("changeStockGoods.success"));
        mesSucc.append(result.getKey() == null ? "" : result.getKey());
        insertSynLog(synLogDTO, ParamUtils.SYNC.SUCCESS, mesSucc.toString());
        //-> commit
        resultKTTS.setStatus(ParamUtils.SYNC.SUCCESS);
        return resultKTTS;
    } catch (Exception e) {
        //e.printStackTrace();
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, e);
        resultKTTS.setStatus(ParamUtils.SYNC.FAIL);
        resultKTTS.setReason(BundelUtils.getkey(ParamUtils.SYSTEM_OR_DATA_ERROR));
        insertSynLog(synLogDTO, ParamUtils.SYNC.FAIL, BundelUtils.getkey(ParamUtils.SYSTEM_OR_DATA_ERROR));
        return resultKTTS;
    } finally {
    }
}

From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java

public Double getEctsCredits() {
    Double ects = null;
    for (CurricularCourse curricularCourse : getAssociatedCurricularCoursesSet()) {
        if (curricularCourse.isActive(getExecutionPeriod())) {
            if (ects == null) {
                ects = curricularCourse.getEctsCredits();
            } else if (!ects.equals(curricularCourse.getEctsCredits())) {
                throw new DomainException("error.invalid.ectsCredits");
            }//from w  w  w  . j av  a  2 s .  c  o m
        }
    }
    return ects;
}

From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java

private void update(RealTimeStockMonitor monitor, final java.util.List<Stock> stocks) {
    final BuyPortfolioTreeTableModelEx buyPortfolioTreeTableModel = (BuyPortfolioTreeTableModelEx) buyTreeTable
            .getTreeTableModel();//from w w  w.j a va2 s.  co m
    final SellPortfolioTreeTableModelEx sellPortfolioTreeTableModel = (SellPortfolioTreeTableModelEx) sellTreeTable
            .getTreeTableModel();

    final Map<Code, Double> stockPrices = this.portfolioRealTimeInfo.stockPrices;
    final Map<Code, Currency> currencies = this.portfolioRealTimeInfo.currencies;

    final Set<Code> buyCodes = this.getBuyCodes();
    final Set<Code> sellCodes = this.getSellCodes();

    for (Stock stock : stocks) {
        final Code code = stock.code;
        final Currency currency = stock.getCurrency();

        boolean needBuyRefresh = false;
        boolean needSellRefresh = false;

        if (buyCodes.contains(code)) {
            final Double price = getNonZeroPriceIfPossible(stock);
            final Double oldPrice = stockPrices.put(code, price);
            if (false == price.equals(oldPrice)) {
                this.portfolioRealTimeInfo.stockPricesDirty = true;
                needBuyRefresh = true;
            }

            // ConcurrentHashMap doesn't support null value.
            // http://stackoverflow.com/questions/698638/why-does-concurrenthashmap-prevent-null-keys-and-values
            if (currency != null) {
                final Currency oldCurrency = currencies.put(code, currency);
                if (false == currency.equals(oldCurrency)) {
                    this.portfolioRealTimeInfo.currenciesDirty = true;
                    needBuyRefresh = true;
                    // Should sell portfolio refresh too, since we have new currency info?
                    if (sellCodes.contains(code)) {
                        needSellRefresh = true;
                    }
                }
            }
        } else if (sellCodes.contains(code)) {
            if (currency != null) {
                final Currency oldCurrency = currencies.put(code, currency);
                if (false == currency.equals(oldCurrency)) {
                    this.portfolioRealTimeInfo.currenciesDirty = true;
                    needSellRefresh = true;
                }

                // Thread safety purpose.
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Set<Code> buyCodes = PortfolioManagementJPanel.this.getBuyCodes();
                        if (false == buyCodes.contains(code)) {
                            // We can remove this code safely.
                            PortfolioManagementJPanel.this.realTimeStockMonitor.removeStockCode(code);
                        }
                    }
                });
            } else {
                // Should I do something here? Or, should I keep retrying
                // without removing code from 
            }

        } else {
            // Thread safety purpose.
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Set<Code> codes = PortfolioManagementJPanel.this.getCodes();
                    if (false == codes.contains(code)) {
                        // We can remove this code safely.
                        PortfolioManagementJPanel.this.realTimeStockMonitor.removeStockCode(code);
                    }
                }
            });

            continue;
        }

        if (needBuyRefresh) {
            // Because we have new price & new currency.
            buyPortfolioTreeTableModel.refresh(code);
        }

        if (needSellRefresh) {
            // Because we have new currency.
            sellPortfolioTreeTableModel.refresh(code);
        }

        // Update currency monitor as well.
        ExchangeRateMonitor _exchangeRateMonitor = this.exchangeRateMonitor;
        if (currency != null && _exchangeRateMonitor != null) {
            final Currency localCurrency = org.yccheok.jstock.portfolio.Utils.getLocalCurrency();
            if (localCurrency != null) {
                if (false == currency.equals(localCurrency)) {
                    CurrencyPair currencyPair = CurrencyPair.create(currency, localCurrency);
                    if (_exchangeRateMonitor.addCurrencyPair(currencyPair)) {
                        _exchangeRateMonitor.startNewThreadsIfNecessary();
                        _exchangeRateMonitor.refresh();
                    }
                }
            }
        }
    } // for

    updateWealthHeader();

    // Update status bar with current time string.
    this.portfolioRealTimeInfo.stockPricesTimestamp = System.currentTimeMillis();

    JStock.instance().updateStatusBarWithLastUpdateDateMessageIfPossible();
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

public void getResultData(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w w  . j a v  a2 s.  co m*/
    LOG.debug("getResultData");
    List<String> errors = new ArrayList<String>();
    try {
        List<AutoProcessingInformation> autoProcList = new ArrayList<AutoProcessingInformation>();
        BreadCrumbsForm bar = BreadCrumbsForm.getIt(request);

        boolean displayOutputParam = false;
        boolean displayDenzoContent = false;

        // booleans to fix which tab will be selected by default
        boolean isEDNACharacterisation = false;
        boolean isAutoprocessing = false;

        String rMerge = (String) request.getSession().getAttribute(Constants.RSYMM);
        String iSigma = (String) request.getSession().getAttribute(Constants.ISIGMA);

        double rMerge_d = DEFAULT_RMERGE;
        double iSigma_d = DEFAULT_ISIGMA;

        int nbRemoved = 0;

        try {
            if (rMerge != null && !rMerge.equals("undefined") && !rMerge.equals(""))
                rMerge_d = Double.parseDouble(rMerge);
            if (iSigma != null && !iSigma.equals("undefined") && !iSigma.equals(""))
                iSigma_d = Double.parseDouble(iSigma);
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        Integer dataCollectionId = null;
        List<List<AutoProcStatus3VO>> interruptedAutoProcEvents1 = new ArrayList<List<AutoProcStatus3VO>>();
        DataCollection3VO dc = null;
        // Just one of them could be visible on the bar
        if (bar.getSelectedDataCollection() != null) {
            dataCollectionId = bar.getSelectedDataCollection().getDataCollectionId();
        }
        if (dataCollectionId == null && request.getParameter(Constants.DATA_COLLECTION_ID) != null)
            dataCollectionId = new Integer(request.getParameter(Constants.DATA_COLLECTION_ID));
        if (dataCollectionId == null && request.getSession().getAttribute(Constants.DATA_COLLECTION_ID) != null)
            dataCollectionId = new Integer(
                    (Integer) request.getSession().getAttribute(Constants.DATA_COLLECTION_ID));

        if (dataCollectionId == null) {
            errors.add("dataCollectionId is null");
            HashMap<String, Object> data = new HashMap<String, Object>();
            data.put("errors", errors);
            // data => Gson
            GSonUtils.sendToJs(response, data, "dd-MM-yyyy HH:mm:ss");
            return;
        }
        dc = dataCollectionService.findByPk(dataCollectionId, false, true);

        // interrupted autoProc
        if (dc != null) {
            List<AutoProcIntegration3VO> autoProcIntegrationList = dc.getAutoProcIntegrationsList();
            if (autoProcIntegrationList != null) {
                for (Iterator<AutoProcIntegration3VO> au = autoProcIntegrationList.iterator(); au.hasNext();) {
                    AutoProcIntegration3VO autoProcIntegration = au.next();
                    if (autoProcIntegration.getAutoProcProgramVO() == null
                            && autoProcIntegration.getAutoProcStatusList() != null) {
                        List<AutoProcStatus3VO> events = autoProcIntegration.getAutoProcStatusList();
                        interruptedAutoProcEvents1.add(events);
                    }
                }
            }
        }

        for (int i = 0; i < 2; i++) {
            boolean anomalous = (i > 0);
            List<AutoProc3VO> autoProcsAnomalous = apService
                    .findByAnomalousDataCollectionIdAndOrderBySpaceGroupNumber(dataCollectionId, anomalous);
            if (autoProcsAnomalous != null) {
                nbRemoved = 0;
                LOG.debug("..nbAutoProc " + anomalous + " found before rMerge =" + autoProcsAnomalous.size());
                for (Iterator<AutoProc3VO> a = autoProcsAnomalous.iterator(); a.hasNext();) {
                    AutoProc3VO apv = a.next();

                    List<AutoProcScalingStatistics3VO> scalingStatistics = apssService
                            .findByAutoProcId(apv.getAutoProcId(), "innerShell");
                    boolean existsUnderRmergeAndOverSigma = false;

                    for (Iterator<AutoProcScalingStatistics3VO> j = scalingStatistics.iterator(); j
                            .hasNext();) {
                        AutoProcScalingStatistics3VO stats = j.next();
                        if (stats.getRmerge() != null && stats.getRmerge() < rMerge_d
                                && stats.getMeanIoverSigI() > iSigma_d)
                            existsUnderRmergeAndOverSigma = true;
                    }

                    if (!existsUnderRmergeAndOverSigma) {
                        a.remove();
                        nbRemoved = nbRemoved + 1;
                    }
                }
                LOG.debug("..nbAutoProc " + anomalous + " found=" + autoProcsAnomalous.size());
                for (Iterator<AutoProc3VO> iterator = autoProcsAnomalous.iterator(); iterator.hasNext();) {
                    AutoProc3VO o = iterator.next();
                    String cmdLine = "";
                    if (o.getAutoProcProgramVO() != null
                            && o.getAutoProcProgramVO().getProcessingPrograms() != null) {
                        cmdLine = o.getAutoProcProgramVO().getProcessingPrograms();
                    }
                    float refinedCellA = ((float) ((int) (o.getRefinedCellA() * 10))) / 10; // round to 1 dp
                    float refinedCellB = ((float) ((int) (o.getRefinedCellB() * 10))) / 10; // round to 1 dp
                    float refinedCellC = ((float) ((int) (o.getRefinedCellC() * 10))) / 10; // round to 1 dp
                    float refinedCellAlpha = ((float) ((int) (o.getRefinedCellAlpha() * 10))) / 10; // round to 1 dp
                    float refinedCellBeta = ((float) ((int) (o.getRefinedCellBeta() * 10))) / 10; // round to 1 dp
                    float refinedCellGamma = ((float) ((int) (o.getRefinedCellGamma() * 10))) / 10; // round to 1 dp

                    String anoTxt = "OFF (Friedel pairs merged)"; // false
                    if (anomalous) {
                        anoTxt = "ON (Friedel pairs unmerged)"; // true
                    }
                    // String anomalousS = anomalous+"= "+anoTxt;
                    AutoProcessingInformation info = new AutoProcessingInformation(o.getAutoProcId(), cmdLine,
                            o.getSpaceGroup(), anoTxt, refinedCellA, refinedCellB, refinedCellC,
                            refinedCellAlpha, refinedCellBeta, refinedCellGamma);
                    autoProcList.add(info);
                }
            }

        }
        Integer autoProcIdSelected = (Integer) request.getSession().getAttribute("lastAutoProcIdSelected");
        // check if autoProcIdSelected is in the list
        boolean idExists = false;
        if (autoProcIdSelected != null) {
            for (Iterator<AutoProcessingInformation> iterator = autoProcList.iterator(); iterator.hasNext();) {
                AutoProcessingInformation info = iterator.next();
                if (info.getAutoProcId().equals(autoProcIdSelected)) {
                    idExists = true;
                    break;
                }
            }
        }
        if (!idExists) {
            autoProcIdSelected = null;
        }

        List<DataCollection3VO> listLastCollectVO = new ArrayList<DataCollection3VO>();
        if (dc != null)
            listLastCollectVO.add(dc);
        AutoProcShellWrapper wrapper = ViewDataCollectionAction.getAutoProcStatistics(listLastCollectVO,
                rMerge_d, iSigma_d);
        int dcIndex = 0;
        // is autoproc ?
        List<AutoProc3VO> autoProcs = apService.findByDataCollectionId(dataCollectionId);
        if (autoProcs != null && autoProcs.size() > 0)
            isAutoprocessing = true;

        String beamLineName = "";
        String proposal = "";
        String proteinAcronym = "";
        String pdbFileName = "";
        String experimentType = "";
        if (dc != null) {
            beamLineName = dc.getDataCollectionGroupVO().getSessionVO().getBeamlineName();
            proposal = dc.getDataCollectionGroupVO().getSessionVO().getProposalVO().getCode()
                    + dc.getDataCollectionGroupVO().getSessionVO().getProposalVO().getNumber();

            BLSample3VO sample = dc.getDataCollectionGroupVO().getBlSampleVO();
            if (sample != null && sample.getCrystalVO() != null && sample.getCrystalVO().getProteinVO() != null)
                proteinAcronym = sample.getCrystalVO().getProteinVO().getAcronym();

            if (sample != null && sample.getCrystalVO() != null && sample.getCrystalVO().hasPdbFile()) {
                pdbFileName = sample.getCrystalVO().getPdbFileName();
            }
            experimentType = dc.getDataCollectionGroupVO().getExperimentType();
        }

        AutoProc3VO autoProc = null;
        AutoProcScalingStatistics3VO autoProcStatisticsOverall = null;
        AutoProcScalingStatistics3VO autoProcStatisticsInner = null;
        AutoProcScalingStatistics3VO autoProcStatisticsOuter = null;
        ScreeningOutputLattice3VO lattice = null;
        ScreeningOutput3VO screeningOutput = null;

        String snapshotFullPath = "";
        boolean hasSnapshot = false;
        Screening3VO[] tabScreening = null;
        if (dc != null) {
            snapshotFullPath = dc.getXtalSnapshotFullPath1();
            snapshotFullPath = PathUtils.FitPathToOS(snapshotFullPath);

            if (snapshotFullPath != null)
                hasSnapshot = (new File(snapshotFullPath)).exists();

            autoProc = wrapper.getAutoProcs()[dcIndex];
            autoProcStatisticsOverall = wrapper.getScalingStatsOverall()[dcIndex];
            autoProcStatisticsInner = wrapper.getScalingStatsInner()[dcIndex];
            autoProcStatisticsOuter = wrapper.getScalingStatsOuter()[dcIndex];
            DataCollectionGroup3VO dcGroup = dataCollectionGroupService
                    .findByPk(dc.getDataCollectionGroupVOId(), false, true);
            tabScreening = dcGroup.getScreeningsTab();
        }

        if (tabScreening != null && tabScreening.length > 0) {
            displayOutputParam = true;// there is at least 1 screening so we display the output params
            Screening3VO screeningVO = tabScreening[0];
            ScreeningOutput3VO[] screeningOutputTab = screeningVO.getScreeningOutputsTab();
            if (screeningOutputTab != null && screeningOutputTab.length > 0) {
                if (screeningOutputTab[0].getScreeningOutputLatticesTab() != null
                        && screeningOutputTab[0].getScreeningOutputLatticesTab().length > 0) {
                    lattice = screeningOutputTab[0].getScreeningOutputLatticesTab()[0];
                }
                screeningOutput = screeningOutputTab[0];
            }
        }

        String autoprocessingStatus = "";
        String autoprocessingStep = "";
        if (wrapper != null && wrapper.getAutoProcs() != null && wrapper.getAutoProcs().length > dcIndex) {
            AutoProcIntegration3VO autoProcIntegration = wrapper.getAutoProcIntegrations()[dcIndex];
            if (autoProcIntegration != null) {
                List<AutoProcStatus3VO> autoProcEvents = autoProcIntegration.getAutoProcStatusList();
                if (autoProcEvents != null && autoProcEvents.size() > 0) {
                    AutoProcStatus3VO st = autoProcEvents.get(autoProcEvents.size() - 1);
                    autoprocessingStatus = st.getStatus();
                    autoprocessingStep = st.getStep();
                }
            }
        }

        boolean hasAutoProcAttachment = false;
        if (wrapper != null && wrapper.getAutoProcs() != null) {

            for (int a = 0; a < autoProcs.size(); a++) {
                Integer autoProcProgramId = autoProcs.get(a).getAutoProcProgramVOId();
                if (autoProcProgramId != null) {
                    List<AutoProcProgramAttachment3VO> attachments = appService
                            .findByPk(autoProcProgramId, true).getAttachmentListVOs();
                    if (attachments != null && attachments.size() > 0) {
                        hasAutoProcAttachment = true;
                        break;
                    }
                }
            }
        }

        DataCollectionBean dataCollection = null;
        if (dc != null) {
            dataCollection = new DataCollectionBean(dc, beamLineName, proposal, proteinAcronym, pdbFileName,
                    experimentType, hasSnapshot, autoProc, autoProcStatisticsOverall, autoProcStatisticsInner,
                    autoProcStatisticsOuter, screeningOutput, lattice, autoprocessingStatus, autoprocessingStep,
                    hasAutoProcAttachment);
        }

        BeamLineSetup3VO beamline = null;
        Session3VO session = null;
        Detector3VO detector = null;

        String fullDenzoPath = null;
        boolean DenzonContentPresent = false;

        if (dc != null) {
            // beamline setup
            beamline = dc.getDataCollectionGroupVO().getSessionVO().getBeamLineSetupVO();
            // Session
            session = dc.getDataCollectionGroupVO().getSessionVO();
            // Detector
            detector = dc.getDetectorVO();

            // energy
            DecimalFormat df3 = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            df3.applyPattern("#####0.000");
            Double energy = null;
            if (dc.getWavelength() != null && dc.getWavelength().compareTo(new Double(0)) != 0)
                energy = Constants.WAVELENGTH_TO_ENERGY_CONSTANT / dc.getWavelength();
            if (energy != null)
                dataCollection.setEnergy(new Double(df3.format(energy)));
            else
                dataCollection.setEnergy(null);
            // axis start label
            String axisStartLabel = dc.getRotationAxis() == null ? "" : dc.getRotationAxis() + " start";
            dataCollection.setAxisStartLabel(axisStartLabel);
            // totalExposureTime
            if (dc.getExposureTime() != null && dc.getNumberOfImages() != null) {
                dataCollection.setTotalExposureTime(
                        new Double(df3.format(dataCollection.getExposureTime() * dc.getNumberOfImages())));
            }
            // kappa
            Double kappa = dc.getKappaStart();
            String kappaStr = "";
            if (kappa == null || kappa.equals(Constants.SILLY_NUMBER))
                kappaStr = new String("0");
            else
                kappaStr = new String(kappa.toString());
            dataCollection.setKappa(kappaStr);
            // phi
            Double phi = dc.getPhiStart();
            String phiStr = "";
            if (phi == null || phi.equals(Constants.SILLY_NUMBER))
                phiStr = new String("0");
            else
                phiStr = new String(phi.toString());
            dataCollection.setPhi(phiStr);
            // undulatorGaps
            DecimalFormat df2 = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            // DecimalFormat df2 = new DecimalFormat("##0.##");
            df2.applyPattern("##0.##");
            StringBuffer buf = new StringBuffer();
            // if no type then there is no meaningful value
            // if no undulator 1 then no 2 and no 3
            if (beamline.getUndulatorType1() != null && beamline.getUndulatorType1().length() > 0) {
                if (dc.getUndulatorGap1() != null && !dc.getUndulatorGap1().equals(Constants.SILLY_NUMBER)) {
                    Double gap1 = new Double(df2.format(dc.getUndulatorGap1()));
                    buf.append(gap1.toString()).append(" mm ");
                }
                if (beamline.getUndulatorType2() != null && beamline.getUndulatorType2().length() > 0) {
                    if (dc.getUndulatorGap2() != null
                            && !dc.getUndulatorGap2().equals(Constants.SILLY_NUMBER)) {
                        Double gap2 = new Double(df2.format(dc.getUndulatorGap2()));
                        buf.append(gap2.toString()).append(" mm ");
                    }
                    if (beamline.getUndulatorType3() != null && beamline.getUndulatorType3().length() > 0) {
                        if (dc.getUndulatorGap3() != null
                                && !dc.getUndulatorGap3().equals(Constants.SILLY_NUMBER)) {
                            Double gap3 = new Double(df2.format(dc.getUndulatorGap3()));
                            buf.append(gap3.toString()).append(" mm ");
                        }
                    }
                }
            }
            String undulatorGaps = buf.toString();
            dataCollection.setUndulatorGaps(undulatorGaps);

            DecimalFormat nf1 = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
            nf1.applyPattern("#");
            DecimalFormat df5 = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            df5.applyPattern("#####0.00000");

            // slitGapHorizontalMicro
            Integer slitGapHorizontalMicro = null;
            if (dc.getSlitGapHorizontal() != null) {
                // in DB beamsize unit is mm, display is in micrometer => conversion
                slitGapHorizontalMicro = new Integer(
                        nf1.format(dc.getSlitGapHorizontal().doubleValue() * 1000));
            }
            dataCollection.setSlitGapHorizontalMicro(slitGapHorizontalMicro);
            // slitGapVerticalMicro
            Integer slitGapVerticalMicro = null;
            if (dc.getSlitGapVertical() != null) {
                // in DB beamsize unit is mm, display is in micrometer => conversion
                slitGapVerticalMicro = new Integer(nf1.format(dc.getSlitGapVertical().doubleValue() * 1000));
            }
            dataCollection.setSlitGapVerticalMicro(slitGapVerticalMicro);
            // detectorPixelSizeHorizontalMicro
            Double detectorPixelSizeHorizontalMicro = null;
            if (detector != null && detector.getDetectorPixelSizeHorizontal() != null) {
                // in DB pixel size unit is mm,
                detectorPixelSizeHorizontalMicro = new Double(
                        df5.format(detector.getDetectorPixelSizeHorizontal()));
            }
            dataCollection.setDetectorPixelSizeHorizontalMicro(detectorPixelSizeHorizontalMicro);
            // detectorPixelSizeHorizontalMicro
            Double detectorPixelSizeVerticalMicro = null;
            if (detector != null && detector.getDetectorPixelSizeVertical() != null) {
                // in DB pixel size unit is mm,
                detectorPixelSizeVerticalMicro = new Double(
                        df5.format(detector.getDetectorPixelSizeVertical()));
            }
            dataCollection.setDetectorPixelSizeVerticalMicro(detectorPixelSizeVerticalMicro);
            // beamSizeAtSampleXMicro
            Integer beamSizeAtSampleXMicro = null;
            if (dc.getBeamSizeAtSampleX() != null) {
                // in DB beamsize unit is mm, display is in micrometer => conversion
                beamSizeAtSampleXMicro = new Integer(
                        nf1.format(dc.getBeamSizeAtSampleX().doubleValue() * 1000));
            }
            dataCollection.setBeamSizeAtSampleXMicro(beamSizeAtSampleXMicro);
            // beamSizeAtSampleYMicro
            Integer beamSizeAtSampleYMicro = null;
            if (dc.getBeamSizeAtSampleY() != null) {
                // in DB beamsize unit is mm, display is in micrometer => conversion
                beamSizeAtSampleYMicro = new Integer(
                        nf1.format(dc.getBeamSizeAtSampleY().doubleValue() * 1000));
            }
            dataCollection.setBeamSizeAtSampleYMicro(beamSizeAtSampleYMicro);
            // beamDivergenceHorizontalInt
            Integer beamDivergenceHorizontalInt = null;
            if (beamline.getBeamDivergenceHorizontal() != null) {
                beamDivergenceHorizontalInt = new Integer(nf1.format(beamline.getBeamDivergenceHorizontal()));
            }
            dataCollection.setBeamDivergenceHorizontalInt(beamDivergenceHorizontalInt);
            // beamDivergenceVerticalInt
            Integer beamDivergenceVerticalInt = null;
            if (beamline.getBeamDivergenceVertical() != null) {
                beamDivergenceVerticalInt = new Integer(nf1.format(beamline.getBeamDivergenceVertical()));
            }
            dataCollection.setBeamDivergenceVerticalInt(beamDivergenceVerticalInt);
            // DNA or EDNA Content present ?
            String fullDNAPath = PathUtils.getFullDNAPath(dc);
            String fullEDNAPath = PathUtils.getFullEDNAPath(dc);
            boolean EDNAContentPresent = (new File(fullEDNAPath + EDNA_FILES_INDEX_FILE)).exists()
                    || (new File(fullDNAPath + Constants.DNA_FILES_INDEX_FILE)).exists();
            isEDNACharacterisation = EDNAContentPresent;

            // Denzo Content present ?

            if (Constants.DENZO_ENABLED) {
                fullDenzoPath = FileUtil.GetFullDenzoPath(dc);
                DenzonContentPresent = (new File(fullDenzoPath)).exists();
                displayDenzoContent = DisplayDenzoContent(dc);

                if (DenzonContentPresent) // Check html file present
                {
                    File denzoIndex = new File(fullDenzoPath + DENZO_HTML_INDEX);
                    if (!denzoIndex.exists()) {
                        errors.add("Denzo File does not exist " + denzoIndex);
                        DenzonContentPresent = false;
                    }
                }
            }
        }

        //
        HashMap<String, Object> data = new HashMap<String, Object>();
        // context path
        data.put("contextPath", request.getContextPath());
        // autoProcList
        data.put("autoProcList", autoProcList);
        // autoProcIdSelected
        data.put("autoProcIdSelected", autoProcIdSelected);
        // rMerge & iSigma
        data.put("rMerge", rMerge);
        data.put("iSigma", iSigma);
        data.put("nbRemoved", nbRemoved);
        data.put("dataCollectionId", dataCollectionId);
        data.put("dataCollection", dataCollection);
        // beamlinesetup
        data.put("beamline", beamline);
        // session
        data.put("session", session);
        // detector
        data.put("detector", detector);
        // interrupted autoProc
        data.put("interruptedAutoProcEvents", interruptedAutoProcEvents1);
        // displayOutputParam
        data.put("displayOutputParam", displayOutputParam);
        // isEDNACharacterisation
        data.put("isEDNACharacterisation", isEDNACharacterisation);
        // isAutoprocessing
        data.put("isAutoprocessing", isAutoprocessing);
        // displayDenzoContent
        data.put("displayDenzoContent", displayDenzoContent);
        // DenzonContentPresent
        data.put("DenzonContentPresent", DenzonContentPresent);
        // fullDenzoPath
        data.put("fullDenzoPath", fullDenzoPath);
        // data => Gson
        GSonUtils.sendToJs(response, data, "dd-MM-yyyy HH:mm:ss");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java

@Override
public void saveGradesAndComments(final String gradebookUid, final Long gradableObjectId,
        List<GradeDefinition> gradeDefList) {
    if (gradebookUid == null || gradableObjectId == null) {
        throw new IllegalArgumentException(
                "Null gradebookUid or gradableObjectId passed to saveGradesAndComments");
    }//  ww  w. j a v a2  s . c  o m

    if (gradeDefList != null) {
        Gradebook gradebook;

        try {
            gradebook = getGradebook(gradebookUid);
        } catch (GradebookNotFoundException gnfe) {
            throw new GradebookNotFoundException("No gradebook exists with the given gradebookUid: "
                    + gradebookUid + "Error: " + gnfe.getMessage());
        }

        Assignment assignment = (Assignment) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                return getAssignmentWithoutStats(gradebookUid, gradableObjectId, session);
            }
        });

        if (assignment == null) {
            throw new AssessmentNotFoundException(
                    "No gradebook item exists with gradable object id = " + gradableObjectId);
        }

        if (!currentUserHasGradingPerm(gradebookUid)) {
            log.warn("User attempted to save grades and comments without authorization");
            throw new SecurityException(
                    "Current user is not authorized to save grades or comments in gradebook " + gradebookUid);
        }

        // let's identify all of the students being updated first
        Map<String, GradeDefinition> studentIdGradeDefMap = new HashMap<String, GradeDefinition>();
        Map<String, String> studentIdToGradeMap = new HashMap<String, String>();

        for (GradeDefinition gradeDef : gradeDefList) {
            studentIdGradeDefMap.put(gradeDef.getStudentUid(), gradeDef);
            studentIdToGradeMap.put(gradeDef.getStudentUid(), gradeDef.getGrade());
        }

        // check for invalid grades
        List invalidStudents = identifyStudentsWithInvalidGrades(gradebookUid, studentIdToGradeMap);
        if (invalidStudents != null && !invalidStudents.isEmpty()) {
            throw new InvalidGradeException("At least one grade passed to be updated is "
                    + "invalid. No grades or comments were updated.");
        }

        boolean userHasGradeAllPerm = currentUserHasGradeAllPerm(gradebookUid);

        // let's retrieve all of the existing grade recs for the given students
        // and assignments
        List<AssignmentGradeRecord> allGradeRecs = getAllAssignmentGradeRecordsForGbItem(gradableObjectId,
                studentIdGradeDefMap.keySet());

        // put in map for easier accessibility
        Map<String, AssignmentGradeRecord> studentIdToAgrMap = new HashMap<String, AssignmentGradeRecord>();
        if (allGradeRecs != null) {
            for (AssignmentGradeRecord rec : allGradeRecs) {
                studentIdToAgrMap.put(rec.getStudentId(), rec);
            }
        }

        // set up the grader and grade time
        String graderId = getAuthn().getUserUid();
        Date now = new Date();

        // get grade mapping, if nec, to convert grades to points
        LetterGradePercentMapping mapping = null;
        if (gradebook.getGrade_type() == GradebookService.GRADE_TYPE_LETTER) {
            mapping = getLetterGradePercentMapping(gradebook);
        }

        // get all of the comments, as well
        List<Comment> allComments = getComments(assignment, studentIdGradeDefMap.keySet());
        // put in a map for easier accessibility
        Map<String, Comment> studentIdCommentMap = new HashMap<String, Comment>();
        if (allComments != null) {
            for (Comment comment : allComments) {
                studentIdCommentMap.put(comment.getStudentId(), comment);
            }
        }

        // these are the records that will need to be updated. iterate through
        // everything and then we'll save it all at once
        Set<AssignmentGradeRecord> agrToUpdate = new HashSet<AssignmentGradeRecord>();
        // do not use a HashSet b/c you may have multiple Comments with null id and the same comment at this point.
        // the Comment object defines objects as equal if they have the same id, comment text, and gb item. the
        // only difference may be the student ids
        List<Comment> commentsToUpdate = new ArrayList<Comment>();
        Set<GradingEvent> eventsToAdd = new HashSet<GradingEvent>();

        for (GradeDefinition gradeDef : gradeDefList) {

            String studentId = gradeDef.getStudentUid();

            // check specific grading privileges if user does not have
            // grade all perm
            if (!userHasGradeAllPerm) {
                if (!isUserAbleToGradeItemForStudent(gradebookUid, gradableObjectId, studentId)) {
                    log.warn("User " + graderId + " attempted to save a grade for " + studentId
                            + " without authorization");

                    throw new SecurityException("User " + graderId + " attempted to save a grade for "
                            + studentId + " without authorization");
                }
            }

            Double convertedGrade = convertInputGradeToPoints(gradebook.getGrade_type(), mapping,
                    assignment.getPointsPossible(), gradeDef.getGrade());

            // let's see if this agr needs to be updated
            AssignmentGradeRecord gradeRec = studentIdToAgrMap.get(studentId);
            if (gradeRec != null) {
                if ((convertedGrade == null && gradeRec.getPointsEarned() != null)
                        || (convertedGrade != null && gradeRec.getPointsEarned() == null)
                        || (convertedGrade != null && gradeRec.getPointsEarned() != null
                                && !convertedGrade.equals(gradeRec.getPointsEarned()))) {

                    gradeRec.setPointsEarned(convertedGrade);
                    gradeRec.setGraderId(graderId);
                    gradeRec.setDateRecorded(now);

                    agrToUpdate.add(gradeRec);

                    // we also need to add a GradingEvent
                    // the event stores the actual input grade, not the converted one
                    GradingEvent event = new GradingEvent(assignment, graderId, studentId, gradeDef.getGrade());
                    eventsToAdd.add(event);
                }
            } else {
                // if the grade is something other than null, add a new AGR
                if (gradeDef.getGrade() != null && !gradeDef.getGrade().trim().equals("")) {
                    gradeRec = new AssignmentGradeRecord(assignment, studentId, convertedGrade);
                    gradeRec.setPointsEarned(convertedGrade);
                    gradeRec.setGraderId(graderId);
                    gradeRec.setDateRecorded(now);

                    agrToUpdate.add(gradeRec);

                    // we also need to add a GradingEvent
                    // the event stores the actual input grade, not the converted one
                    GradingEvent event = new GradingEvent(assignment, graderId, studentId, gradeDef.getGrade());
                    eventsToAdd.add(event);
                }
            }

            // let's see if the comment needs to be updated
            Comment comment = studentIdCommentMap.get(studentId);
            if (comment != null) {
                boolean oldCommentIsNull = comment.getCommentText() == null
                        || comment.getCommentText().equals("");
                boolean newCommentIsNull = gradeDef.getGradeComment() == null
                        || gradeDef.getGradeComment().equals("");

                if ((oldCommentIsNull && !newCommentIsNull) || (!oldCommentIsNull && newCommentIsNull)
                        || (!oldCommentIsNull && !newCommentIsNull
                                && !gradeDef.getGradeComment().equals(comment.getCommentText()))) {
                    // update this comment
                    comment.setCommentText(gradeDef.getGradeComment());
                    comment.setGraderId(graderId);
                    comment.setDateRecorded(now);

                    commentsToUpdate.add(comment);
                }
            } else {
                // if there is a comment, add it
                if (gradeDef.getGradeComment() != null && !gradeDef.getGradeComment().trim().equals("")) {
                    comment = new Comment(studentId, gradeDef.getGradeComment(), assignment);
                    comment.setGraderId(graderId);
                    comment.setDateRecorded(now);

                    commentsToUpdate.add(comment);
                }
            }
        }

        // now let's save them
        try {
            for (AssignmentGradeRecord assignmentGradeRecord : agrToUpdate) {
                getHibernateTemplate().saveOrUpdate(assignmentGradeRecord);
            }
            for (Comment comment : commentsToUpdate) {
                getHibernateTemplate().saveOrUpdate(comment);
            }
            for (GradingEvent gradingEvent : eventsToAdd) {
                getHibernateTemplate().saveOrUpdate(gradingEvent);
            }
        } catch (HibernateOptimisticLockingFailureException holfe) {
            if (log.isInfoEnabled())
                log.info(
                        "An optimistic locking failure occurred while attempting to save scores and comments for gb Item "
                                + gradableObjectId);
            throw new StaleObjectModificationException(holfe);
        } catch (StaleObjectStateException sose) {
            if (log.isInfoEnabled())
                log.info(
                        "An optimistic locking failure occurred while attempting to save scores and comments for gb Item "
                                + gradableObjectId);
            throw new StaleObjectModificationException(sose);
        }
    }
}

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantsService.java

/**
 * //from   ww w.j  a v  a 2  s . c om
 * ?
 * 
 * @Date 2012-03-07
 * @author wang.m
 * @throws Exception
 */
@Transactional
@Deprecated
public Integer addSupplier(HttpServletRequest req, SupplierSp supplierSp) {
    Integer count = 0;
    try {
        SupplierSp supplier = new SupplierSp();
        supplier.setUpdateTimestamp(System.currentTimeMillis());// 
        supplier.setSupplier(supplierSp.getSupplier());// ??
        supplier.setSimpleName(supplierSp.getSimpleName());// 
        supplier.setAddress(supplierSp.getAddress());// ?
        supplier.setTaxRate(supplierSp.getTaxRate());// 
        supplier.setRemark(supplierSp.getRemark());// 
        if (null != supplierSp && supplierSp.getSupplierType() != null
                && "".equals(supplierSp.getSupplierType())) {
            if (supplierSp.getCouponsAllocationProportion() == null) {
                supplier.setCouponsAllocationProportion(supplierSp.getCouponsAllocationProportion());// 
            } else {
                supplier.setCouponsAllocationProportion(0.00);// 
            }
        } else {
            supplier.setCouponsAllocationProportion(0.00);// 
        }
        supplier.setSupplierType(supplierSp.getSupplierType());// 
        supplier.setIsInputYougouWarehouse(supplierSp.getIsInputYougouWarehouse());// ?
        supplier.setSetOfBooksCode(supplierSp.getSetOfBooksCode());// ???
        supplier.setSetOfBooksName(supplierSp.getSetOfBooksName());// ????
        supplier.setBalanceTraderCode(supplierSp.getBalanceTraderCode());// ?
        supplier.setBalanceTraderName(supplierSp.getBalanceTraderName());// ??
        supplier.setPosSourceNo(supplierSp.getPosSourceNo());// pos?
        supplier.setIsUseYougouWms(supplierSp.getIsUseYougouWms());//?WMS
        supplier.setDeleteFlag(1);// 
        supplier.setShipmentType(supplierSp.getShipmentType());// ?
        SystemmgtUser user = GetSessionUtil.getSystemUser(req);
        String loginUser = "";
        if (user != null) {
            loginUser = user.getUsername();
        }
        supplier.setCreator(loginUser);// 
        supplier.setUpdateUser(loginUser);// 
        supplier.setUpdateDate(new Date());//  
        // 
        if (StringUtils.isNotBlank(supplierSp.getId())) {
            // ?
            SupplierSp supplierInfo = getSupplierSpById(supplierSp.getId());
            // ?
            if (supplierInfo != null) {
                supplier.setBank(supplierInfo.getBank());
                supplier.setSubBank(supplierInfo.getSubBank());
                supplier.setDutyCode(supplierInfo.getDutyCode());
                supplier.setContact(supplierInfo.getContact());
                supplier.setPayType(supplierInfo.getPayType());
                supplier.setAccount(supplierInfo.getAccount());
                supplier.setConTime(supplierInfo.getConTime());
            }
            if (supplierInfo != null) {
                // ??()
                if (null != supplierSp && supplierSp.getSupplierType() != null
                        && "".equals(supplierSp.getSupplierType())) {
                    // 
                    Double proportion = supplierInfo.getCouponsAllocationProportion() == null ? 0.0
                            : supplierInfo.getCouponsAllocationProportion();
                    if (supplierSp.getCouponsAllocationProportion() != null
                            && !proportion.equals(supplierSp.getCouponsAllocationProportion())) {
                        count = addMerhcantlog(supplierSp.getId(), "?",
                                "", proportion.toString(),
                                supplierSp.getCouponsAllocationProportion().toString(), loginUser);
                    }
                }
                // ????
                String setOfBooksName = supplierInfo.getSetOfBooksName() == null ? ""
                        : supplierInfo.getSetOfBooksName();
                if (!setOfBooksName.equals(supplierSp.getSetOfBooksName())) {
                    count = addMerhcantlog(supplierSp.getId(), "?",
                            "????", setOfBooksName, supplierSp.getSetOfBooksName(), loginUser);
                }
                // 
                Double taxRate = supplierInfo.getTaxRate() == null ? 0.0 : supplierInfo.getTaxRate();
                if (!taxRate.equals(supplierSp.getTaxRate())) {
                    count = addMerhcantlog(supplierSp.getId(), "?", "",
                            taxRate.toString(), supplierSp.getTaxRate().toString(), loginUser);
                }
                // ?
                Integer warehouse = supplierInfo.getIsInputYougouWarehouse() == null ? 1
                        : supplierInfo.getIsInputYougouWarehouse();
                if (warehouse != supplierSp.getIsInputYougouWarehouse()) {
                    String wareStr = "";
                    String wareStr1 = "";
                    if (warehouse == 1) {
                        wareStr = "";
                        wareStr1 = "?";
                    } else {
                        wareStr = "?";
                        wareStr1 = "";
                    }
                    count = addMerhcantlog(supplierSp.getId(), "?", "",
                            wareStr, wareStr1, loginUser);
                }
            }
            supplier.setId(supplierSp.getId());
            supplier.setSupplierCode(supplierSp.getSupplierCode());// ?
            supplier.setIsValid(supplierSp.getIsValid());// ?
            //supplierDaoImpl.merge(supplier);
            //TODO
        } else {
            String supplierCode = new CodeGenerate().getSupplierCode();
            supplier.setSupplierCode(supplierCode);// ?
            supplier.setIsValid(2);// ? 
            //supplierDaoImpl.save(supplier);
            //TODO
        }

        count = 1;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        logger.error("?!", e);
        e.printStackTrace();
    }
    return count;
}

From source file:org.sakaiproject.tool.assessment.facade.AssessmentGradingFacadeQueries.java

public HashMap getHighestAssessmentGradingByPublishedItem(final Long publishedAssessmentId) {
    HashMap h = new HashMap();
    final String query = "select new AssessmentGradingData(" + " a.assessmentGradingId, p.itemId, "
            + " a.agentId, a.finalScore, a.submittedDate) "
            + " from ItemGradingData i, AssessmentGradingData a, " + " PublishedItemData p where "
            + " i.assessmentGradingId = a.assessmentGradingId and i.publishedItemId = p.itemId and "
            + " a.publishedAssessmentId=? " + " order by a.agentId asc, a.finalScore desc";

    final HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(query);
            q.setLong(0, publishedAssessmentId.longValue());
            return q.list();
        };//from  w w w.  j  a v  a2s  .  co  m
    };
    List assessmentGradings = getHibernateTemplate().executeFind(hcb);

    //    List assessmentGradings = getHibernateTemplate().find(query,
    //         new Object[] { publishedAssessmentId },
    //         new org.hibernate.type.Type[] { Hibernate.LONG });

    //    ArrayList l = new ArrayList();
    String currentAgent = "";
    Double finalScore = null;
    for (int i = 0; i < assessmentGradings.size(); i++) {
        AssessmentGradingData g = (AssessmentGradingData) assessmentGradings.get(i);
        Long itemId = g.getPublishedItemId();
        Long gradingId = g.getAssessmentGradingId();
        log.debug("**** itemId=" + itemId + ", gradingId=" + gradingId + ", agentId=" + g.getAgentId()
                + ", score=" + g.getFinalScore());
        if (i == 0) {
            currentAgent = g.getAgentId();
            finalScore = g.getFinalScore();
        }
        if (currentAgent.equals(g.getAgentId()) && ((finalScore == null && g.getFinalScore() == null)
                || (finalScore != null && finalScore.equals(g.getFinalScore())))) {
            Object o = h.get(itemId);
            if (o != null)
                ((ArrayList) o).add(gradingId);
            else {
                ArrayList gradingIds = new ArrayList();
                gradingIds.add(gradingId);
                h.put(itemId, gradingIds);
            }
        }
        if (!currentAgent.equals(g.getAgentId())) {
            currentAgent = g.getAgentId();
            finalScore = g.getFinalScore();
        }
    }
    return h;
}

From source file:com.selfsoft.business.service.impl.TbBusinessBalanceServiceImpl.java

private Double calcFavourAmount(Double itemTotal, Double favourRate) {

    BigDecimal d = new BigDecimal("0.00");

    if (null != itemTotal && null != favourRate && !favourRate.equals(1.00D)) {

        BigDecimal d_itemTotal = new BigDecimal(String.valueOf(itemTotal));

        BigDecimal d_favourRate = new BigDecimal(String.valueOf(favourRate));

        d = d_itemTotal.multiply(d_favourRate)
                .divide(new BigDecimal("1.00").subtract(d_favourRate), 2, BigDecimal.ROUND_HALF_UP)
                .setScale(2, BigDecimal.ROUND_HALF_UP);
    }/*from   ww  w. ja  va  2s.co  m*/

    return d.doubleValue();
}