Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

In this page you can find the example usage for java.math BigInteger valueOf.

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:com.projity.server.data.mspdi.TimephasedGetter.java

public void execute(Object arg0) {
    if (!consumer.acceptValue(functor.getValue()))
        return; //hack LC

    TimephasedDataType timephasedDataType;
    //try {//from  w w w .  j a v  a 2s  .  co m
    timephasedDataType = factory.createTimephasedDataType();
    //      } catch (JAXBException e) {
    //         e.printStackTrace();
    //         return;
    //      }
    timephasedDataType.setType(this.type);
    timephasedDataType.setUID(this.id);
    //      System.out.println("Id is " + id);

    timephasedDataType.setUnit(BigInteger.valueOf(3L));
    HasStartAndEnd interval = (HasStartAndEnd) arg0;
    Calendar startCal = DateTime.calendarInstance();
    startCal.setTimeInMillis(DateTime.fromGmt(interval.getStart())); // for 2007, convert from gmt
    Calendar endCal = DateTime.calendarInstance();
    endCal.setTimeInMillis(DateTime.fromGmt(interval.getEnd())); // for 2007, convert from gmt
    timephasedDataType.setStart(startCal);
    timephasedDataType.setFinish(endCal);
    double v = functor.getValue() / WorkCalendar.MILLIS_IN_HOUR;
    net.sf.mpxj.Duration d = net.sf.mpxj.Duration.getInstance(v, TimeUnit.HOURS);
    XsdDuration xsdDuration = new XsdDuration(d);
    timephasedDataType.setValue(xsdDuration.toString());
    consumer.consumeTimephased(timephasedDataType);
}

From source file:net.sf.dsig.verify.OCSPHelper.java

/**
 * Check with OCSP protocol whether a certificate is valid
 * /*  ww w .  j a  v a 2  s .co m*/
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:Main.java

public static Duration subtract(XMLGregorianCalendar x1, XMLGregorianCalendar x2) {
    boolean positive = x1.compare(x2) >= 0;

    if (!positive) {
        XMLGregorianCalendar temp = x1;
        x1 = x2;/* ww  w  .j a v a2  s.co m*/
        x2 = temp;
    }

    BigDecimal s1 = getSeconds(x1);
    BigDecimal s2 = getSeconds(x2);
    BigDecimal seconds = s1.subtract(s2);
    if (seconds.compareTo(BigDecimal.ZERO) < 0)
        seconds = seconds.add(BigDecimal.valueOf(60));

    GregorianCalendar g1 = x1.toGregorianCalendar();
    GregorianCalendar g2 = x2.toGregorianCalendar();

    int year = 0;
    for (int f : reverseFields) {
        if (f == Calendar.YEAR) {
            int year1 = g1.get(f);
            int year2 = g2.get(f);
            year = year1 - year2;
        } else {
            subtractField(g1, g2, f);
        }
    }

    return FACTORY.newDuration(positive, BigInteger.valueOf(year), BigInteger.valueOf(g1.get(Calendar.MONTH)),
            BigInteger.valueOf(g1.get(Calendar.DAY_OF_MONTH) - 1),
            BigInteger.valueOf(g1.get(Calendar.HOUR_OF_DAY)), BigInteger.valueOf(g1.get(Calendar.MINUTE)),
            seconds);
}

From source file:piuk.MyRemoteWallet.java

public synchronized BigInteger getBalance(String address) {
    if (this.multiAddrBalancesRoot != null && this.multiAddrBalancesRoot.containsKey(address)) {
        return BigInteger
                .valueOf(((Number) this.multiAddrBalancesRoot.get(address).get("final_balance")).longValue());
    }//from   w  ww.  j  av a  2s .c o m

    return BigInteger.ZERO;
}

From source file:com.emergya.siradmin.invest.InvestmentUpdater.java

public List<LlaveBean> getExistingKeysInChileindica(Integer ano, Integer codigoRegion) {
    LOGGER.info("Obteniendo llaves para del ao " + ano + " y la regin " + codigoRegion);
    try {//from w  w  w.jav  a  2  s .c  o m
        List<LlaveBean> keys = null;
        ConsultaLlavesResponse response = wsConsultaLlaves.getWSConsultaLlavesPort().WSConsultaLlaves(
                BigInteger.valueOf(ano.longValue()), BigInteger.valueOf(codigoRegion.longValue()));
        Respuesta respuesta = response.getRespuesta();
        if (!BigInteger.ZERO.equals(respuesta.getCodigoRespuesta())) {
            LOGGER.error(
                    "El servicio web Consulta de llaves " + wsConsultaLlaves.getWSConsultaLlavesPortAddress()
                            + " ha devuelto un cdigo de error " + respuesta.getCodigoRespuesta()
                            + ". El mensaje de error fue: " + respuesta.getTextoRespuesta());
            throw new WSCallException(respuesta.getCodigoRespuesta(), respuesta.getTextoRespuesta());

        }
        if (response.getLlavesInversion() != null) {
            keys = new ArrayList<LlaveBean>(response.getLlavesInversion().length);
            for (LlavesInversionData projectKey : response.getLlavesInversion()) {
                LlaveBean key = new LlaveBean();
                key.setAno(projectKey.getAno().intValue());
                key.setRegion(codigoRegion);
                key.setcFicha(projectKey.getC_Ficha().intValue());
                key.setcInstitucion(projectKey.getC_Institucion().intValue());
                key.setcPreinversion(projectKey.getC_Preinversion().intValue());
                BigInteger fechaRegistro = projectKey.getFechaRegistro();
                if (fechaRegistro != null) {
                    key.setFechaRegistro(fechaRegistro.intValue());
                }

                boolean updatable = service.checkIfProjectMustBeUpdated(key.getRegion(), key.getAno(),
                        key.getcInstitucion(), key.getcPreinversion(), key.getcFicha(), key.getFechaRegistro());
                key.setUpdatable(updatable);

                keys.add(key);
            }
            return keys;
        } else {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("El WS de consulta de llaves no ha devuelto datos para el ao " + ano
                        + " y la regin " + codigoRegion);
            }
            return new ArrayList<LlaveBean>();
        }

    } catch (RemoteException e) {
        LOGGER.error("Error llamando al servicio web " + wsConsultaLlaves.getWSConsultaLlavesPortAddress(), e);
        throw new WSCallException(e);
    } catch (ServiceException e) {
        LOGGER.error("Error llamando al servicio web " + wsConsultaLlaves.getWSConsultaLlavesPortAddress(), e);
        throw new WSCallException(e);
    }

}

From source file:io.udvi.amqp.mq.transport.link.CAMQPLinkEndpoint.java

/**
 * Establishes an AMQP link to a remote AMQP end-point.
 *
 * @param sourceName/*w  ww.j a va  2 s .c  o  m*/
 * @param targetName
 */
void createLink(String sourceName, String targetName, CAMQPEndpointPolicy endpointPolicy) {
    this.endpointPolicy = endpointPolicy;
    sourceAddress = sourceName;
    targetAddress = targetName;

    linkHandle = CAMQPLinkManager.getNextLinkHandle();
    linkName = UUID.randomUUID().toString();
    CAMQPLinkManager.getLinkHandshakeTracker().registerOutstandingLink(linkName, this);

    CAMQPControlAttach data = new CAMQPControlAttach();
    data.setHandle(linkHandle);
    data.setName(linkName);
    data.setRole(getRole() == LinkRole.LinkReceiver);

    CAMQPDefinitionSource source = new CAMQPDefinitionSource();
    source.setAddress(sourceAddress);
    if (endpointPolicy.getEndpointType() == EndpointType.TOPIC) {
        source.setDistributionMode(CAMQPConstants.STD_DIST_MODE_COPY);
    }
    data.setSource(source);

    CAMQPDefinitionTarget target = new CAMQPDefinitionTarget();
    target.setAddress(targetAddress);
    data.setTarget(target);

    source.setDynamic(false);
    if (getRole() == LinkRole.LinkSender) {
        data.setInitialDeliveryCount(deliveryCount);
    }

    /*
     * Populate the end-point policy info to the ATTACH frame.
     */
    data.setMaxMessageSize(BigInteger.valueOf(endpointPolicy.getMaxMessageSize()));
    data.setSndSettleMode(endpointPolicy.getSenderSettleMode());
    data.setRcvSettleMode(endpointPolicy.getReceiverSettleMode());

    /*
     * Populate custom Endpoint properties
     */
    if (!endpointPolicy.getCustomProperties().isEmpty()) {
        data.getProperties().putAll(endpointPolicy.getCustomProperties());
        data.setRequiredProperties(true);
    }

    linkStateActor.sendAttach(data);
    linkStateActor.waitForAttached(targetAddress);
}

From source file:com.github.nginate.commons.testing.Unique.java

/**
 * Generate unique big integer from unique long
 *
 * @return unique big integer/*from w  w  w .  j  a  v a  2 s  .c om*/
 * @see BigInteger#valueOf(long)
 */
@Nonnull
public static BigInteger uniqueBigInteger() {
    return BigInteger.valueOf(uniqueLong());
}

From source file:org.osmsurround.ae.osmrequest.OsmSignedRequestTemplate.java

protected ByteArrayOutputStream marshallIntoBaos(OsmBasicType amenity, int changesetId) throws JAXBException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    amenity.setChangeset(BigInteger.valueOf(changesetId));
    schemaService.createOsmMarshaller().marshal(osmConvertService.toJaxbElement(amenity), baos);
    return baos;/*from  ww w. ja v  a  2 s. c o m*/
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createRootCaCert(final KeyPair keyPair) throws Exception {

    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

    X500Name idn = X500NameUtil.createRootPrincipal();
    BigInteger sno = BigInteger.valueOf(1);
    Date nb = new Date(System.currentTimeMillis() - ONE_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, idn, pubKey);

    addSubjectKID(certBuilder, pubKey);/*  w  ww .  ja  v  a2s  .c  om*/
    addAuthorityKID(certBuilder, pubKey);
    addCRLDistributionPoints(certBuilder);
    addAuthorityInfoAccess(certBuilder);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, privKey);
    certificate.checkValidity(new Date());
    certificate.verify(pubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesServiceTest.java

/**
 * Test method for {@link com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesService#insertUserIfNotExists(biz.futureware.mantis.rpc.soap.client.AccountData, java.math.BigInteger)}.
 *//*from w  w  w .  ja  v a 2 s.c o  m*/
@Test
public void testInsertUserIfNotExists() {
    final Operation op = insertInto("mantis_project_table").columns("id", "name").values(1, "project_1")
            .build();

    lauchOperation(op);

    final AccountData item = new AccountData();
    item.setId(BigInteger.valueOf(1));
    item.setName("new_user_1");

    dao.insertUserIfNotExists(item, BigInteger.ONE);

    final List<AccountData> list = getJdbcTemplate()
            .query("SELECT usr.id, usr.name" + " FROM mantis_user_table usr"
                    + " INNER JOIN mantis_project_user_list_table pul ON pul.user_id = usr.id"
                    + " WHERE pul.project_id = 1", new BeanPropertyRowMapper<AccountData>(AccountData.class));

    assertEquals(1, list.size());
    assertEquals(item, list.get(0));

    dao.insertUserIfNotExists(item, BigInteger.ONE);
}