List of usage examples for java.math BigInteger valueOf
private static BigInteger valueOf(int val[])
From source file:com.wms.utils.DataUtil.java
public static BigInteger ipv4ToNumber(String ipAddress) { BigInteger result = BigInteger.valueOf(0); String[] atoms = ipAddress.split("\\."); for (int i = 3; i >= 0; i--) { BigInteger bi = new BigInteger(atoms[3 - i]); result = result.shiftLeft(8).add(bi); }/*from w w w .j av a2s.c o m*/ return result; }
From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java
public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, KeyPair keyPair, KeyPair pKeyPair) throws Exception { PublicKey pPubKey = pKeyPair.getPublic(); PrivateKey pPrivKey = pKeyPair.getPrivate(); X500Name idn = X500NameUtil.createClass3RootPrincipal(); BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + FIVE_YEAR); PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey); addSubjectKID(certBuilder, pubKey);//from w w w .j a v a 2 s .c o m addAuthorityKID(certBuilder, pPubKey); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU)); certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE)); if (exts != null) { Set<String> key = exts.keySet(); for (Iterator<String> it = key.iterator(); it.hasNext();) { String oid = it.next(); String value = exts.get(oid); if (!StringUtils.isBlank(value)) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, new DEROctetString(value.getBytes())); } } } X509Certificate certificate = signCert(certBuilder, pPrivKey); certificate.checkValidity(new Date()); certificate.verify(pPubKey); setPKCS9Info(certificate); return certificate; }
From source file:com.lenovo.tensorhusky.common.utils.LinuxResourceCalculatorPlugin.java
/** * Read /proc/stat file, parse and calculate cumulative CPU *///from ww w.ja va2 s .c o m private void readProcStatFile() { // Read "/proc/stat" file BufferedReader in = null; InputStreamReader fReader = null; try { fReader = new InputStreamReader(new FileInputStream(procfsStatFile), Charset.forName("UTF-8")); in = new BufferedReader(fReader); } catch (FileNotFoundException f) { // shouldn't happen.... return; } Matcher mat = null; try { String str = in.readLine(); while (str != null) { mat = CPU_TIME_FORMAT.matcher(str); if (mat.find()) { long uTime = Long.parseLong(mat.group(1)); long nTime = Long.parseLong(mat.group(2)); long sTime = Long.parseLong(mat.group(3)); cpuTimeTracker.updateElapsedJiffies(BigInteger.valueOf(uTime + nTime + sTime), getCurrentTime()); break; } str = in.readLine(); } } catch (IOException io) { LOG.warn("Error reading the stream " + io); } finally { // Close the streams try { fReader.close(); try { in.close(); } catch (IOException i) { LOG.warn("Error closing the stream " + in); } } catch (IOException i) { LOG.warn("Error closing the stream " + fReader); } } }
From source file:org.mongojack.internal.object.BsonObjectTraversingParser.java
@Override public BigInteger getBigIntegerValue() throws IOException { Number n = currentNumericNode(); if (n instanceof BigInteger) { return (BigInteger) n; } else {//from www . ja v a 2s . c o m return BigInteger.valueOf(n.longValue()); } }
From source file:com.github.jrrdev.mantisbtsync.core.jobs.enums.EnumsWritersTest.java
/** * Build the items to write./* w w w .ja v a 2 s. com*/ * * @return items to write */ private List<ObjectRef> buildItems() { final List<ObjectRef> items = new ArrayList<ObjectRef>(); final ObjectRef item1 = new ObjectRef(BigInteger.valueOf(1), "new_value_1"); final ObjectRef item2 = new ObjectRef(BigInteger.valueOf(3), "new_value_3"); items.add(item1); items.add(item2); return items; }
From source file:de.fischer.thotti.core.runner.NDRunner.java
private TestSuiteResult generatedTestResult(List<NDTestResult> resultList) throws RunnerException { if (null == resultList) { throw new NullPointerException(); }/* ww w. j a va 2s . c o m*/ DatatypeFactory datatypeFac = null; try { datatypeFac = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new RunnerException("Failed to instanciate datatype factory.", e); } de.fischer.thotti.core.resources.ndtest.ObjectFactory factory = new de.fischer.thotti.core.resources.ndtest.ObjectFactory(); de.fischer.thotti.core.resources.ndresult.ObjectFactory factory2 = new de.fischer.thotti.core.resources.ndresult.ObjectFactory(); TestSuiteResult suiteResult = factory2.createTestSuiteResult(); for (NDTestResult result : resultList) { NonDistributedTestResultType ndResult = factory2.createNonDistributedTestResultType(); Duration execTime = datatypeFac.newDuration(result.getExecutionTime()); XMLGregorianCalendar startTime = datatypeFac.newXMLGregorianCalendar(result.getStartTime()); ndResult.setTestID(result.getTestId()); ndResult.setExitCode(BigInteger.valueOf(result.getExitCode())); ndResult.setJvmArgsID(result.getJVMArgsID()); ndResult.setJvmArgs(result.getJvmArgs()); ndResult.setExecutionTimeMS(execTime); ndResult.setStartedAt(startTime); ndResult.setParamGrpID(result.getParamGrpID()); try { ndResult.setMahoutVersion(org.apache.mahout.Version.versionFromResource()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } suiteResult.getNonDistributedTestResults().add(ndResult); } suiteResult.setUuid(generateResultUUID()); return suiteResult; }
From source file:org.basdroid.common.NetworkUtils.java
public static String getMacAddressFromNetworkInterface(final Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); }// w w w . j a v a2s . c o m byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); String result; try { InetAddress addr = InetAddress.getByAddress(bytes); NetworkInterface netInterface = NetworkInterface.getByInetAddress(addr); Log.d(TAG, "Wifi netInterface.getName() = " + netInterface.getName()); byte[] mac = netInterface.getHardwareAddress(); if (mac == null || mac.length == 0) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) { buf.append(String.format("%02X:", mac[idx])); } if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } catch (UnknownHostException ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Unknown host.", ex); result = null; } catch (SocketException ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Socket exception.", ex); result = null; } catch (Exception ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Exception.", ex); result = null; } return result; }
From source file:com.emergya.siradmin.invest.InvestmentUpdater.java
public void getWsDataAndUpdateDB(List<LlaveBean> wsProjectList) { // 1. Get an iterator of all Chileindica // 2. Traverse the list of LlaveBean // 3. For every LlaveBean mark database element as no removable // 4. If llaveBean is Updatable, create or update element in DataBase. // 5. If there is any problem cheking with the web service, mark the // element as update error. List<Long> projectDbIds = service.getAllProjectDbIds(); Collections.sort(wsProjectList); for (Iterator<Long> iterator = projectDbIds.iterator(); iterator.hasNext();) { Long dbId = iterator.next(); ChileindicaInversionDataDto dto = (ChileindicaInversionDataDto) service.getById(dbId); LlaveBean keyToSearch = new LlaveBean(); keyToSearch.setAno(dto.getAno()); keyToSearch.setRegion(dto.getRegion()); keyToSearch.setcFicha(dto.getCFicha()); keyToSearch.setcInstitucion(dto.getCInstitucion()); keyToSearch.setcPreinversion(dto.getCPreinversion()); if (LOGGER.isInfoEnabled()) { LOGGER.info("Tratando proyecto existente BBDD " + keyToSearch); }/* ww w .j a va 2 s.c o m*/ // Buscamos si el proyecto existe entre las claves actuales int foundKeyIndex = Collections.binarySearch(wsProjectList, keyToSearch); if (foundKeyIndex >= 0) { LlaveBean foundKey = wsProjectList.get(foundKeyIndex); iterator.remove(); wsProjectList.remove(foundKeyIndex); if (LOGGER.isInfoEnabled()) { LOGGER.info("El proyecto sigue existiendo en el servicio web de consulta de llaves"); } // Si el proyecto ha sido actualizado en Chileindica recuperamos // los detalles del servicio web, borramos el proyecto original // de // la base de datos y creamos una entrada nueva en BD if (foundKey.isUpdatable()) { try { ConsultaInversionPorLlaveGeorefResponse response = this.wsConsultaInversion .getWSConsultaInversionPorLlaveGeorefPort() .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(foundKey.getRegion()), BigInteger.valueOf(foundKey.getAno()), BigInteger.valueOf(foundKey.getcInstitucion()), BigInteger.valueOf(foundKey.getcPreinversion()), BigInteger.valueOf(foundKey.getcFicha())); com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response .getRespuesta(); BigInteger codRespuesta = respuesta.getCodigoRespuesta(); if (BigInteger.ZERO.equals(codRespuesta)) { // delete from DB and create new instance service.delete(dto); ChileindicaInversionDataDto updatedProject = createDtoFromWsResponse(response, foundKey); service.create(updatedProject); foundKey.setStatus(UpdateStatus.OK); if (LOGGER.isInfoEnabled()) { LOGGER.info("Proyecto en BBDD actualizado"); } } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("Error obteniendo informacin del proyecto " + foundKey + ". Cdigo de repuesta = " + codRespuesta + ". Mensaje = " + respuesta.getTextoRespuesta()); } // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); foundKey.setStatus(UpdateStatus.WS_ERROR); service.update(dto); } } catch (DataAccessException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error almacenando proyecto " + foundKey + " en base de datos", e); } foundKey.setStatus(UpdateStatus.DB_ERROR); } catch (RemoteException e) { // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } catch (ServiceException e) { // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } catch (Throwable e) { dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("El proyecto no necesita ser actualizado en BBDD"); } } } else { // si el proyecto no ha sido devuleto por el WS Consulta de // llaves, se borra de la base de datos service.delete(dto); if (LOGGER.isInfoEnabled()) { LOGGER.info("Se elimina el proyecto por no existir en la consulta de llaves " + keyToSearch); } } } // En este punto los elementos que quedan en projectDbIds pueden ser // eliminados de la base de datos puesto que no han sido devueltos por // el servicio web de consulta de llaves // for (Long id : projectDbIds) { // service.deleteById(id); // } // Ahora se crean los proyectos que queden en la lista de llaves // devueltas // por el servicio web. for (LlaveBean llave : wsProjectList) { ConsultaInversionPorLlaveGeorefResponse response; try { response = this.wsConsultaInversion.getWSConsultaInversionPorLlaveGeorefPort() .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(llave.getRegion()), BigInteger.valueOf(llave.getAno()), BigInteger.valueOf(llave.getcInstitucion()), BigInteger.valueOf(llave.getcPreinversion()), BigInteger.valueOf(llave.getcFicha())); com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response.getRespuesta(); BigInteger codRespuesta = respuesta.getCodigoRespuesta(); if (BigInteger.ZERO.equals(codRespuesta)) { ChileindicaInversionDataDto newProject = createDtoFromWsResponse(response, llave); service.create(newProject); llave.setStatus(UpdateStatus.OK); if (LOGGER.isInfoEnabled()) { LOGGER.info("Creada nueva entrada en BBDD"); } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error( "Error obteniendo informacin del proyecto " + llave + ". Cdigo de repuesta = " + codRespuesta + ". Mensaje = " + respuesta.getTextoRespuesta()); } llave.setStatus(UpdateStatus.WS_ERROR); } } catch (DataAccessException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error almacenando proyecto " + llave + " en base de datos", e); } llave.setStatus(UpdateStatus.DB_ERROR); } catch (RemoteException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } catch (ServiceException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } catch (Throwable e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } } }
From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java
@Override public X509Certificate generateCertificate(PublicKey key, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey, Date notAfter) { if (signingKey == null) { LOG.error("No signing key is provided"); return null; }//from w ww .j av a2 s . co m if (signer == null) { LOG.error("No signiner principal is specified"); return null; } if (subjectDn == null) { LOG.error("No subject principal is specified"); return null; } if (key == null) { LOG.error("No requesting key is specified"); return null; } EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(key)); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); certGen.setNotAfter(notAfter); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(key); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:jp.aegif.nemaki.cmis.service.impl.NavigationServiceImpl.java
private List<ObjectInFolderContainer> getDescendantsInternal(CallContext callContext, String repositoryId, ObjectData node, String filter, Boolean includeAllowableActions, Boolean includeAcl, IncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments, int level, int maxLevels, boolean folderOnly) { List<ObjectInFolderContainer> childrenOfFolder = new ArrayList<ObjectInFolderContainer>(); // Check specified folderId is folder(if not, it's a leaf node) if (node.getBaseTypeId() != BaseTypeId.CMIS_FOLDER) { return childrenOfFolder; }//from w ww .j a v a 2s. c o m String folderId = node.getId(); if (maxLevels == -1 || level < maxLevels) { ObjectInFolderList children = getChildrenInternal(callContext, repositoryId, folderId, filter, null, includeAllowableActions, includeRelationships, renditionFilter, includePathSegments, BigInteger.valueOf(Integer.MAX_VALUE), BigInteger.valueOf(0), folderOnly); childrenOfFolder = new ArrayList<ObjectInFolderContainer>(); if (null != children && CollectionUtils.isNotEmpty(children.getObjects())) { for (ObjectInFolderData child : children.getObjects()) { ObjectInFolderContainerImpl oifc = new ObjectInFolderContainerImpl(); List<ObjectInFolderContainer> subChildren = getDescendantsInternal(callContext, repositoryId, child.getObject(), filter, includeAllowableActions, includeAcl, includeRelationships, renditionFilter, includePathSegments, level + 1, maxLevels, folderOnly); oifc.setObject(child); if (CollectionUtils.isNotEmpty(subChildren)) oifc.setChildren(subChildren); childrenOfFolder.add(oifc); } } } return childrenOfFolder; }