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:de.tudarmstadt.ukp.csniper.webapp.project.ProjectRepository.java

/**
 * Gets the maximum column length.<br>
 * Why is this method located here? For convenience reasons - we already have access to
 * projectRepository on the relevant pages (EvaluationPage, AnnotationTypePage).
 * //from   w w w  .  j  a  va2  s .  c om
 * @param aColumn
 *            the column for which the maximum length shall be returned
 * @return the maximum length of the specified column in the specified table
 */
@Transactional
public int getDbColumnLength(String aEntityName, String aColumn) {
    BigInteger length = new BigInteger("255");

    final List<String> query = new ArrayList<String>();
    query.add("SELECT CHARACTER_MAXIMUM_LENGTH");
    query.add("FROM INFORMATION_SCHEMA.COLUMNS");

    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection aConnection) throws SQLException {
            query.add("WHERE table_schema = '" + aConnection.getCatalog() + "'");
        }
    });

    query.add("AND table_name = '" + aEntityName + "'");
    query.add("AND column_name = '" + aColumn + "'");

    try {
        length = (BigInteger) entityManager.createNativeQuery(StringUtils.join(query, " ")).getSingleResult();
    } catch (NoResultException e) {
        // log.debug("No results for query: " + StringUtils.join(query, " "));
    }

    if (length.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
        return Integer.MAX_VALUE;
    } else {
        return length.intValue();
    }
}

From source file:edu.unc.lib.dl.fedora.AccessClient.java

public List<PID> findAllObjectPIDs() throws FedoraException, ServiceException {
    List<PID> result = new ArrayList<PID>();
    FindObjects fo = new FindObjects();
    fo.setMaxResults(BigInteger.valueOf(100000));
    FieldSearchQuery query = new FieldSearchQuery();
    fo.setQuery(query);//w  w w . j a va2 s . c om
    ArrayOfString fields = new ArrayOfString();
    fields.getItem().add("pid");
    fo.setResultFields(fields);
    FindObjectsResponse response = (FindObjectsResponse) this.callService(fo, Action.findObjects);
    for (ObjectFields o : response.getResult().getResultList().getObjectFields()) {
        String s = o.getPid().getValue();
        result.add(new PID(s));
    }
    return result;
}

From source file:com.workday.autoparse.json.demo.InstanceUpdaterTest.java

@Test
public void testSpecialObjects() {
    TestObject testObject = new TestObject();
    testObject.myString = "antman";
    testObject.myBigDecimal = BigDecimal.valueOf(1.1);
    testObject.myBigInteger = BigInteger.valueOf(1);

    Map<String, Object> updates = new HashMap<>();
    updates.put("myString", "batman");
    updates.put("myBigDecimal", BigDecimal.valueOf(2.2));
    updates.put("myBigInteger", BigInteger.valueOf(2));

    TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

    assertEquals("myString", "batman", testObject.myString);
    assertEquals("myBigDecimal", BigDecimal.valueOf(2.2), testObject.myBigDecimal);
    assertEquals("myBigInteger", BigInteger.valueOf(2), testObject.myBigInteger);
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

/**
 * @param certificatePublicKey//from w  w w .java 2s.c  o  m
 * @param caPrivateKey
 * @param issuer
 * @param subject
 *
 * @return
 */
public static X509Certificate generateClientCertificate(PublicKey certificatePublicKey, PrivateKey caPrivateKey,
        X509Name issuer, X509Name subject) throws Exception {

    X509Certificate cert = null;

    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
    gen.setIssuerDN(issuer);
    setNotBeforeNotAfter(gen, 10); // validity from 48 hours in the past until 10 years in the future
    gen.setSubjectDN(subject);
    gen.setPublicKey(certificatePublicKey);
    gen.setSignatureAlgorithm(getSignatureAlgorithm());
    gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    gen = addClientExtensions(gen);

    cert = gen.generate(caPrivateKey, "BC");
    return cert;
}

From source file:org.o3project.optsdn.don.NetworkInformation.java

/**
 * Get informations from IDEx file(idex.txt).
 * - DP ID//from  www.j a  v  a2 s . c o m
 * - OF Port
 * 
 * @param filepath The IDEx file path
 * @throws Exception File Read Failed
 */
private void parseIdExFile(String filepath) throws Exception {
    String idexJson = readIdexAsJson(filepath);

    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, Map<String, String>> value = mapper.readValue(idexJson, Map.class);

    Set<Entry<String, Map<String, String>>> entrySet = value.entrySet();
    dpidMap = new HashMap<String, Long>();
    Map<String, Integer> ofPortMap = new HashMap<String, Integer>();
    for (Entry<String, Map<String, String>> entry : entrySet) {
        Map<String, String> params = entry.getValue();
        BigInteger bigintDpid = new BigInteger(params.get(DPID));
        if (bigintDpid.compareTo(BigInteger.valueOf(0)) < 0
                || bigintDpid.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
            throw new Exception("DP ID is out of boundary. (DP ID valid between 0 and 2^63-1)");
        }
        long dpid = bigintDpid.longValue();

        String informationModelId = entry.getKey();
        Port port = new Port(informationModelId);
        String neId = port.getNeId();

        Long existDpid = dpidMap.get(neId);
        if (existDpid == null) {
            dpidMap.put(neId, dpid);
        } else if (!existDpid.equals(dpid)) {
            logger.warn("Fail to add DP ID[" + dpid + "]. " + "The DP ID of NE[" + neId + "] is already set"
                    + "(exist DP ID[" + existDpid + "]).");
        }

        int ofPortId = Integer.valueOf(params.get(PORT));
        Integer existOfPortId = ofPortMap.get(informationModelId);
        if (existOfPortId != null) {
            if (!existOfPortId.equals(ofPortId)) {
                logger.warn("Fail to add OpenFlow Port ID[" + ofPortId + "]. " + "The OpenFlow Port ID of Port["
                        + informationModelId + "] is already set" + "(exist OpenFlow Port ID[" + existOfPortId
                        + "]).");
            }
        } else {
            if (ofPortId < 0 && ofPortId > Integer.MAX_VALUE) {
                throw new Exception("OpenFlow Port ID is out of boundary. "
                        + "(OpenFlow Port ID valid between 0 and 2^31-1)");
            }

            ofPortMap.put(informationModelId, ofPortId);
        }
    }

    for (Port port : portSet) {
        Integer openFlowPortId = ofPortMap.get(port.getInformationModelId());
        if (openFlowPortId == null) {
            continue;
        }
        port.setOpenFlowPortId(openFlowPortId);
    }

    for (List<List<Port>> linkList : omsConnectionInfoListMap.values()) {
        for (List<Port> link : linkList) {
            Port port1 = link.get(0);
            Integer openFlowPortId1 = ofPortMap.get(port1.getInformationModelId());
            if (openFlowPortId1 != null) {
                port1.setOpenFlowPortId(openFlowPortId1);
            }

            Port port2 = link.get(1);
            Integer openFlowPortId2 = ofPortMap.get(port2.getInformationModelId());
            if (openFlowPortId2 != null) {
                port2.setOpenFlowPortId(openFlowPortId2);
            }
        }
    }
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private static BigInteger binomialCoefficientLargeInteger(final int n, final int k) {
    if ((n == k) || (k == 0)) {
        return BigInteger.valueOf(1);
    }//w ww  .  j  a v a  2s . c  o m
    if ((k == 1) || (k == n - 1)) {
        return BigInteger.valueOf(n);
    }
    if (k > n / 2) {
        return binomialCoefficientLargeInteger(n, n - k);
    }

    BigInteger result = BigInteger.valueOf(1);
    int i = n - k + 1;
    for (int j = 1; j <= k; j++) {
        final int d = gcd(i, j);
        result = result.divide(BigInteger.valueOf(j / d)).multiply(BigInteger.valueOf(i / d));
        i++;
    }
    return result;
}

From source file:mil.jpeojtrs.sca.util.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * //from   w w  w  .  j ava  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:edu.brown.utils.MathUtil.java

/**
 * Calculate n! Derived from http://chaosinmotion.com/blog/?p=622
 * /* w  w w .  j a va2  s  . c  o m*/
 * @param n
 * @return
 */
public static final BigInteger factorial(int n) {
    BigInteger ret;

    if (n == 0)
        return BigInteger.ONE;
    if (null != (ret = CACHE_FACTORIAL.get(n)))
        return ret;
    ret = BigInteger.valueOf(n).multiply(factorial(n - 1));
    CACHE_FACTORIAL.put(n, ret);
    return ret;
}

From source file:ac.elements.parser.SimpleDBConverter.java

/**
 * Encodes real long value into a string by offsetting and zero-padding
 * number up to the specified number of digits. Use this encoding method if
 * the data range set includes both positive and negative values.
 * /*  w  ww.j  a  va  2s  .c  om*/
 * com.xerox.amazonws.sdb.DataUtils
 * 
 * @param number
 *            short to be encoded
 * @return string representation of the short
 */
private static String encodeShort(short number) {
    int maxNumDigits = BigInteger.valueOf(Short.MAX_VALUE).subtract(BigInteger.valueOf(Short.MIN_VALUE))
            .toString(RADIX).length();
    long offsetValue = Short.MIN_VALUE;

    BigInteger offsetNumber = BigInteger.valueOf(number).subtract(BigInteger.valueOf(offsetValue));
    String longString = offsetNumber.toString(RADIX);
    int numZeroes = maxNumDigits - longString.length();
    StringBuffer strBuffer = new StringBuffer(numZeroes + longString.length());
    for (int i = 0; i < numZeroes; i++) {
        strBuffer.insert(i, '0');
    }
    strBuffer.append(longString);
    return strBuffer.toString();
}

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

public X509Certificate createClass3RootCert(KeyPair keyPair, PrivateKey ppk, X509Certificate caCert)
        throws Exception {

    X500Name idn = CertificateUtil.getSubject(caCert);
    BigInteger sno = BigInteger.valueOf(5);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);
    X500Name sdn = X500NameUtil.createClass3RootPrincipal();
    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 2s  . c  o m*/
    addAuthorityKID(certBuilder, caCert.getPublicKey());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, ppk);
    certificate.checkValidity(new Date());
    certificate.verify(caCert.getPublicKey());

    setPKCS9Info(certificate);

    return certificate;
}