List of usage examples for java.math BigInteger toString
public String toString()
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
private Certificate createCertificate(MultipartFile certificate, BindingResult result) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Certificate cert = new Certificate(); if (certificate != null && certificate.getSize() > 0) { try {/*from w w w .j a v a 2 s .co m*/ PEMReader r = new PEMReader( new InputStreamReader(new ByteArrayInputStream(certificate.getBytes()))); Object certObj = r.readObject(); long reference = System.currentTimeMillis(); // validate certificate if (certObj instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) certObj; BigInteger serialNumber = x509cert.getSerialNumber(); String issuerDn = x509cert.getIssuerDN().getName(); String subjectDn = x509cert.getSubjectDN().getName(); cert.setCertificate(certificate.getBytes()); cert.setSerialNumber(serialNumber.toString()); cert.setIssuer(issuerDn); cert.setSubject(subjectDn); cert.setSubjectCommonName(extractFromDn(subjectDn, "CN")); cert.setSubjectOrganization(extractFromDn(subjectDn, "O")); cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU")); cert.setSubjectLocation(extractFromDn(subjectDn, "L")); cert.setSubjectCountry(extractFromDn(subjectDn, "C")); cert.setNotAfter(x509cert.getNotAfter()); cert.setNotBefore(x509cert.getNotBefore()); } else { String line; StringBuilder certString = new StringBuilder(); while ((line = r.readLine()) != null) { certString.append(line + "\n"); } log.warn( "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}", new Object[] { reference, certObj, certString.toString() }); result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt (Reference: " + reference + ")"); } r.close(); } catch (IOException e) { log.warn("Bad certificate"); result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt "); } } return cert; }
From source file:de.topicmapslab.couchtm.core.OccurrenceImpl.java
@Override public void setValue(BigInteger value) { if (!loaded)//from w ww. j ava2s. c om load(); if (mergedIn != null) { mergedIn.setValue(value); return; } Check.valueNotNull(this, value); datatype = new LocatorImpl(IConstant.XSD_INTEGER); this.value = value.toString(); try { _fireEvent(Event.VALUE_CHANGED, null, value); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java
@Override public Collection<Certificate> findCertificatesBySerno(Admin admin, BigInteger serno) { if (log.isTraceEnabled()) { log.trace(">findCertificatesBySerno(), serno=" + serno); }//w w w . ja v a2s .c om ArrayList<Certificate> ret = new ArrayList<Certificate>(); Collection<CertificateData> coll = CertificateData.findBySerialNumber(entityManager, serno.toString()); Iterator<CertificateData> iter = coll.iterator(); while (iter.hasNext()) { ret.add(iter.next().getCertificate()); } if (log.isTraceEnabled()) { log.trace("<findCertificatesBySerno(), serno=" + serno); } return ret; }
From source file:org.apache.hadoop.hive.ql.optimizer.optiq.translator.RexNodeConverter.java
protected RexNode convert(ExprNodeConstantDesc literal) throws OptiqSemanticException { RexBuilder rexBuilder = cluster.getRexBuilder(); RelDataTypeFactory dtFactory = rexBuilder.getTypeFactory(); PrimitiveTypeInfo hiveType = (PrimitiveTypeInfo) literal.getTypeInfo(); RelDataType optiqDataType = TypeConverter.convert(hiveType, dtFactory); PrimitiveCategory hiveTypeCategory = hiveType.getPrimitiveCategory(); ConstantObjectInspector coi = literal.getWritableObjectInspector(); Object value = ObjectInspectorUtils.copyToStandardJavaObject(coi.getWritableConstantValue(), coi); RexNode optiqLiteral = null;/*from ww w.j a va 2s. c o m*/ // TODO: Verify if we need to use ConstantObjectInspector to unwrap data switch (hiveTypeCategory) { case BOOLEAN: optiqLiteral = rexBuilder.makeLiteral(((Boolean) value).booleanValue()); break; case BYTE: byte[] byteArray = new byte[] { (Byte) value }; ByteString bs = new ByteString(byteArray); optiqLiteral = rexBuilder.makeBinaryLiteral(bs); break; case SHORT: optiqLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Short) value), optiqDataType); break; case INT: optiqLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Integer) value)); break; case LONG: optiqLiteral = rexBuilder.makeBigintLiteral(new BigDecimal((Long) value)); break; // TODO: is Decimal an exact numeric or approximate numeric? case DECIMAL: if (value instanceof HiveDecimal) { value = ((HiveDecimal) value).bigDecimalValue(); } else if (value instanceof Decimal128) { value = ((Decimal128) value).toBigDecimal(); } if (value == null) { // We have found an invalid decimal value while enforcing precision and // scale. Ideally, // we would replace it with null here, which is what Hive does. However, // we need to plumb // this thru up somehow, because otherwise having different expression // type in AST causes // the plan generation to fail after CBO, probably due to some residual // state in SA/QB. // For now, we will not run CBO in the presence of invalid decimal // literals. throw new OptiqSemanticException( "Expression " + literal.getExprString() + " is not a valid decimal"); // TODO: return createNullLiteral(literal); } BigDecimal bd = (BigDecimal) value; BigInteger unscaled = bd.unscaledValue(); if (unscaled.compareTo(MIN_LONG_BI) >= 0 && unscaled.compareTo(MAX_LONG_BI) <= 0) { optiqLiteral = rexBuilder.makeExactLiteral(bd); } else { // CBO doesn't support unlimited precision decimals. In practice, this // will work... // An alternative would be to throw CboSemanticException and fall back // to no CBO. RelDataType relType = cluster.getTypeFactory().createSqlType(SqlTypeName.DECIMAL, bd.scale(), unscaled.toString().length()); optiqLiteral = rexBuilder.makeExactLiteral(bd, relType); } break; case FLOAT: optiqLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Float) value), optiqDataType); break; case DOUBLE: optiqLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Double) value), optiqDataType); break; case CHAR: if (value instanceof HiveChar) value = ((HiveChar) value).getValue(); optiqLiteral = rexBuilder.makeLiteral((String) value); break; case VARCHAR: if (value instanceof HiveVarchar) value = ((HiveVarchar) value).getValue(); optiqLiteral = rexBuilder.makeLiteral((String) value); break; case STRING: optiqLiteral = rexBuilder.makeLiteral((String) value); break; case DATE: Calendar cal = new GregorianCalendar(); cal.setTime((Date) value); optiqLiteral = rexBuilder.makeDateLiteral(cal); break; case TIMESTAMP: optiqLiteral = rexBuilder.makeTimestampLiteral((Calendar) value, RelDataType.PRECISION_NOT_SPECIFIED); break; case BINARY: case VOID: case UNKNOWN: default: throw new RuntimeException("UnSupported Literal"); } return optiqLiteral; }
From source file:com.exilant.eGov.src.common.EGovernCommon.java
/** * This API returns the fiscialperiodid for the date passed * @param vDate/* w ww .j av a 2 s . co m*/ * @param con * @return * @throws TaskFailedException */ public String getFiscalPeriod(final String vDate) throws TaskFailedException { BigInteger fiscalPeriod = null; final String sql = "select id from fiscalperiod where '" + vDate + "' between startingdate and endingdate"; try { final Query pst = persistenceService.getSession().createSQLQuery(sql); final List<BigInteger> rset = pst.list(); fiscalPeriod = rset != null ? rset.get(0) : BigInteger.ZERO; } catch (final Exception e) { LOGGER.error("Exception..." + e.getMessage()); throw new TaskFailedException(e.getMessage()); } return fiscalPeriod.toString(); }
From source file:com.magnet.android.mms.controller.RequestPrimitiveTest.java
@SmallTest public void testSingleListBigIntegerPostParam() throws JSONException { ControllerHandler handler = new ControllerHandler(); String methodName = "postBigDecimals"; JMethod method = new JMethod(); JMeta metaInfo = new JMeta(methodName, API_METHOD_POST + methodName, POST); method.setMetaInfo(metaInfo);// w ww . ja v a 2 s. co m // int method.addParam("param0", PLAIN, List.class, BigInteger.class, "", false); List<BigInteger> values = new ArrayList<BigInteger>(); values.add(BigInteger.TEN); values.add(BigInteger.probablePrime(5, new Random())); String uriString = handler.buildUri(method, new Object[] { values }); String bodyString = handler.buildRequestBodyString(method, new Object[] { values }); String expected = API_METHOD_POST + methodName; logger.log(Level.INFO, "uriString=" + uriString); logger.log(Level.INFO, "bodyString=" + bodyString); assertEquals(expected, uriString); JSONArray jarray = new JSONArray(bodyString); int idx = 0; for (BigInteger value : values) { assertEquals(jarray.getString(idx), value.toString()); idx++; } }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
private BigInteger getStartHistoyId() { BigInteger startHistoyId = null; Query query = new Query("StartHistroyEntity"); query.setFilter(FilterOperator.EQUAL.of("StartHistroyEntityKey", "StartHistoryEntityValue")); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery pq = datastore.prepare(query); Entity startHistroyEntity = pq.asSingleEntity(); try {// w ww . j av a 2s . c o m if (startHistroyEntity.hasProperty("id")) { startHistoyId = new BigInteger((String) startHistroyEntity.getProperty("id")); logger.warning("read value : " + startHistoyId.toString()); } } catch (NullPointerException e) { logger.warning("id property is not defined in StartHistroyEntity"); } return startHistoyId; }
From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java
private void updateStats() { if (_key == null) { maxTextField.setText(""); minTextField.setText(""); rangeTextField.setText(""); return;/* ww w .ja v a 2 s . c o m*/ } BigInteger min = _model.getMinimumValue(_key); BigInteger max = _model.getMaximumValue(_key); if (min != null) { minTextField.setText(min.toString()); } else { minTextField.setText(""); } if (max != null) { maxTextField.setText(max.toString()); } else { maxTextField.setText(""); } if (min != null && max != null) { BigInteger range = max.subtract(min); rangeTextField.setText(Float.toString(range.floatValue())); } else { rangeTextField.setText(""); } }
From source file:org.nordapp.web.servlet.IOServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w. ja va 2s . c om*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); // // Session and other services // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue(); //The 'user' session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } EngineBaseService engineBaseService = null; try { engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(), String.valueOf(baseIndex)); } catch (InvalidSyntaxException e1) { } if (engineBaseService == null) throw new IOException( "The mandator base service is not available (maybe down or a version conflict)."); // // Get some data // FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); // // prepare the engine // String[] elem = RequestPath.getPath(req); if (elem.length == 0) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/function-id' but was '" + req.getRequestURI() + "'"); BigInteger engineId = ctrl.decodeCert(); String functionId = elem.length >= 1 ? elem[0] : null; Engine engine = null; try { engine = engineBaseService.getEngine(engineId); } catch (Exception e1) { throw new ServletException(e1); } if (!engine.isLogin()) throw new ServletException("There is no login to this session."); // // Initialize the work // engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString() IdRep processUUID = IdGen.getUUID(); engine.setLocalValue(httpProcessID, processUUID); IOContainer ioc = new IOContainer(); ioc.setProcessUUID(processUUID.toString()); engine.setLocalValue(httpIOContainer, ioc); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data ioc.setField(item.getFieldName(), item); } else { ioc.setFile(IdGen.getUUID().toString(), item); } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } // // Call script // try { engine.call(functionId); } catch (Exception e) { e.printStackTrace(); } ioc.cleanup(); engine.setLocalValue(httpSessionID, null); engine.setLocalValue(httpProcessID, null); engine.setLocalValue(httpIOContainer, null); // // Prints the result from the user-session // StringBuffer buffer = new StringBuffer(); ResponseHandler rsHdl = new ResponseHandler(context, ctrl); logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.", (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID()); rsHdl.getSessionData(buffer, mSession); // // // byte[] bytes = buffer.toString().getBytes(); // // Send the resource // rsHdl.avoidCaching(resp); rsHdl.sendData(bytes, resp); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.RexNodeConverter.java
protected RexNode convert(ExprNodeConstantDesc literal) throws CalciteSemanticException { RexBuilder rexBuilder = cluster.getRexBuilder(); RelDataTypeFactory dtFactory = rexBuilder.getTypeFactory(); PrimitiveTypeInfo hiveType = (PrimitiveTypeInfo) literal.getTypeInfo(); RelDataType calciteDataType = TypeConverter.convert(hiveType, dtFactory); PrimitiveCategory hiveTypeCategory = hiveType.getPrimitiveCategory(); ConstantObjectInspector coi = literal.getWritableObjectInspector(); Object value = ObjectInspectorUtils.copyToStandardJavaObject(coi.getWritableConstantValue(), coi); RexNode calciteLiteral = null;//from ww w . ja v a2 s . com // TODO: Verify if we need to use ConstantObjectInspector to unwrap data switch (hiveTypeCategory) { case BOOLEAN: calciteLiteral = rexBuilder.makeLiteral(((Boolean) value).booleanValue()); break; case BYTE: calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Byte) value), calciteDataType); break; case SHORT: calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Short) value), calciteDataType); break; case INT: calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Integer) value)); break; case LONG: calciteLiteral = rexBuilder.makeBigintLiteral(new BigDecimal((Long) value)); break; // TODO: is Decimal an exact numeric or approximate numeric? case DECIMAL: if (value instanceof HiveDecimal) { value = ((HiveDecimal) value).bigDecimalValue(); } else if (value instanceof Decimal128) { value = ((Decimal128) value).toBigDecimal(); } if (value == null) { // We have found an invalid decimal value while enforcing precision and // scale. Ideally, // we would replace it with null here, which is what Hive does. However, // we need to plumb // this thru up somehow, because otherwise having different expression // type in AST causes // the plan generation to fail after CBO, probably due to some residual // state in SA/QB. // For now, we will not run CBO in the presence of invalid decimal // literals. throw new CalciteSemanticException( "Expression " + literal.getExprString() + " is not a valid decimal", UnsupportedFeature.Invalid_decimal); // TODO: return createNullLiteral(literal); } BigDecimal bd = (BigDecimal) value; BigInteger unscaled = bd.unscaledValue(); if (unscaled.compareTo(MIN_LONG_BI) >= 0 && unscaled.compareTo(MAX_LONG_BI) <= 0) { calciteLiteral = rexBuilder.makeExactLiteral(bd); } else { // CBO doesn't support unlimited precision decimals. In practice, this // will work... // An alternative would be to throw CboSemanticException and fall back // to no CBO. RelDataType relType = cluster.getTypeFactory().createSqlType(SqlTypeName.DECIMAL, bd.scale(), unscaled.toString().length()); calciteLiteral = rexBuilder.makeExactLiteral(bd, relType); } break; case FLOAT: calciteLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Float) value), calciteDataType); break; case DOUBLE: calciteLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Double) value), calciteDataType); break; case CHAR: if (value instanceof HiveChar) { value = ((HiveChar) value).getValue(); } calciteLiteral = rexBuilder.makeLiteral((String) value); break; case VARCHAR: if (value instanceof HiveVarchar) { value = ((HiveVarchar) value).getValue(); } calciteLiteral = rexBuilder.makeLiteral((String) value); break; case STRING: calciteLiteral = rexBuilder.makeLiteral((String) value); break; case DATE: Calendar cal = new GregorianCalendar(); cal.setTime((Date) value); calciteLiteral = rexBuilder.makeDateLiteral(cal); break; case TIMESTAMP: Calendar c = null; if (value instanceof Calendar) { c = (Calendar) value; } else { c = Calendar.getInstance(); c.setTimeInMillis(((Timestamp) value).getTime()); } calciteLiteral = rexBuilder.makeTimestampLiteral(c, RelDataType.PRECISION_NOT_SPECIFIED); break; case INTERVAL_YEAR_MONTH: // Calcite year-month literal value is months as BigDecimal BigDecimal totalMonths = BigDecimal.valueOf(((HiveIntervalYearMonth) value).getTotalMonths()); calciteLiteral = rexBuilder.makeIntervalLiteral(totalMonths, new SqlIntervalQualifier(TimeUnit.YEAR, TimeUnit.MONTH, new SqlParserPos(1, 1))); break; case INTERVAL_DAY_TIME: // Calcite day-time interval is millis value as BigDecimal // Seconds converted to millis BigDecimal secsValueBd = BigDecimal.valueOf(((HiveIntervalDayTime) value).getTotalSeconds() * 1000); // Nanos converted to millis BigDecimal nanosValueBd = BigDecimal.valueOf(((HiveIntervalDayTime) value).getNanos(), 6); calciteLiteral = rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.DAY, TimeUnit.SECOND, new SqlParserPos(1, 1))); break; case VOID: calciteLiteral = cluster.getRexBuilder().makeLiteral(null, cluster.getTypeFactory().createSqlType(SqlTypeName.NULL), true); break; case BINARY: case UNKNOWN: default: throw new RuntimeException("UnSupported Literal"); } return calciteLiteral; }