List of usage examples for java.math BigInteger toString
public String toString()
From source file:com.coinprism.wallet.fragment.SendTab.java
private void onSend() { final String to = toAddress.getText().toString(); final String unitString = amount.getText().toString(); final BigDecimal decimalAmount; final AssetDefinition selectedAsset = (AssetDefinition) assetSpinner.getSelectedItem(); final ProgressDialog progressDialog = new ProgressDialog(); try {/*from ww w.j av a 2 s .c o m*/ decimalAmount = new BigDecimal(unitString); } catch (NumberFormatException exception) { showError(getString(R.string.tab_send_error_invalid_amount)); return; } AsyncTask<Void, Void, Transaction> getTransaction = new AsyncTask<Void, Void, Transaction>() { private String subCode; protected Transaction doInBackground(Void... _) { try { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(SendTab.this.getActivity()); String value = sharedPreferences.getString(UserPreferences.defaultFeesKey, getString(R.string.default_fees)); BigDecimal decimal = new BigDecimal(value); long fees = decimal.scaleByPowerOfTen(8).toBigInteger().longValue(); if (selectedAsset == null) { // Send uncolored bitcoins return WalletState.getState().getAPIClient().buildTransaction( WalletState.getState().getConfiguration().getAddress(), to, decimalAmount.scaleByPowerOfTen(8).toBigInteger().toString(), null, fees); } else { // Send an asset BigInteger unitAmount = decimalAmount.scaleByPowerOfTen(selectedAsset.getDivisibility()) .toBigInteger(); return WalletState.getState().getAPIClient().buildTransaction( WalletState.getState().getConfiguration().getAddress(), to, unitAmount.toString(), selectedAsset.getAssetId(), fees); } } catch (APIException exception) { // The API returned an error subCode = exception.getSubCode(); return null; } catch (Exception exception) { return null; } } @Override protected void onPostExecute(Transaction result) { super.onPostExecute(result); if (!progressDialog.getIsCancelled()) { progressDialog.dismiss(); if (result != null) onConfirm(result, decimalAmount, selectedAsset, to); else if (subCode == null) showError(getString(R.string.tab_send_error_connection_error)); else if (subCode.equals("InsufficientFunds")) showError(getString(R.string.tab_send_error_insufficient_funds)); else if (subCode.equals("InsufficientColoredFunds")) showError(getString(R.string.tab_send_error_insufficient_asset)); else if (subCode.equals("AmountUnderDustThreshold") || subCode.equals("ChangeUnderDustThreshold")) showError(getString(R.string.tab_send_error_amount_too_low)); else showError(getString(R.string.tab_send_error_server_error)); } } }; progressDialog.configure(getString(R.string.tab_send_dialog_please_wait), getString(R.string.tab_send_dialog_verifying_balance), true); progressDialog.show(this.getActivity().getSupportFragmentManager(), ""); getTransaction.execute(); }
From source file:test.unit.be.fedict.trust.service.PersistenceTest.java
@Test public void testFindRevokedCertificate() throws Exception { // setup/*w w w. j a v a2 s. c o m*/ String issuerName = "CN=Test CA"; BigInteger serialNumber = new BigInteger("21267647932558966653497436382356969621"); BigInteger crlNumber = new BigInteger("123465789"); RevokedCertificateEntity revokedCertificateEntity = new RevokedCertificateEntity(issuerName, serialNumber, new Date(), crlNumber); this.entityManager.persist(revokedCertificateEntity); refresh(); // operate Query query = this.entityManager.createNamedQuery(RevokedCertificateEntity.QUERY_WHERE_ISSUER_SERIAL); query.setParameter("issuer", issuerName); query.setParameter("serialNumber", serialNumber.toString()); RevokedCertificateEntity resultRevokedCertificate = (RevokedCertificateEntity) query.getSingleResult(); // verify assertNotNull(resultRevokedCertificate); assertEquals(resultRevokedCertificate.getPk().getIssuer(), issuerName); assertEquals(resultRevokedCertificate.getPk().getSerialNumber(), serialNumber.toString()); assertEquals(resultRevokedCertificate.getCrlNumber(), crlNumber); refresh(); Query deleteQuery = this.entityManager .createNamedQuery(RevokedCertificateEntity.DELETE_WHERE_ISSUER_OLDER_CRL_NUMBER); deleteQuery.setParameter("issuer", issuerName); deleteQuery.setParameter("crlNumber", crlNumber); int zeroDeleteResult = deleteQuery.executeUpdate(); assertEquals(0, zeroDeleteResult); refresh(); deleteQuery.setParameter("crlNumber", crlNumber.add(new BigInteger("1"))); int deleteResult = deleteQuery.executeUpdate(); assertEquals(1, deleteResult); }
From source file:mil.jpeojtrs.sca.util.AnyUtils.java
/** * Attempts to convert the string value to the appropriate Java type. * /*from w ww.j a va 2 s . c o m*/ * @param stringValue the string form of the value * @param type the string form of the TypeCode * @return A Java object of theString corresponding to the typecode */ private static Object primitiveConvertString(final String stringValue, final String type) { if (stringValue == null) { return null; } if ("string".equals(type)) { return stringValue; } else if ("wstring".equals(type)) { return stringValue; } else if ("boolean".equals(type)) { if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) { return Boolean.parseBoolean(stringValue); } throw new IllegalArgumentException(stringValue + " is not a valid boolean value"); } else if ("char".equals(type)) { switch (stringValue.length()) { case 1: return stringValue.charAt(0); case 0: return null; default: throw new IllegalArgumentException(stringValue + " is not a valid char value"); } } else if ("wchar".equals(type)) { return stringValue.charAt(0); } else if ("double".equals(type)) { return Double.parseDouble(stringValue); } else if ("float".equals(type)) { return Float.parseFloat(stringValue); } else if ("short".equals(type)) { return Short.decode(stringValue); } else if ("long".equals(type)) { return Integer.decode(stringValue); } else if ("longlong".equals(type)) { return Long.decode(stringValue); } else if ("ulong".equals(type)) { final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L; final Long retVal = Long.decode(stringValue); if (retVal < 0 || retVal > MAX_UINT) { throw new IllegalArgumentException( "ulong value must be greater than '0' and less than " + MAX_UINT); } return retVal; } else if ("ushort".equals(type)) { final int MAX_USHORT = 2 * Short.MAX_VALUE + 1; final Integer retVal = Integer.decode(stringValue); if (retVal < 0 || retVal > MAX_USHORT) { throw new IllegalArgumentException( "ushort value must be greater than '0' and less than " + MAX_USHORT); } return retVal; } else if ("ulonglong".equals(type)) { final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2)) .add(BigInteger.ONE); final BigInteger retVal = AnyUtils.bigIntegerDecode(stringValue); if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) { throw new IllegalArgumentException( "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString()); } return retVal; } else if ("objref".equals(type)) { if ("".equals(stringValue)) { return null; } final List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:"); for (final String prefix : objrefPrefix) { if (stringValue.startsWith(prefix)) { return stringValue; } } throw new IllegalArgumentException(stringValue + " is not a valid objref value"); } else if ("octet".equals(type)) { final short MIN_OCTET = 0; final short MAX_OCTET = 0xFF; final short val = Short.decode(stringValue); if (val <= MAX_OCTET && val >= MIN_OCTET) { return Short.valueOf(val); } throw new IllegalArgumentException(stringValue + " is not a valid octet value"); } else { throw new IllegalArgumentException("Unknown CORBA Type: " + type); } }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
private void storeStartHistoryId(BigInteger startHistoryId) { Key startHistoryEntityKey = KeyFactory.createKey("StartHistroyEntityKey", "StartHistoryEntityValue"); Entity startHistroyEntity = new Entity("StartHistroyEntity", startHistoryEntityKey); startHistroyEntity.setProperty("id", startHistoryId.toString()); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); logger.warning("stored value : " + startHistoryId.toString()); datastore.put(startHistroyEntity); //save it }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Publishes a object to the ldap directory. * * @param conn a Ldap connection/*from w ww .jav a 2 s .co m*/ * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to publish cert * (null if LDAP publishing is not enabled) * @param object object to publish * (java.security.cert.X509Certificate or, * java.security.cert.X509CRL) */ public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: publish"); try { if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); String name = mDir + File.separator + "cert-" + sno.toString(); if (mDerAttr) { FileOutputStream fos = null; try { String fileName = name + ".der"; fos = new FileOutputStream(fileName); fos.write(cert.getEncoded()); } finally { if (fos != null) fos.close(); } } if (mB64Attr) { String fileName = name + ".b64"; PrintStream ps = null; Base64OutputStream b64 = null; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output))); b64.write(cert.getEncoded()); b64.flush(); ps = new PrintStream(fos); ps.print(output.toString("8859_1")); } finally { if (ps != null) { ps.close(); } if (b64 != null) { b64.close(); } if (fos != null) fos.close(); } } } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); String baseName = mDir + File.separator + namePrefix[0]; String tempFile = baseName + ".temp"; ZipOutputStream zos = null; byte[] encodedArray = null; File destFile = null; String destName = null; File renameFile = null; if (mDerAttr) { FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); encodedArray = crl.getEncoded(); fos.write(encodedArray); } finally { if (fos != null) fos.close(); } if (mZipCRL) { try { zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip")); zos.setLevel(mZipLevel); zos.putNextEntry(new ZipEntry(baseName + ".der")); zos.write(encodedArray, 0, encodedArray.length); zos.closeEntry(); } finally { if (zos != null) zos.close(); } } destName = baseName + ".der"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); if (mLatestCRL) { String linkExt = "."; if (mLinkExt != null && mLinkExt.length() > 0) { linkExt += mLinkExt; } else { linkExt += "der"; } String linkName = mDir + File.separator + namePrefix[1] + linkExt; createLink(linkName, destName); if (mZipCRL) { linkName = mDir + File.separator + namePrefix[1] + ".zip"; createLink(linkName, baseName + ".zip"); } } } // output base64 file if (mB64Attr == true) { if (encodedArray == null) encodedArray = crl.getEncoded(); FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); fos.write(Utils.base64encode(encodedArray, true).getBytes()); } finally { if (fos != null) fos.close(); } destName = baseName + ".b64"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); } purgeExpiredFiles(); purgeExcessFiles(); } } catch (IOException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CertificateEncodingException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CRLException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } }
From source file:be.fedict.eid.pkira.blm.model.contracthandler.services.FieldValidatorBean.java
protected void validateValidityPeriod(BigInteger validityPeriodMonths, List<String> messages) { // Null check is done elsewhere if (validityPeriodMonths == null) { return;// w ww.j ava 2s.c om } // Get valid periods String periodsStr = configurationEntryQuery.findByEntryKey(ConfigurationEntryKey.VALIDITY_PERIODS) .getValue(); if (periodsStr == null) { throw new RuntimeException("Validity periods not set in the configuration"); } String[] periods = periodsStr.split(","); // Check if it is there String thePeriod = validityPeriodMonths.toString(); for (String period : periods) { if (period.trim().equals(thePeriod)) { return; } } messages.add("invalid validity period"); }
From source file:dap4.dap4.Dap4Print.java
protected String valueString(Object value, DapType basetype) throws DataException { if (value == null) return "null"; AtomicType atype = basetype.getAtomicType(); boolean unsigned = atype.isUnsigned(); switch (atype) { case Int8:/* w w w.ja v a2s .c om*/ case UInt8: long lvalue = ((Byte) value).longValue(); if (unsigned) lvalue &= 0xFFL; return String.format("%d", lvalue); case Int16: case UInt16: lvalue = ((Short) value).longValue(); if (unsigned) lvalue &= 0xFFFFL; return String.format("%d", lvalue); case Int32: case UInt32: lvalue = ((Integer) value).longValue(); if (unsigned) lvalue &= 0xFFFFFFFFL; return String.format("%d", lvalue); case Int64: case UInt64: lvalue = ((Long) value).longValue(); if (unsigned) { BigInteger b = BigInteger.valueOf(lvalue); b = b.and(DapUtil.BIG_UMASK64); return b.toString(); } else return String.format("%d", lvalue); case Float32: return String.format("%f", ((Float) value).floatValue()); case Float64: return String.format("%f", ((Double) value).doubleValue()); case Char: return "'" + ((Character) value).toString() + "'"; case String: case URL: return "\"" + ((String) value) + "\""; case Opaque: ByteBuffer opaque = (ByteBuffer) value; String s = "0x"; for (int i = 0; i < opaque.limit(); i++) { byte b = opaque.get(i); char c = hexchar((b >> 4) & 0xF); s += c; c = hexchar((b) & 0xF); s += c; } return s; case Enum: return valueString(value, ((DapEnum) basetype).getBaseType()); default: break; } throw new DataException("Unknown type: " + basetype); }
From source file:org.alfresco.wcm.client.impl.WebSiteServiceImpl.java
private void refreshWebsiteCache() { Map<String, WebSite> newCache = new HashMap<String, WebSite>(5); Session session = CmisSessionHelper.getSession(); // Execute query if (log.isDebugEnabled()) { log.debug("About to run CMIS query: " + QUERY_WEB_ROOTS); }/*from www . jav a 2 s . c o m*/ ItemIterable<QueryResult> results = session.query(QUERY_WEB_ROOTS, false); for (QueryResult result : results) { // Get the details of the returned object String id = result.getPropertyValueById(PropertyIds.OBJECT_ID); String hostName = result.getPropertyValueById(WebSite.PROP_HOSTNAME); BigInteger hostPort = result.getPropertyValueById(WebSite.PROP_HOSTPORT); String context = result.getPropertyValueById(WebSite.PROP_CONTEXT); if (context == null) { context = ""; } if (context.startsWith("/")) { context = context.substring(1); } if (hostPort == null) { // Default to port 80 if not set hostPort = new BigInteger("80"); } String key = (hostName + ":" + hostPort.toString()).toLowerCase() + "/" + context; String title = result.getPropertyValueById(Asset.PROPERTY_TITLE); String description = result.getPropertyValueById(Asset.PROPERTY_DESCRIPTION); List<String> configList = result.getPropertyMultivalueById(WebSite.PROP_SITE_CONFIG); Map<String, String> configProperties = parseSiteConfig(configList); WebsiteInfo siteInfo = getWebsiteInfo(id); WebSiteImpl webSite = new WebSiteImpl(id, hostName, hostPort.intValue(), webSiteSectionCacheRefreshAfter); webSite.setRootSectionId(siteInfo.rootSectionId); webSite.setTitle(title); webSite.setDescription(description); webSite.setContext(context); webSite.setSectionFactory(sectionFactory); webSite.setConfig(configProperties); webSite.setUgcService(createUgcService(session, siteInfo)); newCache.put(key, webSite); // Find the logo asset id Asset logo = assetFactory.getSectionAsset(siteInfo.rootSectionId, logoFilename, true); webSite.setLogo(logo); } webSiteCacheRefeshedAt = System.currentTimeMillis(); webSiteCache = newCache; }
From source file:com.xerox.amazonws.sqs.MessageQueue.java
/** * Internal implementation of receiveMessages. * * @param numMessages the maximum number of messages to return * @param visibilityTimeout the duration (in seconds) the retrieved message is hidden from * subsequent calls to retrieve. * @return an array of message objects//from w w w .j a va 2s .c o m */ protected Message[] receiveMessages(BigInteger numMessages, BigInteger visibilityTimeout) throws SQSException { Map<String, String> params = new HashMap<String, String>(); if (numMessages != null) { params.put("NumberOfMessages", numMessages.toString()); } if (visibilityTimeout != null) { params.put("VisibilityTimeout", visibilityTimeout.toString()); } GetMethod method = new GetMethod(); try { ReceiveMessageResponse response = makeRequest(method, "ReceiveMessage", params, ReceiveMessageResponse.class); if (response.getMessages() == null) { return new Message[0]; } else { ArrayList<Message> msgs = new ArrayList(); for (com.xerox.amazonws.typica.jaxb.Message msg : response.getMessages()) { String decodedMsg = enableEncoding ? new String(Base64.decodeBase64(msg.getMessageBody().getBytes())) : msg.getMessageBody(); msgs.add(new Message(msg.getMessageId(), decodedMsg)); } return msgs.toArray(new Message[msgs.size()]); } } catch (JAXBException ex) { throw new SQSException("Problem parsing returned message.", ex); } catch (HttpException ex) { throw new SQSException(ex.getMessage(), ex); } catch (IOException ex) { throw new SQSException(ex.getMessage(), ex); } finally { method.releaseConnection(); } }
From source file:org.opendaylight.vpnservice.elan.utils.ElanUtils.java
/** * Builds the list of actions to be taken when sending the packet over an * external VxLan tunnel interface, such as stamping the VNI on the VxLAN * header, setting the vlanId if it proceeds and output the packet over the * right port.//from ww w. j a v a 2 s . co m * * @param srcDpnId * Dpn where the tunnelInterface is located * @param torNode * NodeId of the ExternalDevice where the packet must be sent to. * @param vni * Vni to be stamped on the VxLAN Header. * @return the external itm egress action */ public static List<Action> getExternalItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) { List<Action> result = Collections.emptyList(); GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder() .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString()) .setTunnelType(TunnelTypeVxlan.class).build(); Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService .getExternalTunnelInterfaceName(input); try { if (output.get().isSuccessful()) { GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult(); String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName(); if (logger.isDebugEnabled()) logger.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName); result = buildItmEgressActions(tunnelIfaceName, vni); } } catch (InterruptedException | ExecutionException e) { logger.error("Error in RPC call getTunnelInterfaceName {}", e); } return result; }