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.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a certificate builder.//w w  w.ja  v  a  2 s  .c  om
 *
 * @param publicKey
 *            public key for the certificate builder
 * @param issuer
 *            issuer for the certificate builder
 * @return a certificate builder
 * @throws IOException
 *             if any format error occurrs while creating the certificate
 */
private final X509v3CertificateBuilder getCertificateBuilder(final PublicKey publicKey, final String issuer)
        throws IOException {
    final X500Name issuerName; // Issuer name
    final X500Name subjectName; // Subject name
    final BigInteger serial; // Serial number
    final X509v3CertificateBuilder builder; // Certificate builder
    final Date start; // Certificate start date
    final Date end; // Certificate end date
    final KeyUsage usage; // Key usage
    final ASN1EncodableVector purposes; // Certificate purposes

    issuerName = new X500Name(issuer);
    subjectName = issuerName;
    serial = BigInteger.valueOf(getRandom().nextInt());

    // Dates for the certificate
    start = getOneYearBackDate();
    end = getOneHundredYearsFutureDate();

    builder = new JcaX509v3CertificateBuilder(issuerName, serial, start, end, subjectName, publicKey);

    builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
    builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    builder.addExtension(Extension.keyUsage, false, usage);

    purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

    return builder;

}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

/**
 * Test the reader for the table mantis_project_version_table.
 *
 * @throws Exception/*from   www. ja  v a 2s. c  om*/
 *          Technical Exception
 */
@Test
public void testProjectVersionsReader() throws Exception {
    final ProjectVersionData[] expected = new ProjectVersionData[] {
            new ProjectVersionData(BigInteger.ONE, "version_1", BigInteger.ONE, null, null, null, null),
            new ProjectVersionData(BigInteger.valueOf(2), "version_2", BigInteger.ONE, null, null, null,
                    null) };

    Mockito.when(clientStub.mc_project_get_versions("toto", "passwd", BigInteger.ONE)).thenReturn(expected);

    projectVersionsReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final ProjectVersionData item = projectVersionsReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i].getId(), item.getId());
            assertEquals(expected[i].getName(), item.getName());
            assertEquals(expected[i].getProject_id(), item.getProject_id());
        } else {
            assertNull(item);
        }
    }
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

private void generateCertificate() {
    X500Name name = new X500Name(this.name);
    BigInteger serial = BigInteger.valueOf(1);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(this.keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(name, serial,
            this.notBefore, this.notAfter, name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {//from  w  w  w. j  a v  a  2 s.  c  om
        asymmetricKeyParameter = PrivateKeyFactory.createKey(this.keyPair.getPrivate().getEncoded());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

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

public X509Certificate createClass1EndCert(X500Name sdn, PublicKey pubKey, KeyPair pKeyPair) throws Exception {

    PublicKey pPubKey = pKeyPair.getPublic();
    PrivateKey pPrivKey = pKeyPair.getPrivate();

    X500Name issuer = X500NameUtil.createClass1RootPrincipal();
    BigInteger sno = BigInteger.valueOf(System.currentTimeMillis());
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + FIVE_YEAR);

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

    addSubjectKID(certBuilder, pubKey);/*from  w ww . j  a  v a2s .c  o m*/
    addAuthorityKID(certBuilder, pPubKey);
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));
    certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE));

    X509Certificate certificate = signCert(certBuilder, pPrivKey);
    certificate.checkValidity(new Date());
    certificate.verify(pPubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle,
        JSONObject submitConfig) throws ClientProtocolException, IOException {

    String url = getSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody)
            .addPart("json", configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig);

    Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize());

    Object jobId = jsonResponse.get("jobId");
    if (jobId == null)
        return BigInteger.valueOf(-1);
    return new BigInteger(jobId.toString());
}

From source file:main.java.utils.Utility.java

public static String asUnsignedDecimalString(long l) {
    /** the constant 2^64 */
    BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
    BigInteger b = BigInteger.valueOf(l);

    if (b.signum() < 0) {
        b = b.add(TWO_64);//ww  w.j  ava 2  s.c  o  m
    }

    return b.toString();
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

public X509Certificate createX509Certificate(String userName, java.security.KeyPair keyPair) {
    try {// ww  w .j a  va2  s  . co  m
        DateTime startDate = new DateTime().minusDays(1);
        DateTime expiryDate = new DateTime().plusYears(2);

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal dnName = new X500Principal("CN=" + userName);

        certGen.setSubjectDN(dnName);
        // same as subject : self signed certificate
        certGen.setIssuerDN(dnName);
        certGen.setNotBefore(startDate.toDate());
        certGen.setNotAfter(expiryDate.toDate());
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

        return certGen.generate(keyPair.getPrivate(), "BC");

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:net.beaconcontroller.tutorial.LearningSwitchTutorial.java

/**
 * TODO: Learn the source MAC:port pair for each arriving packet. Next send
 * the packet out the port previously learned for the destination MAC, if it
 * exists. Otherwise flood the packet similarly to forwardAsHub.
 * /*from   w  ww  . j a  va 2 s  . co m*/
 * @param sw
 *            the OpenFlow switch object
 * @param pi
 *            the OpenFlow Packet In object
 * @throws IOException
 */
/*
 * public void forwardAsLearningSwitch(IOFSwitch sw, OFPacketIn pi) throws
 * IOException { Map<Long,Short> macTable = macTables.get(sw);
 * 
 * /** START HERE: You'll find descriptions of what needs to be done below
 * here, and starter pseudo code. Your job is to uncomment and replace the
 * pseudo code with actual Java code.
 * 
 * First build the OFMatch object that will be used to match packets from
 * this new flow. See the OFMatch and OFPacketIn class Javadocs, which if
 * you are using the tutorial archive, are in the apidocs folder where you
 * extracted it.
 * 
 * OFMatch match = new OFMatch(); match.loadFromPacket(pi.getPacketData(),
 * pi.getInPort()); byte[] dlDst = match.getDataLayerDestination(); Long
 * dlDstId = Ethernet.toLong(dlDst); byte[] dlSrc =
 * match.getDataLayerSource(); Long dlSrcId = Ethernet.toLong(dlSrc); int
 * bufferId = pi.getBufferId();
 * 
 * /** Learn that the host with the source MAC address in this packet is
 * reachable at the port this packet arrived on. Put this source MAC:port
 * pair into the macTable object for future lookups. HINT: you can use
 * Ethernet.toLong to convert from byte[] to Long, which is the key for the
 * macTable Map object.
 * 
 * macTable.put(dlSrcId,pi.getInPort());
 * log.info("Learned MAC address {} is at port {}", dlSrcId,
 * pi.getInPort());
 * 
 * /** Retrieve the port this packet should be sent out by getting the port
 * associated with the destination MAC address in this packet from the
 * macTable object.
 * 
 * Short outPort = null; if (macTable.containsKey(dlDstId)) outPort =
 * macTable.get(dlDstId);
 * 
 * if(outPort!=null){
 * 
 * }else {
 * 
 * }
 * 
 * /** If the outPort is known for the MAC address (the return value from
 * macTable is not null), then Phase 1: Create and send an OFPacketOut,
 * sending it to the outPort learned previously. After this is tested and
 * works move to phase 2.
 * 
 * Phase 2: Instead of an OFPacketOut, create and send an OFFlowMod using
 * the match created earlier from the packet, and send matched packets to
 * the outPort. For extra credit, after sending the OFFlowMod, send an
 * OFPacketOut, but only if the switch did not buffer the packet
 * (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE), and be sure to set the
 * OFPacketOut's data with the data in pi.
 * 
 * Else if the outPort is not known (return value from macTable is null),
 * then use the forwardAsHub method to send an OFPacketOut that floods out
 * all ports except the port the packet came in.
 * 
 * 
 * // if (outPort != null) { // Phase 1: // OFPacketOut po = ... // ... fill
 * in po, unicast to outPort // ... send po to the switch // // Phase 2: //
 * Comment out the code from phase 1 // OFFlowMod fm = ... // ... fill in fm
 * // ... send fm to the switch // Extra credit: // if (...) { //
 * OFPacketOut po = ... // ... fill in po, unicast to outPort // ... set
 * po's data from pi's data // ... send po to the switch // } //} else { //
 * forwardAsHub(sw, pi); //} }
 */

public static void forwardAsLearningSwitch(IOFSwitch sw, OFPacketIn pi) throws IOException {
    Map<Long, Short> macTable = macTables.get(sw);

    // Build the Match
    OFMatch match = OFMatch.load(pi.getPacketData(), pi.getInPort());

    // Learn the port to reach the packet's source MAC
    macTable.put(Ethernet.toLong(match.getDataLayerSource()), pi.getInPort());

    // Retrieve the port previously learned for the packet's dest MAC
    Short outPort = macTable.get(Ethernet.toLong(match.getDataLayerDestination()));
    byte[] dlDst = match.getDataLayerDestination();
    Long dlDstId = Ethernet.toLong(dlDst);
    byte[] dlSrc = match.getDataLayerSource();
    Long dlSrcId = Ethernet.toLong(dlSrc);
    int bufferId = pi.getBufferId();

    //  JSONObject doc = new JSONObject();
    HashMap doc = new HashMap();
    doc.put(("OF_PACKETS_DEST"), dlDstId);
    doc.put(("OF_PACKETS_SRC"), dlSrcId);
    doc.put(("OF_PACKETS_SRCPORT"), match.getInputPort());
    if (outPort != null) {
        doc.put(("OF_PACKETS_DESTPORT"), outPort);
    } else {
        doc.put(("OF_PACKETS_DESTPORT"), "Flood");
    }

    String netSrc = Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray())
            .toString();
    netSrc = netSrc.substring(1, netSrc.length());
    //doc.put(("OF_PACKETS_NETSRC"),Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray()).toString());
    doc.put(("OF_PACKETS_NETSRC"), netSrc);
    String netDest = Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray())
            .toString();
    netDest = netDest.substring(1, netDest.length());

    doc.put(("OF_PACKETS_NETDEST"), Inet4Address
            .getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray()).toString());

    doc.put(("OF_PACKETS_NETDEST"), netDest);
    doc.put(("OF_PACKETS_SWITCHID"), sw.getId());
    ByteBuffer datap = ByteBuffer.allocate(pi.getLength());
    pi.writeTo(datap);
    doc.put(("OF_PACKETS_OBJ"), datap.array());
    doc.put(("OF_PACKETS_PACKETTYPE"), pi.getType().toString());
    doc.put(("OF_PACKETS_TIMESTAMP"), System.currentTimeMillis());

    try {
        System.out.println("Src:" + dlSrcId + " Dst:" + dlDstId + "SWID:" + sw.getId());
    } catch (Exception exp) {
        System.out.println(exp.toString());
    }

    System.out.println("1" + match.getInputPort());
    System.out.println("2"
            + Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray()).toString());
    System.out.println("3" + Inet4Address
            .getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray()).toString());
    System.out.println(
            "4" + match.getNetworkTypeOfService() + " -- " + Ethernet.toLong(match.getDataLayerSource()));

    try {
        IPv4 ipd = new IPv4();
        ipd.deserialize(pi.getPacketData(), 0, pi.getPacketData().length);
        System.out.println("IP::" + ipd.getIdentification());
        doc.put(("OF_PACKETS_IDEN"), (Short) ipd.getIdentification());
    } catch (Exception e) {
        //e.printStackTrace();
    }

    System.out.println("5 " + pi.getPacketData());

    //SDNDe sdnde = new SDNDe(db);

    if (Settings.isSet() && Settings.BREAKPOINT.equals(Settings.getFnName())
            && String.valueOf(sw.getId()).equals(Settings.getSid())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        Settings.bkQ.add(new AbstractMap.SimpleEntry(sw, new AbstractMap.SimpleEntry(pi, doc)));
        System.out.println("In BreakPoint:" + Settings.bkQ.size());
        for (Entry e : Settings.bkQ)
            System.out.println("Entry:" + e.getKey() + "=" + e.getValue());
        SocketServer.sendAsyncPacket(Settings.BREAKPOINT, null);
        return;

    } else if (Settings.isSet() && Settings.MONITOR.equals(Settings.getFnName())
            && String.valueOf(sw.getId()).equals(Settings.getSid())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        //Settings.bkQ.add(new AbstractMap.SimpleEntry(sw,new AbstractMap.SimpleEntry(pi, doc)));
        //Settings.bkQ.put((Long)sw.getId(), new AbstractMap.SimpleEntry(sw,pi));
        //System.out.println("In Monitor:"+Settings.bkQ.size());
        //for(Entry e:Settings.bkQ)
        //System.out.println("Entry:"+e.getKey()+"="+e.getValue());
        SocketServer.sendAsyncPacket(Settings.MONITOR, doc);
        //return;
    } else if (Settings.isSet() && Settings.STEP.equals(Settings.getFnName())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        /*synchronized (Settings.bkQ) {
           Settings.bkQ.add(new AbstractMap.SimpleEntry(sw,new AbstractMap.SimpleEntry(pi, doc)));
            System.out.println("In Step:"+Settings.bkQ.size());
            for(Entry e:Settings.bkQ)
          System.out.println("Entry:"+e.getKey()+"="+e.getValue());
        }*/

        SocketServer.sendAsyncPacket(Settings.STEP, null);
        if (!Settings.getSid().equals(String.valueOf(sw.getId()))) {
            Settings.setFnName(Settings.BREAKPOINT);
            Settings.setSid(String.valueOf(sw.getId()));
            Settings.bkQ.add(new AbstractMap.SimpleEntry(sw, new AbstractMap.SimpleEntry(pi, doc)));
            return;
        }

    }
    db.createPacketInDB(doc);

    if (outPort != null) {
        // Destination port known, push down a flow
        OFFlowMod fm = new OFFlowMod();
        fm.setBufferId(pi.getBufferId());
        // Use the Flow ADD command
        fm.setCommand(OFFlowMod.OFPFC_ADD);
        // Time out the flow after 5 seconds if inactivity
        fm.setIdleTimeout((short) 5);
        // Match the packet using the match created above
        fm.setMatch(match);
        // Send matching packets to outPort
        OFAction action = new OFActionOutput(outPort);
        fm.setActions(Collections.singletonList((OFAction) action));
        // Send this OFFlowMod to the switch
        sw.getOutputStream().write(fm);

        if (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
            /**
             * EXTRA CREDIT: This is a corner case, the packet was not
             * buffered at the switch so it must be sent as an OFPacketOut
             * after sending the OFFlowMod
             */
            OFPacketOut po = new OFPacketOut();
            action = new OFActionOutput(outPort);
            po.setActions(Collections.singletonList(action));
            po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
            po.setInPort(pi.getInPort());
            po.setPacketData(pi.getPacketData());
            sw.getOutputStream().write(po);
        }
    } else {
        // Destination port unknown, flood packet to all ports
        forwardAsHub(sw, pi);
    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.BaseTableJdbcSourceIT.java

protected static Object generateRandomData(Field.Type fieldType) {
    switch (fieldType) {
    case DATE:// w  w  w .  j a  v  a2 s  .  com
    case DATETIME:
    case TIME:
        return getRandomDateTime(fieldType);
    case ZONED_DATETIME:
        return ZonedDateTime.now();
    case DOUBLE:
        return RANDOM.nextDouble();
    case FLOAT:
        return RANDOM.nextFloat();
    case SHORT:
        return (short) RANDOM.nextInt(Short.MAX_VALUE + 1);
    case INTEGER:
        return RANDOM.nextInt();
    case LONG:
        return RANDOM.nextLong();
    case CHAR:
        return UUID.randomUUID().toString().charAt(0);
    case STRING:
        return UUID.randomUUID().toString();
    case DECIMAL:
        return new BigDecimal(BigInteger.valueOf(RANDOM.nextLong() % (long) Math.pow(10, 20)), 10);
    default:
        return null;
    }
}

From source file:com.google.uzaygezen.core.LongBitVector.java

@Override
public BigInteger toBigInteger() {
    final BigInteger result;
    if (data >= 0) {
        result = BigInteger.valueOf(data);
    } else {/*  w  ww .ja  va2s.  c  om*/
        BigInteger missingLowestBit = BigInteger.valueOf(data >>> 1).shiftLeft(1);
        if ((data & 1) == 1) {
            result = missingLowestBit.setBit(0);
        } else {
            result = missingLowestBit;
        }
    }
    return result;
}