List of usage examples for java.math BigDecimal ONE
BigDecimal ONE
To view the source code for java.math BigDecimal ONE.
Click Source Link
From source file:pe.gob.mef.gescon.web.ui.ParametroMB.java
public void activar(ActionEvent event) { try {/*from w w w.j a va 2 s . co m*/ if (event != null) { if (this.getSelectedParametro() != null) { LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB"); User user = loginMB.getUser(); ParametroService service = (ParametroService) ServiceFinder.findBean("ParametroService"); this.getSelectedParametro().setNactivo(BigDecimal.ONE); this.getSelectedParametro().setDfechamodificacion(new Date()); this.getSelectedParametro().setVusuariomodificacion(user.getVlogin()); service.saveOrUpdate(this.getSelectedParametro()); this.setListaParametro(service.getParametros()); } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "Debe seleccionar el parametro a activar."); FacesContext.getCurrentInstance().addMessage(null, message); } } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:org.openhab.binding.diyonxbee.internal.DiyOnXBeeBinding.java
private PercentType changeBrightness(IncreaseDecreaseType increaseDecrease, final PercentType brightness) { final PercentType newBrightness; if (increaseDecrease == IncreaseDecreaseType.DECREASE) { BigDecimal changed = brightness.toBigDecimal().subtract(BigDecimal.ONE); if (changed.compareTo(BigDecimal.ZERO) < 0) changed = BigDecimal.ZERO; newBrightness = new PercentType(changed); } else {/*w ww. ja v a2s . c om*/ BigDecimal changed = brightness.toBigDecimal().add(BigDecimal.ONE); if (changed.compareTo(PercentType.HUNDRED.toBigDecimal()) > 0) { changed = PercentType.HUNDRED.toBigDecimal(); } newBrightness = new PercentType(changed); } return newBrightness; }
From source file:pe.gob.mef.gescon.web.ui.AlertaMB.java
public void save(ActionEvent event) { try {/*from www.ja va2 s . co m*/ if (CollectionUtils.isEmpty(this.getListaAlerta())) { this.setListaAlerta(Collections.EMPTY_LIST); } Alerta alerta = new Alerta(); alerta.setVnombre(this.getNombre()); alerta.setVdescripcion(this.getDescripcion()); alerta.setNparametroid(this.getSelectedParametro()); alerta.setDfechini(this.getFechfin()); alerta.setDfechfin(this.getFechfin()); alerta.setNcondicion1(this.getCondicion1()); alerta.setNcondicion2(this.getCondicion2()); alerta.setNtipo1(this.getTipo1()); alerta.setNtipo2(this.getTipo2()); alerta.setNuseraplica(this.getUseraplica()); alerta.setNvalor1(this.getValor1()); alerta.setNvalor2(this.getValor2()); if (!errorValidation(alerta)) { LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB"); User user = loginMB.getUser(); AlertaService service = (AlertaService) ServiceFinder.findBean("AlertaService"); alerta.setNalertaid(service.getNextPK()); alerta.setVnombre(StringUtils.upperCase(this.getNombre().trim())); alerta.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim())); alerta.setNactivo(BigDecimal.ONE); alerta.setDfechacreacion(new Date()); alerta.setVusuariocreacion(user.getVlogin()); service.saveOrUpdate(alerta); this.setListaAlerta(service.getAlertas()); this.cleanAttributes(); RequestContext.getCurrentInstance().execute("PF('newDialog').hide();"); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:pe.gob.mef.gescon.web.ui.RangoMB.java
public void activar(ActionEvent event) { try {/*from w w w .jav a2 s . co m*/ if (event != null) { if (this.getSelectedRango() != null) { LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB"); User user = loginMB.getUser(); RangoService service = (RangoService) ServiceFinder.findBean("RangoService"); this.getSelectedRango().setNactivo(BigDecimal.ONE); this.getSelectedRango().setDfechamodificacion(new Date()); this.getSelectedRango().setVusuariomodificacion(user.getVlogin()); service.saveOrUpdate(this.getSelectedRango()); this.setListaRango(service.getRangos()); } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "Debe seleccionar el rango a activar."); FacesContext.getCurrentInstance().addMessage(null, message); } } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:pe.gob.mef.gescon.web.ui.MaestroMB.java
public void activar(ActionEvent event) { try {//from www.j av a2 s . c o m if (event != null) { if (this.getSelectedMaestro() != null) { LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB"); User user = loginMB.getUser(); MaestroService service = (MaestroService) ServiceFinder.findBean("MaestroService"); this.getSelectedMaestro().setNactivo(BigDecimal.ONE); this.getSelectedMaestro().setDfechamodificacion(new Date()); this.getSelectedMaestro().setVusuariomodificacion(user.getVlogin()); service.saveOrUpdate(this.getSelectedMaestro()); this.setListaMaestro(service.getMaestros()); } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "Debe seleccionar el maestro a activar."); FacesContext.getCurrentInstance().addMessage(null, message); } } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement.java
private static int getIdFor(SQLRowValues row, boolean includeMetrique, boolean createIfNotExist) { // On cherche l'article qui lui correspond SQLTable tableArt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete() .getTable("ARTICLE"); SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(tableArt); String req = getMatchRequest(row, includeMetrique); List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler()); if (result != null && result.size() != 0) { Object[] tmp = (Object[]) result.get(0); return ((Number) tmp[0]).intValue(); }/*w w w .ja va 2 s . c o m*/ if (createIfNotExist) { SQLRowValues vals = new SQLRowValues(row); BigDecimal taux = BigDecimal.ONE .add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f)); vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux)); SQLRow rowNew; try { // Liaison avec l'article fournisseur si il existe SQLSelect selMatchingCodeF = new SQLSelect(); final SQLTable table = tableArt.getTable("ARTICLE_FOURNISSEUR"); selMatchingCodeF.addSelect(table.getKey()); selMatchingCodeF.addSelect(table.getField("ID_FOURNISSEUR")); selMatchingCodeF.addSelect(table.getField("CODE_BARRE")); Where wMatchingCodeF = new Where(table.getField("CODE"), "=", vals.getString("CODE")); wMatchingCodeF = wMatchingCodeF.and(new Where(table.getField("NOM"), "=", vals.getString("NOM"))); selMatchingCodeF.setWhere(wMatchingCodeF); List<SQLRow> l = SQLRowListRSH.execute(selMatchingCodeF); if (l.size() > 0) { SQLRowValues rowVals = l.get(0).asRowValues(); vals.put("ID_FOURNISSEUR", rowVals.getObject("ID_FOURNISSEUR")); vals.put("CODE_BARRE", rowVals.getObject("CODE_BARRE")); rowNew = vals.insert(); rowVals.put("ID_ARTICLE", rowNew.getID()); rowVals.commit(); } else { rowNew = vals.insert(); } return rowNew.getID(); } catch (SQLException e) { e.printStackTrace(); } } return -1; }
From source file:org.openhab.persistence.dynamodb.internal.AbstractDynamoDBItemSerializationTest.java
@Test public void testOnOffTypeWithColorItem() throws IOException { DynamoDBItem<?> dbitemOff = testStateGeneric(OnOffType.OFF, BigDecimal.ZERO); testAsHistoricGeneric(dbitemOff, new ColorItem("foo"), new PercentType(BigDecimal.ZERO)); DynamoDBItem<?> dbitemOn = testStateGeneric(OnOffType.ON, BigDecimal.ONE); testAsHistoricGeneric(dbitemOn, new ColorItem("foo"), new PercentType(BigDecimal.ONE)); }
From source file:pe.gob.mef.gescon.hibernate.impl.WikiDaoImpl.java
@Override public List<HashMap> getConcimientosDisponibles(HashMap filters) { String ntipoconocimientoid = ((BigDecimal) filters.get("ntipoconocimientoid")).toString(); String nconocimientovinc = (String) filters.get("nconocimientovinc"); final StringBuilder sql = new StringBuilder(); Object object = null;//from w w w . j a v a 2 s . c om try { if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("1")) { sql.append("SELECT "); sql.append( " a.nbaselegalid AS ID, a.vnumero AS NUMERO, a.vnombre AS NOMBRE, a.vsumilla AS SUMILLA, "); sql.append( " a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, "); sql.append( " 1 AS IDTIPOCONOCIMIENTO, 'Base Legal' AS TIPOCONOCIMIENTO, a.nestadoid AS IDESTADO, c.vnombre AS ESTADO "); sql.append("FROM TBASELEGAL a "); sql.append(" INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid "); sql.append(" INNER JOIN MTESTADO_BASELEGAL c ON a.nestadoid = c.nestadoid "); sql.append("WHERE a.nactivo = :ACTIVO "); sql.append("AND a.nestadoid IN (3,5,6) "); // Publicada, Concordada y Modificada. if (StringUtils.isNotBlank(nconocimientovinc)) { sql.append("AND a.nbaselegalid NOT IN (").append(nconocimientovinc).append(") "); } } if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("2")) { sql.append("SELECT "); sql.append(" a.npreguntaid AS ID, '' AS NUMERO, a.vasunto AS NOMBRE, a.vdetalle AS SUMILLA, "); sql.append( " a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechacreacion AS FECHA, "); sql.append(" 2 AS IDTIPOCONOCIMIENTO, 'Preguntas y Respuestas' AS TIPOCONOCIMIENTO, "); sql.append(" a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO "); sql.append("FROM TPREGUNTA a "); sql.append(" INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid "); sql.append(" INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid "); sql.append("WHERE a.nactivo = :ACTIVO "); sql.append("AND a.nsituacionid = 6 "); // Publicado if (StringUtils.isNotBlank(nconocimientovinc)) { sql.append("AND a.npreguntaid NOT IN (").append(nconocimientovinc).append(") "); } } if (StringUtils.isNotBlank(ntipoconocimientoid) && (ntipoconocimientoid.equals("3") || ntipoconocimientoid.equals("4") || ntipoconocimientoid.equals("5") || ntipoconocimientoid.equals("6"))) { sql.append("SELECT "); sql.append( " a.nconocimientoid AS ID, '' AS NUMERO, a.vtitulo AS NOMBRE, a.vdescripcion AS SUMILLA, "); sql.append( " a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechacreacion AS FECHA, "); sql.append(" a.ntpoconocimientoid AS IDTIPOCONOCIMIENTO, d.vnombre AS TIPOCONOCIMIENTO, "); sql.append(" a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO "); sql.append("FROM TCONOCIMIENTO a "); sql.append(" INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid "); sql.append(" INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid "); sql.append(" INNER JOIN MTTIPO_CONOCIMIENTO d ON a.ntpoconocimientoid = d.ntpoconocimientoid "); sql.append("WHERE a.nactivo = :ACTIVO "); sql.append("AND a.nsituacionid = 6 "); // Publicado if (StringUtils.isNotBlank(nconocimientovinc)) { sql.append("AND a.nconocimientoid NOT IN (").append(nconocimientovinc).append(") "); } } sql.append("ORDER BY 5, 7 DESC "); object = getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException { Query query = session.createSQLQuery(sql.toString()); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); if (StringUtils.isNotBlank(sql.toString())) { query.setParameter("ACTIVO", BigDecimal.ONE); } return query.list(); } }); } catch (DataAccessException e) { e.getMessage(); e.printStackTrace(); } return (List<HashMap>) object; }
From source file:org.egov.infra.gis.service.GeoLocationService.java
/** * /*from w w w.j ava 2 s . com*/ * @param TotalNos e.g = 50 * @param colorMap - the different colours to be shown in the kml. * @return = [0-10,11-20,21-30,31-40,41-50] */ private static Map<String, String> getColorRange(BigDecimal wardDataMinAmount, BigDecimal wardDataMaxAmount, BigDecimal rangeSize, Map<Integer, String> colorCodes) { int totalNoOfColors = colorCodes.size(); Map<String, String> colorRangeMap = new LinkedHashMap<String, String>(); // map to hold the colour code and the range . BigDecimal rangeStartVal = wardDataMinAmount; BigDecimal rangeEndVal = wardDataMinAmount; for (int i = 0; i < totalNoOfColors; i++) { if (totalNoOfColors != i + 1) { rangeEndVal = (rangeStartVal.add(rangeSize)).subtract(BigDecimal.ONE); } else { rangeEndVal = wardDataMaxAmount; } String colorRange = rangeStartVal + " - " + rangeEndVal; colorRangeMap.put(colorCodes.get((totalNoOfColors - i)), colorRange); BigDecimal nextRangeStartVal = rangeEndVal.add(BigDecimal.ONE); rangeStartVal = nextRangeStartVal; } return colorRangeMap; }
From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java
private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying, Period[] expiries) {//from w w w .j a v a 2s . c om ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); } ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); String formattedName = MessageFormatter.format("[{}] {}", underlying, longName); ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (int i = 0; i < expiries.length; i++) { Period bucketPeriod = expiries[i]; ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1)); LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run LocalDate targetExpiry = nowish.plus(bucketPeriod); LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.warn("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] { chosenExpiry, bucketPeriod, targetExpiry }); Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (ExternalId optionTicker : tickersToLoad) { ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (Exception ex) { s_logger.error("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }